LLVM 24.0.0git
OMPIRBuilder.cpp
Go to the documentation of this file.
1//===- OpenMPIRBuilder.cpp - Builder for LLVM-IR for OpenMP directives ----===//
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/// \file
9///
10/// This file implements the OpenMPIRBuilder class, which is used as a
11/// convenient way to create LLVM instructions for OpenMP directives.
12///
13//===----------------------------------------------------------------------===//
14
17#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/StringSet.h"
29#include "llvm/IR/Attributes.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CFG.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DIBuilder.h"
38#include "llvm/IR/Function.h"
40#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/MDBuilder.h"
44#include "llvm/IR/Metadata.h"
46#include "llvm/IR/PassManager.h"
48#include "llvm/IR/Value.h"
50#include "llvm/Support/Error.h"
57
58#include <cstdint>
59#include <optional>
60
61#define DEBUG_TYPE "openmp-ir-builder"
62
63using namespace llvm;
64using namespace omp;
65
66static cl::opt<bool>
67 OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
68 cl::desc("Use optimistic attributes describing "
69 "'as-if' properties of runtime calls."),
70 cl::init(false));
71
73 "openmp-ir-builder-use-default-max-threads", cl::Hidden,
74 cl::desc("Use a default max threads if none is provided."), cl::init(true));
75
76#ifndef NDEBUG
77/// Return whether IP1 and IP2 are ambiguous, i.e. that inserting instructions
78/// at position IP1 may change the meaning of IP2 or vice-versa. This is because
79/// an InsertPoint stores the instruction before something is inserted. For
80/// instance, if both point to the same instruction, two IRBuilders alternating
81/// creating instruction will cause the instructions to be interleaved.
84 if (!IP1.isValid() || !IP2.isValid())
85 return false;
86 return IP1 == IP2;
87}
88
90 // Valid ordered/unordered and base algorithm combinations.
91 switch (SchedType & ~OMPScheduleType::MonotonicityMask) {
92 case OMPScheduleType::UnorderedStaticChunked:
93 case OMPScheduleType::UnorderedStatic:
94 case OMPScheduleType::UnorderedDynamicChunked:
95 case OMPScheduleType::UnorderedGuidedChunked:
96 case OMPScheduleType::UnorderedRuntime:
97 case OMPScheduleType::UnorderedAuto:
98 case OMPScheduleType::UnorderedTrapezoidal:
99 case OMPScheduleType::UnorderedGreedy:
100 case OMPScheduleType::UnorderedBalanced:
101 case OMPScheduleType::UnorderedGuidedIterativeChunked:
102 case OMPScheduleType::UnorderedGuidedAnalyticalChunked:
103 case OMPScheduleType::UnorderedSteal:
104 case OMPScheduleType::UnorderedStaticBalancedChunked:
105 case OMPScheduleType::UnorderedGuidedSimd:
106 case OMPScheduleType::UnorderedRuntimeSimd:
107 case OMPScheduleType::OrderedStaticChunked:
108 case OMPScheduleType::OrderedStatic:
109 case OMPScheduleType::OrderedDynamicChunked:
110 case OMPScheduleType::OrderedGuidedChunked:
111 case OMPScheduleType::OrderedRuntime:
112 case OMPScheduleType::OrderedAuto:
113 case OMPScheduleType::OrderdTrapezoidal:
114 case OMPScheduleType::NomergeUnorderedStaticChunked:
115 case OMPScheduleType::NomergeUnorderedStatic:
116 case OMPScheduleType::NomergeUnorderedDynamicChunked:
117 case OMPScheduleType::NomergeUnorderedGuidedChunked:
118 case OMPScheduleType::NomergeUnorderedRuntime:
119 case OMPScheduleType::NomergeUnorderedAuto:
120 case OMPScheduleType::NomergeUnorderedTrapezoidal:
121 case OMPScheduleType::NomergeUnorderedGreedy:
122 case OMPScheduleType::NomergeUnorderedBalanced:
123 case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:
124 case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:
125 case OMPScheduleType::NomergeUnorderedSteal:
126 case OMPScheduleType::NomergeOrderedStaticChunked:
127 case OMPScheduleType::NomergeOrderedStatic:
128 case OMPScheduleType::NomergeOrderedDynamicChunked:
129 case OMPScheduleType::NomergeOrderedGuidedChunked:
130 case OMPScheduleType::NomergeOrderedRuntime:
131 case OMPScheduleType::NomergeOrderedAuto:
132 case OMPScheduleType::NomergeOrderedTrapezoidal:
133 case OMPScheduleType::OrderedDistributeChunked:
134 case OMPScheduleType::OrderedDistribute:
135 break;
136 default:
137 return false;
138 }
139
140 // Must not set both monotonicity modifiers at the same time.
141 OMPScheduleType MonotonicityFlags =
142 SchedType & OMPScheduleType::MonotonicityMask;
143 if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
144 return false;
145
146 return true;
147}
148#endif
149
150/// This is a wrapper over IRBuilderBase::restoreIP that also restores a current
151/// debug location when the insert point is at the end of a block. It picks a
152/// location scoped to the current function: the block's last instruction
153/// location if the block is non-empty, otherwise a location synthesized from
154/// the function's subprogram (when the function has debug info).
157 Builder.restoreIP(IP);
158 // When IP points at a real instruction, restoreIP (SetInsertPoint) already
159 // set the debug location from that instruction, so leave it alone.
160 llvm::BasicBlock *BB = Builder.GetInsertBlock();
161 if (Builder.GetInsertPoint() != BB->end())
162 return;
163
164 // At the end of a block, pick a location guaranteed to belong to the current
165 // insertion function's subprogram. Prefer the block's own last instruction;
166 // otherwise synthesize a location from the function's subprogram.
167 if (!BB->empty())
168 Builder.SetCurrentDebugLocation(BB->back().getDebugLoc());
169 else if (llvm::DISubprogram *FSP =
170 BB->getParent() ? BB->getParent()->getSubprogram() : nullptr) {
171 unsigned Line = FSP->getScopeLine() ? FSP->getScopeLine() : FSP->getLine();
172 Builder.SetCurrentDebugLocation(
173 llvm::DILocation::get(FSP->getContext(), Line, /*Column=*/0, FSP));
174 }
175}
176
177static bool hasGridValue(const Triple &T) {
178 return T.isAMDGPU() || T.isNVPTX() || T.isSPIRV();
179}
180
181static const omp::GV &getGridValue(const Triple &T, Function *Kernel) {
182 if (T.isAMDGPU()) {
183 StringRef Features =
184 Kernel->getFnAttribute("target-features").getValueAsString();
185 if (Features.count("+wavefrontsize64"))
188 }
189 if (T.isNVPTX())
191 if (T.isSPIRV())
193 llvm_unreachable("No grid value available for this architecture!");
194}
195
196/// Determine which scheduling algorithm to use, determined from schedule clause
197/// arguments.
198static OMPScheduleType
199getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks,
200 bool HasSimdModifier, bool HasDistScheduleChunks) {
201 // Currently, the default schedule it static.
202 switch (ClauseKind) {
203 case OMP_SCHEDULE_Default:
204 case OMP_SCHEDULE_Static:
205 return HasChunks ? OMPScheduleType::BaseStaticChunked
206 : OMPScheduleType::BaseStatic;
207 case OMP_SCHEDULE_Dynamic:
208 return OMPScheduleType::BaseDynamicChunked;
209 case OMP_SCHEDULE_Guided:
210 return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd
211 : OMPScheduleType::BaseGuidedChunked;
212 case OMP_SCHEDULE_Auto:
214 case OMP_SCHEDULE_Runtime:
215 return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd
216 : OMPScheduleType::BaseRuntime;
217 case OMP_SCHEDULE_Distribute:
218 return HasDistScheduleChunks ? OMPScheduleType::BaseDistributeChunked
219 : OMPScheduleType::BaseDistribute;
220 }
221 llvm_unreachable("unhandled schedule clause argument");
222}
223
224/// Adds ordering modifier flags to schedule type.
225static OMPScheduleType
227 bool HasOrderedClause) {
228 assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
229 OMPScheduleType::None &&
230 "Must not have ordering nor monotonicity flags already set");
231
232 OMPScheduleType OrderingModifier = HasOrderedClause
233 ? OMPScheduleType::ModifierOrdered
234 : OMPScheduleType::ModifierUnordered;
235 OMPScheduleType OrderingScheduleType = BaseScheduleType | OrderingModifier;
236
237 // Unsupported combinations
238 if (OrderingScheduleType ==
239 (OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))
240 return OMPScheduleType::OrderedGuidedChunked;
241 else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |
242 OMPScheduleType::ModifierOrdered))
243 return OMPScheduleType::OrderedRuntime;
244
245 return OrderingScheduleType;
246}
247
248/// Adds monotonicity modifier flags to schedule type.
249static OMPScheduleType
251 bool HasSimdModifier, bool HasMonotonic,
252 bool HasNonmonotonic, bool HasOrderedClause) {
253 assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==
254 OMPScheduleType::None &&
255 "Must not have monotonicity flags already set");
256 assert((!HasMonotonic || !HasNonmonotonic) &&
257 "Monotonic and Nonmonotonic are contradicting each other");
258
259 if (HasMonotonic) {
260 return ScheduleType | OMPScheduleType::ModifierMonotonic;
261 } else if (HasNonmonotonic) {
262 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
263 } else {
264 // OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.
265 // If the static schedule kind is specified or if the ordered clause is
266 // specified, and if the nonmonotonic modifier is not specified, the
267 // effect is as if the monotonic modifier is specified. Otherwise, unless
268 // the monotonic modifier is specified, the effect is as if the
269 // nonmonotonic modifier is specified.
270 OMPScheduleType BaseScheduleType =
271 ScheduleType & ~OMPScheduleType::ModifierMask;
272 if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
273 (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
274 HasOrderedClause) {
275 // The monotonic is used by default in openmp runtime library, so no need
276 // to set it.
277 return ScheduleType;
278 } else {
279 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
280 }
281 }
282}
283
284/// Determine the schedule type using schedule and ordering clause arguments.
285static OMPScheduleType
286computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks,
287 bool HasSimdModifier, bool HasMonotonicModifier,
288 bool HasNonmonotonicModifier, bool HasOrderedClause,
289 bool HasDistScheduleChunks) {
291 ClauseKind, HasChunks, HasSimdModifier, HasDistScheduleChunks);
292 OMPScheduleType OrderedSchedule =
293 getOpenMPOrderingScheduleType(BaseSchedule, HasOrderedClause);
295 OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
296 HasNonmonotonicModifier, HasOrderedClause);
297
299 return Result;
300}
301
302/// Given a function, if it represents the entry point of a target kernel, this
303/// returns the execution mode flags associated with that kernel.
304static std::optional<omp::OMPTgtExecModeFlags>
306 CallInst *TargetInitCall = nullptr;
307 for (Instruction &Inst : Kernel.getEntryBlock()) {
308 if (auto *Call = dyn_cast<CallInst>(&Inst)) {
309 if (Call->getCalledFunction()->getName() == "__kmpc_target_init") {
310 TargetInitCall = Call;
311 break;
312 }
313 }
314 }
315
316 if (!TargetInitCall)
317 return std::nullopt;
318
319 // Get the kernel mode information from the global variable associated to the
320 // first argument to the call to __kmpc_target_init. Refer to
321 // createTargetInit() to see how this is initialized.
322 Value *InitOperand = TargetInitCall->getArgOperand(0);
323 GlobalVariable *KernelEnv = nullptr;
324 if (auto *Cast = dyn_cast<ConstantExpr>(InitOperand))
325 KernelEnv = cast<GlobalVariable>(Cast->getOperand(0));
326 else
327 KernelEnv = cast<GlobalVariable>(InitOperand);
328 auto *KernelEnvInit = cast<ConstantStruct>(KernelEnv->getInitializer());
329 auto *ConfigEnv = cast<ConstantStruct>(KernelEnvInit->getOperand(0));
330 auto *KernelMode = cast<ConstantInt>(ConfigEnv->getOperand(2));
331 return static_cast<OMPTgtExecModeFlags>(KernelMode->getZExtValue());
332}
333
334static bool isGenericKernel(Function &Fn) {
335 std::optional<omp::OMPTgtExecModeFlags> ExecMode =
337 return !ExecMode || (*ExecMode & OMP_TGT_EXEC_MODE_GENERIC);
338}
339
340/// Make \p Source branch to \p Target.
341///
342/// Handles two situations:
343/// * \p Source already has an unconditional branch.
344/// * \p Source is a degenerate block (no terminator because the BB is
345/// the current head of the IR construction).
347 if (Instruction *Term = Source->getTerminatorOrNull()) {
348 auto *Br = cast<UncondBrInst>(Term);
349 BasicBlock *Succ = Br->getSuccessor();
350 Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
351 Br->setSuccessor(Target);
352 return;
353 }
354
355 auto *NewBr = UncondBrInst::Create(Target, Source);
356 NewBr->setDebugLoc(DL);
357}
358
360 bool CreateBranch, DebugLoc DL) {
361 assert(New->getFirstInsertionPt() == New->begin() &&
362 "Target BB must not have PHI nodes");
363
364 // Move instructions to new block.
365 BasicBlock *Old = IP.getNodeParent();
366 // If the `Old` block is empty then there are no instructions to move. But in
367 // the new debug scheme, it could have trailing debug records which will be
368 // moved to `New` in `spliceDebugInfoEmptyBlock`. We dont want that for 2
369 // reasons:
370 // 1. If `New` is also empty, `BasicBlock::splice` crashes.
371 // 2. Even if `New` is not empty, the rationale to move those records to `New`
372 // (in `spliceDebugInfoEmptyBlock`) does not apply here. That function
373 // assumes that `Old` is optimized out and is going away. This is not the case
374 // here. The `Old` block is still being used e.g. a branch instruction is
375 // added to it later in this function.
376 // So we call `BasicBlock::splice` only when `Old` is not empty.
377 if (!Old->empty())
378 New->splice(New->begin(), Old, IP, Old->end());
379
380 if (CreateBranch) {
381 auto *NewBr = UncondBrInst::Create(New, Old);
382 NewBr->setDebugLoc(DL);
383 }
384}
385
386void llvm::spliceBB(IRBuilder<> &Builder, BasicBlock *New, bool CreateBranch) {
387 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
388 BasicBlock *Old = Builder.GetInsertBlock();
389
390 spliceBB(Builder.saveIP(), New, CreateBranch, DebugLoc);
391 if (CreateBranch)
392 Builder.SetInsertPoint(Old->getTerminator());
393 else
394 Builder.SetInsertPoint(Old);
395
396 // SetInsertPoint also updates the Builder's debug location, but we want to
397 // keep the one the Builder was configured to use.
398 Builder.SetCurrentDebugLocation(DebugLoc);
399}
400
402 DebugLoc DL, llvm::Twine Name) {
403 BasicBlock *Old = IP.getNodeParent();
405 Old->getContext(), Name.isTriviallyEmpty() ? Old->getName() : Name,
406 Old->getParent(), Old->getNextNode());
407 spliceBB(IP, New, CreateBranch, DL);
408 New->replaceSuccessorsPhiUsesWith(Old, New);
409 return New;
410}
411
412BasicBlock *llvm::splitBB(IRBuilderBase &Builder, bool CreateBranch,
413 llvm::Twine Name) {
414 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
415 BasicBlock *Old = Builder.GetInsertBlock();
416 BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, DebugLoc, Name);
417 if (CreateBranch)
418 Builder.SetInsertPoint(Old->getTerminator());
419 else
420 Builder.SetInsertPoint(Old);
421 // SetInsertPoint also updates the Builder's debug location, but we want to
422 // keep the one the Builder was configured to use.
423 Builder.SetCurrentDebugLocation(DebugLoc);
424 return New;
425}
426
427BasicBlock *llvm::splitBB(IRBuilder<> &Builder, bool CreateBranch,
428 llvm::Twine Name) {
429 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
430 BasicBlock *Old = Builder.GetInsertBlock();
431 BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, DebugLoc, Name);
432 if (CreateBranch)
433 Builder.SetInsertPoint(Old->getTerminator());
434 else
435 Builder.SetInsertPoint(Old);
436 // SetInsertPoint also updates the Builder's debug location, but we want to
437 // keep the one the Builder was configured to use.
438 Builder.SetCurrentDebugLocation(DebugLoc);
439 return New;
440}
441
443 llvm::Twine Suffix) {
444 BasicBlock *Old = Builder.GetInsertBlock();
445 return splitBB(Builder, CreateBranch, Old->getName() + Suffix);
446}
447
448// This function creates a fake integer value and a fake use for the integer
449// value. It returns the fake value created. This is useful in modeling the
450// extra arguments to the outlined functions.
452 OpenMPIRBuilder::InsertPointTy OuterAllocaIP,
454 OpenMPIRBuilder::InsertPointTy InnerAllocaIP,
455 const Twine &Name = "", bool AsPtr = true,
456 bool Is64Bit = false) {
457 Builder.restoreIP(OuterAllocaIP);
458 IntegerType *IntTy = Is64Bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
459 Instruction *FakeVal;
460 AllocaInst *FakeValAddr =
461 Builder.CreateAlloca(IntTy, nullptr, Name + ".addr");
462 ToBeDeleted.push_back(FakeValAddr);
463
464 if (AsPtr) {
465 FakeVal = FakeValAddr;
466 // The runtime passes these extra arguments to the outlined function as
467 // generic pointers, so cast away a non-zero alloca address space.
468 if (FakeValAddr->getAddressSpace() != 0) {
469 FakeVal = cast<Instruction>(Builder.CreateAddrSpaceCast(
470 FakeValAddr, Builder.getPtrTy(), Name + ".ascast"));
471 ToBeDeleted.push_back(FakeVal);
472 }
473 } else {
474 FakeVal = Builder.CreateLoad(IntTy, FakeValAddr, Name + ".val");
475 ToBeDeleted.push_back(FakeVal);
476 }
477
478 // Generate a fake use of this value
479 Builder.restoreIP(InnerAllocaIP);
480 Instruction *UseFakeVal;
481 if (AsPtr) {
482 UseFakeVal = Builder.CreateLoad(IntTy, FakeVal, Name + ".use");
483 } else {
484 UseFakeVal = cast<BinaryOperator>(Builder.CreateAdd(
485 FakeVal, Is64Bit ? Builder.getInt64(10) : Builder.getInt32(10)));
486 }
487 ToBeDeleted.push_back(UseFakeVal);
488 return FakeVal;
489}
490
491//===----------------------------------------------------------------------===//
492// OpenMPIRBuilderConfig
493//===----------------------------------------------------------------------===//
494
495namespace {
497/// Values for bit flags for marking which requires clauses have been used.
498enum OpenMPOffloadingRequiresDirFlags {
499 /// flag undefined.
500 OMP_REQ_UNDEFINED = 0x000,
501 /// no requires directive present.
502 OMP_REQ_NONE = 0x001,
503 /// reverse_offload clause.
504 OMP_REQ_REVERSE_OFFLOAD = 0x002,
505 /// unified_address clause.
506 OMP_REQ_UNIFIED_ADDRESS = 0x004,
507 /// unified_shared_memory clause.
508 OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
509 /// dynamic_allocators clause.
510 OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
511 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)
512};
513
514class OMPCodeExtractor : public CodeExtractor {
515public:
516 OMPCodeExtractor(OpenMPIRBuilder &OMPBuilder, ArrayRef<BasicBlock *> BBs,
517 DominatorTree *DT = nullptr, bool AggregateArgs = false,
518 BlockFrequencyInfo *BFI = nullptr,
519 BranchProbabilityInfo *BPI = nullptr,
520 AssumptionCache *AC = nullptr, bool AllowVarArgs = false,
521 bool AllowAlloca = false,
522 BasicBlock *AllocationBlock = nullptr,
523 ArrayRef<BasicBlock *> DeallocationBlocks = {},
524 std::string Suffix = "", bool ArgsInZeroAddressSpace = false)
525 : CodeExtractor(BBs, DT, AggregateArgs, BFI, BPI, AC, AllowVarArgs,
526 AllowAlloca, AllocationBlock, DeallocationBlocks, Suffix,
527 ArgsInZeroAddressSpace),
528 OMPBuilder(OMPBuilder) {}
529
530 virtual ~OMPCodeExtractor() = default;
531
532protected:
533 OpenMPIRBuilder &OMPBuilder;
534};
535
536class DeviceSharedMemCodeExtractor : public OMPCodeExtractor {
537public:
538 using OMPCodeExtractor::OMPCodeExtractor;
539 virtual ~DeviceSharedMemCodeExtractor() = default;
540
541protected:
542 virtual Instruction *
543 allocateVar(IRBuilder<>::InsertPoint AllocaIP, DebugLoc DL, Type *VarType,
544 const Twine &Name = Twine(""),
545 AddrSpaceCastInst **CastedAlloc = nullptr) override {
546 return OMPBuilder.createOMPAllocShared({AllocaIP, DL}, VarType, Name);
547 }
548
549 virtual Instruction *deallocateVar(IRBuilder<>::InsertPoint DeallocIP,
550 DebugLoc DL, Value *Var,
551 Type *VarType) override {
552 return OMPBuilder.createOMPFreeShared({DeallocIP, DL}, Var, VarType);
553 }
554};
555
556/// Helper storing information about regions to outline using device shared
557/// memory for intermediate allocations.
558struct DeviceSharedMemOutlineInfo : public OpenMPIRBuilder::OutlineInfo {
559 OpenMPIRBuilder &OMPBuilder;
560
561 DeviceSharedMemOutlineInfo(OpenMPIRBuilder &OMPBuilder)
562 : OMPBuilder(OMPBuilder) {}
563 virtual ~DeviceSharedMemOutlineInfo() = default;
564
565 virtual std::unique_ptr<CodeExtractor>
566 createCodeExtractor(ArrayRef<BasicBlock *> Blocks,
567 bool ArgsInZeroAddressSpace,
568 Twine Suffix = Twine("")) override;
569};
570
571} // anonymous namespace
572
574 : RequiresFlags(OMP_REQ_UNDEFINED) {}
575
578 bool HasRequiresReverseOffload, bool HasRequiresUnifiedAddress,
579 bool HasRequiresUnifiedSharedMemory, bool HasRequiresDynamicAllocators)
582 RequiresFlags(OMP_REQ_UNDEFINED) {
583 if (HasRequiresReverseOffload)
584 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
585 if (HasRequiresUnifiedAddress)
586 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
587 if (HasRequiresUnifiedSharedMemory)
588 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
589 if (HasRequiresDynamicAllocators)
590 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
591}
592
594 return RequiresFlags & OMP_REQ_REVERSE_OFFLOAD;
595}
596
598 return RequiresFlags & OMP_REQ_UNIFIED_ADDRESS;
599}
600
602 return RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY;
603}
604
606 return RequiresFlags & OMP_REQ_DYNAMIC_ALLOCATORS;
607}
608
610 return hasRequiresFlags() ? RequiresFlags
611 : static_cast<int64_t>(OMP_REQ_NONE);
612}
613
615 if (Value)
616 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
617 else
618 RequiresFlags &= ~OMP_REQ_REVERSE_OFFLOAD;
619}
620
622 if (Value)
623 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
624 else
625 RequiresFlags &= ~OMP_REQ_UNIFIED_ADDRESS;
626}
627
629 if (Value)
630 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
631 else
632 RequiresFlags &= ~OMP_REQ_UNIFIED_SHARED_MEMORY;
633}
634
636 if (Value)
637 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
638 else
639 RequiresFlags &= ~OMP_REQ_DYNAMIC_ALLOCATORS;
640}
641
642//===----------------------------------------------------------------------===//
643// OpenMPIRBuilder
644//===----------------------------------------------------------------------===//
645
648 SmallVector<Value *> &ArgsVector) {
650 Value *PointerNum = Builder.getInt32(KernelArgs.NumTargetItems);
651 auto Int32Ty = Type::getInt32Ty(Builder.getContext());
652 constexpr size_t MaxDim = 3;
653 Value *ZeroArray = Constant::getNullValue(ArrayType::get(Int32Ty, MaxDim));
654
655 Value *HasNoWaitFlag = Builder.getInt64(KernelArgs.HasNoWait);
656
657 Value *DynCGroupMemFallbackFlag =
658 Builder.getInt64(static_cast<uint64_t>(KernelArgs.DynCGroupMemFallback));
659 DynCGroupMemFallbackFlag = Builder.CreateShl(DynCGroupMemFallbackFlag, 2);
660
661 Value *StrictBlocksFlag = Builder.getInt64(KernelArgs.StrictBlocks);
662 Value *StrictThreadsFlag = Builder.getInt64(KernelArgs.StrictThreads);
663
664 StrictBlocksFlag = Builder.CreateShl(StrictBlocksFlag, 6);
665 StrictThreadsFlag = Builder.CreateShl(StrictThreadsFlag, 7);
666
667 Value *Flags = Builder.CreateOr(HasNoWaitFlag, DynCGroupMemFallbackFlag);
668 Flags = Builder.CreateOr(Flags, StrictBlocksFlag);
669 Flags = Builder.CreateOr(Flags, StrictThreadsFlag);
670
671 assert(!KernelArgs.NumTeams.empty() && !KernelArgs.NumThreads.empty());
672
673 Value *NumTeams3D =
674 Builder.CreateInsertValue(ZeroArray, KernelArgs.NumTeams[0], {0});
675 Value *NumThreads3D =
676 Builder.CreateInsertValue(ZeroArray, KernelArgs.NumThreads[0], {0});
677 for (unsigned I :
678 seq<unsigned>(1, std::min(KernelArgs.NumTeams.size(), MaxDim)))
679 NumTeams3D =
680 Builder.CreateInsertValue(NumTeams3D, KernelArgs.NumTeams[I], {I});
681 for (unsigned I :
682 seq<unsigned>(1, std::min(KernelArgs.NumThreads.size(), MaxDim)))
683 NumThreads3D =
684 Builder.CreateInsertValue(NumThreads3D, KernelArgs.NumThreads[I], {I});
685
686 ArgsVector = {Version,
687 PointerNum,
688 KernelArgs.RTArgs.BasePointersArray,
689 KernelArgs.RTArgs.PointersArray,
690 KernelArgs.RTArgs.SizesArray,
691 KernelArgs.RTArgs.MapTypesArray,
692 KernelArgs.RTArgs.MapNamesArray,
693 KernelArgs.RTArgs.MappersArray,
694 KernelArgs.NumIterations,
695 Flags,
696 NumTeams3D,
697 NumThreads3D,
698 KernelArgs.DynCGroupMem};
699}
700
702 LLVMContext &Ctx = Fn.getContext();
703
704 // Get the function's current attributes.
705 auto Attrs = Fn.getAttributes();
706 auto FnAttrs = Attrs.getFnAttrs();
707 auto RetAttrs = Attrs.getRetAttrs();
709 for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
710 ArgAttrs.emplace_back(Attrs.getParamAttrs(ArgNo));
711
712 // Add AS to FnAS while taking special care with integer extensions.
713 auto addAttrSet = [&](AttributeSet &FnAS, const AttributeSet &AS,
714 bool Param = true) -> void {
715 bool HasSignExt = AS.hasAttribute(Attribute::SExt);
716 bool HasZeroExt = AS.hasAttribute(Attribute::ZExt);
717 if (HasSignExt || HasZeroExt) {
718 assert(AS.getNumAttributes() == 1 &&
719 "Currently not handling extension attr combined with others.");
720 if (Param) {
721 if (auto AK = TargetLibraryInfo::getExtAttrForI32Param(T, HasSignExt))
722 FnAS = FnAS.addAttribute(Ctx, AK);
723 } else if (auto AK =
724 TargetLibraryInfo::getExtAttrForI32Return(T, HasSignExt))
725 FnAS = FnAS.addAttribute(Ctx, AK);
726 } else {
727 FnAS = FnAS.addAttributes(Ctx, AS);
728 }
729 };
730
731#define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
732#include "llvm/Frontend/OpenMP/OMPKinds.def"
733
734 // Add attributes to the function declaration.
735 switch (FnID) {
736#define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \
737 case Enum: \
738 FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet); \
739 addAttrSet(RetAttrs, RetAttrSet, /*Param*/ false); \
740 for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo) \
741 addAttrSet(ArgAttrs[ArgNo], ArgAttrSets[ArgNo]); \
742 Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs)); \
743 break;
744#include "llvm/Frontend/OpenMP/OMPKinds.def"
745 default:
746 // Attributes are optional.
747 break;
748 }
749}
750
753 FunctionType *FnTy = nullptr;
754 StringRef Name;
755
756 switch (FnID) {
757#define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \
758 case Enum: \
759 FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__}, \
760 IsVarArg); \
761 Name = Str; \
762 break;
763#include "llvm/Frontend/OpenMP/OMPKinds.def"
764 }
765
766 return M.getOrInsertFunction(Name, FnTy, [&](Function &Fn) {
767 Fn.setCallingConv(Config.getRuntimeCC());
768 // Add information if the runtime function takes a callback function
769 if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
770 LLVMContext &Ctx = Fn.getContext();
771 MDBuilder MDB(Ctx);
772 // Annotate the callback behavior of the runtime function:
773 // - The callback callee is argument number 2 (microtask).
774 // - The first two arguments of the callback callee are unknown (-1).
775 // - All variadic arguments to the runtime function are passed to the
776 // callback callee.
777 Fn.addMetadata(
778 LLVMContext::MD_callback,
780 2, {-1, -1}, /* VarArgsArePassed */ true)}));
781 }
782
783 LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn.getName()
784 << " with type " << *Fn.getFunctionType() << "\n");
785 addAttributes(FnID, Fn);
786 });
787}
788
791 if (!FiniBB) {
792 Function *ParentFunc = Builder.GetInsertBlock()->getParent();
794 FiniBB = BasicBlock::Create(Builder.getContext(), ".fini", ParentFunc);
795 Builder.SetInsertPoint(FiniBB);
796 // FiniCB adds the branch to the exit stub.
797 if (Error Err = FiniCB(Builder.saveIP()))
798 return Err;
799 }
800 return FiniBB;
801}
802
804 BasicBlock *OtherFiniBB) {
805 // Simple case: FiniBB does not exist yet: re-use OtherFiniBB.
806 if (!FiniBB) {
807 FiniBB = OtherFiniBB;
808
809 Builder.SetInsertPoint(FiniBB->getFirstNonPHIIt());
810 if (Error Err = FiniCB(Builder.saveIP()))
811 return Err;
812
813 return Error::success();
814 }
815
816 // Move instructions from FiniBB to the start of OtherFiniBB.
817 auto EndIt = FiniBB->end();
818 if (FiniBB->size() >= 1)
819 if (auto Prev = std::prev(EndIt); Prev->isTerminator())
820 EndIt = Prev;
821 OtherFiniBB->splice(OtherFiniBB->getFirstNonPHIIt(), FiniBB, FiniBB->begin(),
822 EndIt);
823
824 FiniBB->replaceAllUsesWith(OtherFiniBB);
825 FiniBB->eraseFromParent();
826 FiniBB = OtherFiniBB;
827 return Error::success();
828}
829
832 auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
833 assert(Fn && "Failed to create OpenMP runtime function pointer");
834 return Fn;
835}
836
839 const Twine &Name) {
840 CallInst *Call = Builder.CreateCall(Callee, Args, Name);
841 Call->setCallingConv(Config.getRuntimeCC());
842 return Call;
843}
844
845void OpenMPIRBuilder::initialize() { initializeTypes(M); }
846
849 BasicBlock &EntryBlock = Function->getEntryBlock();
850 BasicBlock::iterator MoveLocInst = EntryBlock.getFirstNonPHIIt();
851
852 // Loop over blocks looking for constant allocas, skipping the entry block
853 // as any allocas there are already in the desired location.
854 for (auto Block = std::next(Function->begin(), 1); Block != Function->end();
855 Block++) {
856 for (auto Inst = Block->getReverseIterator()->begin();
857 Inst != Block->getReverseIterator()->end();) {
859 Inst++;
861 continue;
862 AllocaInst->moveBeforePreserving(MoveLocInst);
863 } else {
864 Inst++;
865 }
866 }
867 }
868}
869
872
873 auto ShouldHoistAlloca = [](const llvm::AllocaInst &AllocaInst) {
874 // TODO: For now, we support simple static allocations, we might need to
875 // move non-static ones as well. However, this will need further analysis to
876 // move the lenght arguments as well.
878 };
879
880 for (llvm::Instruction &Inst : Block)
882 if (ShouldHoistAlloca(*AllocaInst))
883 AllocasToMove.push_back(AllocaInst);
884
885 auto InsertPoint =
886 Block.getParent()->getEntryBlock().getTerminator()->getIterator();
887
888 for (llvm::Instruction *AllocaInst : AllocasToMove)
890}
891
893 PostDominatorTree PostDomTree(*Func);
894 for (llvm::BasicBlock &BB : *Func)
895 if (PostDomTree.properlyDominates(&BB, &Func->getEntryBlock()))
897}
898
899#ifndef NDEBUG
900/// Return true if \p Name names an OpenMP runtime function.
902 static const StringSet<> Names = {
903#define OMP_RTL(Enum, Str, ...) Str,
904#include "llvm/Frontend/OpenMP/OMPKinds.def"
905 };
906 return Names.contains(Name);
907}
908
909/// Assert that every direct call to an OpenMP runtime function in \p M has a
910/// debug location if its function has a subprogram.
912 for (Function &F : M) {
913 if (!F.getSubprogram())
914 continue;
915 for (Instruction &I : instructions(F)) {
916 auto *CB = dyn_cast<CallBase>(&I);
917 if (!CB || CB->getDebugLoc())
918 continue;
919 Function *Callee = CB->getCalledFunction();
920 if (Callee && isRuntimeFunctionName(Callee->getName())) {
921 errs() << "OpenMP runtime call to '" << Callee->getName()
922 << "' in function '" << F.getName()
923 << "' has no debug location\n";
924 llvm_unreachable("OpenMP runtime call has no debug location");
925 }
926 }
927 }
928}
929#endif
930
932 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
934 SmallVector<std::unique_ptr<OutlineInfo>, 16> DeferredOutlines;
935 for (std::unique_ptr<OutlineInfo> &OI : OutlineInfos) {
936 // Skip functions that have not finalized yet; may happen with nested
937 // function generation.
938 if (Fn && OI->getFunction() != Fn) {
939 DeferredOutlines.push_back(std::move(OI));
940 continue;
941 }
942
943 ParallelRegionBlockSet.clear();
944 Blocks.clear();
945 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
946
947 Function *OuterFn = OI->getFunction();
948 CodeExtractorAnalysisCache CEAC(*OuterFn);
949 // If we generate code for the target device, we need to allocate
950 // struct for aggregate params in the device default alloca address space.
951 // OpenMP runtime requires that the params of the extracted functions are
952 // passed as zero address space pointers. This flag ensures that
953 // CodeExtractor generates correct code for extracted functions
954 // which are used by OpenMP runtime.
955 bool ArgsInZeroAddressSpace = Config.isTargetDevice();
956 std::unique_ptr<CodeExtractor> Extractor =
957 OI->createCodeExtractor(Blocks, ArgsInZeroAddressSpace, ".omp_par");
958
959 LLVM_DEBUG(dbgs() << "Before outlining: " << *OuterFn << "\n");
960 LLVM_DEBUG(dbgs() << "Entry " << OI->EntryBB->getName()
961 << " Exit: " << OI->ExitBB->getName() << "\n");
962 assert(Extractor->isEligible() &&
963 "Expected OpenMP outlining to be possible!");
964
965 for (auto *V : OI->ExcludeArgsFromAggregate)
966 Extractor->excludeArgFromAggregate(V);
967
968 Function *OutlinedFn =
969 Extractor->extractCodeRegion(CEAC, OI->Inputs, OI->Outputs);
970
971 // Forward target-cpu, target-features attributes to the outlined function.
972 auto TargetCpuAttr = OuterFn->getFnAttribute("target-cpu");
973 if (TargetCpuAttr.isStringAttribute())
974 OutlinedFn->addFnAttr(TargetCpuAttr);
975
976 auto TargetFeaturesAttr = OuterFn->getFnAttribute("target-features");
977 if (TargetFeaturesAttr.isStringAttribute())
978 OutlinedFn->addFnAttr(TargetFeaturesAttr);
979
980 LLVM_DEBUG(dbgs() << "After outlining: " << *OuterFn << "\n");
981 LLVM_DEBUG(dbgs() << " Outlined function: " << *OutlinedFn << "\n");
982 assert(OutlinedFn->getReturnType()->isVoidTy() &&
983 "OpenMP outlined functions should not return a value!");
984
985 // For compability with the clang CG we move the outlined function after the
986 // one with the parallel region.
987 OutlinedFn->removeFromParent();
988 M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
989
990 // Remove the artificial entry introduced by the extractor right away, we
991 // made our own entry block after all.
992 {
993 BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
994 assert(ArtificialEntry.getUniqueSuccessor() == OI->EntryBB);
995 assert(OI->EntryBB->getUniquePredecessor() == &ArtificialEntry);
996 // Move instructions from the to-be-deleted ArtificialEntry to the entry
997 // basic block of the parallel region. CodeExtractor generates
998 // instructions to unwrap the aggregate argument and may sink
999 // allocas/bitcasts for values that are solely used in the outlined region
1000 // and do not escape.
1001 assert(!ArtificialEntry.empty() &&
1002 "Expected instructions to add in the outlined region entry");
1003 for (BasicBlock::reverse_iterator It = ArtificialEntry.rbegin(),
1004 End = ArtificialEntry.rend();
1005 It != End;) {
1006 Instruction &I = *It;
1007 It++;
1008
1009 if (I.isTerminator()) {
1010 // Absorb any debug value that terminator may have
1011 if (Instruction *TI = OI->EntryBB->getTerminatorOrNull())
1012 TI->adoptDbgRecords(&ArtificialEntry, I.getIterator(), false);
1013 continue;
1014 }
1015
1016 I.moveBeforePreserving(*OI->EntryBB,
1017 OI->EntryBB->getFirstInsertionPt());
1018 }
1019
1020 OI->EntryBB->moveBefore(&ArtificialEntry);
1021 ArtificialEntry.eraseFromParent();
1022 }
1023 assert(&OutlinedFn->getEntryBlock() == OI->EntryBB);
1024 assert(OutlinedFn && OutlinedFn->hasNUses(1));
1025
1026 // Run a user callback, e.g. to add attributes.
1027 if (OI->PostOutlineCB)
1028 OI->PostOutlineCB(*OutlinedFn);
1029
1030 if (OI->FixUpNonEntryAllocas)
1032 }
1033
1034 // Remove work items that have been completed.
1035 OutlineInfos = std::move(DeferredOutlines);
1036
1037 // The createTarget functions embeds user written code into
1038 // the target region which may inject allocas which need to
1039 // be moved to the entry block of our target or risk malformed
1040 // optimisations by later passes (however, we do not block on
1041 // that here, it's up to the inserter to the list to do so).
1042 // This notbaly has to occur after the OutlinedInfo candidates
1043 // have been extracted so we have an end product that will not
1044 // be implicitly adversely affected by any raises unless
1045 // intentionally appended to the list.
1046 // NOTE: This only does so for ConstantData, it could be extended
1047 // to ConstantExpr's with further effort, however, they should
1048 // largely be folded when they get here. Extending it to runtime
1049 // defined/read+writeable allocation sizes would be non-trivial
1050 // (need to factor in movement of any stores to variables the
1051 // allocation size depends on, as well as the usual loads,
1052 // otherwise it'll yield the wrong result after movement) and
1053 // likely be more suitable as an LLVM optimisation pass.
1056
1057 EmitMetadataErrorReportFunctionTy &&ErrorReportFn =
1058 [](EmitMetadataErrorKind Kind,
1059 const TargetRegionEntryInfo &EntryInfo) -> void {
1060 errs() << "Error of kind: " << Kind
1061 << " when emitting offload entries and metadata during "
1062 "OMPIRBuilder finalization \n";
1063 };
1064
1065 // Function finalization must not emit module-wide offload entries.
1066 if (!Fn && !OffloadInfoManager.empty())
1068
1069 // Rewrite uses of globals to their replacement declare target globals if
1070 // we are processing a device module.
1071 if (Config.isTargetDevice())
1072 applyDeclareTargetGlobalReplacements();
1073
1074 if (!Fn && Config.EmitLLVMUsedMetaInfo.value_or(false)) {
1075 std::vector<WeakTrackingVH> LLVMCompilerUsed = {
1076 M.getGlobalVariable("__openmp_nvptx_data_transfer_temporary_storage")};
1077 emitUsed("llvm.compiler.used", LLVMCompilerUsed);
1078 }
1079
1080 IsFinalized = true;
1081
1082#ifndef NDEBUG
1083 // A caller finalizing one function at a time would have the module walked
1084 // once per function, so only check when the whole module is finalized.
1085 if (!Fn)
1087#endif
1088}
1089
1090bool OpenMPIRBuilder::isFinalized() { return IsFinalized; }
1091
1093 GlobalValue *Original, GlobalValue *Replacement) {
1094 assert(Original && Replacement &&
1095 "Null values provided to registerDeclareTargetGlobalReplacement");
1096 DeclareTargetGlobalReplacements.push_back({Original, Replacement});
1097}
1098
1099void OpenMPIRBuilder::applyDeclareTargetGlobalReplacements() {
1100 for (DeclareTargetGlobalReplacement &R : DeclareTargetGlobalReplacements) {
1101 GlobalValue *OldGV = R.Original;
1102 GlobalValue *NewGV = R.Replacement;
1103
1104 assert(OldGV && NewGV &&
1105 "A null value was inserted into DeclareTargetGlobalReplacements");
1106
1107 // The assert above should catch this case, but this is kept to attempt
1108 // to proceed without issue when asserts are off.
1109 if (!OldGV || !NewGV)
1110 continue;
1111
1112 // The replacement global is a reference pointer that holds the
1113 // address of the device-resident storage. Every use must load the
1114 // reference pointer first and use the loaded address.
1115 //
1116 // Constant expression users (e.g. a constant GEP embedded in another
1117 // global's initializer or in an instruction) cannot have a load inserted
1118 // in place, so first expand any constant-expression users that live inside
1119 // functions into instructions. Any remaining constant users are handled
1120 // via a direct constant rewrite below as we cannot materialize a load
1121 // there.
1122 //
1123 // NOTE: We extend the constant rewrite to module scope, as we replace all
1124 // usages.
1125 if (auto *OldConst = dyn_cast<Constant>(OldGV))
1127 /*RestrictToFunc=*/nullptr,
1128 /*RemoveDeadConstants=*/false);
1129
1130 IRBuilderBase::InsertPointGuard Guard(Builder);
1132 for (User *U : Users) {
1133 auto *Insn = dyn_cast<Instruction>(U);
1134 if (!Insn)
1135 continue;
1136
1137 // A PHI node cannot have a load inserted immediately before it, as PHIs
1138 // must remain grouped at the top of their basic block. So we need to
1139 // make sure any loads we emit are generated in the preceding edge, a
1140 // PHI may reference the global on more than one edge, so every matching
1141 // slot must be handled.
1142 if (auto *PHI = dyn_cast<PHINode>(Insn)) {
1143 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
1144 if (PHI->getIncomingValue(I) != OldGV)
1145 continue;
1146
1147 BasicBlock *IncomingBB = PHI->getIncomingBlock(I);
1148 Builder.SetInsertPoint(IncomingBB->getTerminator());
1149 Builder.SetCurrentDebugLocation(PHI->getDebugLoc());
1150 LoadInst *EdgeLoad = Builder.CreateLoad(NewGV->getType(), NewGV);
1151 PHI->setIncomingValue(I, EdgeLoad);
1152 }
1153 continue;
1154 }
1155
1156 Builder.SetInsertPoint(Insn);
1157 Builder.SetCurrentDebugLocation(Insn->getDebugLoc());
1158 LoadInst *Load = Builder.CreateLoad(NewGV->getType(), NewGV);
1159
1160 // The replacement declare target global lives in the default address
1161 // space, whereas the original global may reside in a non-default
1162 // address space. In that case the initial lowering may have
1163 // emitted an addrspacecast that is no longer valid. Replace the
1164 // whole addrspacecast with the load and erase it rather than
1165 // feeding the load back into the (now pointless) cast.
1166 // NOTE: If we end up with replacement declare target globals in
1167 // non-zero AS's the below will need some minor extensions to have the
1168 // option to alter the address space cast to the new address space where
1169 // required rather than just replacing it.
1170 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(Insn)) {
1171 unsigned NewGVAS = NewGV->getType()->getPointerAddressSpace();
1172 assert(NewGVAS == 0 &&
1173 "Non-default address space declare target global");
1174 unsigned OldGVAS = OldGV->getType()->getPointerAddressSpace();
1175 unsigned DestAS = ASC->getType()->getPointerAddressSpace();
1176 if (DestAS == 0 && NewGVAS != OldGVAS) {
1177 ASC->replaceAllUsesWith(Load);
1178 ASC->eraseFromParent();
1179 continue;
1180 }
1181 }
1182
1183 Insn->replaceUsesOfWith(OldGV, Load);
1184 }
1185 }
1186
1188}
1189
1191 assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
1192}
1193
1195 IntegerType *I32Ty = Type::getInt32Ty(M.getContext());
1196 auto *GV =
1197 new GlobalVariable(M, I32Ty,
1198 /* isConstant = */ true, GlobalValue::WeakODRLinkage,
1199 ConstantInt::get(I32Ty, Value), Name);
1200 GV->setVisibility(GlobalValue::HiddenVisibility);
1201
1202 return GV;
1203}
1204
1206 if (List.empty())
1207 return;
1208
1209 // Convert List to what ConstantArray needs.
1211 UsedArray.resize(List.size());
1212 for (unsigned I = 0, E = List.size(); I != E; ++I)
1214 cast<Constant>(&*List[I]), Builder.getPtrTy());
1215
1216 if (UsedArray.empty())
1217 return;
1218 ArrayType *ATy = ArrayType::get(Builder.getPtrTy(), UsedArray.size());
1219
1220 auto *GV = new GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
1221 ConstantArray::get(ATy, UsedArray), Name);
1222
1223 GV->setSection("llvm.metadata");
1224}
1225
1228 OMPTgtExecModeFlags Mode) {
1229 auto *Int8Ty = Builder.getInt8Ty();
1230 auto *GVMode = new GlobalVariable(
1231 M, Int8Ty, /*isConstant=*/true, GlobalValue::WeakAnyLinkage,
1232 ConstantInt::get(Int8Ty, Mode), Twine(KernelName, "_exec_mode"));
1233 GVMode->setVisibility(GlobalVariable::ProtectedVisibility);
1234 return GVMode;
1235}
1236
1238 uint32_t SrcLocStrSize,
1239 IdentFlag LocFlags,
1240 unsigned Reserve2Flags) {
1241 // Enable "C-mode".
1242 LocFlags |= OMP_IDENT_FLAG_KMPC;
1243
1244 Constant *&Ident =
1245 IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
1246 if (!Ident) {
1247 Constant *I32Null = ConstantInt::getNullValue(Int32);
1248 Constant *IdentData[] = {I32Null,
1249 ConstantInt::get(Int32, uint32_t(LocFlags)),
1250 ConstantInt::get(Int32, Reserve2Flags),
1251 ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
1252
1253 size_t SrcLocStrArgIdx = 4;
1254 if (OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx)
1256 IdentData[SrcLocStrArgIdx]->getType()->getPointerAddressSpace())
1257 IdentData[SrcLocStrArgIdx] = ConstantExpr::getAddrSpaceCast(
1258 SrcLocStr, OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx));
1259 Constant *Initializer =
1260 ConstantStruct::get(OpenMPIRBuilder::Ident, IdentData);
1261
1262 // Look for existing encoding of the location + flags, not needed but
1263 // minimizes the difference to the existing solution while we transition.
1264 for (GlobalVariable &GV : M.globals())
1265 if (GV.getValueType() == OpenMPIRBuilder::Ident && GV.hasInitializer())
1266 if (GV.getInitializer() == Initializer)
1267 Ident = &GV;
1268
1269 if (!Ident) {
1270 auto *GV = new GlobalVariable(
1271 M, OpenMPIRBuilder::Ident,
1272 /* isConstant = */ true, GlobalValue::PrivateLinkage, Initializer, "",
1274 M.getDataLayout().getDefaultGlobalsAddressSpace());
1275 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1276 GV->setAlignment(Align(8));
1277 Ident = GV;
1278 }
1279 }
1280
1281 return ConstantExpr::getPointerBitCastOrAddrSpaceCast(Ident, IdentPtr);
1282}
1283
1285 uint32_t &SrcLocStrSize) {
1286 SrcLocStrSize = LocStr.size();
1287 Constant *&SrcLocStr = SrcLocStrMap[LocStr];
1288 if (!SrcLocStr) {
1289 Constant *Initializer =
1290 ConstantDataArray::getString(M.getContext(), LocStr);
1291
1292 // Look for existing encoding of the location, not needed but minimizes the
1293 // difference to the existing solution while we transition.
1294 for (GlobalVariable &GV : M.globals())
1295 if (GV.isConstant() && GV.hasInitializer() &&
1296 GV.getInitializer() == Initializer)
1297 return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
1298
1299 SrcLocStr = Builder.CreateGlobalString(
1300 LocStr, /*Name=*/"", M.getDataLayout().getDefaultGlobalsAddressSpace(),
1301 &M);
1302 }
1303 return SrcLocStr;
1304}
1305
1307 StringRef FileName,
1308 unsigned Line, unsigned Column,
1309 uint32_t &SrcLocStrSize) {
1310 SmallString<128> Buffer;
1311 Buffer.push_back(';');
1312 Buffer.append(FileName);
1313 Buffer.push_back(';');
1314 Buffer.append(FunctionName);
1315 Buffer.push_back(';');
1316 Buffer.append(std::to_string(Line));
1317 Buffer.push_back(';');
1318 Buffer.append(std::to_string(Column));
1319 Buffer.push_back(';');
1320 Buffer.push_back(';');
1321 return getOrCreateSrcLocStr(Buffer.str(), SrcLocStrSize);
1322}
1323
1324Constant *
1326 StringRef UnknownLoc = ";unknown;unknown;0;0;;";
1327 return getOrCreateSrcLocStr(UnknownLoc, SrcLocStrSize);
1328}
1329
1331 uint32_t &SrcLocStrSize,
1332 const Function *F) {
1333 DILocation *DIL = DL.get();
1334 if (!DIL)
1335 return getOrCreateDefaultSrcLocStr(SrcLocStrSize);
1336 StringRef FileName =
1337 !DIL->getFilename().empty() ? DIL->getFilename() : M.getName();
1338 StringRef Function = DIL->getScope()->getSubprogram()->getName();
1339 if (Function.empty() && F)
1340 Function = F->getName();
1341 return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
1342 DIL->getColumn(), SrcLocStrSize);
1343}
1344
1346 uint32_t &SrcLocStrSize) {
1347 return getOrCreateSrcLocStr(Loc.DL, SrcLocStrSize,
1348 Loc.IP.getNodeParent()->getParent());
1349}
1350
1353 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
1354 "omp_global_thread_num");
1355}
1356
1357OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createTargetInReduction(
1358 const LocationDescription &Loc, ArrayRef<Value *> OrigPtrs,
1359 ArrayRef<Type *> ResultPtrTys,
1360 function_ref<void(unsigned, Value *)> MapPrivateCB) {
1361 assert(OrigPtrs.size() == ResultPtrTys.size() &&
1362 "expected one result pointer type per in_reduction item");
1363 if (!updateToLocation(Loc))
1364 return Loc.IP;
1365 if (OrigPtrs.empty())
1366 return Builder.saveIP();
1367
1368 // Compute the executing thread's gtid once for the whole target body and
1369 // reuse it for every in_reduction lookup, so a target with several
1370 // in_reduction items does not emit a redundant __kmpc_global_thread_num per
1371 // item.
1372 uint32_t SrcLocStrSize;
1373 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1374 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1375 Value *Gtid = getOrCreateThreadID(Ident);
1376
1377 // The runtime entry point takes (and returns) a generic, default-address-
1378 // space `ptr`. A NULL descriptor makes the runtime walk the enclosing
1379 // taskgroups to find the matching task_reduction registration for the item.
1380 Type *PtrTy = PointerType::getUnqual(M.getContext());
1381 Value *NullDesc = ConstantPointerNull::get(PtrTy);
1382 FunctionCallee GetThData =
1383 getOrCreateRuntimeFunction(M, OMPRTL___kmpc_task_reduction_get_th_data);
1384
1385 for (unsigned Idx = 0; Idx < OrigPtrs.size(); ++Idx) {
1386 // Normalize a non-default-address-space original pointer to the generic
1387 // address space before the call.
1388 Value *OrigPtr = OrigPtrs[Idx];
1389 if (auto *OrigPtrTy = dyn_cast<PointerType>(OrigPtr->getType());
1390 OrigPtrTy && OrigPtrTy->getAddressSpace() != 0)
1391 OrigPtr = Builder.CreateAddrSpaceCast(OrigPtr, PtrTy);
1392
1394 GetThData, {Gtid, NullDesc, OrigPtr}, "omp.inred.priv");
1395
1396 // Cast the returned private pointer back to the requested address space
1397 // when it differs.
1398 if (auto *ResPtrTy = dyn_cast<PointerType>(ResultPtrTys[Idx]);
1399 ResPtrTy && ResPtrTy->getAddressSpace() != 0)
1400 Priv = Builder.CreateAddrSpaceCast(Priv, ResultPtrTys[Idx]);
1401
1402 MapPrivateCB(Idx, Priv);
1403 }
1404 return Builder.saveIP();
1405}
1406
1409 bool ForceSimpleCall, bool CheckCancelFlag) {
1410 if (!updateToLocation(Loc))
1411 return Loc.IP;
1412
1413 // Build call __kmpc_cancel_barrier(loc, thread_id) or
1414 // __kmpc_barrier(loc, thread_id);
1415
1416 IdentFlag BarrierLocFlags;
1417 switch (Kind) {
1418 case OMPD_for:
1419 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
1420 break;
1421 case OMPD_sections:
1422 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
1423 break;
1424 case OMPD_single:
1425 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
1426 break;
1427 case OMPD_barrier:
1428 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
1429 break;
1430 default:
1431 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
1432 break;
1433 }
1434
1435 uint32_t SrcLocStrSize;
1436 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1437 Value *Args[] = {
1438 getOrCreateIdent(SrcLocStr, SrcLocStrSize, BarrierLocFlags),
1439 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize))};
1440
1441 // If we are in a cancellable parallel region, barriers are cancellation
1442 // points.
1443 // TODO: Check why we would force simple calls or to ignore the cancel flag.
1444 bool UseCancelBarrier =
1445 !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
1446
1448 getOrCreateRuntimeFunctionPtr(UseCancelBarrier
1449 ? OMPRTL___kmpc_cancel_barrier
1450 : OMPRTL___kmpc_barrier),
1451 Args);
1452
1453 if (UseCancelBarrier && CheckCancelFlag)
1454 if (Error Err = emitCancelationCheckImpl(Result, OMPD_parallel))
1455 return Err;
1456
1457 return Builder.saveIP();
1458}
1459
1462 Value *IfCondition,
1463 omp::Directive CanceledDirective) {
1464 if (!updateToLocation(Loc))
1465 return Loc.IP;
1466
1467 // LLVM utilities like blocks with terminators.
1468 auto *UI = Builder.CreateUnreachable();
1469
1470 Instruction *ThenTI = UI, *ElseTI = nullptr;
1471 if (IfCondition) {
1472 SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
1473
1474 // Even if the if condition evaluates to false, this should count as a
1475 // cancellation point
1476 Builder.SetInsertPoint(ElseTI);
1477 auto ElseIP = Builder.saveIP();
1478
1480 LocationDescription{ElseIP, Loc.DL}, CanceledDirective);
1481 if (!IPOrErr)
1482 return IPOrErr;
1483 }
1484
1485 Builder.SetInsertPoint(ThenTI);
1486
1487 Value *CancelKind = nullptr;
1488 switch (CanceledDirective) {
1489#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1490 case DirectiveEnum: \
1491 CancelKind = Builder.getInt32(Value); \
1492 break;
1493#include "llvm/Frontend/OpenMP/OMPKinds.def"
1494 default:
1495 llvm_unreachable("Unknown cancel kind!");
1496 }
1497
1498 uint32_t SrcLocStrSize;
1499 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1500 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1501 Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
1503 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
1504
1505 // The actual cancel logic is shared with others, e.g., cancel_barriers.
1506 if (Error Err = emitCancelationCheckImpl(Result, CanceledDirective))
1507 return Err;
1508
1509 // Update the insertion point and remove the terminator we introduced.
1510 Builder.SetInsertPoint(UI->getParent());
1511 UI->eraseFromParent();
1512
1513 return Builder.saveIP();
1514}
1515
1518 omp::Directive CanceledDirective) {
1519 if (!updateToLocation(Loc))
1520 return Loc.IP;
1521
1522 // LLVM utilities like blocks with terminators.
1523 auto *UI = Builder.CreateUnreachable();
1524 Builder.SetInsertPoint(UI);
1525
1526 Value *CancelKind = nullptr;
1527 switch (CanceledDirective) {
1528#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1529 case DirectiveEnum: \
1530 CancelKind = Builder.getInt32(Value); \
1531 break;
1532#include "llvm/Frontend/OpenMP/OMPKinds.def"
1533 default:
1534 llvm_unreachable("Unknown cancel kind!");
1535 }
1536
1537 uint32_t SrcLocStrSize;
1538 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1539 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1540 Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
1542 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancellationpoint), Args);
1543
1544 // The actual cancel logic is shared with others, e.g., cancel_barriers.
1545 if (Error Err = emitCancelationCheckImpl(Result, CanceledDirective))
1546 return Err;
1547
1548 // Update the insertion point and remove the terminator we introduced.
1549 Builder.SetInsertPoint(UI->getParent());
1550 UI->eraseFromParent();
1551
1552 return Builder.saveIP();
1553}
1554
1556 const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return,
1557 Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads,
1558 Value *HostPtr, ArrayRef<Value *> KernelArgs) {
1559 if (!updateToLocation(Loc))
1560 return Loc.IP;
1561
1562 Builder.restoreIP(AllocaIP);
1563 auto *KernelArgsPtr =
1564 Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs, nullptr, "kernel_args");
1566
1567 for (unsigned I = 0, Size = KernelArgs.size(); I != Size; ++I) {
1568 llvm::Value *Arg =
1569 Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr, I);
1570 Builder.CreateAlignedStore(
1571 KernelArgs[I], Arg,
1572 M.getDataLayout().getPrefTypeAlign(KernelArgs[I]->getType()));
1573 }
1574
1575 SmallVector<Value *> OffloadingArgs{Ident, DeviceID, NumTeams,
1576 NumThreads, HostPtr, KernelArgsPtr};
1577
1579 getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel),
1580 OffloadingArgs);
1581
1582 return Builder.saveIP();
1583}
1584
1586 const LocationDescription &Loc, Value *OutlinedFnID,
1587 EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,
1588 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP) {
1589
1590 if (!updateToLocation(Loc))
1591 return Loc.IP;
1592
1593 // On top of the arrays that were filled up, the target offloading call
1594 // takes as arguments the device id as well as the host pointer. The host
1595 // pointer is used by the runtime library to identify the current target
1596 // region, so it only has to be unique and not necessarily point to
1597 // anything. It could be the pointer to the outlined function that
1598 // implements the target region, but we aren't using that so that the
1599 // compiler doesn't need to keep that, and could therefore inline the host
1600 // function if proven worthwhile during optimization.
1601
1602 // From this point on, we need to have an ID of the target region defined.
1603 assert(OutlinedFnID && "Invalid outlined function ID!");
1604 (void)OutlinedFnID;
1605
1606 // Return value of the runtime offloading call.
1607 Value *Return = nullptr;
1608
1609 // Arguments for the target kernel.
1610 SmallVector<Value *> ArgsVector;
1611 getKernelArgsVector(Args, Builder, ArgsVector);
1612
1613 // The target region is an outlined function launched by the runtime
1614 // via calls to __tgt_target_kernel().
1615 //
1616 // Note that on the host and CPU targets, the runtime implementation of
1617 // these calls simply call the outlined function without forking threads.
1618 // The outlined functions themselves have runtime calls to
1619 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
1620 // the compiler in emitTeamsCall() and emitParallelCall().
1621 //
1622 // In contrast, on the NVPTX target, the implementation of
1623 // __tgt_target_teams() launches a GPU kernel with the requested number
1624 // of teams and threads so no additional calls to the runtime are required.
1625 // Check the error code and execute the host version if required.
1626 Builder.restoreIP(emitTargetKernel(
1627 Builder, AllocaIP, Return, RTLoc, DeviceID, Args.NumTeams.front(),
1628 Args.NumThreads.front(), OutlinedFnID, ArgsVector));
1629
1630 BasicBlock *OffloadFailedBlock =
1631 BasicBlock::Create(Builder.getContext(), "omp_offload.failed");
1632 BasicBlock *OffloadContBlock =
1633 BasicBlock::Create(Builder.getContext(), "omp_offload.cont");
1634 Value *Failed = Builder.CreateIsNotNull(Return);
1635 Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
1636
1637 auto CurFn = Builder.GetInsertBlock()->getParent();
1638 emitBlock(OffloadFailedBlock, CurFn);
1639 InsertPointOrErrorTy AfterIP = EmitTargetCallFallbackCB(Builder.saveIP());
1640 if (!AfterIP)
1641 return AfterIP.takeError();
1642 Builder.restoreIP(*AfterIP);
1643 emitBranch(OffloadContBlock);
1644 emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);
1645 return Builder.saveIP();
1646}
1647
1649 Value *CancelFlag, omp::Directive CanceledDirective) {
1650 assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
1651 "Unexpected cancellation!");
1652
1653 // For a cancel barrier we create two new blocks.
1654 BasicBlock *BB = Builder.GetInsertBlock();
1655 BasicBlock *NonCancellationBlock;
1656 if (Builder.GetInsertPoint() == BB->end()) {
1657 // TODO: This branch will not be needed once we moved to the
1658 // OpenMPIRBuilder codegen completely.
1659 NonCancellationBlock = BasicBlock::Create(
1660 BB->getContext(), BB->getName() + ".cont", BB->getParent());
1661 } else {
1662 NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
1664 Builder.SetInsertPoint(BB);
1665 }
1666 BasicBlock *CancellationBlock = BasicBlock::Create(
1667 BB->getContext(), BB->getName() + ".cncl", BB->getParent());
1668
1669 // Jump to them based on the return value.
1670 Value *Cmp = Builder.CreateIsNull(CancelFlag);
1671 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
1672 /* TODO weight */ nullptr, nullptr);
1673
1674 // From the cancellation block we finalize all variables and go to the
1675 // post finalization block that is known to the FiniCB callback.
1676 auto &FI = FinalizationStack.back();
1677 Expected<BasicBlock *> FiniBBOrErr = FI.getFiniBB(Builder);
1678 if (!FiniBBOrErr)
1679 return FiniBBOrErr.takeError();
1680 Builder.SetInsertPoint(CancellationBlock);
1681 Builder.CreateBr(*FiniBBOrErr);
1682
1683 // The continuation block is where code generation continues.
1684 Builder.SetInsertPoint(NonCancellationBlock->begin());
1685 return Error::success();
1686}
1687
1688/// Create wrapper function used to gather the outlined function's argument
1689/// structure from a shared buffer and to forward them to it when running in
1690/// Generic mode.
1691///
1692/// The outlined function is expected to receive 2 integer arguments followed by
1693/// an optional pointer argument to an argument structure holding the rest.
1695 Function &OutlinedFn) {
1696 size_t NumArgs = OutlinedFn.arg_size();
1697 assert((NumArgs == 2 || NumArgs == 3) &&
1698 "expected a 2-3 argument parallel outlined function");
1699 bool UseArgStruct = NumArgs == 3;
1700
1701 IRBuilder<> &Builder = OMPIRBuilder->Builder;
1702 IRBuilder<>::InsertPointGuard IPG(Builder);
1703 auto *FnTy = FunctionType::get(Builder.getVoidTy(),
1704 {Builder.getInt16Ty(), Builder.getInt32Ty()},
1705 /*isVarArg=*/false);
1706 auto *WrapperFn =
1708 OutlinedFn.getName() + ".wrapper", OMPIRBuilder->M);
1709
1710 WrapperFn->addParamAttr(0, Attribute::NoUndef);
1711 WrapperFn->addParamAttr(0, Attribute::ZExt);
1712 WrapperFn->addParamAttr(1, Attribute::NoUndef);
1713
1714 BasicBlock *EntryBB =
1715 BasicBlock::Create(OMPIRBuilder->M.getContext(), "entry", WrapperFn);
1716 Builder.SetInsertPoint(EntryBB);
1717
1718 // Allocation.
1719 Value *AddrAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1720 /*ArraySize=*/nullptr, "addr");
1721 AddrAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1722 AddrAlloca, Builder.getPtrTy(/*AddrSpace=*/0),
1723 AddrAlloca->getName() + ".ascast");
1724
1725 Value *ZeroAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1726 /*ArraySize=*/nullptr, "zero");
1727 ZeroAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1728 ZeroAlloca, Builder.getPtrTy(/*AddrSpace=*/0),
1729 ZeroAlloca->getName() + ".ascast");
1730
1731 Value *ArgsAlloca = nullptr;
1732 if (UseArgStruct) {
1733 ArgsAlloca = Builder.CreateAlloca(Builder.getPtrTy(),
1734 /*ArraySize=*/nullptr, "global_args");
1735 ArgsAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1736 ArgsAlloca, Builder.getPtrTy(/*AddrSpace=*/0),
1737 ArgsAlloca->getName() + ".ascast");
1738 }
1739
1740 // Initialization.
1741 Builder.CreateStore(WrapperFn->getArg(1), AddrAlloca);
1742 Builder.CreateStore(Builder.getInt32(0), ZeroAlloca);
1743 if (UseArgStruct) {
1744 OMPIRBuilder->createRuntimeFunctionCall(
1745 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(
1746 llvm::omp::RuntimeFunction::OMPRTL___kmpc_get_shared_variables),
1747 {ArgsAlloca});
1748 }
1749
1750 SmallVector<Value *, 3> Args{AddrAlloca, ZeroAlloca};
1751
1752 // Load structArg from global_args.
1753 if (UseArgStruct) {
1754 Value *StructArg = Builder.CreateLoad(Builder.getPtrTy(), ArgsAlloca);
1755 StructArg = Builder.CreateInBoundsGEP(Builder.getPtrTy(), StructArg,
1756 {Builder.getInt64(0)});
1757 StructArg = Builder.CreateLoad(Builder.getPtrTy(), StructArg, "structArg");
1758 Args.push_back(StructArg);
1759 }
1760
1761 // Call the outlined function holding the parallel body.
1762 Builder.CreateCall(&OutlinedFn, Args);
1763 Builder.CreateRetVoid();
1764
1765 return WrapperFn;
1766}
1767
1768// Callback used to create OpenMP runtime calls to support
1769// omp parallel clause for the device.
1770// We need to use this callback to replace call to the OutlinedFn in OuterFn
1771// by the call to the OpenMP DeviceRTL runtime function (kmpc_parallel_60)
1773 OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn,
1774 BasicBlock *OuterAllocaBB, Value *Ident, Value *IfCondition,
1775 Value *NumThreads, Instruction *PrivTID, AllocaInst *PrivTIDAddr,
1776 Value *ThreadID, const SmallVector<Instruction *, 4> &ToBeDeleted) {
1777 assert(OutlinedFn.arg_size() >= 2 &&
1778 "Expected at least tid and bounded tid as arguments");
1779 unsigned NumCapturedVars = OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1780
1781 // Add some known attributes.
1782 IRBuilder<> &Builder = OMPIRBuilder->Builder;
1783 OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1784 OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1785 OutlinedFn.addParamAttr(0, Attribute::NoUndef);
1786 OutlinedFn.addParamAttr(1, Attribute::NoUndef);
1787 OutlinedFn.addFnAttr(Attribute::NoUnwind);
1788
1789 CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1790 assert(CI && "Expected call instruction to outlined function");
1791 CI->getParent()->setName("omp_parallel");
1792
1793 Builder.SetInsertPoint(CI);
1794 Type *PtrTy = OMPIRBuilder->VoidPtr;
1795
1796 // Add alloca for kernel args
1797 OpenMPIRBuilder ::InsertPointTy CurrentIP = Builder.saveIP();
1798 Builder.SetInsertPoint(OuterAllocaBB->getFirstInsertionPt());
1799 AllocaInst *ArgsAlloca =
1800 Builder.CreateAlloca(ArrayType::get(PtrTy, NumCapturedVars));
1801 Value *Args = ArgsAlloca;
1802 // Add address space cast if array for storing arguments is not allocated
1803 // in address space 0
1804 if (ArgsAlloca->getAddressSpace())
1805 Args = Builder.CreatePointerCast(ArgsAlloca, PtrTy);
1806 Builder.restoreIP(CurrentIP);
1807
1808 // Store captured vars which are used by kmpc_parallel_60
1809 for (unsigned Idx = 0; Idx < NumCapturedVars; Idx++) {
1810 Value *V = *(CI->arg_begin() + 2 + Idx);
1811 Value *StoreAddress = Builder.CreateConstInBoundsGEP2_64(
1812 ArrayType::get(PtrTy, NumCapturedVars), Args, 0, Idx);
1813 Builder.CreateStore(V, StoreAddress);
1814 }
1815
1816 Value *Cond =
1817 IfCondition ? Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32)
1818 : Builder.getInt32(1);
1819 Value *NumThreadsArg =
1820 NumThreads ? Builder.CreateZExtOrTrunc(NumThreads, OMPIRBuilder->Int32)
1821 : Builder.getInt32(-1);
1822
1823 // If this is not a Generic kernel, we can skip generating the wrapper.
1824 Value *WrapperFn;
1825 if (isGenericKernel(*OuterFn))
1826 WrapperFn = createTargetParallelWrapper(OMPIRBuilder, OutlinedFn);
1827 else
1828 WrapperFn = Constant::getNullValue(PtrTy);
1829
1830 // Build kmpc_parallel_60 call
1831 Value *Parallel60CallArgs[] = {
1832 /* identifier*/ Ident,
1833 /* global thread num*/ ThreadID,
1834 /* if expression */ Cond,
1835 /* number of threads */ NumThreadsArg,
1836 /* Proc bind */ Builder.getInt32(-1),
1837 /* outlined function */ &OutlinedFn,
1838 /* wrapper function */ WrapperFn,
1839 /* arguments of the outlined funciton*/ Args,
1840 /* number of arguments */ Builder.getInt64(NumCapturedVars),
1841 /* strict for number of threads */ Builder.getInt32(0)};
1842
1843 FunctionCallee RTLFn =
1844 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_parallel_60);
1845
1846 OMPIRBuilder->createRuntimeFunctionCall(RTLFn, Parallel60CallArgs);
1847
1848 LLVM_DEBUG(dbgs() << "With kmpc_parallel_60 placed: "
1849 << *Builder.GetInsertBlock()->getParent() << "\n");
1850
1851 // Initialize the local TID stack location with the argument value.
1852 Builder.SetInsertPoint(PrivTID);
1853 Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1854 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1855 PrivTIDAddr);
1856
1857 // Remove redundant call to the outlined function.
1858 CI->eraseFromParent();
1859
1860 for (Instruction *I : ToBeDeleted) {
1861 I->eraseFromParent();
1862 }
1863}
1864
1865// Callback used to create OpenMP runtime calls to support
1866// omp parallel clause for the host.
1867// We need to use this callback to replace call to the OutlinedFn in OuterFn
1868// by the call to the OpenMP host runtime function ( __kmpc_fork_call[_if])
1869static void
1871 Function *OuterFn, Value *Ident, Value *IfCondition,
1872 Instruction *PrivTID, AllocaInst *PrivTIDAddr,
1873 const SmallVector<Instruction *, 4> &ToBeDeleted) {
1874 IRBuilder<> &Builder = OMPIRBuilder->Builder;
1875 FunctionCallee RTLFn;
1876 if (IfCondition) {
1877 RTLFn =
1878 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call_if);
1879 } else {
1880 RTLFn =
1881 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
1882 }
1883 if (auto *F = dyn_cast<Function>(RTLFn.getCallee())) {
1884 if (!F->hasMetadata(LLVMContext::MD_callback)) {
1885 LLVMContext &Ctx = F->getContext();
1886 MDBuilder MDB(Ctx);
1887 // Annotate the callback behavior of the __kmpc_fork_call:
1888 // - The callback callee is argument number 2 (microtask).
1889 // - The first two arguments of the callback callee are unknown (-1).
1890 // - All variadic arguments to the __kmpc_fork_call are passed to the
1891 // callback callee.
1892 F->addMetadata(LLVMContext::MD_callback,
1894 2, {-1, -1},
1895 /* VarArgsArePassed */ true)}));
1896 }
1897 }
1898 // Add some known attributes.
1899 OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1900 OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1901 OutlinedFn.addFnAttr(Attribute::NoUnwind);
1902
1903 assert(OutlinedFn.arg_size() >= 2 &&
1904 "Expected at least tid and bounded tid as arguments");
1905 unsigned NumCapturedVars = OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1906
1907 CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1908
1909 // CodeExtractor creates an alloca aggregate struct containing pointers to all
1910 // the captured values. The address of this struct is then passed as a
1911 // parameter to the outlined function. This parameter of the outlined function
1912 // can be marked noalias because CodeExractor + this host OpenMP lowering
1913 // maintains the following invariants:
1914 // - The caller initializes the fields before starting any callbacks.
1915 // - Neither the caller, OpenMP runtime, nor callbacks modify the structure
1916 // while callbacks are executing.
1917 // - The callbacks only load captured values from the structure; they do not
1918 // use it to write results back to the caller. This is generated code; the
1919 // user has no way to modify the structure directly.
1920 //
1921 // Multiple callbacks may read the same structure. This is allowed by noalias,
1922 // which permits aliasing accesses to memory that is not modified during the
1923 // call.
1924 //
1925 // The synchronous fork keeps the structure alive until all callbacks return,
1926 // which justifies nofreeobj. Neither attribute extends to the objects pointed
1927 // to by the captured fields.
1928 if (NumCapturedVars) {
1929 assert(NumCapturedVars == 1 && "Expected an aggregate capture argument");
1932 ->getAllocatedType()
1933 ->isStructTy() &&
1934 "Expected a stack-allocated capture structure");
1935
1936 OutlinedFn.addParamAttr(2, Attribute::NoAlias);
1937 OutlinedFn.addParamAttr(2, Attribute::NoFreeObj);
1938 }
1939
1940 CI->getParent()->setName("omp_parallel");
1941 Builder.SetInsertPoint(CI);
1942
1943 // Build call __kmpc_fork_call[_if](Ident, n, microtask, var1, .., varn);
1944 Value *ForkCallArgs[] = {Ident, Builder.getInt32(NumCapturedVars),
1945 &OutlinedFn};
1946
1947 SmallVector<Value *, 16> RealArgs;
1948 RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1949 if (IfCondition) {
1950 Value *Cond = Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32);
1951 RealArgs.push_back(Cond);
1952 }
1953 RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
1954
1955 // __kmpc_fork_call_if always expects a void ptr as the last argument
1956 // If there are no arguments, pass a null pointer.
1957 auto PtrTy = OMPIRBuilder->VoidPtr;
1958 if (IfCondition && NumCapturedVars == 0) {
1959 Value *NullPtrValue = Constant::getNullValue(PtrTy);
1960 RealArgs.push_back(NullPtrValue);
1961 }
1962
1963 OMPIRBuilder->createRuntimeFunctionCall(RTLFn, RealArgs);
1964
1965 LLVM_DEBUG(dbgs() << "With fork_call placed: "
1966 << *Builder.GetInsertBlock()->getParent() << "\n");
1967
1968 // Initialize the local TID stack location with the argument value.
1969 Builder.SetInsertPoint(PrivTID);
1970 Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1971 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1972 PrivTIDAddr);
1973
1974 // Remove redundant call to the outlined function.
1975 CI->eraseFromParent();
1976
1977 for (Instruction *I : ToBeDeleted) {
1978 I->eraseFromParent();
1979 }
1980}
1981
1983 const LocationDescription &Loc, InsertPointTy OuterAllocIP,
1984 ArrayRef<BasicBlock *> OuterDeallocBlocks, BodyGenCallbackTy BodyGenCB,
1985 PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition,
1986 Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable) {
1987 assert(!isConflictIP(Loc.IP, OuterAllocIP) && "IPs must not be ambiguous");
1988
1989 if (!updateToLocation(Loc))
1990 return Loc.IP;
1991
1992 uint32_t SrcLocStrSize;
1993 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1994 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1995 const bool NeedThreadID = NumThreads || Config.isTargetDevice() ||
1996 (ProcBind != OMP_PROC_BIND_default);
1997 Value *ThreadID = NeedThreadID ? getOrCreateThreadID(Ident) : nullptr;
1998 // If we generate code for the target device, we need to allocate
1999 // struct for aggregate params in the device default alloca address space.
2000 // OpenMP runtime requires that the params of the extracted functions are
2001 // passed as zero address space pointers. This flag ensures that extracted
2002 // function arguments are declared in zero address space
2003 bool ArgsInZeroAddressSpace = Config.isTargetDevice();
2004
2005 // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
2006 // only if we compile for host side.
2007 if (NumThreads && !Config.isTargetDevice()) {
2008 Value *Args[] = {
2009 Ident, ThreadID,
2010 Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
2012 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
2013 }
2014
2015 if (ProcBind != OMP_PROC_BIND_default) {
2016 // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
2017 Value *Args[] = {
2018 Ident, ThreadID,
2019 ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
2021 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
2022 }
2023
2024 BasicBlock *InsertBB = Builder.GetInsertBlock();
2025 Function *OuterFn = InsertBB->getParent();
2026
2027 // Save the outer alloca block because the insertion iterator may get
2028 // invalidated and we still need this later.
2029 BasicBlock *OuterAllocaBlock = OuterAllocIP.getNodeParent();
2030
2031 // Vector to remember instructions we used only during the modeling but which
2032 // we want to delete at the end.
2034
2035 // Change the location to the outer alloca insertion point to create and
2036 // initialize the allocas we pass into the parallel region.
2037 InsertPointTy NewOuter(OuterAllocaBlock->begin());
2038 Builder.restoreIP(NewOuter);
2039 AllocaInst *TIDAddrAlloca = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
2040 AllocaInst *ZeroAddrAlloca =
2041 Builder.CreateAlloca(Int32, nullptr, "zero.addr");
2042 Instruction *TIDAddr = TIDAddrAlloca;
2043 Instruction *ZeroAddr = ZeroAddrAlloca;
2044 if (ArgsInZeroAddressSpace && M.getDataLayout().getAllocaAddrSpace() != 0) {
2045 // Add additional casts to enforce pointers in zero address space
2046 TIDAddr = new AddrSpaceCastInst(
2047 TIDAddrAlloca, PointerType ::get(M.getContext(), 0), "tid.addr.ascast");
2048 TIDAddr->insertAfter(TIDAddrAlloca->getIterator());
2049 ToBeDeleted.push_back(TIDAddr);
2050 ZeroAddr = new AddrSpaceCastInst(ZeroAddrAlloca,
2051 PointerType ::get(M.getContext(), 0),
2052 "zero.addr.ascast");
2053 ZeroAddr->insertAfter(ZeroAddrAlloca->getIterator());
2054 ToBeDeleted.push_back(ZeroAddr);
2055 }
2056
2057 // We only need TIDAddr and ZeroAddr for modeling purposes to get the
2058 // associated arguments in the outlined function, so we delete them later.
2059 ToBeDeleted.push_back(TIDAddrAlloca);
2060 ToBeDeleted.push_back(ZeroAddrAlloca);
2061
2062 // Create an artificial insertion point that will also ensure the blocks we
2063 // are about to split are not degenerated.
2064 auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
2065 UI->setDebugLoc(Loc.DL);
2066
2067 BasicBlock *EntryBB = UI->getParent();
2068 BasicBlock *PRegEntryBB = EntryBB->splitBasicBlock(UI, "omp.par.entry");
2069 BasicBlock *PRegBodyBB = PRegEntryBB->splitBasicBlock(UI, "omp.par.region");
2070 BasicBlock *PRegPreFiniBB =
2071 PRegBodyBB->splitBasicBlock(UI, "omp.par.pre_finalize");
2072 BasicBlock *PRegExitBB = PRegPreFiniBB->splitBasicBlock(UI, "omp.par.exit");
2073
2074 auto FiniCBWrapper = [&](InsertPointTy IP) {
2075 // Hide "open-ended" blocks from the given FiniCB by setting the right jump
2076 // target to the region exit block.
2077 if (IP == IP.getNodeParent()->end()) {
2079 Builder.restoreIP(IP);
2080 Instruction *I = Builder.CreateBr(PRegExitBB);
2081 IP = I->getIterator();
2082 }
2083 assert(IP.getNodeParent()->getTerminator()->getNumSuccessors() == 1 &&
2084 IP.getNodeParent()->getTerminator()->getSuccessor(0) == PRegExitBB &&
2085 "Unexpected insertion point for finalization call!");
2086 return FiniCB(IP);
2087 };
2088
2089 FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
2090
2091 // Generate the privatization allocas in the block that will become the entry
2092 // of the outlined function.
2093 Builder.SetInsertPoint(PRegEntryBB->getTerminator());
2094 InsertPointTy InnerAllocaIP = Builder.saveIP();
2095
2096 AllocaInst *PrivTIDAddr =
2097 Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
2098 Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
2099
2100 // Add some fake uses for OpenMP provided arguments.
2101 ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
2102 Instruction *ZeroAddrUse =
2103 Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");
2104 ToBeDeleted.push_back(ZeroAddrUse);
2105
2106 // EntryBB
2107 // |
2108 // V
2109 // PRegionEntryBB <- Privatization allocas are placed here.
2110 // |
2111 // V
2112 // PRegionBodyBB <- BodeGen is invoked here.
2113 // |
2114 // V
2115 // PRegPreFiniBB <- The block we will start finalization from.
2116 // |
2117 // V
2118 // PRegionExitBB <- A common exit to simplify block collection.
2119 //
2120
2121 LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
2122
2123 // Let the caller create the body.
2124 assert(BodyGenCB && "Expected body generation callback!");
2125 InsertPointTy CodeGenIP(PRegBodyBB->begin());
2126 if (Error Err = BodyGenCB(InnerAllocaIP, CodeGenIP, PRegExitBB))
2127 return Err;
2128
2129 LLVM_DEBUG(dbgs() << "After body codegen: " << *OuterFn << "\n");
2130
2131 // If OuterFn is a Generic kernel, we need to use device shared memory to
2132 // allocate argument structures. Otherwise, we use stack allocations as usual.
2133 bool UsesDeviceSharedMemory =
2134 Config.isTargetDevice() && isGenericKernel(*OuterFn);
2135 std::unique_ptr<OutlineInfo> OI =
2136 UsesDeviceSharedMemory
2137 ? std::make_unique<DeviceSharedMemOutlineInfo>(*this)
2138 : std::make_unique<OutlineInfo>();
2139
2140 if (Config.isTargetDevice()) {
2141 // Generate OpenMP target specific runtime call
2142 OI->PostOutlineCB = [=, ToBeDeletedVec =
2143 std::move(ToBeDeleted)](Function &OutlinedFn) {
2144 targetParallelCallback(this, OutlinedFn, OuterFn, OuterAllocaBlock, Ident,
2145 IfCondition, NumThreads, PrivTID, PrivTIDAddr,
2146 ThreadID, ToBeDeletedVec);
2147 };
2148 } else {
2149 // Generate OpenMP host runtime call
2150 OI->PostOutlineCB = [=, ToBeDeletedVec =
2151 std::move(ToBeDeleted)](Function &OutlinedFn) {
2152 hostParallelCallback(this, OutlinedFn, OuterFn, Ident, IfCondition,
2153 PrivTID, PrivTIDAddr, ToBeDeletedVec);
2154 };
2155 }
2156
2157 OI->FixUpNonEntryAllocas = true;
2158 OI->OuterAllocBB = OuterAllocaBlock;
2159 OI->EntryBB = PRegEntryBB;
2160 OI->ExitBB = PRegExitBB;
2161 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.size());
2162 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.end());
2163
2164 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
2166 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
2167
2168 CodeExtractorAnalysisCache CEAC(*OuterFn);
2169 CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
2170 /* AggregateArgs */ false,
2171 /* BlockFrequencyInfo */ nullptr,
2172 /* BranchProbabilityInfo */ nullptr,
2173 /* AssumptionCache */ nullptr,
2174 /* AllowVarArgs */ true,
2175 /* AllowAlloca */ true,
2176 /* AllocationBlock */ OuterAllocaBlock,
2177 /* DeallocationBlocks */ {},
2178 /* Suffix */ ".omp_par", ArgsInZeroAddressSpace);
2179
2180 // Find inputs to, outputs from the code region.
2181 BasicBlock *CommonExit = nullptr;
2182 SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
2183 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
2184
2185 Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands,
2186 /*CollectGlobalInputs=*/true);
2187
2188 Inputs.remove_if([&](Value *I) {
2190 return GV->getValueType() == OpenMPIRBuilder::Ident;
2191
2192 return false;
2193 });
2194
2195 LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
2196
2197 FunctionCallee TIDRTLFn =
2198 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
2199
2200 auto PrivHelper = [&](Value &V) -> Error {
2201 if (&V == TIDAddr || &V == ZeroAddr) {
2202 OI->ExcludeArgsFromAggregate.push_back(&V);
2203 return Error::success();
2204 }
2205
2207 for (Use &U : V.uses())
2208 if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
2209 if (ParallelRegionBlockSet.count(UserI->getParent()))
2210 Uses.insert(&U);
2211
2212 // __kmpc_fork_call expects extra arguments as pointers. If the input
2213 // already has a pointer type, everything is fine. Otherwise, store the
2214 // value onto stack and load it back inside the to-be-outlined region. This
2215 // will ensure only the pointer will be passed to the function.
2216 // FIXME: if there are more than 15 trailing arguments, they must be
2217 // additionally packed in a struct.
2218 Value *Inner = &V;
2219 if (!V.getType()->isPointerTy()) {
2221 LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
2222
2223 Builder.restoreIP(OuterAllocIP);
2224 Value *Ptr;
2225 if (UsesDeviceSharedMemory) {
2226 // Use device shared memory instead, if needed.
2227 Ptr = createOMPAllocShared(Builder, V.getType(),
2228 V.getName() + ".reloaded");
2229 for (BasicBlock *DeallocBlock : OuterDeallocBlocks) {
2230 assert(DeallocBlock->getParent() ==
2231 OuterAllocIP.getNodeParent()->getParent() &&
2232 "Dealloc block must be in the allocation's function to reuse "
2233 "its debug location");
2234 createOMPFreeShared({DeallocBlock->getFirstInsertionPt(),
2235 Builder.getCurrentDebugLocation()},
2236 Ptr, V.getType());
2237 }
2238 } else {
2239 Ptr = Builder.CreateAlloca(V.getType(), nullptr,
2240 V.getName() + ".reloaded");
2241 }
2242
2243 // Store to stack at end of the block that currently branches to the entry
2244 // block of the to-be-outlined region.
2245 Builder.SetInsertPoint(InsertBB->getTerminator()->getIterator());
2246 Builder.CreateStore(&V, Ptr);
2247
2248 // Load back next to allocations in the to-be-outlined region.
2249 Builder.restoreIP(InnerAllocaIP);
2250 Inner = Builder.CreateLoad(V.getType(), Ptr);
2251 }
2252
2253 Value *ReplacementValue = nullptr;
2254 CallInst *CI = dyn_cast<CallInst>(&V);
2255 if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
2256 ReplacementValue = PrivTID;
2257 } else {
2258 InsertPointOrErrorTy AfterIP =
2259 PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue);
2260 if (!AfterIP)
2261 return AfterIP.takeError();
2262 Builder.restoreIP(*AfterIP);
2263 InnerAllocaIP =
2264 InnerAllocaIP.getNodeParent()->getTerminator()->getIterator();
2265
2266 assert(ReplacementValue &&
2267 "Expected copy/create callback to set replacement value!");
2268 if (ReplacementValue == &V)
2269 return Error::success();
2270 }
2271
2272 for (Use *UPtr : Uses)
2273 UPtr->set(ReplacementValue);
2274
2275 return Error::success();
2276 };
2277
2278 // Reset the inner alloca insertion as it will be used for loading the values
2279 // wrapped into pointers before passing them into the to-be-outlined region.
2280 // Configure it to insert immediately after the fake use of zero address so
2281 // that they are available in the generated body and so that the
2282 // OpenMP-related values (thread ID and zero address pointers) remain leading
2283 // in the argument list.
2284 InnerAllocaIP = ZeroAddrUse->getNextNode()->getIterator();
2285
2286 // Reset the outer alloca insertion point to the entry of the relevant block
2287 // in case it was invalidated.
2288 OuterAllocIP = OuterAllocaBlock->getFirstInsertionPt();
2289
2290 for (Value *Input : Inputs) {
2291 LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
2292 if (Error Err = PrivHelper(*Input))
2293 return Err;
2294 }
2295 LLVM_DEBUG({
2296 for (Value *Output : Outputs)
2297 LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
2298 });
2299 assert(Outputs.empty() &&
2300 "OpenMP outlining should not produce live-out values!");
2301
2302 LLVM_DEBUG(dbgs() << "After privatization: " << *OuterFn << "\n");
2303 LLVM_DEBUG({
2304 for (auto *BB : Blocks)
2305 dbgs() << " PBR: " << BB->getName() << "\n";
2306 });
2307
2308 // Adjust the finalization stack, verify the adjustment, and call the
2309 // finalize function a last time to finalize values between the pre-fini
2310 // block and the exit block if we left the parallel "the normal way".
2311 auto FiniInfo = FinalizationStack.pop_back_val();
2312 (void)FiniInfo;
2313 assert(FiniInfo.DK == OMPD_parallel &&
2314 "Unexpected finalization stack state!");
2315
2316 Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
2317
2318 InsertPointTy PreFiniIP(PRegPreFiniTI->getIterator());
2319 Expected<BasicBlock *> FiniBBOrErr = FiniInfo.getFiniBB(Builder);
2320 if (!FiniBBOrErr)
2321 return FiniBBOrErr.takeError();
2322 {
2324 Builder.restoreIP(PreFiniIP);
2325 Builder.CreateBr(*FiniBBOrErr);
2326 // There's currently a branch to omp.par.exit. Delete it. We will get there
2327 // via the fini block
2328 Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
2329 }
2330
2331 // Register the outlined info.
2332 addOutlineInfo(std::move(OI));
2333
2334 InsertPointTy AfterIP(UI->getParent()->end());
2335 UI->eraseFromParent();
2336
2337 return AfterIP;
2338}
2339
2341 AtomicOrdering AO, AtomicScope Scope) {
2342 // A flush with a list is a strong flush, which is treated as seq_cst.
2343 if (AO == AtomicOrdering::NotAtomic)
2345
2346 // A flush without a list corresponds to atomic_thread_fence, so on a GPU
2347 // emit the fence directly rather than calling into the device runtime.
2348 if (Config.IsGPU.value_or(M.getTargetTriple().isGPU())) {
2349 StringRef ScopeName =
2350 getAtomicScopeIRString(M.getTargetTriple(), Scope).value_or("");
2351 Builder.CreateFence(AO, M.getContext().getOrInsertSyncScopeID(ScopeName));
2352 return;
2353 }
2354
2355 uint32_t SrcLocStrSize;
2356 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2357 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2359 Scope == AtomicScope::Device) {
2360 // Build call void __kmpc_flush(ident_t *loc)
2362 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), {Ident});
2363 return;
2364 }
2365 // Build call void __kmpc_flush_explicit(ident_t *loc, kmp_int32 order,
2366 // kmp_int32 scope), where order is an __ATOMIC_* value and scope is a
2367 // __MEMORY_SCOPE_* value.
2368 Value *Args[] = {Ident, Builder.getInt32(static_cast<unsigned>(toCABI(AO))),
2369 Builder.getInt32(static_cast<unsigned>(Scope))};
2371 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush_explicit), Args);
2372}
2373
2375 AtomicOrdering AO, AtomicScope Scope) {
2376 if (!updateToLocation(Loc))
2377 return;
2378 emitFlush(Loc, AO, Scope);
2379}
2380
2382 Value *Message) {
2383 if (!updateToLocation(Loc))
2384 return;
2385
2386 // Build call void __kmpc_error(ident_t *loc, int severity,
2387 // const char *message)
2388 uint32_t SrcLocStrSize;
2389 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2390 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2391 // Severity: 1 = warning, 2 = fatal.
2392 Value *Severity = ConstantInt::get(Int32, IsFatal ? 2 : 1);
2393 Value *MessageArg = Message ? Message : ConstantPointerNull::get(Int8Ptr);
2394 Value *Args[] = {Ident, Severity, MessageArg};
2395
2397 Args);
2398}
2399
2401 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2402 uint32_t SrcLocStrSize;
2403 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2404 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2405 Constant *I32Null = ConstantInt::getNullValue(Int32);
2406 Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
2407
2409 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield), Args);
2410}
2411
2417
2419 const DependData &Dep) {
2420 // Store the pointer to the variable
2421 Value *Addr = Builder.CreateStructGEP(
2422 DependInfo, Entry,
2423 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
2424 Value *DepValPtr = Builder.CreatePtrToInt(Dep.DepVal, SizeTy);
2425 Builder.CreateStore(DepValPtr, Addr);
2426 // Store the size of the variable
2427 Value *Size = Builder.CreateStructGEP(
2428 DependInfo, Entry, static_cast<unsigned int>(RTLDependInfoFields::Len));
2429 Builder.CreateStore(
2430 ConstantInt::get(SizeTy,
2431 M.getDataLayout().getTypeStoreSize(Dep.DepValueType)),
2432 Size);
2433 // Store the dependency kind
2434 Value *Flags = Builder.CreateStructGEP(
2435 DependInfo, Entry, static_cast<unsigned int>(RTLDependInfoFields::Flags));
2436 Builder.CreateStore(ConstantInt::get(Builder.getInt8Ty(),
2437 static_cast<unsigned int>(Dep.DepKind)),
2438 Flags);
2439}
2440
2441// Processes the dependencies in Dependencies and does the following
2442// - Allocates space on the stack of an array of DependInfo objects
2443// - Populates each DependInfo object with relevant information of
2444// the corresponding dependence.
2445// - All code is inserted in the entry block of the current function.
2447 OpenMPIRBuilder &OMPBuilder,
2449 // Early return if we have no dependencies to process
2450 if (Dependencies.empty())
2451 return nullptr;
2452
2453 // Given a vector of DependData objects, in this function we create an
2454 // array on the stack that holds kmp_depend_info objects corresponding
2455 // to each dependency. This is then passed to the OpenMP runtime.
2456 // For example, if there are 'n' dependencies then the following psedo
2457 // code is generated. Assume the first dependence is on a variable 'a'
2458 //
2459 // \code{c}
2460 // DepArray = alloc(n x sizeof(kmp_depend_info);
2461 // idx = 0;
2462 // DepArray[idx].base_addr = ptrtoint(&a);
2463 // DepArray[idx].len = 8;
2464 // DepArray[idx].flags = Dep.DepKind; /*(See OMPContants.h for DepKind)*/
2465 // ++idx;
2466 // DepArray[idx].base_addr = ...;
2467 // \endcode
2468
2469 IRBuilderBase &Builder = OMPBuilder.Builder;
2470 Type *DependInfo = OMPBuilder.DependInfo;
2471
2472 Value *DepArray = nullptr;
2473 Type *DepArrayTy = ArrayType::get(DependInfo, Dependencies.size());
2474 {
2475 // Use a InsertPointGuard to restore the location back along with the
2476 // insertion point.
2477 IRBuilderBase::InsertPointGuard IPGuard(Builder);
2478 Builder.SetInsertPoint(
2479 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator());
2480 DepArray = Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");
2481 }
2482
2483 for (const auto &[DepIdx, Dep] : enumerate(Dependencies)) {
2484 Value *Base =
2485 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2486 OMPBuilder.emitTaskDependency(Builder, Base, Dep);
2487 }
2488 return DepArray;
2489}
2490
2492 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2493 // global_tid);
2494 uint32_t SrcLocStrSize;
2495 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2496 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2497 Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
2498
2499 // Ignore return result until untied tasks are supported.
2501 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait), Args);
2502}
2503
2505 DependenciesInfo Dependencies,
2506 bool IsNowait) {
2507 if (!updateToLocation(Loc))
2508 return;
2509
2510 Value *DepArray = nullptr;
2511 Type *DepArrayTy = nullptr;
2512 Value *NumDeps = nullptr;
2513 if (Dependencies.DepArray) {
2514 DepArray = Dependencies.DepArray;
2515 NumDeps = Dependencies.NumDeps;
2516 } else if (!Dependencies.Deps.empty()) {
2517 DepArrayTy = ArrayType::get(DependInfo, Dependencies.Deps.size());
2518 NumDeps = Builder.getInt32(Dependencies.Deps.size());
2519 {
2521 BasicBlock &entryBB =
2522 Builder.GetInsertBlock()->getParent()->getEntryBlock();
2523 Builder.SetInsertPoint(entryBB.getFirstInsertionPt());
2524 DepArray = Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");
2525 }
2526
2527 for (const auto &[DepIdx, Dep] : enumerate(Dependencies.Deps)) {
2528 Value *Base =
2529 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2530 this->emitTaskDependency(Builder, Base, Dep);
2531 }
2532 }
2533
2534 if (DepArray) {
2535 uint32_t SrcLocStrSize;
2536 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2537 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2538 Value *Args[] = {
2539 Ident,
2540 getOrCreateThreadID(Ident),
2541 NumDeps,
2542 DepArray,
2543 ConstantInt::get(Builder.getInt32Ty(), 0),
2545 ConstantInt::get(Builder.getInt32Ty(), IsNowait)};
2548 omp::RuntimeFunction::OMPRTL___kmpc_omp_taskwait_deps_51),
2549 Args);
2550 } else {
2552 }
2553}
2554
2555/// Create the task duplication function passed to kmpc_taskloop.
2556Expected<Value *> OpenMPIRBuilder::createTaskDuplicationFunction(
2557 Type *PrivatesTy, int32_t PrivatesIndex, TaskDupCallbackTy DupCB) {
2558 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2559 if (!DupCB)
2561 PointerType::get(Builder.getContext(), ProgramAddressSpace));
2562
2563 // From OpenMP Runtime p_task_dup_t:
2564 // Routine optionally generated by the compiler for setting the lastprivate
2565 // flag and calling needed constructors for private/firstprivate objects (used
2566 // to form taskloop tasks from pattern task) Parameters: dest task, src task,
2567 // lastprivate flag.
2568 // typedef void (*p_task_dup_t)(kmp_task_t *, kmp_task_t *, kmp_int32);
2569
2570 auto *VoidPtrTy = PointerType::get(Builder.getContext(), ProgramAddressSpace);
2571
2572 FunctionType *DupFuncTy = FunctionType::get(
2573 Builder.getVoidTy(), {VoidPtrTy, VoidPtrTy, Builder.getInt32Ty()},
2574 /*isVarArg=*/false);
2575
2576 Function *DupFunction = Function::Create(DupFuncTy, Function::InternalLinkage,
2577 "omp_taskloop_dup", M);
2578 Value *DestTaskArg = DupFunction->getArg(0);
2579 Value *SrcTaskArg = DupFunction->getArg(1);
2580 Value *LastprivateFlagArg = DupFunction->getArg(2);
2581 DestTaskArg->setName("dest_task");
2582 SrcTaskArg->setName("src_task");
2583 LastprivateFlagArg->setName("lastprivate_flag");
2584
2585 IRBuilderBase::InsertPointGuard Guard(Builder);
2586 Builder.SetInsertPoint(
2587 BasicBlock::Create(Builder.getContext(), "entry", DupFunction));
2588
2589 auto GetTaskContextPtrFromArg = [&](Value *Arg) -> Value * {
2590 Type *TaskWithPrivatesTy =
2591 StructType::get(Builder.getContext(), {Task, PrivatesTy});
2592 Value *TaskPrivates = Builder.CreateGEP(
2593 TaskWithPrivatesTy, Arg, {Builder.getInt32(0), Builder.getInt32(1)});
2594 Value *ContextPtr = Builder.CreateGEP(
2595 PrivatesTy, TaskPrivates,
2596 {Builder.getInt32(0), Builder.getInt32(PrivatesIndex)});
2597 return ContextPtr;
2598 };
2599
2600 Value *DestTaskContextPtr = GetTaskContextPtrFromArg(DestTaskArg);
2601 Value *SrcTaskContextPtr = GetTaskContextPtrFromArg(SrcTaskArg);
2602
2603 DestTaskContextPtr->setName("destPtr");
2604 SrcTaskContextPtr->setName("srcPtr");
2605
2606 InsertPointTy AllocaIP(DupFunction->getEntryBlock().begin());
2607 InsertPointTy CodeGenIP = Builder.saveIP();
2608 Expected<IRBuilderBase::InsertPoint> AfterIPOrError =
2609 DupCB(AllocaIP, CodeGenIP, DestTaskContextPtr, SrcTaskContextPtr);
2610 if (!AfterIPOrError)
2611 return AfterIPOrError.takeError();
2612 Builder.restoreIP(*AfterIPOrError);
2613
2614 Builder.CreateRetVoid();
2615
2616 return DupFunction;
2617}
2618
2619OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::createTaskloop(
2620 const LocationDescription &Loc, InsertPointTy AllocaIP,
2621 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
2622 llvm::function_ref<llvm::Expected<llvm::CanonicalLoopInfo *>()> LoopInfo,
2623 Value *LBVal, Value *UBVal, Value *StepVal, bool Untied, Value *IfCond,
2624 Value *GrainSize, bool NoGroup, int Sched, Value *Final, bool Mergeable,
2625 Value *Priority, uint64_t NumOfCollapseLoops, TaskDupCallbackTy DupCB,
2626 Value *TaskContextStructPtrVal, bool FreeAgent) {
2627
2628 if (!updateToLocation(Loc))
2629 return InsertPointTy();
2630
2631 uint32_t SrcLocStrSize;
2632 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2633 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2634
2635 BasicBlock *TaskloopExitBB =
2636 splitBB(Builder, /*CreateBranch=*/true, "taskloop.exit");
2637 BasicBlock *TaskloopBodyBB =
2638 splitBB(Builder, /*CreateBranch=*/true, "taskloop.body");
2639 BasicBlock *TaskloopAllocaBB =
2640 splitBB(Builder, /*CreateBranch=*/true, "taskloop.alloca");
2641
2642 InsertPointTy TaskloopAllocaIP = TaskloopAllocaBB->begin();
2643 InsertPointTy TaskloopBodyIP = TaskloopBodyBB->begin();
2644
2645 if (Error Err = BodyGenCB(TaskloopAllocaIP, TaskloopBodyIP, TaskloopExitBB))
2646 return Err;
2647
2648 llvm::Expected<llvm::CanonicalLoopInfo *> result = LoopInfo();
2649 if (!result) {
2650 return result.takeError();
2651 }
2652
2653 llvm::CanonicalLoopInfo *CLI = result.get();
2654 if (CLI->VirtualCollapse)
2655 CLI->reportUnsupportedVirtualCollapse();
2656 auto OI = std::make_unique<OutlineInfo>();
2657 OI->EntryBB = TaskloopAllocaBB;
2658 OI->OuterAllocBB = AllocaIP.getNodeParent();
2659 OI->ExitBB = TaskloopExitBB;
2660 OI->OuterDeallocBBs.reserve(DeallocBlocks.size());
2661 copy(DeallocBlocks, OI->OuterDeallocBBs.end());
2662
2663 // Add the thread ID argument.
2664 SmallVector<Instruction *> ToBeDeleted;
2665 // dummy instruction to be used as a fake argument
2666 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
2667 Builder, AllocaIP, ToBeDeleted, TaskloopAllocaIP, "global.tid", false));
2668 Value *FakeLB = createFakeIntVal(Builder, AllocaIP, ToBeDeleted,
2669 TaskloopAllocaIP, "lb", false, true);
2670 Value *FakeUB = createFakeIntVal(Builder, AllocaIP, ToBeDeleted,
2671 TaskloopAllocaIP, "ub", false, true);
2672 Value *FakeStep = createFakeIntVal(Builder, AllocaIP, ToBeDeleted,
2673 TaskloopAllocaIP, "step", false, true);
2674 // For Taskloop, we want to force the bounds being the first 3 inputs in the
2675 // aggregate struct
2676 OI->Inputs.insert(FakeLB);
2677 OI->Inputs.insert(FakeUB);
2678 OI->Inputs.insert(FakeStep);
2679 if (TaskContextStructPtrVal)
2680 OI->Inputs.insert(TaskContextStructPtrVal);
2681 assert(((TaskContextStructPtrVal && DupCB) ||
2682 (!TaskContextStructPtrVal && !DupCB)) &&
2683 "Task context struct ptr and duplication callback must be both set "
2684 "or both null");
2685
2686 // It isn't safe to run the duplication bodygen callback inside the post
2687 // outlining callback so this has to be run now before we know the real task
2688 // shareds structure type.
2689 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2690 Type *PointerTy = PointerType::get(Builder.getContext(), ProgramAddressSpace);
2691 Type *FakeSharedsTy = StructType::get(
2692 Builder.getContext(),
2693 {FakeLB->getType(), FakeUB->getType(), FakeStep->getType(), PointerTy});
2694 Expected<Value *> TaskDupFnOrErr = createTaskDuplicationFunction(
2695 FakeSharedsTy,
2696 /*PrivatesIndex: the pointer after the three indices above*/ 3, DupCB);
2697 if (!TaskDupFnOrErr) {
2698 return TaskDupFnOrErr.takeError();
2699 }
2700 Value *TaskDupFn = *TaskDupFnOrErr;
2701
2702 OI->PostOutlineCB = [this, Ident, LBVal, UBVal, StepVal, Untied,
2703 TaskloopAllocaBB, CLI, TaskDupFn, ToBeDeleted, IfCond,
2704 GrainSize, NoGroup, Sched, FakeLB, FakeUB, FakeStep,
2705 FakeSharedsTy, Final, Mergeable, Priority,
2706 NumOfCollapseLoops,
2707 FreeAgent](Function &OutlinedFn) mutable {
2708 // Replace the Stale CI by appropriate RTL function call.
2709 assert(OutlinedFn.hasOneUse() &&
2710 "there must be a single user for the outlined function");
2711 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
2712
2713 /* Create the casting for the Bounds Values that can be used when outlining
2714 * to replace the uses of the fakes with real values */
2715 BasicBlock *CodeReplBB = StaleCI->getParent();
2716 Builder.SetInsertPoint(CodeReplBB->getFirstInsertionPt());
2717 Value *CastedLBVal =
2718 Builder.CreateIntCast(LBVal, Builder.getInt64Ty(), true, "lb64");
2719 Value *CastedUBVal =
2720 Builder.CreateIntCast(UBVal, Builder.getInt64Ty(), true, "ub64");
2721 Value *CastedStepVal =
2722 Builder.CreateIntCast(StepVal, Builder.getInt64Ty(), true, "step64");
2723
2724 Builder.SetInsertPoint(StaleCI);
2725
2726 // Gather the arguments for emitting the runtime call for
2727 // @__kmpc_omp_task_alloc
2728 Function *TaskAllocFn =
2729 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
2730
2731 Value *ThreadID = getOrCreateThreadID(Ident);
2732
2733 if (!NoGroup) {
2734 // Emit runtime call for @__kmpc_taskgroup
2735 Function *TaskgroupFn =
2736 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);
2737 createRuntimeFunctionCall(TaskgroupFn, {Ident, ThreadID});
2738 }
2739
2740 // `flags` Argument Configuration
2741 // Task is tied if (Flags & 1) == 1.
2742 // Task is untied if (Flags & 1) == 0.
2743 // Task is final if (Flags & 2) == 2.
2744 // Task is not final if (Flags & 2) == 0.
2745 // Task is mergeable if (Flags & 4) == 4.
2746 // Task is not mergeable if (Flags & 4) == 0.
2747 // Task is priority if (Flags & 32) == 32.
2748 // Task is not priority if (Flags & 32) == 0.
2749 // Task is free-agent eligible if (Flags & 128) == 128.
2750 // Task is not free-agent eligible if (Flags & 128) == 0.
2751 Value *Flags = Builder.getInt32(Untied ? 0 : 1);
2752 if (Final)
2753 Flags = Builder.CreateOr(Builder.getInt32(2), Flags);
2754 if (Mergeable)
2755 Flags = Builder.CreateOr(Builder.getInt32(4), Flags);
2756 if (Priority)
2757 Flags = Builder.CreateOr(Builder.getInt32(32), Flags);
2758 if (FreeAgent)
2759 Flags = Builder.CreateOr(Builder.getInt32(128), Flags);
2760
2761 Value *TaskSize = Builder.getInt64(
2762 divideCeil(M.getDataLayout().getTypeSizeInBits(Task), 8));
2763
2764 AllocaInst *ArgStructAlloca =
2766 assert(ArgStructAlloca &&
2767 "Unable to find the alloca instruction corresponding to arguments "
2768 "for extracted function");
2769 std::optional<TypeSize> ArgAllocSize =
2770 ArgStructAlloca->getAllocationSize(M.getDataLayout());
2771 assert(ArgAllocSize &&
2772 "Unable to determine size of arguments for extracted function");
2773 Value *SharedsSize = Builder.getInt64(ArgAllocSize->getFixedValue());
2774
2775 // Emit the @__kmpc_omp_task_alloc runtime call
2776 // The runtime call returns a pointer to an area where the task captured
2777 // variables must be copied before the task is run (TaskData)
2778 CallInst *TaskData = createRuntimeFunctionCall(
2779 TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
2780 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
2781 /*task_func=*/&OutlinedFn});
2782
2783 Value *Shareds = StaleCI->getArgOperand(1);
2784 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
2785 Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);
2786 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
2787 SharedsSize);
2788 // Get the pointer to loop lb, ub, step from task ptr
2789 // and set up the lowerbound,upperbound and step values
2790 llvm::Value *Lb = Builder.CreateGEP(
2791 FakeSharedsTy, TaskShareds, {Builder.getInt32(0), Builder.getInt32(0)});
2792
2793 llvm::Value *Ub = Builder.CreateGEP(
2794 FakeSharedsTy, TaskShareds, {Builder.getInt32(0), Builder.getInt32(1)});
2795
2796 llvm::Value *Step = Builder.CreateGEP(
2797 FakeSharedsTy, TaskShareds, {Builder.getInt32(0), Builder.getInt32(2)});
2798 llvm::Value *Loadstep = Builder.CreateLoad(Builder.getInt64Ty(), Step);
2799
2800 // set up the arguments for emitting kmpc_taskloop runtime call
2801 // setting values for ifval, nogroup, sched, grainsize, task_dup
2802 Value *IfCondVal =
2803 IfCond ? Builder.CreateIntCast(IfCond, Builder.getInt32Ty(), true)
2804 : Builder.getInt32(1);
2805 // As __kmpc_taskgroup is called manually in OMPIRBuilder, NoGroupVal should
2806 // always be 1 when calling __kmpc_taskloop to ensure it is not called again
2807 Value *NoGroupVal = Builder.getInt32(1);
2808 Value *SchedVal = Builder.getInt32(Sched);
2809 Value *GrainSizeVal =
2810 GrainSize ? Builder.CreateIntCast(GrainSize, Builder.getInt64Ty(), true)
2811 : Builder.getInt64(0);
2812 Value *TaskDup = TaskDupFn;
2813
2814 Value *Args[] = {Ident, ThreadID, TaskData, IfCondVal, Lb, Ub,
2815 Loadstep, NoGroupVal, SchedVal, GrainSizeVal, TaskDup};
2816
2817 // taskloop runtime call
2818 Function *TaskloopFn =
2819 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskloop);
2820 createRuntimeFunctionCall(TaskloopFn, Args);
2821
2822 // Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup if
2823 // nogroup is not defined
2824 if (!NoGroup) {
2825 Function *EndTaskgroupFn =
2826 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);
2827 createRuntimeFunctionCall(EndTaskgroupFn, {Ident, ThreadID});
2828 }
2829
2830 StaleCI->eraseFromParent();
2831
2832 Builder.SetInsertPoint(TaskloopAllocaBB->begin());
2833
2834 LoadInst *SharedsOutlined =
2835 Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
2836 OutlinedFn.getArg(1)->replaceUsesWithIf(
2837 SharedsOutlined,
2838 [SharedsOutlined](Use &U) { return U.getUser() != SharedsOutlined; });
2839
2840 Value *IV = CLI->getIndVar();
2841 Type *IVTy = IV->getType();
2842 Constant *One = ConstantInt::get(Builder.getInt64Ty(), 1);
2843
2844 // When outlining, CodeExtractor will create GEP's to the LowerBound and
2845 // UpperBound. These GEP's can be reused for loading the tasks respective
2846 // bounds.
2847 Value *TaskLB = nullptr;
2848 Value *TaskUB = nullptr;
2849 Value *TaskStep = nullptr;
2850 Value *LoadTaskLB = nullptr;
2851 Value *LoadTaskUB = nullptr;
2852 Value *LoadTaskStep = nullptr;
2853 for (Instruction &I : *TaskloopAllocaBB) {
2854 if (I.getOpcode() == Instruction::GetElementPtr) {
2855 GetElementPtrInst &Gep = cast<GetElementPtrInst>(I);
2856 if (ConstantInt *CI = dyn_cast<ConstantInt>(Gep.getOperand(2))) {
2857 switch (CI->getZExtValue()) {
2858 case 0:
2859 TaskLB = &I;
2860 break;
2861 case 1:
2862 TaskUB = &I;
2863 break;
2864 case 2:
2865 TaskStep = &I;
2866 break;
2867 }
2868 }
2869 } else if (I.getOpcode() == Instruction::Load) {
2870 LoadInst &Load = cast<LoadInst>(I);
2871 if (Load.getPointerOperand() == TaskLB) {
2872 assert(TaskLB != nullptr && "Expected value for TaskLB");
2873 LoadTaskLB = &I;
2874 } else if (Load.getPointerOperand() == TaskUB) {
2875 assert(TaskUB != nullptr && "Expected value for TaskUB");
2876 LoadTaskUB = &I;
2877 } else if (Load.getPointerOperand() == TaskStep) {
2878 assert(TaskStep != nullptr && "Expected value for TaskStep");
2879 LoadTaskStep = &I;
2880 }
2881 }
2882 }
2883
2884 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2885
2886 assert(LoadTaskLB != nullptr && "Expected value for LoadTaskLB");
2887 assert(LoadTaskUB != nullptr && "Expected value for LoadTaskUB");
2888 assert(LoadTaskStep != nullptr && "Expected value for LoadTaskStep");
2889 Value *TripCountMinusOne = Builder.CreateSDiv(
2890 Builder.CreateSub(LoadTaskUB, LoadTaskLB), LoadTaskStep);
2891 Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One, "trip_cnt");
2892 Value *CastedTripCount = Builder.CreateIntCast(TripCount, IVTy, true);
2893 Value *CastedTaskLB = Builder.CreateIntCast(LoadTaskLB, IVTy, true);
2894 // set the trip count in the CLI
2895 CLI->setTripCount(CastedTripCount);
2896
2897 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
2898
2899 if (NumOfCollapseLoops > 1) {
2900 llvm::SmallVector<User *> UsersToReplace;
2901 // When using the collapse clause, the bounds of the loop have to be
2902 // adjusted to properly represent the iterator of the outer loop.
2903 Value *IVPlusTaskLB = Builder.CreateAdd(
2904 CLI->getIndVar(),
2905 Builder.CreateSub(CastedTaskLB, ConstantInt::get(IVTy, 1)));
2906 // To ensure every Use is correctly captured, we first want to record
2907 // which users to replace the value in, and then replace the value.
2908 for (auto IVUse = CLI->getIndVar()->uses().begin();
2909 IVUse != CLI->getIndVar()->uses().end(); IVUse++) {
2910 User *IVUser = IVUse->getUser();
2911 if (auto *Op = dyn_cast<BinaryOperator>(IVUser)) {
2912 if (Op->getOpcode() == Instruction::URem ||
2913 Op->getOpcode() == Instruction::UDiv) {
2914 UsersToReplace.push_back(IVUser);
2915 }
2916 }
2917 }
2918 for (User *User : UsersToReplace) {
2919 User->replaceUsesOfWith(CLI->getIndVar(), IVPlusTaskLB);
2920 }
2921 } else {
2922 // The canonical loop is generated with a fixed lower bound. We need to
2923 // update the index calculation code to use the task's lower bound. The
2924 // generated code looks like this:
2925 // %omp_loop.iv = phi ...
2926 // ...
2927 // %tmp = mul [type] %omp_loop.iv, step
2928 // %user_index = add [type] tmp, lb
2929 // OpenMPIRBuilder constructs canonical loops to have exactly three uses
2930 // of the normalised induction variable:
2931 // 1. This one: converting the normalised IV to the user IV
2932 // 2. The increment (add)
2933 // 3. The comparison against the trip count (icmp)
2934 // (1) is the only use that is a mul followed by an add so this cannot
2935 // match other IR.
2936 assert(CLI->getIndVar()->getNumUses() == 3 &&
2937 "Canonical loop should have exactly three uses of the ind var");
2938 for (User *IVUser : CLI->getIndVar()->users()) {
2939 if (auto *Mul = dyn_cast<BinaryOperator>(IVUser)) {
2940 if (Mul->getOpcode() == Instruction::Mul) {
2941 for (User *MulUser : Mul->users()) {
2942 if (auto *Add = dyn_cast<BinaryOperator>(MulUser)) {
2943 if (Add->getOpcode() == Instruction::Add) {
2944 Add->setOperand(1, CastedTaskLB);
2945 }
2946 }
2947 }
2948 }
2949 }
2950 }
2951 }
2952
2953 FakeLB->replaceAllUsesWith(CastedLBVal);
2954 FakeUB->replaceAllUsesWith(CastedUBVal);
2955 FakeStep->replaceAllUsesWith(CastedStepVal);
2956 for (Instruction *I : llvm::reverse(ToBeDeleted)) {
2957 I->eraseFromParent();
2958 }
2959 };
2960
2961 addOutlineInfo(std::move(OI));
2962 Builder.SetInsertPoint(TaskloopExitBB->begin());
2963 return Builder.saveIP();
2964}
2965
2968 M.getContext(), M.getDataLayout().getPointerSizeInBits());
2970 llvm::Type::getInt32Ty(M.getContext()));
2971}
2972
2974 const LocationDescription &Loc, InsertPointTy AllocaIP,
2975 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
2976 bool Tied, Value *Final, Value *IfCondition,
2977 const DependenciesInfo &Dependencies, const AffinityData &Affinities,
2978 bool Mergeable, Value *EventHandle, Value *Priority, bool FreeAgent) {
2979
2980 if (!updateToLocation(Loc))
2981 return InsertPointTy();
2982
2983 uint32_t SrcLocStrSize;
2984 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2985 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2986 // The current basic block is split into four basic blocks. After outlining,
2987 // they will be mapped as follows:
2988 // ```
2989 // def current_fn() {
2990 // current_basic_block:
2991 // br label %task.exit
2992 // task.exit:
2993 // ; instructions after task
2994 // }
2995 // def outlined_fn() {
2996 // task.alloca:
2997 // br label %task.body
2998 // task.body:
2999 // ret void
3000 // }
3001 // ```
3002 BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");
3003 BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");
3004 BasicBlock *TaskAllocaBB =
3005 splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
3006
3007 InsertPointTy TaskAllocaIP = TaskAllocaBB->begin();
3008 InsertPointTy TaskBodyIP = TaskBodyBB->begin();
3009 if (Error Err = BodyGenCB(TaskAllocaIP, TaskBodyIP, TaskExitBB))
3010 return Err;
3011
3012 auto OI = std::make_unique<OutlineInfo>();
3013 OI->EntryBB = TaskAllocaBB;
3014 OI->OuterAllocBB = AllocaIP.getNodeParent();
3015 OI->ExitBB = TaskExitBB;
3016 OI->OuterDeallocBBs.reserve(DeallocBlocks.size());
3017 copy(DeallocBlocks, OI->OuterDeallocBBs.end());
3018
3019 // Add the thread ID argument.
3021 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
3022 Builder, AllocaIP, ToBeDeleted, TaskAllocaIP, "global.tid", false));
3023
3024 OI->PostOutlineCB = [this, Ident, Tied, Final, IfCondition, Dependencies,
3025 Affinities, Mergeable, Priority, EventHandle, FreeAgent,
3026 TaskAllocaBB,
3027 ToBeDeleted](Function &OutlinedFn) mutable {
3028 // Replace the Stale CI by appropriate RTL function call.
3029 assert(OutlinedFn.hasOneUse() &&
3030 "there must be a single user for the outlined function");
3031 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
3032
3033 // HasShareds is true if any variables are captured in the outlined region,
3034 // false otherwise.
3035 bool HasShareds = StaleCI->arg_size() > 1;
3036 Builder.SetInsertPoint(StaleCI);
3037
3038 // Gather the arguments for emitting the runtime call for
3039 // @__kmpc_omp_task_alloc
3040 Function *TaskAllocFn =
3041 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
3042
3043 // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
3044 // call.
3045 Value *ThreadID = getOrCreateThreadID(Ident);
3046
3047 // Argument - `flags`
3048 // Task is tied iff (Flags & 1) == 1.
3049 // Task is untied iff (Flags & 1) == 0.
3050 // Task is final iff (Flags & 2) == 2.
3051 // Task is not final iff (Flags & 2) == 0.
3052 // Task is mergeable or merged-if0 iff (Flags & 4) == 4.
3053 // Task is neither mergeable nor merged-if0 iff (Flags & 4) == 0.
3054 // Task is detachable iff (Flags & 64) == 64.
3055 // Task is not detachable iff (Flags & 64) == 0.
3056 // Task is priority iff (Flags & 32) == 32.
3057 // Task is not priority iff (Flags & 32) == 0.
3058 // Task is free-agent eligible iff (Flags & 128) == 128.
3059 // Task is not free-agent eligible iff (Flags & 128) == 0.
3060 // TODO: Handle the other flags.
3061 Value *Flags = Builder.getInt32(Tied);
3062 auto *ConstIfCondition = dyn_cast_or_null<ConstantInt>(IfCondition);
3063 bool UseMergedIf0Path = ConstIfCondition && ConstIfCondition->isZero();
3064 if (Final) {
3065 Value *FinalFlag =
3066 Builder.CreateSelect(Final, Builder.getInt32(2), Builder.getInt32(0));
3067 Flags = Builder.CreateOr(FinalFlag, Flags);
3068 }
3069
3070 if (Mergeable || UseMergedIf0Path)
3071 Flags = Builder.CreateOr(Builder.getInt32(4), Flags);
3072 if (EventHandle)
3073 Flags = Builder.CreateOr(Builder.getInt32(64), Flags);
3074 if (Priority)
3075 Flags = Builder.CreateOr(Builder.getInt32(32), Flags);
3076 if (FreeAgent)
3077 Flags = Builder.CreateOr(Builder.getInt32(128), Flags);
3078
3079 // Argument - `sizeof_kmp_task_t` (TaskSize)
3080 // Tasksize refers to the size in bytes of kmp_task_t data structure
3081 // including private vars accessed in task.
3082 // TODO: add kmp_task_t_with_privates (privates)
3083 Value *TaskSize = Builder.getInt64(
3084 divideCeil(M.getDataLayout().getTypeSizeInBits(Task), 8));
3085
3086 // Argument - `sizeof_shareds` (SharedsSize)
3087 // SharedsSize refers to the shareds array size in the kmp_task_t data
3088 // structure.
3089 Value *SharedsSize = Builder.getInt64(0);
3090 if (HasShareds) {
3091 AllocaInst *ArgStructAlloca =
3093 assert(ArgStructAlloca &&
3094 "Unable to find the alloca instruction corresponding to arguments "
3095 "for extracted function");
3096 std::optional<TypeSize> ArgAllocSize =
3097 ArgStructAlloca->getAllocationSize(M.getDataLayout());
3098 assert(ArgAllocSize &&
3099 "Unable to determine size of arguments for extracted function");
3100 SharedsSize = Builder.getInt64(ArgAllocSize->getFixedValue());
3101 }
3102 // Emit the @__kmpc_omp_task_alloc runtime call
3103 // The runtime call returns a pointer to an area where the task captured
3104 // variables must be copied before the task is run (TaskData)
3106 TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
3107 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
3108 /*task_func=*/&OutlinedFn});
3109
3110 if (Affinities.Count && Affinities.Info) {
3112 OMPRTL___kmpc_omp_reg_task_with_affinity);
3113
3114 createRuntimeFunctionCall(RegAffFn, {Ident, ThreadID, TaskData,
3115 Affinities.Count, Affinities.Info});
3116 }
3117
3118 // Emit detach clause initialization.
3119 // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid,
3120 // task_descriptor);
3121 if (EventHandle) {
3123 OMPRTL___kmpc_task_allow_completion_event);
3124 llvm::Value *EventVal =
3125 createRuntimeFunctionCall(TaskDetachFn, {Ident, ThreadID, TaskData});
3126 llvm::Value *EventHandleAddr =
3127 Builder.CreatePointerBitCastOrAddrSpaceCast(EventHandle,
3128 Builder.getPtrTy(0));
3129 EventVal = Builder.CreatePtrToInt(EventVal, Builder.getInt64Ty());
3130 Builder.CreateStore(EventVal, EventHandleAddr);
3131 }
3132 // Copy the arguments for outlined function
3133 if (HasShareds) {
3134 Value *Shareds = StaleCI->getArgOperand(1);
3135 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
3136 Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);
3137 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
3138 SharedsSize);
3139 }
3140
3141 if (Priority) {
3142 //
3143 // The return type of "__kmpc_omp_task_alloc" is "kmp_task_t *",
3144 // we populate the priority information into the "kmp_task_t" here
3145 //
3146 // The struct "kmp_task_t" definition is available in kmp.h
3147 // kmp_task_t = { shareds, routine, part_id, data1, data2 }
3148 // data2 is used for priority
3149 //
3150 Type *Int32Ty = Builder.getInt32Ty();
3151 Constant *Zero = ConstantInt::get(Int32Ty, 0);
3152 // kmp_task_t* => { ptr }
3153 Type *TaskPtr = StructType::get(VoidPtr);
3154 Value *TaskGEP =
3155 Builder.CreateInBoundsGEP(TaskPtr, TaskData, {Zero, Zero});
3156 // kmp_task_t => { ptr, ptr, i32, ptr, ptr }
3157 Type *TaskStructType = StructType::get(
3158 VoidPtr, VoidPtr, Builder.getInt32Ty(), VoidPtr, VoidPtr);
3159 Value *PriorityData = Builder.CreateInBoundsGEP(
3160 TaskStructType, TaskGEP, {Zero, ConstantInt::get(Int32Ty, 4)});
3161 // kmp_cmplrdata_t => { ptr, ptr }
3162 Type *CmplrStructType = StructType::get(VoidPtr, VoidPtr);
3163 Value *CmplrData = Builder.CreateInBoundsGEP(CmplrStructType,
3164 PriorityData, {Zero, Zero});
3165 Builder.CreateStore(Priority, CmplrData);
3166 }
3167
3168 Value *DepArray = nullptr;
3169 Value *NumDeps = nullptr;
3170 if (Dependencies.DepArray) {
3171 DepArray = Dependencies.DepArray;
3172 NumDeps = Dependencies.NumDeps;
3173 } else if (!Dependencies.Deps.empty()) {
3174 DepArray = emitTaskDependencies(*this, Dependencies.Deps);
3175 NumDeps = Builder.getInt32(Dependencies.Deps.size());
3176 }
3177
3178 // In the presence of the `if` clause, the following IR is generated:
3179 // ...
3180 // %data = call @__kmpc_omp_task_alloc(...)
3181 // br i1 %if_condition, label %then, label %else
3182 // then:
3183 // call @__kmpc_omp_task(...)
3184 // br label %exit
3185 // else:
3186 // ;; Wait for resolution of dependencies, if any, before
3187 // ;; beginning the task
3188 // call @__kmpc_omp_wait_deps(...)
3189 // call @__kmpc_omp_task_begin_if0(...)
3190 // call @outlined_fn(...)
3191 // call @__kmpc_omp_task_complete_if0(...)
3192 // br label %exit
3193 // exit:
3194 // ...
3195 if (IfCondition && !UseMergedIf0Path) {
3196 // `SplitBlockAndInsertIfThenElse` requires the block to have a
3197 // terminator.
3198 splitBB(Builder, /*CreateBranch=*/true, "if.end");
3199 Instruction *IfTerminator =
3200 Builder.GetInsertPoint()->getParent()->getTerminator();
3201 Instruction *ThenTI = IfTerminator, *ElseTI = nullptr;
3202 Builder.SetInsertPoint(IfTerminator);
3203 SplitBlockAndInsertIfThenElse(IfCondition, IfTerminator, &ThenTI,
3204 &ElseTI);
3205 Builder.SetInsertPoint(ElseTI);
3206
3207 if (DepArray) {
3208 Function *TaskWaitFn =
3209 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_wait_deps);
3211 TaskWaitFn,
3212 {Ident, ThreadID, NumDeps, DepArray,
3213 ConstantInt::get(Builder.getInt32Ty(), 0),
3215 }
3216 Function *TaskBeginFn =
3217 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);
3218 Function *TaskCompleteFn =
3219 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);
3220 createRuntimeFunctionCall(TaskBeginFn, {Ident, ThreadID, TaskData});
3221 CallInst *CI = nullptr;
3222 if (HasShareds)
3223 CI = createRuntimeFunctionCall(&OutlinedFn, {ThreadID, TaskData});
3224 else
3225 CI = createRuntimeFunctionCall(&OutlinedFn, {ThreadID});
3226 CI->setDebugLoc(StaleCI->getDebugLoc());
3227 createRuntimeFunctionCall(TaskCompleteFn, {Ident, ThreadID, TaskData});
3228 Builder.SetInsertPoint(ThenTI);
3229 }
3230
3231 if (DepArray) {
3232 Function *TaskFn =
3233 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);
3235 TaskFn,
3236 {Ident, ThreadID, TaskData, NumDeps, DepArray,
3237 ConstantInt::get(Builder.getInt32Ty(), 0),
3239
3240 } else {
3241 // Emit the @__kmpc_omp_task runtime call to spawn the task
3242 Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
3243 createRuntimeFunctionCall(TaskFn, {Ident, ThreadID, TaskData});
3244 }
3245
3246 StaleCI->eraseFromParent();
3247
3248 Builder.SetInsertPoint(TaskAllocaBB->begin());
3249 if (HasShareds) {
3250 LoadInst *Shareds = Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
3251 OutlinedFn.getArg(1)->replaceUsesWithIf(
3252 Shareds, [Shareds](Use &U) { return U.getUser() != Shareds; });
3253 }
3254
3255 // The insert point may refer to one of the instructions about to be
3256 // deleted. It is not needed anymore so clear it instead of leaving it
3257 // dangling.
3258 Builder.ClearInsertionPoint();
3259 for (Instruction *I : llvm::reverse(ToBeDeleted))
3260 I->eraseFromParent();
3261 };
3262
3263 addOutlineInfo(std::move(OI));
3264 Builder.SetInsertPoint(TaskExitBB->begin());
3265
3266 return Builder.saveIP();
3267}
3268
3270 const LocationDescription &Loc, InsertPointTy AllocaIP,
3271 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB) {
3272 if (!updateToLocation(Loc))
3273 return InsertPointTy();
3274
3275 uint32_t SrcLocStrSize;
3276 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3277 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3278 Value *ThreadID = getOrCreateThreadID(Ident);
3279
3280 // Emit the @__kmpc_taskgroup runtime call to start the taskgroup
3281 Function *TaskgroupFn =
3282 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);
3283 createRuntimeFunctionCall(TaskgroupFn, {Ident, ThreadID});
3284
3285 BasicBlock *TaskgroupExitBB = splitBB(Builder, true, "taskgroup.exit");
3286 if (Error Err = BodyGenCB(AllocaIP, Builder.saveIP(), DeallocBlocks))
3287 return Err;
3288
3289 Builder.SetInsertPoint(TaskgroupExitBB);
3290 // Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup
3291 Function *EndTaskgroupFn =
3292 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);
3293 createRuntimeFunctionCall(EndTaskgroupFn, {Ident, ThreadID});
3294
3295 return Builder.saveIP();
3296}
3297
3299 const LocationDescription &Loc, InsertPointTy AllocaIP,
3301 FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {
3302 assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");
3303
3304 if (!updateToLocation(Loc))
3305 return Loc.IP;
3306
3307 FinalizationStack.push_back({FiniCB, OMPD_sections, IsCancellable});
3308
3309 // Each section is emitted as a switch case
3310 // Each finalization callback is handled from clang.EmitOMPSectionDirective()
3311 // -> OMP.createSection() which generates the IR for each section
3312 // Iterate through all sections and emit a switch construct:
3313 // switch (IV) {
3314 // case 0:
3315 // <SectionStmt[0]>;
3316 // break;
3317 // ...
3318 // case <NumSection> - 1:
3319 // <SectionStmt[<NumSection> - 1]>;
3320 // break;
3321 // }
3322 // ...
3323 // section_loop.after:
3324 // <FiniCB>;
3325 auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) -> Error {
3326 Builder.restoreIP(CodeGenIP);
3328 splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");
3329 Function *CurFn = Continue->getParent();
3330 SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);
3331
3332 unsigned CaseNumber = 0;
3333 for (auto SectionCB : SectionCBs) {
3335 M.getContext(), "omp_section_loop.body.case", CurFn, Continue);
3336 SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
3337 Builder.SetInsertPoint(CaseBB);
3338 UncondBrInst *CaseEndBr = Builder.CreateBr(Continue);
3339 if (Error Err = SectionCB(InsertPointTy(), CaseEndBr->getIterator(), {}))
3340 return Err;
3341 CaseNumber++;
3342 }
3343 // remove the existing terminator from body BB since there can be no
3344 // terminators after switch/case
3345 return Error::success();
3346 };
3347 // Loop body ends here
3348 // LowerBound, UpperBound, and STride for createCanonicalLoop
3349 Type *I32Ty = Type::getInt32Ty(M.getContext());
3350 Value *LB = ConstantInt::get(I32Ty, 0);
3351 Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
3352 Value *ST = ConstantInt::get(I32Ty, 1);
3354 Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
3355 if (!LoopInfo)
3356 return LoopInfo.takeError();
3357
3358 InsertPointOrErrorTy WsloopIP =
3359 applyStaticWorkshareLoop(Loc.DL, *LoopInfo, AllocaIP,
3360 WorksharingLoopType::ForStaticLoop, !IsNowait);
3361 if (!WsloopIP)
3362 return WsloopIP.takeError();
3363 InsertPointTy AfterIP = *WsloopIP;
3364
3365 BasicBlock *LoopFini = AfterIP.getNodeParent()->getSinglePredecessor();
3366 assert(LoopFini && "Bad structure of static workshare loop finalization");
3367
3368 // Apply the finalization callback in LoopAfterBB
3369 auto FiniInfo = FinalizationStack.pop_back_val();
3370 assert(FiniInfo.DK == OMPD_sections &&
3371 "Unexpected finalization stack state!");
3372 if (Error Err = FiniInfo.mergeFiniBB(Builder, LoopFini))
3373 return Err;
3374
3375 return AfterIP;
3376}
3377
3380 BodyGenCallbackTy BodyGenCB,
3381 FinalizeCallbackTy FiniCB) {
3382 if (!updateToLocation(Loc))
3383 return Loc.IP;
3384
3385 auto FiniCBWrapper = [&](InsertPointTy IP) {
3386 if (IP != IP.getNodeParent()->end())
3387 return FiniCB(IP);
3388 // This must be done otherwise any nested constructs using FinalizeOMPRegion
3389 // will fail because that function requires the Finalization Basic Block to
3390 // have a terminator, which is already removed by EmitOMPRegionBody.
3391 // IP is currently at cancelation block.
3392 // We need to backtrack to the condition block to fetch
3393 // the exit block and create a branch from cancelation
3394 // to exit block.
3396 Builder.restoreIP(IP);
3397 auto *CaseBB = Loc.IP.getNodeParent();
3398 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
3399 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
3400 Instruction *I = Builder.CreateBr(ExitBB);
3401 IP = I->getIterator();
3402 return FiniCB(IP);
3403 };
3404
3405 Directive OMPD = Directive::OMPD_sections;
3406 // Since we are using Finalization Callback here, HasFinalize
3407 // and IsCancellable have to be true
3408 return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
3409 /*Conditional*/ false, /*hasFinalize*/ true,
3410 /*IsCancellable*/ true);
3411}
3412
3418
3419Value *OpenMPIRBuilder::getGPUThreadID() {
3422 OMPRTL___kmpc_get_hardware_thread_id_in_block),
3423 {});
3424}
3425
3426Value *OpenMPIRBuilder::getGPUWarpSize() {
3428 getOrCreateRuntimeFunction(M, OMPRTL___kmpc_get_warp_size), {});
3429}
3430
3431Value *OpenMPIRBuilder::getNVPTXWarpID() {
3432 unsigned LaneIDBits = Log2_32(Config.getGridValue().GV_Warp_Size);
3433 return Builder.CreateAShr(getGPUThreadID(), LaneIDBits, "nvptx_warp_id");
3434}
3435
3436Value *OpenMPIRBuilder::getNVPTXLaneID() {
3437 unsigned LaneIDBits = Log2_32(Config.getGridValue().GV_Warp_Size);
3438 assert(LaneIDBits < 32 && "Invalid LaneIDBits size in NVPTX device.");
3439 unsigned LaneIDMask = ~0u >> (32u - LaneIDBits);
3440 return Builder.CreateAnd(getGPUThreadID(), Builder.getInt32(LaneIDMask),
3441 "nvptx_lane_id");
3442}
3443
3444Value *OpenMPIRBuilder::castValueToType(InsertPointTy AllocaIP, Value *From,
3445 Type *ToType) {
3446 Type *FromType = From->getType();
3447 uint64_t FromSize = M.getDataLayout().getTypeStoreSize(FromType);
3448 uint64_t ToSize = M.getDataLayout().getTypeStoreSize(ToType);
3449 assert(FromSize > 0 && "From size must be greater than zero");
3450 assert(ToSize > 0 && "To size must be greater than zero");
3451 if (FromType == ToType)
3452 return From;
3453 if (FromSize == ToSize)
3454 return Builder.CreateBitCast(From, ToType);
3455 if (ToType->isIntegerTy() && FromType->isIntegerTy())
3456 return Builder.CreateIntCast(From, ToType, /*isSigned*/ true);
3457 InsertPointTy SaveIP = Builder.saveIP();
3458 Builder.restoreIP(AllocaIP);
3459 Value *CastItem = Builder.CreateAlloca(ToType);
3460 Builder.restoreIP(SaveIP);
3461
3462 Value *ValCastItem = Builder.CreatePointerBitCastOrAddrSpaceCast(
3463 CastItem, Builder.getPtrTy(0));
3464 Builder.CreateStore(From, ValCastItem);
3465 return Builder.CreateLoad(ToType, CastItem);
3466}
3467
3468Value *OpenMPIRBuilder::createRuntimeShuffleFunction(InsertPointTy AllocaIP,
3469 Value *Element,
3470 Type *ElementType,
3471 Value *Offset) {
3472 uint64_t Size = M.getDataLayout().getTypeStoreSize(ElementType);
3473 assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction");
3474
3475 // Cast all types to 32- or 64-bit values before calling shuffle routines.
3476 Type *CastTy = Builder.getIntNTy(Size <= 4 ? 32 : 64);
3477 Value *ElemCast = castValueToType(AllocaIP, Element, CastTy);
3478 Value *WarpSize =
3479 Builder.CreateIntCast(getGPUWarpSize(), Builder.getInt16Ty(), true);
3481 Size <= 4 ? RuntimeFunction::OMPRTL___kmpc_shuffle_int32
3482 : RuntimeFunction::OMPRTL___kmpc_shuffle_int64);
3483 Value *WarpSizeCast =
3484 Builder.CreateIntCast(WarpSize, Builder.getInt16Ty(), /*isSigned=*/true);
3485 Value *ShuffleCall =
3486 createRuntimeFunctionCall(ShuffleFunc, {ElemCast, Offset, WarpSizeCast});
3487 // The shuffle runtime functions return a 32- or 64-bit value. Cast it back
3488 // down to the requested element type, otherwise storing the result would
3489 // write past the end of an element narrower than the shuffle width.
3490 return castValueToType(AllocaIP, ShuffleCall, ElementType);
3491}
3492
3493void OpenMPIRBuilder::shuffleAndStore(InsertPointTy AllocaIP, Value *SrcAddr,
3494 Value *DstAddr, Type *ElemType,
3495 Value *Offset, Type *ReductionArrayTy,
3496 bool IsByRefElem) {
3497 uint64_t Size = M.getDataLayout().getTypeStoreSize(ElemType);
3498 // Create the loop over the big sized data.
3499 // ptr = (void*)Elem;
3500 // ptrEnd = (void*) Elem + 1;
3501 // Step = 8;
3502 // while (ptr + Step < ptrEnd)
3503 // shuffle((int64_t)*ptr);
3504 // Step = 4;
3505 // while (ptr + Step < ptrEnd)
3506 // shuffle((int32_t)*ptr);
3507 // ...
3508 Type *IndexTy = Builder.getIndexTy(
3509 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
3510 Value *ElemPtr = DstAddr;
3511 Value *Ptr = SrcAddr;
3512 for (unsigned IntSize = 8; IntSize >= 1; IntSize /= 2) {
3513 if (Size < IntSize)
3514 continue;
3515 Type *IntType = Builder.getIntNTy(IntSize * 8);
3516 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3517 Ptr, Builder.getPtrTy(0), Ptr->getName() + ".ascast");
3518 Value *SrcAddrGEP =
3519 Builder.CreateGEP(ElemType, SrcAddr, {ConstantInt::get(IndexTy, 1)});
3520 ElemPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3521 ElemPtr, Builder.getPtrTy(0), ElemPtr->getName() + ".ascast");
3522
3523 Function *CurFunc = Builder.GetInsertBlock()->getParent();
3524 if ((Size / IntSize) > 1) {
3525 Value *PtrEnd = Builder.CreatePointerBitCastOrAddrSpaceCast(
3526 SrcAddrGEP, Builder.getPtrTy());
3527 BasicBlock *PreCondBB =
3528 BasicBlock::Create(M.getContext(), ".shuffle.pre_cond");
3529 BasicBlock *ThenBB = BasicBlock::Create(M.getContext(), ".shuffle.then");
3530 BasicBlock *ExitBB = BasicBlock::Create(M.getContext(), ".shuffle.exit");
3531 BasicBlock *CurrentBB = Builder.GetInsertBlock();
3532 emitBlock(PreCondBB, CurFunc);
3533 PHINode *PhiSrc =
3534 Builder.CreatePHI(Ptr->getType(), /*NumReservedValues=*/2);
3535 PhiSrc->addIncoming(Ptr, CurrentBB);
3536 PHINode *PhiDest =
3537 Builder.CreatePHI(ElemPtr->getType(), /*NumReservedValues=*/2);
3538 PhiDest->addIncoming(ElemPtr, CurrentBB);
3539 Ptr = PhiSrc;
3540 ElemPtr = PhiDest;
3541 Value *PtrDiff = Builder.CreatePtrDiff(
3542 Builder.getInt8Ty(), PtrEnd,
3543 Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr, Builder.getPtrTy()));
3544 Builder.CreateCondBr(
3545 Builder.CreateICmpSGT(PtrDiff, Builder.getInt64(IntSize - 1)), ThenBB,
3546 ExitBB);
3547 emitBlock(ThenBB, CurFunc);
3548 Value *Res = createRuntimeShuffleFunction(
3549 AllocaIP,
3550 Builder.CreateAlignedLoad(
3551 IntType, Ptr, M.getDataLayout().getPrefTypeAlign(ElemType)),
3552 IntType, Offset);
3553 Builder.CreateAlignedStore(Res, ElemPtr,
3554 M.getDataLayout().getPrefTypeAlign(ElemType));
3555 Value *LocalPtr =
3556 Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3557 Value *LocalElemPtr =
3558 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3559 PhiSrc->addIncoming(LocalPtr, ThenBB);
3560 PhiDest->addIncoming(LocalElemPtr, ThenBB);
3561 emitBranch(PreCondBB);
3562 emitBlock(ExitBB, CurFunc);
3563 } else {
3564 // The shuffled value comes back as the chunk's integer type, so the
3565 // store covers exactly this chunk regardless of what ElemType is.
3566 Value *Res = createRuntimeShuffleFunction(
3567 AllocaIP, Builder.CreateLoad(IntType, Ptr), IntType, Offset);
3568 Builder.CreateStore(Res, ElemPtr);
3569 Ptr = Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3570 ElemPtr =
3571 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3572 }
3573 Size = Size % IntSize;
3574 }
3575}
3576
3577Error OpenMPIRBuilder::emitReductionListCopy(
3578 InsertPointTy AllocaIP, CopyAction Action, Type *ReductionArrayTy,
3579 ArrayRef<ReductionInfo> ReductionInfos, Value *SrcBase, Value *DestBase,
3580 ArrayRef<bool> IsByRef, CopyOptionsTy CopyOptions) {
3581 Type *IndexTy = Builder.getIndexTy(
3582 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
3583 Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
3584
3585 // Iterates, element-by-element, through the source Reduce list and
3586 // make a copy.
3587 for (auto En : enumerate(ReductionInfos)) {
3588 const ReductionInfo &RI = En.value();
3589 Value *SrcElementAddr = nullptr;
3590 AllocaInst *DestAlloca = nullptr;
3591 Value *DestElementAddr = nullptr;
3592 Value *DestElementPtrAddr = nullptr;
3593 // Should we shuffle in an element from a remote lane?
3594 bool ShuffleInElement = false;
3595 // Set to true to update the pointer in the dest Reduce list to a
3596 // newly created element.
3597 bool UpdateDestListPtr = false;
3598
3599 // Step 1.1: Get the address for the src element in the Reduce list.
3600 Value *SrcElementPtrAddr = Builder.CreateInBoundsGEP(
3601 ReductionArrayTy, SrcBase,
3602 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3603 SrcElementAddr = Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrAddr);
3604
3605 // Step 1.2: Create a temporary to store the element in the destination
3606 // Reduce list.
3607 DestElementPtrAddr = Builder.CreateInBoundsGEP(
3608 ReductionArrayTy, DestBase,
3609 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3610 bool IsByRefElem = (!IsByRef.empty() && IsByRef[En.index()]);
3611 switch (Action) {
3613 InsertPointTy CurIP = Builder.saveIP();
3614 Builder.restoreIP(AllocaIP);
3615
3616 Type *DestAllocaType =
3617 IsByRefElem ? RI.ByRefAllocatedType : RI.ElementType;
3618 DestAlloca = Builder.CreateAlloca(DestAllocaType, nullptr,
3619 ".omp.reduction.element");
3620 DestAlloca->setAlignment(
3621 M.getDataLayout().getPrefTypeAlign(DestAllocaType));
3622 DestElementAddr = DestAlloca;
3623 DestElementAddr =
3624 Builder.CreateAddrSpaceCast(DestElementAddr, Builder.getPtrTy(),
3625 DestElementAddr->getName() + ".ascast");
3626 Builder.restoreIP(CurIP);
3627 ShuffleInElement = true;
3628 UpdateDestListPtr = true;
3629 break;
3630 }
3632 DestElementAddr =
3633 Builder.CreateLoad(Builder.getPtrTy(), DestElementPtrAddr);
3634 break;
3635 }
3636 }
3637
3638 // Now that all active lanes have read the element in the
3639 // Reduce list, shuffle over the value from the remote lane.
3640 if (ShuffleInElement) {
3641 Type *ShuffleType = RI.ElementType;
3642 Value *ShuffleSrcAddr = SrcElementAddr;
3643 Value *ShuffleDestAddr = DestElementAddr;
3644 AllocaInst *LocalStorage = nullptr;
3645
3646 if (IsByRefElem) {
3647 assert(RI.ByRefElementType && "Expected by-ref element type to be set");
3648 assert(RI.ByRefAllocatedType &&
3649 "Expected by-ref allocated type to be set");
3650 // For by-ref reductions, we need to copy from the remote lane the
3651 // actual value of the partial reduction computed by that remote lane;
3652 // rather than, for example, a pointer to that data or, even worse, a
3653 // pointer to the descriptor of the by-ref reduction element.
3654 ShuffleType = RI.ByRefElementType;
3655
3656 if (RI.DataPtrPtrGen) {
3657 // Descriptor-based by-ref: extract data pointer from descriptor.
3658 InsertPointOrErrorTy GenResult = RI.DataPtrPtrGen(
3659 Builder.saveIP(), ShuffleSrcAddr, ShuffleSrcAddr);
3660
3661 if (!GenResult)
3662 return GenResult.takeError();
3663
3664 ShuffleSrcAddr =
3665 Builder.CreateLoad(Builder.getPtrTy(), ShuffleSrcAddr);
3666
3667 {
3668 InsertPointTy OldIP = Builder.saveIP();
3669 Builder.restoreIP(AllocaIP);
3670
3671 LocalStorage = Builder.CreateAlloca(ShuffleType);
3672 Builder.restoreIP(OldIP);
3673 ShuffleDestAddr = LocalStorage;
3674 }
3675 } else {
3676 // Non-descriptor by-ref: the pointer already references data
3677 // directly. Shuffle into the destination alloca.
3678 ShuffleDestAddr = DestElementAddr;
3679 }
3680 }
3681
3682 shuffleAndStore(AllocaIP, ShuffleSrcAddr, ShuffleDestAddr, ShuffleType,
3683 RemoteLaneOffset, ReductionArrayTy, IsByRefElem);
3684
3685 if (IsByRefElem && RI.DataPtrPtrGen) {
3686 // Copy descriptor from source and update base_ptr to shuffled data
3687 Value *DestDescriptorAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3688 DestAlloca, Builder.getPtrTy(), ".ascast");
3689
3690 InsertPointOrErrorTy GenResult = generateReductionDescriptor(
3691 DestDescriptorAddr, LocalStorage, SrcElementAddr,
3692 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
3693
3694 if (!GenResult)
3695 return GenResult.takeError();
3696 }
3697 } else {
3698 switch (RI.EvaluationKind) {
3699 case EvalKind::Scalar: {
3700 Value *Elem = Builder.CreateLoad(RI.ElementType, SrcElementAddr);
3701 // Store the source element value to the dest element address.
3702 Builder.CreateStore(Elem, DestElementAddr);
3703 break;
3704 }
3705 case EvalKind::Complex: {
3706 Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(
3707 RI.ElementType, SrcElementAddr, 0, 0, ".realp");
3708 Value *SrcReal = Builder.CreateLoad(
3709 RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");
3710 Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(
3711 RI.ElementType, SrcElementAddr, 0, 1, ".imagp");
3712 Value *SrcImg = Builder.CreateLoad(
3713 RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");
3714
3715 Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(
3716 RI.ElementType, DestElementAddr, 0, 0, ".realp");
3717 Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(
3718 RI.ElementType, DestElementAddr, 0, 1, ".imagp");
3719 Builder.CreateStore(SrcReal, DestRealPtr);
3720 Builder.CreateStore(SrcImg, DestImgPtr);
3721 break;
3722 }
3723 case EvalKind::Aggregate: {
3724 Value *SizeVal = Builder.getInt64(
3725 M.getDataLayout().getTypeStoreSize(RI.ElementType));
3726 Builder.CreateMemCpy(
3727 DestElementAddr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3728 SrcElementAddr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3729 SizeVal, false);
3730 break;
3731 }
3732 };
3733 }
3734
3735 // Step 3.1: Modify reference in dest Reduce list as needed.
3736 // Modifying the reference in Reduce list to point to the newly
3737 // created element. The element is live in the current function
3738 // scope and that of functions it invokes (i.e., reduce_function).
3739 // RemoteReduceData[i] = (void*)&RemoteElem
3740 if (UpdateDestListPtr) {
3741 Value *CastDestAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3742 DestElementAddr, Builder.getPtrTy(),
3743 DestElementAddr->getName() + ".ascast");
3744 Builder.CreateStore(CastDestAddr, DestElementPtrAddr);
3745 }
3746 }
3747
3748 return Error::success();
3749}
3750
3751Expected<Function *> OpenMPIRBuilder::emitInterWarpCopyFunction(
3752 const LocationDescription &Loc, ArrayRef<ReductionInfo> ReductionInfos,
3753 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
3754 IRBuilder<>::InsertPointGuard IPG(Builder);
3755 LLVMContext &Ctx = M.getContext();
3756 FunctionType *FuncTy = FunctionType::get(
3757 Builder.getVoidTy(), {Builder.getPtrTy(), Builder.getInt32Ty()},
3758 /* IsVarArg */ false);
3759 Function *WcFunc =
3761 "_omp_reduction_inter_warp_copy_func", &M);
3762 WcFunc->setCallingConv(Config.getRuntimeCC());
3763 WcFunc->setAttributes(FuncAttrs);
3764 WcFunc->addParamAttr(0, Attribute::NoUndef);
3765 WcFunc->addParamAttr(1, Attribute::NoUndef);
3766 BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", WcFunc);
3767 Builder.SetInsertPoint(EntryBB);
3768 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
3769
3770 // ReduceList: thread local Reduce list.
3771 // At the stage of the computation when this function is called, partially
3772 // aggregated values reside in the first lane of every active warp.
3773 Argument *ReduceListArg = WcFunc->getArg(0);
3774 // NumWarps: number of warps active in the parallel region. This could
3775 // be smaller than 32 (max warps in a CTA) for partial block reduction.
3776 Argument *NumWarpsArg = WcFunc->getArg(1);
3777
3778 // This array is used as a medium to transfer, one reduce element at a time,
3779 // the data from the first lane of every warp to lanes in the first warp
3780 // in order to perform the final step of a reduction in a parallel region
3781 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3782 // for reduced latency, as well as to have a distinct copy for concurrently
3783 // executing target regions. The array is declared with common linkage so
3784 // as to be shared across compilation units.
3785 StringRef TransferMediumName =
3786 "__openmp_nvptx_data_transfer_temporary_storage";
3787 GlobalVariable *TransferMedium = M.getGlobalVariable(TransferMediumName);
3788 unsigned WarpSize = Config.getGridValue().GV_Warp_Size;
3789 ArrayType *ArrayTy = ArrayType::get(Builder.getInt32Ty(), WarpSize);
3790 if (!TransferMedium) {
3791 TransferMedium = new GlobalVariable(
3792 M, ArrayTy, /*isConstant=*/false, GlobalVariable::WeakAnyLinkage,
3793 UndefValue::get(ArrayTy), TransferMediumName,
3794 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
3795 /*AddressSpace=*/3);
3796 }
3797
3798 // Get the CUDA thread id of the current OpenMP thread on the GPU.
3799 Value *GPUThreadID = getGPUThreadID();
3800 // nvptx_lane_id = nvptx_id % warpsize
3801 Value *LaneID = getNVPTXLaneID();
3802 // nvptx_warp_id = nvptx_id / warpsize
3803 Value *WarpID = getNVPTXWarpID();
3804
3805 InsertPointTy AllocaIP = Builder.GetInsertBlock()->getFirstInsertionPt();
3806 Type *Arg0Type = ReduceListArg->getType();
3807 Type *Arg1Type = NumWarpsArg->getType();
3808 Builder.restoreIP(AllocaIP);
3809 AllocaInst *ReduceListAlloca = Builder.CreateAlloca(
3810 Arg0Type, nullptr, ReduceListArg->getName() + ".addr");
3811 AllocaInst *NumWarpsAlloca =
3812 Builder.CreateAlloca(Arg1Type, nullptr, NumWarpsArg->getName() + ".addr");
3813 Value *ReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
3814 ReduceListAlloca, Arg0Type, ReduceListAlloca->getName() + ".ascast");
3815 Value *NumWarpsAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
3816 NumWarpsAlloca, Builder.getPtrTy(0),
3817 NumWarpsAlloca->getName() + ".ascast");
3818 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
3819 Builder.CreateStore(NumWarpsArg, NumWarpsAddrCast);
3820 AllocaIP = getInsertPointAfterInstr(NumWarpsAlloca);
3821 InsertPointTy CodeGenIP =
3822 getInsertPointAfterInstr(&Builder.GetInsertBlock()->back());
3823 Builder.restoreIP(CodeGenIP);
3824
3825 Value *ReduceList =
3826 Builder.CreateLoad(Builder.getPtrTy(), ReduceListAddrCast);
3827
3828 for (auto En : enumerate(ReductionInfos)) {
3829 //
3830 // Warp master copies reduce element to transfer medium in __shared__
3831 // memory.
3832 //
3833 const ReductionInfo &RI = En.value();
3834 bool IsByRefElem = !IsByRef.empty() && IsByRef[En.index()];
3835 unsigned RealTySize = M.getDataLayout().getTypeAllocSize(
3836 IsByRefElem ? RI.ByRefElementType : RI.ElementType);
3837 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /= 2) {
3838 Type *CType = Builder.getIntNTy(TySize * 8);
3839
3840 unsigned NumIters = RealTySize / TySize;
3841 if (NumIters == 0)
3842 continue;
3843 Value *Cnt = nullptr;
3844 Value *CntAddr = nullptr;
3845 BasicBlock *PrecondBB = nullptr;
3846 BasicBlock *ExitBB = nullptr;
3847 if (NumIters > 1) {
3848 CodeGenIP = Builder.saveIP();
3849 Builder.restoreIP(AllocaIP);
3850 CntAddr =
3851 Builder.CreateAlloca(Builder.getInt32Ty(), nullptr, ".cnt.addr");
3852
3853 CntAddr = Builder.CreateAddrSpaceCast(CntAddr, Builder.getPtrTy(),
3854 CntAddr->getName() + ".ascast");
3855 Builder.restoreIP(CodeGenIP);
3856 Builder.CreateStore(Constant::getNullValue(Builder.getInt32Ty()),
3857 CntAddr,
3858 /*Volatile=*/false);
3859 PrecondBB = BasicBlock::Create(Ctx, "precond");
3860 ExitBB = BasicBlock::Create(Ctx, "exit");
3861 BasicBlock *BodyBB = BasicBlock::Create(Ctx, "body");
3862 emitBlock(PrecondBB, Builder.GetInsertBlock()->getParent());
3863 Cnt = Builder.CreateLoad(Builder.getInt32Ty(), CntAddr,
3864 /*Volatile=*/false);
3865 Value *Cmp = Builder.CreateICmpULT(
3866 Cnt, ConstantInt::get(Builder.getInt32Ty(), NumIters));
3867 Builder.CreateCondBr(Cmp, BodyBB, ExitBB);
3868 emitBlock(BodyBB, Builder.GetInsertBlock()->getParent());
3869 }
3870
3871 // kmpc_barrier.
3872 InsertPointOrErrorTy BarrierIP1 =
3874 omp::Directive::OMPD_unknown,
3875 /* ForceSimpleCall */ false,
3876 /* CheckCancelFlag */ true);
3877 if (!BarrierIP1)
3878 return BarrierIP1.takeError();
3879 BasicBlock *ThenBB = BasicBlock::Create(Ctx, "then");
3880 BasicBlock *ElseBB = BasicBlock::Create(Ctx, "else");
3881 BasicBlock *MergeBB = BasicBlock::Create(Ctx, "ifcont");
3882
3883 // if (lane_id == 0)
3884 Value *IsWarpMaster = Builder.CreateIsNull(LaneID, "warp_master");
3885 Builder.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3886 emitBlock(ThenBB, Builder.GetInsertBlock()->getParent());
3887
3888 // Reduce element = LocalReduceList[i]
3889 auto *RedListArrayTy =
3890 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
3891 Type *IndexTy = Builder.getIndexTy(
3892 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
3893 Value *ElemPtrPtr =
3894 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3895 {ConstantInt::get(IndexTy, 0),
3896 ConstantInt::get(IndexTy, En.index())});
3897 // elemptr = ((CopyType*)(elemptrptr)) + I
3898 Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);
3899
3900 if (IsByRefElem && RI.DataPtrPtrGen) {
3901 InsertPointOrErrorTy GenRes =
3902 RI.DataPtrPtrGen(Builder.saveIP(), ElemPtr, ElemPtr);
3903
3904 if (!GenRes)
3905 return GenRes.takeError();
3906
3907 ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtr);
3908 }
3909
3910 if (NumIters > 1)
3911 ElemPtr = Builder.CreateGEP(Builder.getInt32Ty(), ElemPtr, Cnt);
3912
3913 // Get pointer to location in transfer medium.
3914 // MediumPtr = &medium[warp_id]
3915 Value *MediumPtr = Builder.CreateInBoundsGEP(
3916 ArrayTy, TransferMedium, {Builder.getInt64(0), WarpID});
3917 // elem = *elemptr
3918 //*MediumPtr = elem
3919 Value *Elem = Builder.CreateLoad(CType, ElemPtr);
3920 // Store the source element value to the dest element address.
3921 Builder.CreateStore(Elem, MediumPtr,
3922 /*IsVolatile*/ true);
3923 Builder.CreateBr(MergeBB);
3924
3925 // else
3926 emitBlock(ElseBB, Builder.GetInsertBlock()->getParent());
3927 Builder.CreateBr(MergeBB);
3928
3929 // endif
3930 emitBlock(MergeBB, Builder.GetInsertBlock()->getParent());
3931 InsertPointOrErrorTy BarrierIP2 =
3933 omp::Directive::OMPD_unknown,
3934 /* ForceSimpleCall */ false,
3935 /* CheckCancelFlag */ true);
3936 if (!BarrierIP2)
3937 return BarrierIP2.takeError();
3938
3939 // Warp 0 copies reduce element from transfer medium
3940 BasicBlock *W0ThenBB = BasicBlock::Create(Ctx, "then");
3941 BasicBlock *W0ElseBB = BasicBlock::Create(Ctx, "else");
3942 BasicBlock *W0MergeBB = BasicBlock::Create(Ctx, "ifcont");
3943
3944 Value *NumWarpsVal =
3945 Builder.CreateLoad(Builder.getInt32Ty(), NumWarpsAddrCast);
3946 // Up to 32 threads in warp 0 are active.
3947 Value *IsActiveThread =
3948 Builder.CreateICmpULT(GPUThreadID, NumWarpsVal, "is_active_thread");
3949 Builder.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3950
3951 emitBlock(W0ThenBB, Builder.GetInsertBlock()->getParent());
3952
3953 // SecMediumPtr = &medium[tid]
3954 // SrcMediumVal = *SrcMediumPtr
3955 Value *SrcMediumPtrVal = Builder.CreateInBoundsGEP(
3956 ArrayTy, TransferMedium, {Builder.getInt64(0), GPUThreadID});
3957 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3958 Value *TargetElemPtrPtr =
3959 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3960 {ConstantInt::get(IndexTy, 0),
3961 ConstantInt::get(IndexTy, En.index())});
3962 Value *TargetElemPtrVal =
3963 Builder.CreateLoad(Builder.getPtrTy(), TargetElemPtrPtr);
3964 Value *TargetElemPtr = TargetElemPtrVal;
3965
3966 if (IsByRefElem && RI.DataPtrPtrGen) {
3967 InsertPointOrErrorTy GenRes =
3968 RI.DataPtrPtrGen(Builder.saveIP(), TargetElemPtr, TargetElemPtr);
3969
3970 if (!GenRes)
3971 return GenRes.takeError();
3972
3973 TargetElemPtr = Builder.CreateLoad(Builder.getPtrTy(), TargetElemPtr);
3974 }
3975
3976 if (NumIters > 1)
3977 TargetElemPtr =
3978 Builder.CreateGEP(Builder.getInt32Ty(), TargetElemPtr, Cnt);
3979
3980 // *TargetElemPtr = SrcMediumVal;
3981 Value *SrcMediumValue =
3982 Builder.CreateLoad(CType, SrcMediumPtrVal, /*IsVolatile*/ true);
3983 Builder.CreateStore(SrcMediumValue, TargetElemPtr);
3984 Builder.CreateBr(W0MergeBB);
3985
3986 emitBlock(W0ElseBB, Builder.GetInsertBlock()->getParent());
3987 Builder.CreateBr(W0MergeBB);
3988
3989 emitBlock(W0MergeBB, Builder.GetInsertBlock()->getParent());
3990
3991 if (NumIters > 1) {
3992 Cnt = Builder.CreateNSWAdd(
3993 Cnt, ConstantInt::get(Builder.getInt32Ty(), /*V=*/1));
3994 Builder.CreateStore(Cnt, CntAddr, /*Volatile=*/false);
3995
3996 auto *CurFn = Builder.GetInsertBlock()->getParent();
3997 emitBranch(PrecondBB);
3998 emitBlock(ExitBB, CurFn);
3999 }
4000 RealTySize %= TySize;
4001 }
4002 }
4003
4004 Builder.CreateRetVoid();
4005
4006 return WcFunc;
4007}
4008
4009Expected<Function *> OpenMPIRBuilder::emitShuffleAndReduceFunction(
4010 ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,
4011 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4012 LLVMContext &Ctx = M.getContext();
4013 IRBuilder<>::InsertPointGuard IPG(Builder);
4014 FunctionType *FuncTy =
4015 FunctionType::get(Builder.getVoidTy(),
4016 {Builder.getPtrTy(), Builder.getInt16Ty(),
4017 Builder.getInt16Ty(), Builder.getInt16Ty()},
4018 /* IsVarArg */ false);
4019 Function *SarFunc =
4021 "_omp_reduction_shuffle_and_reduce_func", &M);
4022 SarFunc->setCallingConv(Config.getRuntimeCC());
4023 SarFunc->setAttributes(FuncAttrs);
4024 SarFunc->addParamAttr(0, Attribute::NoUndef);
4025 SarFunc->addParamAttr(1, Attribute::NoUndef);
4026 SarFunc->addParamAttr(2, Attribute::NoUndef);
4027 SarFunc->addParamAttr(3, Attribute::NoUndef);
4028 SarFunc->addParamAttr(1, Attribute::SExt);
4029 SarFunc->addParamAttr(2, Attribute::SExt);
4030 SarFunc->addParamAttr(3, Attribute::SExt);
4031 BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", SarFunc);
4032 Builder.SetInsertPoint(EntryBB);
4033 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4034
4035 // Thread local Reduce list used to host the values of data to be reduced.
4036 Argument *ReduceListArg = SarFunc->getArg(0);
4037 // Current lane id; could be logical.
4038 Argument *LaneIDArg = SarFunc->getArg(1);
4039 // Offset of the remote source lane relative to the current lane.
4040 Argument *RemoteLaneOffsetArg = SarFunc->getArg(2);
4041 // Algorithm version. This is expected to be known at compile time.
4042 Argument *AlgoVerArg = SarFunc->getArg(3);
4043
4044 Type *ReduceListArgType = ReduceListArg->getType();
4045 Type *LaneIDArgType = LaneIDArg->getType();
4046 Type *LaneIDArgPtrType = Builder.getPtrTy(0);
4047 Value *ReduceListAlloca = Builder.CreateAlloca(
4048 ReduceListArgType, nullptr, ReduceListArg->getName() + ".addr");
4049 Value *LaneIdAlloca = Builder.CreateAlloca(LaneIDArgType, nullptr,
4050 LaneIDArg->getName() + ".addr");
4051 Value *RemoteLaneOffsetAlloca = Builder.CreateAlloca(
4052 LaneIDArgType, nullptr, RemoteLaneOffsetArg->getName() + ".addr");
4053 Value *AlgoVerAlloca = Builder.CreateAlloca(LaneIDArgType, nullptr,
4054 AlgoVerArg->getName() + ".addr");
4055 ArrayType *RedListArrayTy =
4056 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4057
4058 // Create a local thread-private variable to host the Reduce list
4059 // from a remote lane.
4060 Instruction *RemoteReductionListAlloca = Builder.CreateAlloca(
4061 RedListArrayTy, nullptr, ".omp.reduction.remote_reduce_list");
4062
4063 Value *ReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4064 ReduceListAlloca, ReduceListArgType,
4065 ReduceListAlloca->getName() + ".ascast");
4066 Value *LaneIdAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4067 LaneIdAlloca, LaneIDArgPtrType, LaneIdAlloca->getName() + ".ascast");
4068 Value *RemoteLaneOffsetAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4069 RemoteLaneOffsetAlloca, LaneIDArgPtrType,
4070 RemoteLaneOffsetAlloca->getName() + ".ascast");
4071 Value *AlgoVerAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4072 AlgoVerAlloca, LaneIDArgPtrType, AlgoVerAlloca->getName() + ".ascast");
4073 Value *RemoteListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4074 RemoteReductionListAlloca, Builder.getPtrTy(),
4075 RemoteReductionListAlloca->getName() + ".ascast");
4076
4077 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
4078 Builder.CreateStore(LaneIDArg, LaneIdAddrCast);
4079 Builder.CreateStore(RemoteLaneOffsetArg, RemoteLaneOffsetAddrCast);
4080 Builder.CreateStore(AlgoVerArg, AlgoVerAddrCast);
4081
4082 Value *ReduceList = Builder.CreateLoad(ReduceListArgType, ReduceListAddrCast);
4083 Value *LaneId = Builder.CreateLoad(LaneIDArgType, LaneIdAddrCast);
4084 Value *RemoteLaneOffset =
4085 Builder.CreateLoad(LaneIDArgType, RemoteLaneOffsetAddrCast);
4086 Value *AlgoVer = Builder.CreateLoad(LaneIDArgType, AlgoVerAddrCast);
4087
4088 InsertPointTy AllocaIP = getInsertPointAfterInstr(RemoteReductionListAlloca);
4089
4090 // This loop iterates through the list of reduce elements and copies,
4091 // element by element, from a remote lane in the warp to RemoteReduceList,
4092 // hosted on the thread's stack.
4093 Error EmitRedLsCpRes = emitReductionListCopy(
4094 AllocaIP, CopyAction::RemoteLaneToThread, RedListArrayTy, ReductionInfos,
4095 ReduceList, RemoteListAddrCast, IsByRef,
4096 {RemoteLaneOffset, nullptr, nullptr});
4097
4098 if (EmitRedLsCpRes)
4099 return EmitRedLsCpRes;
4100
4101 // The actions to be performed on the Remote Reduce list is dependent
4102 // on the algorithm version.
4103 //
4104 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
4105 // LaneId % 2 == 0 && Offset > 0):
4106 // do the reduction value aggregation
4107 //
4108 // The thread local variable Reduce list is mutated in place to host the
4109 // reduced data, which is the aggregated value produced from local and
4110 // remote lanes.
4111 //
4112 // Note that AlgoVer is expected to be a constant integer known at compile
4113 // time.
4114 // When AlgoVer==0, the first conjunction evaluates to true, making
4115 // the entire predicate true during compile time.
4116 // When AlgoVer==1, the second conjunction has only the second part to be
4117 // evaluated during runtime. Other conjunctions evaluates to false
4118 // during compile time.
4119 // When AlgoVer==2, the third conjunction has only the second part to be
4120 // evaluated during runtime. Other conjunctions evaluates to false
4121 // during compile time.
4122 Value *CondAlgo0 = Builder.CreateIsNull(AlgoVer);
4123 Value *Algo1 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(1));
4124 Value *LaneComp = Builder.CreateICmpULT(LaneId, RemoteLaneOffset);
4125 Value *CondAlgo1 = Builder.CreateAnd(Algo1, LaneComp);
4126 Value *Algo2 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(2));
4127 Value *LaneIdAnd1 = Builder.CreateAnd(LaneId, Builder.getInt16(1));
4128 Value *LaneIdComp = Builder.CreateIsNull(LaneIdAnd1);
4129 Value *Algo2AndLaneIdComp = Builder.CreateAnd(Algo2, LaneIdComp);
4130 Value *RemoteOffsetComp =
4131 Builder.CreateICmpSGT(RemoteLaneOffset, Builder.getInt16(0));
4132 Value *CondAlgo2 = Builder.CreateAnd(Algo2AndLaneIdComp, RemoteOffsetComp);
4133 Value *CA0OrCA1 = Builder.CreateOr(CondAlgo0, CondAlgo1);
4134 Value *CondReduce = Builder.CreateOr(CA0OrCA1, CondAlgo2);
4135
4136 BasicBlock *ThenBB = BasicBlock::Create(Ctx, "then");
4137 BasicBlock *ElseBB = BasicBlock::Create(Ctx, "else");
4138 BasicBlock *MergeBB = BasicBlock::Create(Ctx, "ifcont");
4139
4140 Builder.CreateCondBr(CondReduce, ThenBB, ElseBB);
4141 emitBlock(ThenBB, Builder.GetInsertBlock()->getParent());
4142 Value *LocalReduceListPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4143 ReduceList, Builder.getPtrTy());
4144 Value *RemoteReduceListPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4145 RemoteListAddrCast, Builder.getPtrTy());
4146 createRuntimeFunctionCall(ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr})
4147 ->addFnAttr(Attribute::NoUnwind);
4148 Builder.CreateBr(MergeBB);
4149
4150 emitBlock(ElseBB, Builder.GetInsertBlock()->getParent());
4151 Builder.CreateBr(MergeBB);
4152
4153 emitBlock(MergeBB, Builder.GetInsertBlock()->getParent());
4154
4155 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
4156 // Reduce list.
4157 Algo1 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(1));
4158 Value *LaneIdGtOffset = Builder.CreateICmpUGE(LaneId, RemoteLaneOffset);
4159 Value *CondCopy = Builder.CreateAnd(Algo1, LaneIdGtOffset);
4160
4161 BasicBlock *CpyThenBB = BasicBlock::Create(Ctx, "then");
4162 BasicBlock *CpyElseBB = BasicBlock::Create(Ctx, "else");
4163 BasicBlock *CpyMergeBB = BasicBlock::Create(Ctx, "ifcont");
4164 Builder.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
4165
4166 emitBlock(CpyThenBB, Builder.GetInsertBlock()->getParent());
4167
4168 EmitRedLsCpRes = emitReductionListCopy(
4169 AllocaIP, CopyAction::ThreadCopy, RedListArrayTy, ReductionInfos,
4170 RemoteListAddrCast, ReduceList, IsByRef);
4171
4172 if (EmitRedLsCpRes)
4173 return EmitRedLsCpRes;
4174
4175 Builder.CreateBr(CpyMergeBB);
4176
4177 emitBlock(CpyElseBB, Builder.GetInsertBlock()->getParent());
4178 Builder.CreateBr(CpyMergeBB);
4179
4180 emitBlock(CpyMergeBB, Builder.GetInsertBlock()->getParent());
4181
4182 Builder.CreateRetVoid();
4183
4184 return SarFunc;
4185}
4186
4188OpenMPIRBuilder::generateReductionDescriptor(
4189 Value *DescriptorAddr, Value *DataPtr, Value *SrcDescriptorAddr,
4190 Type *DescriptorType,
4191 function_ref<InsertPointOrErrorTy(InsertPointTy, Value *, Value *&)>
4192 DataPtrPtrGen) {
4193
4194 // Copy the source descriptor to preserve all metadata (rank, extents,
4195 // strides, etc.)
4196 Value *DescriptorSize =
4197 Builder.getInt64(M.getDataLayout().getTypeStoreSize(DescriptorType));
4198 Builder.CreateMemCpy(
4199 DescriptorAddr, M.getDataLayout().getPrefTypeAlign(DescriptorType),
4200 SrcDescriptorAddr, M.getDataLayout().getPrefTypeAlign(DescriptorType),
4201 DescriptorSize);
4202
4203 // Update the base pointer field to point to the local shuffled data
4204 Value *DataPtrField;
4205 InsertPointOrErrorTy GenResult =
4206 DataPtrPtrGen(Builder.saveIP(), DescriptorAddr, DataPtrField);
4207
4208 if (!GenResult)
4209 return GenResult.takeError();
4210
4211 Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
4212 DataPtr, Builder.getPtrTy(), ".ascast"),
4213 DataPtrField);
4214
4215 return Builder.saveIP();
4216}
4217
4218Expected<Value *> OpenMPIRBuilder::createReductionDescriptorCopy(
4219 InsertPointTy AllocaIP, const ReductionInfo &RI, Value *DataPtr,
4220 Value *SrcDescriptorAddr, Type *DescriptorPtrTy, const Twine &Name) {
4221 InsertPointTy OldIP = Builder.saveIP();
4222 Builder.restoreIP(AllocaIP);
4223
4224 AllocaInst *DescriptorAlloca =
4225 Builder.CreateAlloca(RI.ByRefAllocatedType, nullptr, Name);
4226 DescriptorAlloca->setAlignment(
4227 M.getDataLayout().getPrefTypeAlign(RI.ByRefAllocatedType));
4228 Value *DescriptorAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4229 DescriptorAlloca, DescriptorPtrTy,
4230 DescriptorAlloca->getName() + ".ascast");
4231
4232 Builder.restoreIP(OldIP);
4233
4234 InsertPointOrErrorTy GenResult =
4235 generateReductionDescriptor(DescriptorAddr, DataPtr, SrcDescriptorAddr,
4236 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
4237 if (!GenResult)
4238 return GenResult.takeError();
4239
4240 return DescriptorAddr;
4241}
4242
4243Expected<Function *> OpenMPIRBuilder::emitListToGlobalCopyFunction(
4244 ArrayRef<ReductionInfo> ReductionInfos, Type *ReductionsBufferTy,
4245 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4246 IRBuilder<>::InsertPointGuard IPG(Builder);
4247 LLVMContext &Ctx = M.getContext();
4248 FunctionType *FuncTy = FunctionType::get(
4249 Builder.getVoidTy(),
4250 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4251 /* IsVarArg */ false);
4252 Function *LtGCFunc =
4254 "_omp_reduction_list_to_global_copy_func", &M);
4255 LtGCFunc->setAttributes(FuncAttrs);
4256 LtGCFunc->addParamAttr(0, Attribute::NoUndef);
4257 LtGCFunc->addParamAttr(1, Attribute::NoUndef);
4258 LtGCFunc->addParamAttr(2, Attribute::NoUndef);
4259
4260 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGCFunc);
4261 Builder.SetInsertPoint(EntryBlock);
4262 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4263
4264 // Buffer: global reduction buffer.
4265 Argument *BufferArg = LtGCFunc->getArg(0);
4266 // Idx: index of the buffer.
4267 Argument *IdxArg = LtGCFunc->getArg(1);
4268 // ReduceList: thread local Reduce list.
4269 Argument *ReduceListArg = LtGCFunc->getArg(2);
4270
4271 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4272 BufferArg->getName() + ".addr");
4273 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4274 IdxArg->getName() + ".addr");
4275 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4276 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4277 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4278 BufferArgAlloca, Builder.getPtrTy(),
4279 BufferArgAlloca->getName() + ".ascast");
4280 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4281 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4282 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4283 ReduceListArgAlloca, Builder.getPtrTy(),
4284 ReduceListArgAlloca->getName() + ".ascast");
4285
4286 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4287 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4288 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4289
4290 Value *LocalReduceList =
4291 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4292 Value *BufferArgVal =
4293 Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4294 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4295 Type *IndexTy = Builder.getIndexTy(
4296 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4297 for (auto En : enumerate(ReductionInfos)) {
4298 const ReductionInfo &RI = En.value();
4299 auto *RedListArrayTy =
4300 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4301 // Reduce element = LocalReduceList[i]
4302 Value *ElemPtrPtr = Builder.CreateInBoundsGEP(
4303 RedListArrayTy, LocalReduceList,
4304 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4305 // elemptr = ((CopyType*)(elemptrptr)) + I
4306 Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);
4307
4308 // Global = Buffer.VD[Idx];
4309 Value *BufferVD =
4310 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferArgVal, Idxs);
4311 Value *GlobVal = Builder.CreateConstInBoundsGEP2_32(
4312 ReductionsBufferTy, BufferVD, 0, En.index());
4313
4314 switch (RI.EvaluationKind) {
4315 case EvalKind::Scalar: {
4316 Value *TargetElement;
4317
4318 if (IsByRef.empty() || !IsByRef[En.index()]) {
4319 TargetElement = Builder.CreateLoad(RI.ElementType, ElemPtr);
4320 } else {
4321 if (RI.DataPtrPtrGen) {
4322 InsertPointOrErrorTy GenResult =
4323 RI.DataPtrPtrGen(Builder.saveIP(), ElemPtr, ElemPtr);
4324
4325 if (!GenResult)
4326 return GenResult.takeError();
4327
4328 ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtr);
4329 }
4330 TargetElement = Builder.CreateLoad(RI.ByRefElementType, ElemPtr);
4331 }
4332
4333 Builder.CreateStore(TargetElement, GlobVal);
4334 break;
4335 }
4336 case EvalKind::Complex: {
4337 Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(
4338 RI.ElementType, ElemPtr, 0, 0, ".realp");
4339 Value *SrcReal = Builder.CreateLoad(
4340 RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");
4341 Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(
4342 RI.ElementType, ElemPtr, 0, 1, ".imagp");
4343 Value *SrcImg = Builder.CreateLoad(
4344 RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");
4345
4346 Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(
4347 RI.ElementType, GlobVal, 0, 0, ".realp");
4348 Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(
4349 RI.ElementType, GlobVal, 0, 1, ".imagp");
4350 Builder.CreateStore(SrcReal, DestRealPtr);
4351 Builder.CreateStore(SrcImg, DestImgPtr);
4352 break;
4353 }
4354 case EvalKind::Aggregate: {
4355 Value *SizeVal =
4356 Builder.getInt64(M.getDataLayout().getTypeStoreSize(RI.ElementType));
4357 Builder.CreateMemCpy(
4358 GlobVal, M.getDataLayout().getPrefTypeAlign(RI.ElementType), ElemPtr,
4359 M.getDataLayout().getPrefTypeAlign(RI.ElementType), SizeVal, false);
4360 break;
4361 }
4362 }
4363 }
4364
4365 Builder.CreateRetVoid();
4366 return LtGCFunc;
4367}
4368
4369Expected<Function *> OpenMPIRBuilder::emitListToGlobalReduceFunction(
4370 ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,
4371 Type *ReductionsBufferTy, AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4372 IRBuilder<>::InsertPointGuard IPG(Builder);
4373 LLVMContext &Ctx = M.getContext();
4374 FunctionType *FuncTy = FunctionType::get(
4375 Builder.getVoidTy(),
4376 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4377 /* IsVarArg */ false);
4378 Function *LtGRFunc =
4380 "_omp_reduction_list_to_global_reduce_func", &M);
4381 LtGRFunc->setAttributes(FuncAttrs);
4382 LtGRFunc->addParamAttr(0, Attribute::NoUndef);
4383 LtGRFunc->addParamAttr(1, Attribute::NoUndef);
4384 LtGRFunc->addParamAttr(2, Attribute::NoUndef);
4385
4386 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGRFunc);
4387 Builder.SetInsertPoint(EntryBlock);
4388 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4389
4390 // Buffer: global reduction buffer.
4391 Argument *BufferArg = LtGRFunc->getArg(0);
4392 // Idx: index of the buffer.
4393 Argument *IdxArg = LtGRFunc->getArg(1);
4394 // ReduceList: thread local Reduce list.
4395 Argument *ReduceListArg = LtGRFunc->getArg(2);
4396
4397 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4398 BufferArg->getName() + ".addr");
4399 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4400 IdxArg->getName() + ".addr");
4401 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4402 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4403 auto *RedListArrayTy =
4404 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4405
4406 // 1. Build a list of reduction variables.
4407 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4408 Value *LocalReduceList =
4409 Builder.CreateAlloca(RedListArrayTy, nullptr, ".omp.reduction.red_list");
4410
4411 InsertPointTy AllocaIP(EntryBlock->begin());
4412
4413 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4414 BufferArgAlloca, Builder.getPtrTy(),
4415 BufferArgAlloca->getName() + ".ascast");
4416 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4417 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4418 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4419 ReduceListArgAlloca, Builder.getPtrTy(),
4420 ReduceListArgAlloca->getName() + ".ascast");
4421 Value *LocalReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4422 LocalReduceList, Builder.getPtrTy(),
4423 LocalReduceList->getName() + ".ascast");
4424
4425 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4426 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4427 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4428
4429 Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4430 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4431 Type *IndexTy = Builder.getIndexTy(
4432 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4433 for (auto En : enumerate(ReductionInfos)) {
4434 const ReductionInfo &RI = En.value();
4435
4436 Value *TargetElementPtrPtr = Builder.CreateInBoundsGEP(
4437 RedListArrayTy, LocalReduceListAddrCast,
4438 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4439 Value *BufferVD =
4440 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4441 // Global = Buffer.VD[Idx];
4442 Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(
4443 ReductionsBufferTy, BufferVD, 0, En.index());
4444
4445 if (!IsByRef.empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4446 // Get source descriptor from the reduce list argument
4447 Value *ReduceList =
4448 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4449 Value *SrcElementPtrPtr =
4450 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
4451 {ConstantInt::get(IndexTy, 0),
4452 ConstantInt::get(IndexTy, En.index())});
4453 Value *SrcDescriptorAddr =
4454 Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrPtr);
4455
4456 // Copy descriptor from source and update base_ptr to global buffer data
4457 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4458 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr, Builder.getPtrTy());
4459 if (!ByRefAlloc)
4460 return ByRefAlloc.takeError();
4461
4462 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4463 } else {
4464 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4465 }
4466 }
4467
4468 // Call reduce_function(GlobalReduceList, ReduceList)
4469 Value *ReduceList =
4470 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4471 createRuntimeFunctionCall(ReduceFn, {LocalReduceListAddrCast, ReduceList})
4472 ->addFnAttr(Attribute::NoUnwind);
4473 Builder.CreateRetVoid();
4474 return LtGRFunc;
4475}
4476
4477Expected<Function *> OpenMPIRBuilder::emitGlobalToListCopyFunction(
4478 ArrayRef<ReductionInfo> ReductionInfos, Type *ReductionsBufferTy,
4479 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4480 IRBuilder<>::InsertPointGuard IPG(Builder);
4481 LLVMContext &Ctx = M.getContext();
4482 FunctionType *FuncTy = FunctionType::get(
4483 Builder.getVoidTy(),
4484 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4485 /* IsVarArg */ false);
4486 Function *GtLCFunc =
4488 "_omp_reduction_global_to_list_copy_func", &M);
4489 GtLCFunc->setAttributes(FuncAttrs);
4490 GtLCFunc->addParamAttr(0, Attribute::NoUndef);
4491 GtLCFunc->addParamAttr(1, Attribute::NoUndef);
4492 GtLCFunc->addParamAttr(2, Attribute::NoUndef);
4493
4494 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", GtLCFunc);
4495 Builder.SetInsertPoint(EntryBlock);
4496 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4497
4498 // Buffer: global reduction buffer.
4499 Argument *BufferArg = GtLCFunc->getArg(0);
4500 // Idx: index of the buffer.
4501 Argument *IdxArg = GtLCFunc->getArg(1);
4502 // ReduceList: thread local Reduce list.
4503 Argument *ReduceListArg = GtLCFunc->getArg(2);
4504
4505 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4506 BufferArg->getName() + ".addr");
4507 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4508 IdxArg->getName() + ".addr");
4509 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4510 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4511 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4512 BufferArgAlloca, Builder.getPtrTy(),
4513 BufferArgAlloca->getName() + ".ascast");
4514 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4515 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4516 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4517 ReduceListArgAlloca, Builder.getPtrTy(),
4518 ReduceListArgAlloca->getName() + ".ascast");
4519 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4520 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4521 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4522
4523 Value *LocalReduceList =
4524 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4525 Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4526 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4527 Type *IndexTy = Builder.getIndexTy(
4528 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4529 for (auto En : enumerate(ReductionInfos)) {
4530 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
4531 auto *RedListArrayTy =
4532 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4533 // Reduce element = LocalReduceList[i]
4534 Value *ElemPtrPtr = Builder.CreateInBoundsGEP(
4535 RedListArrayTy, LocalReduceList,
4536 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4537 // elemptr = ((CopyType*)(elemptrptr)) + I
4538 Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);
4539 // Global = Buffer.VD[Idx];
4540 Value *BufferVD =
4541 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4542 Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(
4543 ReductionsBufferTy, BufferVD, 0, En.index());
4544
4545 switch (RI.EvaluationKind) {
4546 case EvalKind::Scalar: {
4547 Type *ElemType = RI.ElementType;
4548
4549 if (!IsByRef.empty() && IsByRef[En.index()]) {
4550 ElemType = RI.ByRefElementType;
4551 if (RI.DataPtrPtrGen) {
4552 InsertPointOrErrorTy GenResult =
4553 RI.DataPtrPtrGen(Builder.saveIP(), ElemPtr, ElemPtr);
4554
4555 if (!GenResult)
4556 return GenResult.takeError();
4557
4558 ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtr);
4559 }
4560 }
4561
4562 Value *TargetElement = Builder.CreateLoad(ElemType, GlobValPtr);
4563 Builder.CreateStore(TargetElement, ElemPtr);
4564 break;
4565 }
4566 case EvalKind::Complex: {
4567 Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(
4568 RI.ElementType, GlobValPtr, 0, 0, ".realp");
4569 Value *SrcReal = Builder.CreateLoad(
4570 RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");
4571 Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(
4572 RI.ElementType, GlobValPtr, 0, 1, ".imagp");
4573 Value *SrcImg = Builder.CreateLoad(
4574 RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");
4575
4576 Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(
4577 RI.ElementType, ElemPtr, 0, 0, ".realp");
4578 Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(
4579 RI.ElementType, ElemPtr, 0, 1, ".imagp");
4580 Builder.CreateStore(SrcReal, DestRealPtr);
4581 Builder.CreateStore(SrcImg, DestImgPtr);
4582 break;
4583 }
4584 case EvalKind::Aggregate: {
4585 Value *SizeVal =
4586 Builder.getInt64(M.getDataLayout().getTypeStoreSize(RI.ElementType));
4587 Builder.CreateMemCpy(
4588 ElemPtr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
4589 GlobValPtr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
4590 SizeVal, false);
4591 break;
4592 }
4593 }
4594 }
4595
4596 Builder.CreateRetVoid();
4597 return GtLCFunc;
4598}
4599
4600Expected<Function *> OpenMPIRBuilder::emitGlobalToListReduceFunction(
4601 ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,
4602 Type *ReductionsBufferTy, AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4603 IRBuilder<>::InsertPointGuard IPG(Builder);
4604 LLVMContext &Ctx = M.getContext();
4605 auto *FuncTy = FunctionType::get(
4606 Builder.getVoidTy(),
4607 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4608 /* IsVarArg */ false);
4609 Function *GtLRFunc =
4611 "_omp_reduction_global_to_list_reduce_func", &M);
4612 GtLRFunc->setAttributes(FuncAttrs);
4613 GtLRFunc->addParamAttr(0, Attribute::NoUndef);
4614 GtLRFunc->addParamAttr(1, Attribute::NoUndef);
4615 GtLRFunc->addParamAttr(2, Attribute::NoUndef);
4616
4617 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", GtLRFunc);
4618 Builder.SetInsertPoint(EntryBlock);
4619 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4620
4621 // Buffer: global reduction buffer.
4622 Argument *BufferArg = GtLRFunc->getArg(0);
4623 // Idx: index of the buffer.
4624 Argument *IdxArg = GtLRFunc->getArg(1);
4625 // ReduceList: thread local Reduce list.
4626 Argument *ReduceListArg = GtLRFunc->getArg(2);
4627
4628 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4629 BufferArg->getName() + ".addr");
4630 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4631 IdxArg->getName() + ".addr");
4632 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4633 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4634 ArrayType *RedListArrayTy =
4635 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4636
4637 // 1. Build a list of reduction variables.
4638 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4639 Value *LocalReduceList =
4640 Builder.CreateAlloca(RedListArrayTy, nullptr, ".omp.reduction.red_list");
4641
4642 InsertPointTy AllocaIP(EntryBlock->begin());
4643
4644 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4645 BufferArgAlloca, Builder.getPtrTy(),
4646 BufferArgAlloca->getName() + ".ascast");
4647 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4648 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4649 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4650 ReduceListArgAlloca, Builder.getPtrTy(),
4651 ReduceListArgAlloca->getName() + ".ascast");
4652 Value *ReductionList = Builder.CreatePointerBitCastOrAddrSpaceCast(
4653 LocalReduceList, Builder.getPtrTy(),
4654 LocalReduceList->getName() + ".ascast");
4655
4656 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4657 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4658 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4659
4660 Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4661 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4662 Type *IndexTy = Builder.getIndexTy(
4663 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4664 for (auto En : enumerate(ReductionInfos)) {
4665 const ReductionInfo &RI = En.value();
4666
4667 Value *TargetElementPtrPtr = Builder.CreateInBoundsGEP(
4668 RedListArrayTy, ReductionList,
4669 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4670 // Global = Buffer.VD[Idx];
4671 Value *BufferVD =
4672 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4673 Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(
4674 ReductionsBufferTy, BufferVD, 0, En.index());
4675
4676 if (!IsByRef.empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4677 // Get source descriptor from the reduce list
4678 Value *ReduceListVal =
4679 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4680 Value *SrcElementPtrPtr =
4681 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceListVal,
4682 {ConstantInt::get(IndexTy, 0),
4683 ConstantInt::get(IndexTy, En.index())});
4684 Value *SrcDescriptorAddr =
4685 Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrPtr);
4686
4687 // Copy descriptor from source and update base_ptr to global buffer data
4688 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4689 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr, Builder.getPtrTy());
4690 if (!ByRefAlloc)
4691 return ByRefAlloc.takeError();
4692
4693 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4694 } else {
4695 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4696 }
4697 }
4698
4699 // Call reduce_function(ReduceList, GlobalReduceList)
4700 Value *ReduceList =
4701 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4702 createRuntimeFunctionCall(ReduceFn, {ReduceList, ReductionList})
4703 ->addFnAttr(Attribute::NoUnwind);
4704 Builder.CreateRetVoid();
4705 return GtLRFunc;
4706}
4707
4708std::string OpenMPIRBuilder::getReductionFuncName(StringRef Name) const {
4709 std::string Suffix =
4710 createPlatformSpecificName({"omp", "reduction", "reduction_func"});
4711 return (Name + Suffix).str();
4712}
4713
4714Expected<Function *> OpenMPIRBuilder::createReductionFunction(
4715 StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,
4717 AttributeList FuncAttrs) {
4718 IRBuilder<>::InsertPointGuard IPG(Builder);
4719 auto *FuncTy = FunctionType::get(Builder.getVoidTy(),
4720 {Builder.getPtrTy(), Builder.getPtrTy()},
4721 /* IsVarArg */ false);
4722 std::string Name = getReductionFuncName(ReducerName);
4723 Function *ReductionFunc =
4725 ReductionFunc->setCallingConv(Config.getRuntimeCC());
4726 ReductionFunc->setAttributes(FuncAttrs);
4727 ReductionFunc->addParamAttr(0, Attribute::NoUndef);
4728 ReductionFunc->addParamAttr(1, Attribute::NoUndef);
4729 BasicBlock *EntryBB =
4730 BasicBlock::Create(M.getContext(), "entry", ReductionFunc);
4731 Builder.SetInsertPoint(EntryBB);
4732 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4733
4734 // Need to alloca memory here and deal with the pointers before getting
4735 // LHS/RHS pointers out
4736 Value *LHSArrayPtr = nullptr;
4737 Value *RHSArrayPtr = nullptr;
4738 Argument *Arg0 = ReductionFunc->getArg(0);
4739 Argument *Arg1 = ReductionFunc->getArg(1);
4740 Type *Arg0Type = Arg0->getType();
4741 Type *Arg1Type = Arg1->getType();
4742
4743 Value *LHSAlloca =
4744 Builder.CreateAlloca(Arg0Type, nullptr, Arg0->getName() + ".addr");
4745 Value *RHSAlloca =
4746 Builder.CreateAlloca(Arg1Type, nullptr, Arg1->getName() + ".addr");
4747 Value *LHSAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4748 LHSAlloca, Arg0Type, LHSAlloca->getName() + ".ascast");
4749 Value *RHSAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4750 RHSAlloca, Arg1Type, RHSAlloca->getName() + ".ascast");
4751 Builder.CreateStore(Arg0, LHSAddrCast);
4752 Builder.CreateStore(Arg1, RHSAddrCast);
4753 LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);
4754 RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);
4755
4756 Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4757 Type *IndexTy = Builder.getIndexTy(
4758 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4759 SmallVector<Value *> LHSPtrs, RHSPtrs;
4760 for (auto En : enumerate(ReductionInfos)) {
4761 const ReductionInfo &RI = En.value();
4762 Value *RHSI8PtrPtr = Builder.CreateInBoundsGEP(
4763 RedArrayTy, RHSArrayPtr,
4764 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4765 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);
4766 Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4767 RHSI8Ptr, RI.PrivateVariable->getType(),
4768 RHSI8Ptr->getName() + ".ascast");
4769
4770 Value *LHSI8PtrPtr = Builder.CreateInBoundsGEP(
4771 RedArrayTy, LHSArrayPtr,
4772 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4773 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);
4774 Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4775 LHSI8Ptr, RI.Variable->getType(), LHSI8Ptr->getName() + ".ascast");
4776
4778 LHSPtrs.emplace_back(LHSPtr);
4779 RHSPtrs.emplace_back(RHSPtr);
4780 } else {
4781 Value *LHS = LHSPtr;
4782 Value *RHS = RHSPtr;
4783
4784 if (!IsByRef.empty() && !IsByRef[En.index()]) {
4785 LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
4786 RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
4787 }
4788
4789 Value *Reduced;
4790 InsertPointOrErrorTy AfterIP =
4791 RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced);
4792 if (!AfterIP)
4793 return AfterIP.takeError();
4794 if (!Builder.GetInsertBlock())
4795 return ReductionFunc;
4796
4797 Builder.restoreIP(*AfterIP);
4798
4799 if (!IsByRef.empty() && !IsByRef[En.index()])
4800 Builder.CreateStore(Reduced, LHSPtr);
4801 }
4802 }
4803
4805 for (auto En : enumerate(ReductionInfos)) {
4806 unsigned Index = En.index();
4807 const ReductionInfo &RI = En.value();
4808 Value *LHSFixupPtr, *RHSFixupPtr;
4809 Builder.restoreIP(RI.ReductionGenClang(
4810 Builder.saveIP(), Index, &LHSFixupPtr, &RHSFixupPtr, ReductionFunc));
4811
4812 // Fix the CallBack code genereated to use the correct Values for the LHS
4813 // and RHS
4814 LHSFixupPtr->replaceUsesWithIf(
4815 LHSPtrs[Index], [ReductionFunc](const Use &U) {
4816 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
4817 ReductionFunc;
4818 });
4819 RHSFixupPtr->replaceUsesWithIf(
4820 RHSPtrs[Index], [ReductionFunc](const Use &U) {
4821 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
4822 ReductionFunc;
4823 });
4824 }
4825
4826 Builder.CreateRetVoid();
4827 // Compiling with `-O0`, `alloca`s emitted in non-entry blocks are not hoisted
4828 // to the entry block (this is dones for higher opt levels by later passes in
4829 // the pipeline). This has caused issues because non-entry `alloca`s force the
4830 // function to use dynamic stack allocations and we might run out of scratch
4831 // memory.
4832 hoistNonEntryAllocasToEntryBlock(ReductionFunc);
4833
4834 return ReductionFunc;
4835}
4836
4837static void
4839 bool IsGPU) {
4840 for (const OpenMPIRBuilder::ReductionInfo &RI : ReductionInfos) {
4841 (void)RI;
4842 assert(RI.Variable && "expected non-null variable");
4843 assert(RI.PrivateVariable && "expected non-null private variable");
4844 assert((RI.ReductionGen || RI.ReductionGenClang) &&
4845 "expected non-null reduction generator callback");
4846 if (!IsGPU) {
4847 assert(
4848 RI.Variable->getType() == RI.PrivateVariable->getType() &&
4849 "expected variables and their private equivalents to have the same "
4850 "type");
4851 }
4852 assert(RI.Variable->getType()->isPointerTy() &&
4853 "expected variables to be pointers");
4854 }
4855}
4856
4857// The atomic cross-team reduction fast path applies when every reduction in the
4858// set can be represented by an atomicrmw. Clang only populates it for scalar
4859// reductions with a supported atomic operator.
4862 return all_of(ReductionInfos, [](const OpenMPIRBuilder::ReductionInfo &RI) {
4863 return static_cast<bool>(RI.AtomicReductionGen);
4864 });
4865}
4866
4868 const LocationDescription &Loc, InsertPointTy AllocaIP,
4869 InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,
4870 ArrayRef<bool> IsByRef, bool IsNoWait, bool IsTeamsReduction, bool IsSPMD,
4871 ReductionGenCBKind ReductionGenCBKind, std::optional<omp::GV> GridValue,
4872 Value *SrcLocInfo) {
4873 if (!updateToLocation(Loc))
4874 return InsertPointTy();
4875 Builder.restoreIP(CodeGenIP);
4876 Builder.SetCurrentDebugLocation(Loc.DL);
4877 checkReductionInfos(ReductionInfos, /*IsGPU*/ true);
4878 LLVMContext &Ctx = M.getContext();
4879
4880 // Source location for the ident struct
4881 if (!SrcLocInfo) {
4882 uint32_t SrcLocStrSize;
4883 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4884 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4885 }
4886
4887 if (ReductionInfos.size() == 0)
4888 return Builder.saveIP();
4889
4890 BasicBlock *ContinuationBlock = nullptr;
4892 // Copied code from createReductions
4893 BasicBlock *InsertBlock = Loc.IP.getNodeParent();
4894 ContinuationBlock = InsertBlock->splitBasicBlock(Loc.IP, "reduce.finalize");
4895 InsertBlock->getTerminator()->eraseFromParent();
4896 Builder.SetInsertPoint(InsertBlock->end());
4897 }
4898
4899 Function *CurFunc = Builder.GetInsertBlock()->getParent();
4900 AttributeList FuncAttrs;
4901 AttrBuilder AttrBldr(Ctx);
4902 for (auto Attr : CurFunc->getAttributes().getFnAttrs())
4903 AttrBldr.addAttribute(Attr);
4904 AttrBldr.removeAttribute(Attribute::OptimizeNone);
4905 FuncAttrs = FuncAttrs.addFnAttributes(Ctx, AttrBldr);
4906
4907 Expected<Function *> ReductionResult = createReductionFunction(
4908 Builder.GetInsertBlock()->getParent()->getName(), ReductionInfos, IsByRef,
4909 ReductionGenCBKind, FuncAttrs);
4910 if (!ReductionResult)
4911 return ReductionResult.takeError();
4912 Function *ReductionFunc = *ReductionResult;
4913
4914 // Set the grid value in the config needed for lowering later on
4915 if (GridValue.has_value())
4916 Config.setGridValue(GridValue.value());
4917 else
4918 Config.setGridValue(getGridValue(T, ReductionFunc));
4919
4920 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
4921 // RedList, shuffle_reduce_func, interwarp_copy_func);
4922 // or
4923 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
4924 Value *Res;
4925
4926 // 1. Build a list of reduction variables.
4927 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4928 auto Size = ReductionInfos.size();
4929 Type *PtrTy = PointerType::get(Ctx, Config.getDefaultTargetAS());
4930 Type *FuncPtrTy =
4931 Builder.getPtrTy(M.getDataLayout().getProgramAddressSpace());
4932 Type *RedArrayTy = ArrayType::get(PtrTy, Size);
4933 Value *ReductionList;
4934 {
4936 Builder.restoreIP(AllocaIP);
4937 Value *ReductionListAlloca =
4938 Builder.CreateAlloca(RedArrayTy, nullptr, ".omp.reduction.red_list");
4939 ReductionList = Builder.CreatePointerBitCastOrAddrSpaceCast(
4940 ReductionListAlloca, PtrTy, ReductionListAlloca->getName() + ".ascast");
4941 }
4942 Type *IndexTy = Builder.getIndexTy(
4943 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4944 for (auto En : enumerate(ReductionInfos)) {
4945 const ReductionInfo &RI = En.value();
4946 Value *ElemPtr = Builder.CreateInBoundsGEP(
4947 RedArrayTy, ReductionList,
4948 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4949
4950 Value *PrivateVar = RI.PrivateVariable;
4951 bool IsByRefElem = !IsByRef.empty() && IsByRef[En.index()];
4952 if (IsByRefElem)
4953 PrivateVar = Builder.CreateLoad(RI.ElementType, PrivateVar);
4954
4955 Value *CastElem =
4956 Builder.CreatePointerBitCastOrAddrSpaceCast(PrivateVar, PtrTy);
4957 Builder.CreateStore(CastElem, ElemPtr);
4958 }
4959 Expected<Function *> SarFunc = emitShuffleAndReduceFunction(
4960 ReductionInfos, ReductionFunc, FuncAttrs, IsByRef);
4961
4962 if (!SarFunc)
4963 return SarFunc.takeError();
4964
4965 Expected<Function *> CopyResult =
4966 emitInterWarpCopyFunction(Loc, ReductionInfos, FuncAttrs, IsByRef);
4967 if (!CopyResult)
4968 return CopyResult.takeError();
4969 Function *WcFunc = *CopyResult;
4970
4971 Value *RL = Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList, PtrTy);
4972
4973 // NOTE: ReductionDataSize is passed as the reduce_data_size argument to
4974 // __kmpc_nvptx_parallel_reduce_nowait_v2, but the runtime implementations do
4975 // not currently use it. It is computed here conservatively as max(element
4976 // sizes) * N rather than the exact sum, which over-calculates the size for
4977 // mixed reduction types but is harmless given the argument is unused.
4978 // TODO: Consider dropping this computation if the runtime API is ever revised
4979 // to remove the unused parameter.
4980 unsigned MaxDataSize = 0;
4981 SmallVector<Type *> ReductionTypeArgs;
4982 for (auto En : enumerate(ReductionInfos)) {
4983 // Use ByRefElementType for by-ref reductions so that MaxDataSize matches
4984 // the actual data size stored in the global reduction buffer, consistent
4985 // with the ReductionsBufferTy struct used for GEP offsets below.
4986 Type *RedTypeArg = (!IsByRef.empty() && IsByRef[En.index()])
4987 ? En.value().ByRefElementType
4988 : En.value().ElementType;
4989 auto Size = M.getDataLayout().getTypeStoreSize(RedTypeArg);
4990 if (Size > MaxDataSize)
4991 MaxDataSize = Size;
4992 ReductionTypeArgs.emplace_back(RedTypeArg);
4993 }
4994 Value *ReductionDataSize =
4995 Builder.getInt64(MaxDataSize * ReductionInfos.size());
4996
4997 // Helper function to copy thread-local data back to the original reduction
4998 // list.
4999 Function *CopyScratchToListFunc = nullptr;
5000 // Thread-local storage for the reduction variables.
5001 Value *ScratchForCopyBack = nullptr;
5002 // RL pointer to which the final value from the per-thread scratch should be
5003 // copied back. (Basically RL, appropriately casted if necessary.)
5004 Value *RLForCopyBack = RL;
5005
5006 bool IsAtomicReduction =
5007 IsTeamsReduction && isAtomicableReductionSet(ReductionInfos);
5008
5009 if (!IsTeamsReduction) {
5010 Value *SarFuncCast =
5011 Builder.CreatePointerBitCastOrAddrSpaceCast(*SarFunc, FuncPtrTy);
5012 Value *WcFuncCast =
5013 Builder.CreatePointerBitCastOrAddrSpaceCast(WcFunc, FuncPtrTy);
5014 Value *Args[] = {SrcLocInfo, ReductionDataSize, RL, SarFuncCast,
5015 WcFuncCast};
5017 RuntimeFunction::OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2);
5018 Res = createRuntimeFunctionCall(Pv2Ptr, Args);
5019 } else if (IsAtomicReduction) {
5020 // Atomic cross-team reduction fast path: determine the team's main thread
5021 // that is later to fold its value atomically into the mapped variable.
5022 Function *IsMainThreadFn = getOrCreateRuntimeFunctionPtr(
5023 RuntimeFunction::OMPRTL___kmpc_is_team_main_thread);
5024 Res = createRuntimeFunctionCall(IsMainThreadFn, {});
5025 } else {
5026 StructType *ReductionsBufferTy = StructType::create(
5027 Ctx, ReductionTypeArgs, "struct._globalized_locals_ty");
5028
5029 Expected<Function *> LtGCFunc = emitListToGlobalCopyFunction(
5030 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5031 if (!LtGCFunc)
5032 return LtGCFunc.takeError();
5033
5034 Expected<Function *> GtLCFunc = emitGlobalToListCopyFunction(
5035 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5036 if (!GtLCFunc)
5037 return GtLCFunc.takeError();
5038
5039 Expected<Function *> GtLRFunc = emitGlobalToListReduceFunction(
5040 ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs, IsByRef);
5041 if (!GtLRFunc)
5042 return GtLRFunc.takeError();
5043
5044 // The runtime's cross-team final aggregate uses the storage pointed at by
5045 // its reduce-list argument as per-thread scratch. When the surrounding
5046 // kernel is already in SPMD execution mode, clang emitted each reduction
5047 // private as a per-thread `alloca addrspace(5)`, so the original red_list
5048 // (RL) is already per-thread and nothing else is needed.
5049 //
5050 // When the kernel is in Non-SPMD execution mode at codegen time, clang's
5051 // Generic-mode globalization put the reduction private into team-shared
5052 // LDS. OpenMPOpt may later upgrade the kernel to Generic-SPMD, at which
5053 // point all threads of the last team would race on the shared LDS slot.
5054 // Emit a per-thread scratch buffer and a per-thread RL, copy the team-local
5055 // value in, and hand the per-thread RL to the runtime instead. The writer
5056 // thread copies the final value from that per-thread scratch back to RL
5057 // before running the existing combine path below.
5058
5059 // Thread-local RL (might need localization below before being passed to the
5060 // runtime).
5061 Value *RuntimeRL = RL;
5062
5063 if (!IsSPMD) {
5064 Value *PerThreadScratch;
5065
5066 {
5068 Builder.restoreIP(AllocaIP);
5069 // Allocate thread-local buffer for the reduction variables.
5070 Value *PerThreadScratchAlloca =
5071 Builder.CreateAlloca(ReductionsBufferTy, /*ArraySize=*/nullptr,
5072 ".omp.reduction.scratch");
5073 PerThreadScratch = Builder.CreatePointerBitCastOrAddrSpaceCast(
5074 PerThreadScratchAlloca, PtrTy,
5075 PerThreadScratchAlloca->getName() + ".ascast");
5076 // Allocate thread-local buffer for the pointers to the reduction
5077 // variables.
5078 Value *PerThreadRedListAlloca =
5079 Builder.CreateAlloca(RedArrayTy, /*ArraySize=*/nullptr,
5080 ".omp.reduction.per_thread_red_list");
5081 RuntimeRL = Builder.CreatePointerBitCastOrAddrSpaceCast(
5082 PerThreadRedListAlloca, PtrTy,
5083 PerThreadRedListAlloca->getName() + ".ascast");
5084 }
5085
5086 // Iterate over the reduction variables and copy the team-local value to
5087 // the thread-local buffer.
5088 for (auto En : enumerate(ReductionInfos)) {
5089 const ReductionInfo &RI = En.value();
5090 bool IsByRefElem = !IsByRef.empty() && IsByRef[En.index()];
5091
5092 Value *FieldPtr = Builder.CreateConstInBoundsGEP2_32(
5093 ReductionsBufferTy, PerThreadScratch, 0, En.index());
5094 Value *Slot = Builder.CreateConstInBoundsGEP2_32(RedArrayTy, RuntimeRL,
5095 0, En.index());
5096
5097 Value *RuntimeListEntry = FieldPtr;
5098 if (IsByRefElem && RI.DataPtrPtrGen) {
5099 Value *SrcDescriptor =
5100 Builder.CreateLoad(RI.ElementType, RI.PrivateVariable);
5101 Expected<Value *> Descriptor = createReductionDescriptorCopy(
5102 AllocaIP, RI, FieldPtr, SrcDescriptor, PtrTy);
5103 if (!Descriptor)
5104 return Descriptor.takeError();
5105 RuntimeListEntry = *Descriptor;
5106 }
5107 Builder.CreateStore(RuntimeListEntry, Slot);
5108 }
5109 // The copy helpers were emitted with default-AS (AS 0) pointer params
5110 // (see emitListToGlobalCopyFunction / emitGlobalToListCopyFunction),
5111 // but PerThreadScratch and RL live in the target's default AS, which
5112 // is non-zero on e.g. SPIRV. (See Config.getDefaultTargetAS().)
5113 Type *CopyArg0Ty = (*LtGCFunc)->getFunctionType()->getParamType(0);
5114 Type *CopyArg2Ty = (*LtGCFunc)->getFunctionType()->getParamType(2);
5115 ScratchForCopyBack = Builder.CreatePointerBitCastOrAddrSpaceCast(
5116 PerThreadScratch, CopyArg0Ty);
5117 RLForCopyBack =
5118 Builder.CreatePointerBitCastOrAddrSpaceCast(RL, CopyArg2Ty);
5119 // Use index 0 because there is no array of target values to index into,
5120 // there is only one thread-local memory slot.
5121 // restoreIP above left a stale/empty debug location; this inlinable call
5122 // to a debug-info-bearing helper needs one or the verifier rejects the
5123 // module ("!dbg attachment points at wrong subprogram") after inlining.
5124 Builder.SetCurrentDebugLocation(Loc.DL);
5125 Builder.CreateCall(
5126 *LtGCFunc, {ScratchForCopyBack, Builder.getInt32(0), RLForCopyBack});
5127 CopyScratchToListFunc = *GtLCFunc;
5128 }
5129
5130 Value *Args3[] = {SrcLocInfo, RuntimeRL, *SarFunc, WcFunc,
5131 *LtGCFunc, *GtLCFunc, *GtLRFunc};
5132
5133 Function *TeamsReduceFn = getOrCreateRuntimeFunctionPtr(
5134 RuntimeFunction::OMPRTL___kmpc_gpu_xteam_reduce_nowait);
5135 Res = createRuntimeFunctionCall(TeamsReduceFn, Args3);
5136 }
5137
5138 // 5. Build if (res == 1)
5139 BasicBlock *ExitBB = BasicBlock::Create(Ctx, ".omp.reduction.done");
5140 BasicBlock *ThenBB = BasicBlock::Create(Ctx, ".omp.reduction.then");
5141 Value *Cond = Builder.CreateICmpEQ(Res, Builder.getInt32(1));
5142 Builder.CreateCondBr(Cond, ThenBB, ExitBB);
5143
5144 // 6. Build then branch: where we have reduced values in the master
5145 // thread in each team.
5146 // __kmpc_end_reduce{_nowait}(<gtid>);
5147 // break;
5148 emitBlock(ThenBB, CurFunc);
5149
5150 // Copy the writer thread's per-thread scratch result back into the original
5151 // red-list storage before the existing combine path reads RI.PrivateVariable.
5152 // Set a debug location: this inlinable call to a debug-info-bearing helper
5153 // needs one or the verifier rejects the module after inlining.
5154 if (ScratchForCopyBack) {
5155 Builder.SetCurrentDebugLocation(Loc.DL);
5156 Builder.CreateCall(
5157 CopyScratchToListFunc,
5158 {ScratchForCopyBack, Builder.getInt32(0), RLForCopyBack});
5159 }
5160
5161 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
5162 for (auto En : enumerate(ReductionInfos)) {
5163 const ReductionInfo &RI = En.value();
5164
5165 // Atomic cross-team fast path: each team's main thread folds its
5166 // team-reduced value directly into the mapped reduction variable with a
5167 // single atomicrmw.
5168 if (IsAtomicReduction) {
5170 Builder.saveIP(), RI.ElementType, RI.Variable, RI.PrivateVariable);
5171 if (!AfterIP)
5172 return AfterIP.takeError();
5173 Builder.restoreIP(*AfterIP);
5174 continue;
5175 }
5176
5178 Value *RedValue = RI.Variable;
5179
5180 Value *RHS =
5181 Builder.CreatePointerBitCastOrAddrSpaceCast(RI.PrivateVariable, PtrTy);
5182
5184 Value *LHSPtr, *RHSPtr;
5185 Builder.restoreIP(RI.ReductionGenClang(Builder.saveIP(), En.index(),
5186 &LHSPtr, &RHSPtr, CurFunc));
5187
5188 // Fix the CallBack code genereated to use the correct Values for the LHS
5189 // and RHS. Cast to match types before replacing (necessary to handle
5190 // different address spaces).
5191 if (LHSPtr->getType() != RedValue->getType())
5192 RedValue = Builder.CreatePointerBitCastOrAddrSpaceCast(
5193 RedValue, LHSPtr->getType());
5194 if (RHSPtr->getType() != RHS->getType())
5195 RHS =
5196 Builder.CreatePointerBitCastOrAddrSpaceCast(RHS, RHSPtr->getType());
5197
5198 LHSPtr->replaceUsesWithIf(RedValue, [ReductionFunc](const Use &U) {
5199 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
5200 ReductionFunc;
5201 });
5202 RHSPtr->replaceUsesWithIf(RHS, [ReductionFunc](const Use &U) {
5203 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
5204 ReductionFunc;
5205 });
5206 } else {
5207 if (IsByRef.empty() || !IsByRef[En.index()]) {
5208 RedValue = Builder.CreateLoad(ValueType, RI.Variable,
5209 "red.value." + Twine(En.index()));
5210 }
5211 Value *PrivateRedValue = Builder.CreateLoad(
5212 ValueType, RHS, "red.private.value" + Twine(En.index()));
5213 Value *Reduced;
5214 InsertPointOrErrorTy AfterIP =
5215 RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced);
5216 if (!AfterIP)
5217 return AfterIP.takeError();
5218 Builder.restoreIP(*AfterIP);
5219
5220 if (!IsByRef.empty() && !IsByRef[En.index()])
5221 Builder.CreateStore(Reduced, RI.Variable);
5222 }
5223 }
5224 emitBlock(ExitBB, CurFunc);
5225 if (ContinuationBlock) {
5226 Builder.CreateBr(ContinuationBlock);
5227 Builder.SetInsertPoint(ContinuationBlock);
5228 }
5229 Config.setEmitLLVMUsed();
5230
5231 return Builder.saveIP();
5232}
5233
5235 Type *VoidTy = Type::getVoidTy(M.getContext());
5236 Type *Int8PtrTy = PointerType::getUnqual(M.getContext());
5237 auto *FuncTy =
5238 FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
5240 ".omp.reduction.func", &M);
5241}
5242
5244 Function *ReductionFunc,
5246 IRBuilder<> &Builder, ArrayRef<bool> IsByRef, bool IsGPU) {
5247 IRBuilder<>::InsertPointGuard IPG(Builder);
5248 Module *Module = ReductionFunc->getParent();
5249 BasicBlock *ReductionFuncBlock =
5250 BasicBlock::Create(Module->getContext(), "", ReductionFunc);
5251 Builder.SetInsertPoint(ReductionFuncBlock);
5252 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
5253 Value *LHSArrayPtr = nullptr;
5254 Value *RHSArrayPtr = nullptr;
5255 if (IsGPU) {
5256 // Need to alloca memory here and deal with the pointers before getting
5257 // LHS/RHS pointers out
5258 //
5259 Argument *Arg0 = ReductionFunc->getArg(0);
5260 Argument *Arg1 = ReductionFunc->getArg(1);
5261 Type *Arg0Type = Arg0->getType();
5262 Type *Arg1Type = Arg1->getType();
5263
5264 Value *LHSAlloca =
5265 Builder.CreateAlloca(Arg0Type, nullptr, Arg0->getName() + ".addr");
5266 Value *RHSAlloca =
5267 Builder.CreateAlloca(Arg1Type, nullptr, Arg1->getName() + ".addr");
5268 Value *LHSAddrCast =
5269 Builder.CreatePointerBitCastOrAddrSpaceCast(LHSAlloca, Arg0Type);
5270 Value *RHSAddrCast =
5271 Builder.CreatePointerBitCastOrAddrSpaceCast(RHSAlloca, Arg1Type);
5272 Builder.CreateStore(Arg0, LHSAddrCast);
5273 Builder.CreateStore(Arg1, RHSAddrCast);
5274 LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);
5275 RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);
5276 } else {
5277 LHSArrayPtr = ReductionFunc->getArg(0);
5278 RHSArrayPtr = ReductionFunc->getArg(1);
5279 }
5280
5281 unsigned NumReductions = ReductionInfos.size();
5282 Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), NumReductions);
5283
5284 for (auto En : enumerate(ReductionInfos)) {
5285 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
5286 Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5287 RedArrayTy, LHSArrayPtr, 0, En.index());
5288 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);
5289 Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5290 LHSI8Ptr, RI.Variable->getType());
5291 Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
5292 Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5293 RedArrayTy, RHSArrayPtr, 0, En.index());
5294 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);
5295 Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5296 RHSI8Ptr, RI.PrivateVariable->getType());
5297 Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
5298 Value *Reduced;
5300 RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced);
5301 if (!AfterIP)
5302 return AfterIP.takeError();
5303
5304 Builder.restoreIP(*AfterIP);
5305 // TODO: Consider flagging an error.
5306 if (!Builder.GetInsertBlock())
5307 return Error::success();
5308
5309 // store is inside of the reduction region when using by-ref
5310 if (!IsByRef[En.index()])
5311 Builder.CreateStore(Reduced, LHSPtr);
5312 }
5313 Builder.CreateRetVoid();
5314 return Error::success();
5315}
5316
5318 const LocationDescription &Loc, InsertPointTy AllocaIP,
5319 ArrayRef<ReductionInfo> ReductionInfos, ArrayRef<bool> IsByRef,
5320 bool IsNoWait, bool IsTeamsReduction) {
5321 assert(ReductionInfos.size() == IsByRef.size());
5322 if (Config.isGPU())
5323 return createReductionsGPU(Loc, AllocaIP, Builder.saveIP(), ReductionInfos,
5324 IsByRef, IsNoWait, IsTeamsReduction);
5325
5326 checkReductionInfos(ReductionInfos, /*IsGPU*/ false);
5327
5328 if (!updateToLocation(Loc))
5329 return InsertPointTy();
5330
5331 if (ReductionInfos.size() == 0)
5332 return Builder.saveIP();
5333
5334 BasicBlock *InsertBlock = Loc.IP.getNodeParent();
5335 BasicBlock *ContinuationBlock =
5336 InsertBlock->splitBasicBlock(Loc.IP, "reduce.finalize");
5337 InsertBlock->getTerminator()->eraseFromParent();
5338
5339 // Create and populate array of type-erased pointers to private reduction
5340 // values.
5341 unsigned NumReductions = ReductionInfos.size();
5342 Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), NumReductions);
5343 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getTerminator());
5344 Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
5345
5346 Builder.SetInsertPoint(InsertBlock->end());
5347 // Emitting the alloca moved the insertion point into the alloca block and
5348 // can clear the debug loc. Restore back to Loc.DL.
5349 Builder.SetCurrentDebugLocation(Loc.DL);
5350
5351 for (auto En : enumerate(ReductionInfos)) {
5352 unsigned Index = En.index();
5353 const ReductionInfo &RI = En.value();
5354 Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
5355 RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
5356 Builder.CreateStore(RI.PrivateVariable, RedArrayElemPtr);
5357 }
5358
5359 // Emit a call to the runtime function that orchestrates the reduction.
5360 // Declare the reduction function in the process.
5361 Type *IndexTy = Builder.getIndexTy(
5362 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
5363 Function *Func = Builder.GetInsertBlock()->getParent();
5364 Module *Module = Func->getParent();
5365 uint32_t SrcLocStrSize;
5366 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
5367 bool CanGenerateAtomic = all_of(ReductionInfos, [](const ReductionInfo &RI) {
5368 return RI.AtomicReductionGen;
5369 });
5370 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
5371 CanGenerateAtomic
5372 ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
5373 : IdentFlag(0));
5374 Value *ThreadId = getOrCreateThreadID(Ident);
5375 Constant *NumVariables = Builder.getInt32(NumReductions);
5376 const DataLayout &DL = Module->getDataLayout();
5377 unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
5378 Constant *RedArraySize = ConstantInt::get(IndexTy, RedArrayByteSize);
5379 Function *ReductionFunc = getFreshReductionFunc(*Module);
5380 Value *Lock = getOMPCriticalRegionLock(".reduction");
5382 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
5383 : RuntimeFunction::OMPRTL___kmpc_reduce);
5384 CallInst *ReduceCall =
5385 createRuntimeFunctionCall(ReduceFunc,
5386 {Ident, ThreadId, NumVariables, RedArraySize,
5387 RedArray, ReductionFunc, Lock},
5388 "reduce");
5389
5390 // Create final reduction entry blocks for the atomic and non-atomic case.
5391 // Emit IR that dispatches control flow to one of the blocks based on the
5392 // reduction supporting the atomic mode.
5393 BasicBlock *NonAtomicRedBlock =
5394 BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
5395 BasicBlock *AtomicRedBlock =
5396 BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
5397 SwitchInst *Switch =
5398 Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
5399 Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
5400 Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
5401
5402 // Populate the non-atomic reduction using the elementwise reduction function.
5403 // This loads the elements from the global and private variables and reduces
5404 // them before storing back the result to the global variable.
5405 Builder.SetInsertPoint(NonAtomicRedBlock);
5406 for (auto En : enumerate(ReductionInfos)) {
5407 const ReductionInfo &RI = En.value();
5409 // We have one less load for by-ref case because that load is now inside of
5410 // the reduction region
5411 Value *RedValue = RI.Variable;
5412 if (!IsByRef[En.index()]) {
5413 RedValue = Builder.CreateLoad(ValueType, RI.Variable,
5414 "red.value." + Twine(En.index()));
5415 }
5416 Value *PrivateRedValue =
5417 Builder.CreateLoad(ValueType, RI.PrivateVariable,
5418 "red.private.value." + Twine(En.index()));
5419 Value *Reduced;
5420 InsertPointOrErrorTy AfterIP =
5421 RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced);
5422 if (!AfterIP)
5423 return AfterIP.takeError();
5424 Builder.restoreIP(*AfterIP);
5425
5426 if (!Builder.GetInsertBlock())
5427 return InsertPointTy();
5428 // for by-ref case, the load is inside of the reduction region
5429 if (!IsByRef[En.index()])
5430 Builder.CreateStore(Reduced, RI.Variable);
5431 }
5432 Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
5433 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
5434 : RuntimeFunction::OMPRTL___kmpc_end_reduce);
5435 createRuntimeFunctionCall(EndReduceFunc, {Ident, ThreadId, Lock});
5436 Builder.CreateBr(ContinuationBlock);
5437
5438 // Populate the atomic reduction using the atomic elementwise reduction
5439 // function. There are no loads/stores here because they will be happening
5440 // inside the atomic elementwise reduction.
5441 Builder.SetInsertPoint(AtomicRedBlock);
5442 if (CanGenerateAtomic && llvm::none_of(IsByRef, [](bool P) { return P; })) {
5443 for (const ReductionInfo &RI : ReductionInfos) {
5445 Builder.saveIP(), RI.ElementType, RI.Variable, RI.PrivateVariable);
5446 if (!AfterIP)
5447 return AfterIP.takeError();
5448 Builder.restoreIP(*AfterIP);
5449 if (!Builder.GetInsertBlock())
5450 return InsertPointTy();
5451 }
5452 Builder.CreateBr(ContinuationBlock);
5453 } else {
5454 Builder.CreateUnreachable();
5455 }
5456
5457 // Populate the outlined reduction function using the elementwise reduction
5458 // function. Partial values are extracted from the type-erased array of
5459 // pointers to private variables.
5460 Error Err = populateReductionFunction(ReductionFunc, ReductionInfos, Builder,
5461 IsByRef, /*isGPU=*/false);
5462 if (Err)
5463 return Err;
5464
5465 if (!Builder.GetInsertBlock())
5466 return InsertPointTy();
5467
5468 Builder.SetInsertPoint(ContinuationBlock);
5469 return Builder.saveIP();
5470}
5471
5474 BodyGenCallbackTy BodyGenCB,
5475 FinalizeCallbackTy FiniCB) {
5476 if (!updateToLocation(Loc))
5477 return Loc.IP;
5478
5479 Directive OMPD = Directive::OMPD_master;
5480 uint32_t SrcLocStrSize;
5481 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
5482 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
5483 Value *ThreadId = getOrCreateThreadID(Ident);
5484 Value *Args[] = {Ident, ThreadId};
5485
5486 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
5487 Instruction *EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
5488
5489 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
5490 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
5491
5492 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5493 /*Conditional*/ true, /*hasFinalize*/ true);
5494}
5495
5498 BodyGenCallbackTy BodyGenCB,
5499 FinalizeCallbackTy FiniCB, Value *Filter) {
5501 if (!updateToLocation(Loc))
5502 return Loc.IP;
5503
5504 Directive OMPD = Directive::OMPD_masked;
5505 uint32_t SrcLocStrSize;
5506 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
5507 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
5508 Value *ThreadId = getOrCreateThreadID(Ident);
5509 Value *Args[] = {Ident, ThreadId, Filter};
5510 Value *ArgsEnd[] = {Ident, ThreadId};
5511
5512 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
5513 Instruction *EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
5514
5515 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
5516 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, ArgsEnd);
5517
5518 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5519 /*Conditional*/ true, /*hasFinalize*/ true);
5520}
5521
5523 llvm::FunctionCallee Callee,
5525 const llvm::Twine &Name) {
5526 llvm::CallInst *Call = Builder.CreateCall(
5527 Callee, Args, SmallVector<llvm::OperandBundleDef, 1>(), Name);
5528 Call->setDoesNotThrow();
5529 return Call;
5530}
5531
5532// Expects input basic block is dominated by BeforeScanBB.
5533// Once Scan directive is encountered, the code after scan directive should be
5534// dominated by AfterScanBB. Scan directive splits the code sequence to
5535// scan and input phase. Based on whether inclusive or exclusive
5536// clause is used in the scan directive and whether input loop or scan loop
5537// is lowered, it adds jumps to input and scan phase. First Scan loop is the
5538// input loop and second is the scan loop. The code generated handles only
5539// inclusive scans now.
5541 const LocationDescription &Loc, InsertPointTy AllocaIP,
5542 ArrayRef<llvm::Value *> ScanVars, ArrayRef<llvm::Type *> ScanVarsType,
5543 bool IsInclusive, ScanInfo *ScanRedInfo) {
5544 if (ScanRedInfo->OMPFirstScanLoop) {
5545 llvm::Error Err = emitScanBasedDirectiveDeclsIR(AllocaIP, ScanVars,
5546 ScanVarsType, ScanRedInfo);
5547 if (Err)
5548 return Err;
5549 }
5550 if (!updateToLocation(Loc))
5551 return Loc.IP;
5552
5553 llvm::Value *IV = ScanRedInfo->IV;
5554
5555 if (ScanRedInfo->OMPFirstScanLoop) {
5556 // Emit buffer[i] = red; at the end of the input phase.
5557 for (size_t i = 0; i < ScanVars.size(); i++) {
5558 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]];
5559 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5560 Type *DestTy = ScanVarsType[i];
5561 Value *Val = Builder.CreateInBoundsGEP(DestTy, Buff, IV, "arrayOffset");
5562 Value *Src = Builder.CreateLoad(DestTy, ScanVars[i]);
5563
5564 Builder.CreateStore(Src, Val);
5565 }
5566 }
5567 Builder.CreateBr(ScanRedInfo->OMPScanLoopExit);
5568 emitBlock(ScanRedInfo->OMPScanDispatch,
5569 Builder.GetInsertBlock()->getParent());
5570
5571 if (!ScanRedInfo->OMPFirstScanLoop) {
5572 IV = ScanRedInfo->IV;
5573 // Emit red = buffer[i]; at the entrance to the scan phase.
5574 // TODO: if exclusive scan, the red = buffer[i-1] needs to be updated.
5575 for (size_t i = 0; i < ScanVars.size(); i++) {
5576 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]];
5577 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5578 Type *DestTy = ScanVarsType[i];
5579 Value *SrcPtr =
5580 Builder.CreateInBoundsGEP(DestTy, Buff, IV, "arrayOffset");
5581 Value *Src = Builder.CreateLoad(DestTy, SrcPtr);
5582 Builder.CreateStore(Src, ScanVars[i]);
5583 }
5584 }
5585
5586 // TODO: Update it to CreateBr and remove dead blocks
5587 llvm::Value *CmpI = Builder.getInt1(true);
5588 if (ScanRedInfo->OMPFirstScanLoop == IsInclusive) {
5589 Builder.CreateCondBr(CmpI, ScanRedInfo->OMPBeforeScanBlock,
5590 ScanRedInfo->OMPAfterScanBlock);
5591 } else {
5592 Builder.CreateCondBr(CmpI, ScanRedInfo->OMPAfterScanBlock,
5593 ScanRedInfo->OMPBeforeScanBlock);
5594 }
5595 emitBlock(ScanRedInfo->OMPAfterScanBlock,
5596 Builder.GetInsertBlock()->getParent());
5597 Builder.SetInsertPoint(ScanRedInfo->OMPAfterScanBlock);
5598 return Builder.saveIP();
5599}
5600
5601Error OpenMPIRBuilder::emitScanBasedDirectiveDeclsIR(
5602 InsertPointTy AllocaIP, ArrayRef<Value *> ScanVars,
5603 ArrayRef<Type *> ScanVarsType, ScanInfo *ScanRedInfo) {
5604
5605 Builder.restoreIP(AllocaIP);
5606 // Create the shared pointer at alloca IP.
5607 for (size_t i = 0; i < ScanVars.size(); i++) {
5608 llvm::Value *BuffPtr =
5609 Builder.CreateAlloca(Builder.getPtrTy(), nullptr, "vla");
5610 (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]] = BuffPtr;
5611 }
5612
5613 // Allocate temporary buffer by master thread
5614 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
5615 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
5616 Builder.restoreIP(CodeGenIP);
5617 Value *AllocSpan =
5618 Builder.CreateAdd(ScanRedInfo->Span, Builder.getInt32(1));
5619 for (size_t i = 0; i < ScanVars.size(); i++) {
5620 Type *IntPtrTy = Builder.getInt32Ty();
5621 Value *Allocsize = Builder.CreateTypeSize(
5622 IntPtrTy, M.getDataLayout().getTypeAllocSize(ScanVarsType[i]));
5623 Value *Buff =
5624 Builder.CreateMalloc(IntPtrTy, Allocsize, AllocSpan, nullptr, "arr");
5625 Builder.CreateStore(Buff, (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]]);
5626 }
5627 return Error::success();
5628 };
5629 // TODO: Perform finalization actions for variables. This has to be
5630 // called for variables which have destructors/finalizers.
5631 auto FiniCB = [&](InsertPointTy CodeGenIP) { return llvm::Error::success(); };
5632
5633 Builder.SetInsertPoint(ScanRedInfo->OMPScanInit->getTerminator());
5634 llvm::Value *FilterVal = Builder.getInt32(0);
5636 createMasked(Builder, BodyGenCB, FiniCB, FilterVal);
5637
5638 if (!AfterIP)
5639 return AfterIP.takeError();
5640 Builder.restoreIP(*AfterIP);
5641 BasicBlock *InputBB = Builder.GetInsertBlock();
5642 if (InputBB->hasTerminator())
5643 Builder.SetInsertPoint(InputBB->getTerminator());
5644 AfterIP = createBarrier(Builder, llvm::omp::OMPD_barrier);
5645 if (!AfterIP)
5646 return AfterIP.takeError();
5647 Builder.restoreIP(*AfterIP);
5648
5649 return Error::success();
5650}
5651
5652Error OpenMPIRBuilder::emitScanBasedDirectiveFinalsIR(
5653 ArrayRef<ReductionInfo> ReductionInfos, ScanInfo *ScanRedInfo) {
5654 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
5655 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
5656 Builder.restoreIP(CodeGenIP);
5657 for (ReductionInfo RedInfo : ReductionInfos) {
5658 Value *PrivateVar = RedInfo.PrivateVariable;
5659 Value *OrigVar = RedInfo.Variable;
5660 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[PrivateVar];
5661 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5662
5663 Type *SrcTy = RedInfo.ElementType;
5664 Value *Val = Builder.CreateInBoundsGEP(SrcTy, Buff, ScanRedInfo->Span,
5665 "arrayOffset");
5666 Value *Src = Builder.CreateLoad(SrcTy, Val);
5667
5668 Builder.CreateStore(Src, OrigVar);
5669 Builder.CreateFree(Buff);
5670 }
5671 return Error::success();
5672 };
5673 // TODO: Perform finalization actions for variables. This has to be
5674 // called for variables which have destructors/finalizers.
5675 auto FiniCB = [&](InsertPointTy CodeGenIP) { return llvm::Error::success(); };
5676
5677 if (Instruction *TI = ScanRedInfo->OMPScanFinish->getTerminatorOrNull())
5678 Builder.SetInsertPoint(TI);
5679 else
5680 Builder.SetInsertPoint(ScanRedInfo->OMPScanFinish);
5681
5682 llvm::Value *FilterVal = Builder.getInt32(0);
5684 createMasked(Builder, BodyGenCB, FiniCB, FilterVal);
5685
5686 if (!AfterIP)
5687 return AfterIP.takeError();
5688 Builder.restoreIP(*AfterIP);
5689 BasicBlock *InputBB = Builder.GetInsertBlock();
5690 if (InputBB->hasTerminator())
5691 Builder.SetInsertPoint(InputBB->getTerminator());
5692 AfterIP = createBarrier(Builder, llvm::omp::OMPD_barrier);
5693 if (!AfterIP)
5694 return AfterIP.takeError();
5695 Builder.restoreIP(*AfterIP);
5696 return Error::success();
5697}
5698
5700 const LocationDescription &Loc,
5702 ScanInfo *ScanRedInfo) {
5703
5704 if (!updateToLocation(Loc))
5705 return Loc.IP;
5706 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
5707 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
5708 Builder.restoreIP(CodeGenIP);
5709 Function *CurFn = Builder.GetInsertBlock()->getParent();
5710 // for (int k = 0; k <= ceil(log2(n)); ++k)
5711 llvm::BasicBlock *LoopBB =
5712 BasicBlock::Create(CurFn->getContext(), "omp.outer.log.scan.body");
5713 llvm::BasicBlock *ExitBB =
5714 splitBB(Builder, false, "omp.outer.log.scan.exit");
5716 Builder.getModule(), (llvm::Intrinsic::ID)llvm::Intrinsic::log2,
5717 Builder.getDoubleTy());
5718 llvm::BasicBlock *InputBB = Builder.GetInsertBlock();
5719 llvm::Value *Arg =
5720 Builder.CreateUIToFP(ScanRedInfo->Span, Builder.getDoubleTy());
5721 llvm::Value *LogVal = emitNoUnwindRuntimeCall(Builder, F, Arg, "");
5723 Builder.getModule(), (llvm::Intrinsic::ID)llvm::Intrinsic::ceil,
5724 Builder.getDoubleTy());
5725 LogVal = emitNoUnwindRuntimeCall(Builder, F, LogVal, "");
5726 LogVal = Builder.CreateFPToUI(LogVal, Builder.getInt32Ty());
5727 llvm::Value *NMin1 = Builder.CreateNUWSub(
5728 ScanRedInfo->Span,
5729 llvm::ConstantInt::get(ScanRedInfo->Span->getType(), 1));
5730 Builder.SetInsertPoint(InputBB);
5731 Builder.CreateBr(LoopBB);
5732 emitBlock(LoopBB, CurFn);
5733 Builder.SetInsertPoint(LoopBB);
5734
5735 PHINode *Counter = Builder.CreatePHI(Builder.getInt32Ty(), 2);
5736 // size pow2k = 1;
5737 PHINode *Pow2K = Builder.CreatePHI(Builder.getInt32Ty(), 2);
5738 Counter->addIncoming(llvm::ConstantInt::get(Builder.getInt32Ty(), 0),
5739 InputBB);
5740 Pow2K->addIncoming(llvm::ConstantInt::get(Builder.getInt32Ty(), 1),
5741 InputBB);
5742 // for (size i = n - 1; i >= 2 ^ k; --i)
5743 // tmp[i] op= tmp[i-pow2k];
5744 llvm::BasicBlock *InnerLoopBB =
5745 BasicBlock::Create(CurFn->getContext(), "omp.inner.log.scan.body");
5746 llvm::BasicBlock *InnerExitBB =
5747 BasicBlock::Create(CurFn->getContext(), "omp.inner.log.scan.exit");
5748 llvm::Value *CmpI = Builder.CreateICmpUGE(NMin1, Pow2K);
5749 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5750 emitBlock(InnerLoopBB, CurFn);
5751 Builder.SetInsertPoint(InnerLoopBB);
5752 PHINode *IVal = Builder.CreatePHI(Builder.getInt32Ty(), 2);
5753 IVal->addIncoming(NMin1, LoopBB);
5754 for (ReductionInfo RedInfo : ReductionInfos) {
5755 Value *ReductionVal = RedInfo.PrivateVariable;
5756 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[ReductionVal];
5757 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5758 Type *DestTy = RedInfo.ElementType;
5759 Value *IV = Builder.CreateAdd(IVal, Builder.getInt32(1));
5760 Value *LHSPtr =
5761 Builder.CreateInBoundsGEP(DestTy, Buff, IV, "arrayOffset");
5762 Value *OffsetIval = Builder.CreateNUWSub(IV, Pow2K);
5763 Value *RHSPtr =
5764 Builder.CreateInBoundsGEP(DestTy, Buff, OffsetIval, "arrayOffset");
5765 Value *LHS = Builder.CreateLoad(DestTy, LHSPtr);
5766 Value *RHS = Builder.CreateLoad(DestTy, RHSPtr);
5767 llvm::Value *Result;
5768 InsertPointOrErrorTy AfterIP =
5769 RedInfo.ReductionGen(Builder.saveIP(), LHS, RHS, Result);
5770 if (!AfterIP)
5771 return AfterIP.takeError();
5772 Builder.CreateStore(Result, LHSPtr);
5773 }
5774 llvm::Value *NextIVal = Builder.CreateNUWSub(
5775 IVal, llvm::ConstantInt::get(Builder.getInt32Ty(), 1));
5776 IVal->addIncoming(NextIVal, Builder.GetInsertBlock());
5777 CmpI = Builder.CreateICmpUGE(NextIVal, Pow2K);
5778 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5779 emitBlock(InnerExitBB, CurFn);
5780 llvm::Value *Next = Builder.CreateNUWAdd(
5781 Counter, llvm::ConstantInt::get(Counter->getType(), 1));
5782 Counter->addIncoming(Next, Builder.GetInsertBlock());
5783 // pow2k <<= 1;
5784 llvm::Value *NextPow2K = Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true);
5785 Pow2K->addIncoming(NextPow2K, Builder.GetInsertBlock());
5786 llvm::Value *Cmp = Builder.CreateICmpNE(Next, LogVal);
5787 Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
5788 Builder.SetInsertPoint(ExitBB->getFirstInsertionPt());
5789 return Error::success();
5790 };
5791
5792 // TODO: Perform finalization actions for variables. This has to be
5793 // called for variables which have destructors/finalizers.
5794 auto FiniCB = [&](InsertPointTy CodeGenIP) { return llvm::Error::success(); };
5795
5796 llvm::Value *FilterVal = Builder.getInt32(0);
5798 createMasked(Builder, BodyGenCB, FiniCB, FilterVal);
5799
5800 if (!AfterIP)
5801 return AfterIP.takeError();
5802 Builder.restoreIP(*AfterIP);
5803 AfterIP = createBarrier(Builder, llvm::omp::OMPD_barrier);
5804
5805 if (!AfterIP)
5806 return AfterIP.takeError();
5807 Builder.restoreIP(*AfterIP);
5808 Error Err = emitScanBasedDirectiveFinalsIR(ReductionInfos, ScanRedInfo);
5809 if (Err)
5810 return Err;
5811
5812 return AfterIP;
5813}
5814
5815Error OpenMPIRBuilder::emitScanBasedDirectiveIR(
5816 llvm::function_ref<Error()> InputLoopGen,
5817 llvm::function_ref<Error(LocationDescription Loc)> ScanLoopGen,
5818 ScanInfo *ScanRedInfo) {
5819
5820 {
5821 // Emit loop with input phase:
5822 // for (i: 0..<num_iters>) {
5823 // <input phase>;
5824 // buffer[i] = red;
5825 // }
5826 ScanRedInfo->OMPFirstScanLoop = true;
5827 Error Err = InputLoopGen();
5828 if (Err)
5829 return Err;
5830 }
5831 {
5832 // Emit loop with scan phase:
5833 // for (i: 0..<num_iters>) {
5834 // red = buffer[i];
5835 // <scan phase>;
5836 // }
5837 ScanRedInfo->OMPFirstScanLoop = false;
5838 Error Err = ScanLoopGen(Builder);
5839 if (Err)
5840 return Err;
5841 }
5842 return Error::success();
5843}
5844
5845void OpenMPIRBuilder::createScanBBs(ScanInfo *ScanRedInfo) {
5846 Function *Fun = Builder.GetInsertBlock()->getParent();
5847 ScanRedInfo->OMPScanDispatch =
5848 BasicBlock::Create(Fun->getContext(), "omp.inscan.dispatch");
5849 ScanRedInfo->OMPAfterScanBlock =
5850 BasicBlock::Create(Fun->getContext(), "omp.after.scan.bb");
5851 ScanRedInfo->OMPBeforeScanBlock =
5852 BasicBlock::Create(Fun->getContext(), "omp.before.scan.bb");
5853 ScanRedInfo->OMPScanLoopExit =
5854 BasicBlock::Create(Fun->getContext(), "omp.scan.loop.exit");
5855}
5857 DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
5858 BasicBlock *PostInsertBefore, const Twine &Name, bool IsCollapsed) {
5859 Module *M = F->getParent();
5860 LLVMContext &Ctx = M->getContext();
5861 Type *IndVarTy = TripCount->getType();
5862
5863 // Create the basic block structure.
5864 BasicBlock *Preheader =
5865 BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
5866 BasicBlock *Header =
5867 BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
5868 BasicBlock *Cond =
5869 BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
5870 BasicBlock *Body =
5871 BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
5872 BasicBlock *Latch =
5873 BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
5874 BasicBlock *Exit =
5875 BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
5876 BasicBlock *After =
5877 BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
5878
5879 // Use specified DebugLoc for new instructions.
5880 Builder.SetCurrentDebugLocation(DL);
5881
5882 Builder.SetInsertPoint(Preheader);
5883 Builder.CreateBr(Header);
5884
5885 Builder.SetInsertPoint(Header);
5886 PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
5887 IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
5888 Builder.CreateBr(Cond);
5889
5890 Builder.SetInsertPoint(Cond);
5891 Value *Cmp =
5892 Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
5893 Builder.CreateCondBr(Cmp, Body, Exit);
5894
5895 Builder.SetInsertPoint(Body);
5896 Builder.CreateBr(Latch);
5897
5898 Builder.SetInsertPoint(Latch);
5899 // Decide whether the induction variable increment can carry nsw.
5900 //
5901 // Single loops: nsw is always kept (matching Clang). Any Fortran program
5902 // whose trip count overflows i32 is non-conforming per F2018 11.1.7.4.1, so
5903 // for valid programs 0 <= count <= INT_MAX always holds.
5904 //
5905 // Collapsed loops: the trip count is a product that can overflow i32 even for
5906 // a conforming program, so nsw is kept only when the product is a constant
5907 // that provably fits, dropped otherwise.
5908 bool HasNSW = Config.hasNoSignedWrap();
5909 if (HasNSW) {
5910 if (auto *CI = dyn_cast<ConstantInt>(TripCount)) {
5911 unsigned BitWidth = CI->getType()->getIntegerBitWidth();
5913 if (CI->getValue().ugt(SignedMax))
5914 HasNSW = false;
5915 } else if (IsCollapsed) {
5916 HasNSW = false;
5917 }
5918 }
5919 Value *Next =
5920 Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
5921 "omp_" + Name + ".next", /*HasNUW=*/true, HasNSW);
5922 Builder.CreateBr(Header);
5923 IndVarPHI->addIncoming(Next, Latch);
5924
5925 Builder.SetInsertPoint(Exit);
5926 Builder.CreateBr(After);
5927
5928 // Remember and return the canonical control flow.
5929 LoopInfos.emplace_front();
5930 CanonicalLoopInfo *CL = &LoopInfos.front();
5931
5932 CL->Header = Header;
5933 CL->Cond = Cond;
5934 CL->Latch = Latch;
5935 CL->Exit = Exit;
5936
5937#ifndef NDEBUG
5938 CL->assertOK();
5939#endif
5940 return CL;
5941}
5942
5945 LoopBodyGenCallbackTy BodyGenCB,
5946 Value *TripCount, const Twine &Name) {
5947 BasicBlock *BB = Loc.IP.getNodeParent();
5948 BasicBlock *NextBB = BB->getNextNode();
5949
5950 CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
5951 NextBB, NextBB, Name);
5952 BasicBlock *After = CL->getAfter();
5953
5954 // If location is not set, don't connect the loop.
5955 if (updateToLocation(Loc)) {
5956 // Split the loop at the insertion point: Branch to the preheader and move
5957 // every following instruction to after the loop (the After BB). Also, the
5958 // new successor is the loop's after block.
5959 spliceBB(Builder, After, /*CreateBranch=*/false);
5960 Builder.CreateBr(CL->getPreheader());
5961 }
5962
5963 // Emit the body content. We do it after connecting the loop to the CFG to
5964 // avoid that the callback encounters degenerate BBs.
5965 if (Error Err = BodyGenCB(CL->getBodyIP(), CL->getIndVar()))
5966 return Err;
5967
5968#ifndef NDEBUG
5969 CL->assertOK();
5970#endif
5971 return CL;
5972}
5973
5975 ScanInfos.emplace_front();
5976 ScanInfo *Result = &ScanInfos.front();
5977 return Result;
5978}
5979
5983 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
5984 InsertPointTy ComputeIP, const Twine &Name, ScanInfo *ScanRedInfo) {
5985 LocationDescription ComputeLoc =
5986 ComputeIP.isValid() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
5987 updateToLocation(ComputeLoc);
5988
5990
5992 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
5993 ScanRedInfo->Span = TripCount;
5994 ScanRedInfo->OMPScanInit = splitBB(Builder, true, "scan.init");
5995 Builder.SetInsertPoint(ScanRedInfo->OMPScanInit);
5996
5997 auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
5998 Builder.restoreIP(CodeGenIP);
5999 ScanRedInfo->IV = IV;
6000 createScanBBs(ScanRedInfo);
6001 BasicBlock *InputBlock = Builder.GetInsertBlock();
6002 Instruction *Terminator = InputBlock->getTerminator();
6003 assert(Terminator->getNumSuccessors() == 1);
6004 BasicBlock *ContinueBlock = Terminator->getSuccessor(0);
6005 Terminator->setSuccessor(0, ScanRedInfo->OMPScanDispatch);
6006 emitBlock(ScanRedInfo->OMPBeforeScanBlock,
6007 Builder.GetInsertBlock()->getParent());
6008 Builder.CreateBr(ScanRedInfo->OMPScanLoopExit);
6009 emitBlock(ScanRedInfo->OMPScanLoopExit,
6010 Builder.GetInsertBlock()->getParent());
6011 Builder.CreateBr(ContinueBlock);
6012 Builder.SetInsertPoint(
6013 ScanRedInfo->OMPBeforeScanBlock->getFirstInsertionPt());
6014 return BodyGenCB(Builder.saveIP(), IV);
6015 };
6016
6017 const auto &&InputLoopGen = [&]() -> Error {
6019 createCanonicalLoop(Builder, BodyGen, Start, Stop, Step, IsSigned,
6020 InclusiveStop, ComputeIP, Name, true, ScanRedInfo);
6021 if (!LoopInfo)
6022 return LoopInfo.takeError();
6023 Result.push_back(*LoopInfo);
6024 Builder.restoreIP((*LoopInfo)->getAfterIP());
6025 return Error::success();
6026 };
6027 const auto &&ScanLoopGen = [&](LocationDescription Loc) -> Error {
6029 createCanonicalLoop(Loc, BodyGen, Start, Stop, Step, IsSigned,
6030 InclusiveStop, ComputeIP, Name, true, ScanRedInfo);
6031 if (!LoopInfo)
6032 return LoopInfo.takeError();
6033 Result.push_back(*LoopInfo);
6034 Builder.restoreIP((*LoopInfo)->getAfterIP());
6035 ScanRedInfo->OMPScanFinish = Builder.GetInsertBlock();
6036 return Error::success();
6037 };
6038 Error Err = emitScanBasedDirectiveIR(InputLoopGen, ScanLoopGen, ScanRedInfo);
6039 if (Err)
6040 return Err;
6041 return Result;
6042}
6043
6045 const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step,
6046 bool IsSigned, bool InclusiveStop, const Twine &Name) {
6047
6048 // Consider the following difficulties (assuming 8-bit signed integers):
6049 // * Adding \p Step to the loop counter which passes \p Stop may overflow:
6050 // DO I = 1, 100, 50
6051 /// * A \p Step of INT_MIN cannot not be normalized to a positive direction:
6052 // DO I = 100, 0, -128
6053
6054 // Start, Stop and Step must be of the same integer type.
6055 auto *IndVarTy = cast<IntegerType>(Start->getType());
6056 assert(IndVarTy == Stop->getType() && "Stop type mismatch");
6057 assert(IndVarTy == Step->getType() && "Step type mismatch");
6058
6060
6061 ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
6062 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
6063
6064 // Like Step, but always positive.
6065 Value *Incr = Step;
6066
6067 // Distance between Start and Stop; always positive.
6068 Value *Span;
6069
6070 // Condition whether there are no iterations are executed at all, e.g. because
6071 // UB < LB.
6072 Value *ZeroCmp;
6073
6074 if (IsSigned) {
6075 // Ensure that increment is positive. If not, negate and invert LB and UB.
6076 Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
6077 Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
6078 Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
6079 Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
6080 Span = Builder.CreateSub(UB, LB, "", false, true);
6081 ZeroCmp = Builder.CreateICmp(
6082 InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
6083 } else {
6084 Span = Builder.CreateSub(Stop, Start, "", true);
6085 ZeroCmp = Builder.CreateICmp(
6086 InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
6087 }
6088
6089 Value *CountIfLooping;
6090 if (InclusiveStop) {
6091 CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
6092 } else {
6093 // Avoid incrementing past stop since it could overflow.
6094 Value *CountIfTwo = Builder.CreateAdd(
6095 Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
6096 Value *OneCmp = Builder.CreateICmp(CmpInst::ICMP_ULE, Span, Incr);
6097 CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
6098 }
6099
6100 return Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
6101 "omp_" + Name + ".tripcount");
6102}
6103
6106 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
6107 InsertPointTy ComputeIP, const Twine &Name, bool InScan,
6108 ScanInfo *ScanRedInfo) {
6109 LocationDescription ComputeLoc =
6110 ComputeIP.isValid() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
6111
6113 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
6114
6115 auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
6116 Builder.restoreIP(CodeGenIP);
6117 Value *Span = Builder.CreateMul(IV, Step, "", /*HasNUW=*/false,
6118 /*HasNSW=*/Config.hasNoSignedWrap());
6119 Value *IndVar = Builder.CreateAdd(Span, Start, "", /*HasNUW=*/false,
6120 /*HasNSW=*/Config.hasNoSignedWrap());
6121 if (InScan)
6122 ScanRedInfo->IV = IndVar;
6123 return BodyGenCB(Builder.saveIP(), IndVar);
6124 };
6125 LocationDescription LoopLoc =
6126 ComputeIP.isValid()
6127 ? Loc
6128 : LocationDescription(Builder.saveIP(),
6129 Builder.getCurrentDebugLocation());
6130 return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
6131}
6132
6133// Returns an LLVM function to call for initializing loop bounds using OpenMP
6134// static scheduling for composite `distribute parallel for` depending on
6135// `type`. Only i32 and i64 are supported by the runtime. Always interpret
6136// integers as unsigned similarly to CanonicalLoopInfo.
6137static FunctionCallee
6139 OpenMPIRBuilder &OMPBuilder) {
6140 unsigned Bitwidth = Ty->getIntegerBitWidth();
6141 if (Bitwidth == 32)
6142 return OMPBuilder.getOrCreateRuntimeFunction(
6143 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_4u);
6144 if (Bitwidth == 64)
6145 return OMPBuilder.getOrCreateRuntimeFunction(
6146 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_8u);
6147 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6148}
6149
6150// Returns an LLVM function to call for initializing loop bounds using OpenMP
6151// static scheduling depending on `type`. Only i32 and i64 are supported by the
6152// runtime. Always interpret integers as unsigned similarly to
6153// CanonicalLoopInfo.
6155 OpenMPIRBuilder &OMPBuilder) {
6156 unsigned Bitwidth = Ty->getIntegerBitWidth();
6157 if (Bitwidth == 32)
6158 return OMPBuilder.getOrCreateRuntimeFunction(
6159 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
6160 if (Bitwidth == 64)
6161 return OMPBuilder.getOrCreateRuntimeFunction(
6162 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
6163 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6164}
6165
6166OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::applyStaticWorkshareLoop(
6167 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
6168 WorksharingLoopType LoopType, bool NeedsBarrier, bool HasDistSchedule,
6169 OMPScheduleType DistScheduleSchedType) {
6170 assert(CLI->isValid() && "Requires a valid canonical loop");
6171 assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
6172 "Require dedicated allocate IP");
6173
6174 // Set up the source location value for OpenMP runtime.
6175 Builder.restoreIP(CLI->getPreheaderIP());
6176 Builder.SetCurrentDebugLocation(DL);
6177
6178 uint32_t SrcLocStrSize;
6179 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6181 switch (LoopType) {
6182 case WorksharingLoopType::ForStaticLoop:
6183 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6184 break;
6185 case WorksharingLoopType::DistributeStaticLoop:
6186 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6187 break;
6188 case WorksharingLoopType::DistributeForStaticLoop:
6189 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6190 break;
6191 }
6192 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize, Flag);
6193
6194 // Declare useful OpenMP runtime functions.
6195 Type *IVTy = CLI->getIndVarType();
6196 FunctionCallee StaticInit =
6197 LoopType == WorksharingLoopType::DistributeForStaticLoop
6198 ? getKmpcDistForStaticInitForType(IVTy, M, *this)
6199 : getKmpcForStaticInitForType(IVTy, M, *this);
6200 FunctionCallee StaticFini =
6201 getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
6202
6203 // Allocate space for computed loop bounds as expected by the "init" function.
6204 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6205
6206 Type *I32Type = Type::getInt32Ty(M.getContext());
6207 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6208 Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
6209 Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
6210 Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
6211 CLI->setLastIter(PLastIter);
6212
6213 // At the end of the preheader, prepare for calling the "init" function by
6214 // storing the current loop bounds into the allocated space. A canonical loop
6215 // always iterates from 0 to trip-count with step 1. Note that "init" expects
6216 // and produces an inclusive upper bound.
6217 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
6218 Constant *Zero = ConstantInt::get(IVTy, 0);
6219 Constant *One = ConstantInt::get(IVTy, 1);
6220 Builder.CreateStore(Zero, PLowerBound);
6221 Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
6222 Builder.CreateStore(UpperBound, PUpperBound);
6223 Builder.CreateStore(One, PStride);
6224
6225 Value *ThreadNum =
6226 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize));
6227
6228 OMPScheduleType SchedType =
6229 (LoopType == WorksharingLoopType::DistributeStaticLoop)
6230 ? OMPScheduleType::OrderedDistribute
6232 Constant *SchedulingType =
6233 ConstantInt::get(I32Type, static_cast<int>(SchedType));
6234
6235 // Call the "init" function and update the trip count of the loop with the
6236 // value it produced.
6237 auto BuildInitCall = [LoopType, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6238 PUpperBound, IVTy, PStride, One, Zero, StaticInit,
6239 this](Value *SchedulingType, auto &Builder) {
6240 SmallVector<Value *, 10> Args({SrcLoc, ThreadNum, SchedulingType, PLastIter,
6241 PLowerBound, PUpperBound});
6242 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6243 Value *PDistUpperBound =
6244 Builder.CreateAlloca(IVTy, nullptr, "p.distupperbound");
6245 Args.push_back(PDistUpperBound);
6246 }
6247 Args.append({PStride, One, Zero});
6248 createRuntimeFunctionCall(StaticInit, Args);
6249 };
6250 BuildInitCall(SchedulingType, Builder);
6251 if (HasDistSchedule &&
6252 LoopType != WorksharingLoopType::DistributeStaticLoop) {
6253 Constant *DistScheduleSchedType = ConstantInt::get(
6254 I32Type, static_cast<int>(omp::OMPScheduleType::OrderedDistribute));
6255 // We want to emit a second init function call for the dist_schedule clause
6256 // to the Distribute construct. This should only be done however if a
6257 // Workshare Loop is nested within a Distribute Construct
6258 BuildInitCall(DistScheduleSchedType, Builder);
6259 }
6260 Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
6261 Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
6262 Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
6263 Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
6264 if (CLI->VirtualCollapse) {
6265 bindCollapsedRange(CLI, LowerBound, TripCount);
6266#ifndef NDEBUG
6267 CLI->assertOK();
6268#endif
6269 } else {
6270 CLI->setTripCount(TripCount);
6271 }
6272
6273 // Update all uses of the induction variable except the one in the condition
6274 // block that compares it with the actual upper bound, and the increment in
6275 // the latch block.
6276
6277 if (!CLI->VirtualCollapse)
6278 CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
6279 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
6280 Builder.SetCurrentDebugLocation(DL);
6281 return Builder.CreateAdd(OldIV, LowerBound, "", /*HasNUW=*/false,
6282 /*HasNSW=*/Config.hasNoSignedWrap());
6283 });
6284
6285 // In the "exit" block, call the "fini" function.
6286 Builder.SetInsertPoint(CLI->getExit()->getTerminator()->getIterator());
6287 createRuntimeFunctionCall(StaticFini, {SrcLoc, ThreadNum});
6288
6289 // Add the barrier if requested.
6290 if (NeedsBarrier) {
6291 InsertPointOrErrorTy BarrierIP =
6293 omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
6294 /* CheckCancelFlag */ false);
6295 if (!BarrierIP)
6296 return BarrierIP.takeError();
6297 }
6298
6299 InsertPointTy AfterIP = CLI->getAfterIP();
6300 // TODO: Removing Virtual's outer bound requires another way to reject idle
6301 // assignments whose raw count wraps. Keep it for correctness and trip-count
6302 // information for analyses. The expected saving is small; investigate the
6303 // effects on downstream optimizations before removing it.
6304 CLI->invalidate();
6305
6306 return AfterIP;
6307}
6308
6309static void addAccessGroupMetadata(BasicBlock *Block, MDNode *AccessGroup,
6310 LoopInfo &LI);
6311static void addLoopMetadata(CanonicalLoopInfo *Loop,
6313
6315 LLVMContext &Ctx, Loop *Loop,
6317 SmallVector<Metadata *> &LoopMDList) {
6318 SmallSet<BasicBlock *, 8> Reachable;
6319
6320 // Get the basic blocks from the loop in which memref instructions
6321 // can be found.
6322 // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
6323 // preferably without running any passes.
6324 for (BasicBlock *Block : Loop->getBlocks()) {
6325 if (Block == CLI->getCond() || Block == CLI->getHeader())
6326 continue;
6327 Reachable.insert(Block);
6328 }
6329
6330 // Add access group metadata to memory-access instructions.
6332 for (BasicBlock *BB : Reachable)
6334 // TODO: If the loop has existing parallel access metadata, have
6335 // to combine two lists.
6336 LoopMDList.push_back(MDNode::get(
6337 Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"), AccessGroup}));
6338}
6339
6341OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
6342 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
6343 bool NeedsBarrier, Value *ChunkSize, OMPScheduleType SchedType,
6344 Value *DistScheduleChunkSize, OMPScheduleType DistScheduleSchedType) {
6345 assert(CLI->isValid() && "Requires a valid canonical loop");
6346 assert((ChunkSize || DistScheduleChunkSize) && "Chunk size is required");
6347
6348 LLVMContext &Ctx = CLI->getFunction()->getContext();
6349 Value *IV = CLI->getIndVar();
6350 Value *OrigTripCount = CLI->getTripCount();
6351 Type *IVTy = IV->getType();
6352 assert(IVTy->getIntegerBitWidth() <= 64 &&
6353 "Max supported tripcount bitwidth is 64 bits");
6354 Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
6355 : Type::getInt64Ty(Ctx);
6356 Type *I32Type = Type::getInt32Ty(M.getContext());
6357 Constant *Zero = ConstantInt::get(InternalIVTy, 0);
6358 Constant *One = ConstantInt::get(InternalIVTy, 1);
6359
6360 Function *F = CLI->getFunction();
6361 // Blocks must have terminators.
6362 // FIXME: Don't run analyses on incomplete/invalid IR.
6363 SmallVector<Instruction *> UIs;
6364 for (BasicBlock &BB : *F)
6365 if (!BB.hasTerminator())
6366 UIs.push_back(new UnreachableInst(F->getContext(), &BB));
6368 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
6369 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
6370 LoopAnalysis LIA;
6371 LoopInfo &&LI = LIA.run(*F, FAM);
6372 for (Instruction *I : UIs)
6373 I->eraseFromParent();
6374 Loop *L = LI.getLoopFor(CLI->getHeader());
6375 SmallVector<Metadata *> LoopMDList;
6376 if (ChunkSize || DistScheduleChunkSize)
6377 applyParallelAccessesMetadata(CLI, Ctx, L, LI, LoopMDList);
6378 addLoopMetadata(CLI, LoopMDList);
6379
6380 // Declare useful OpenMP runtime functions.
6381 FunctionCallee StaticInit =
6382 getKmpcForStaticInitForType(InternalIVTy, M, *this);
6383 FunctionCallee StaticFini =
6384 getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
6385
6386 // Allocate space for computed loop bounds as expected by the "init" function.
6387 Builder.restoreIP(AllocaIP);
6388 Builder.SetCurrentDebugLocation(DL);
6389 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6390 Value *PLowerBound =
6391 Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
6392 Value *PUpperBound =
6393 Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
6394 Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
6395 CLI->setLastIter(PLastIter);
6396
6397 // Set up the source location value for the OpenMP runtime.
6398 Builder.restoreIP(CLI->getPreheaderIP());
6399 Builder.SetCurrentDebugLocation(DL);
6400
6401 // TODO: Detect overflow in ubsan or max-out with current tripcount.
6402 Value *CastedChunkSize = Builder.CreateZExtOrTrunc(
6403 ChunkSize ? ChunkSize : Zero, InternalIVTy, "chunksize");
6404 Value *CastedDistScheduleChunkSize = Builder.CreateZExtOrTrunc(
6405 DistScheduleChunkSize ? DistScheduleChunkSize : Zero, InternalIVTy,
6406 "distschedulechunksize");
6407 Value *CastedTripCount =
6408 Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
6409
6410 Constant *SchedulingType =
6411 ConstantInt::get(I32Type, static_cast<int>(SchedType));
6412 Constant *DistSchedulingType =
6413 ConstantInt::get(I32Type, static_cast<int>(DistScheduleSchedType));
6414 Builder.CreateStore(Zero, PLowerBound);
6415 Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
6416 Value *IsTripCountZero = Builder.CreateICmpEQ(CastedTripCount, Zero);
6417 Value *UpperBound =
6418 Builder.CreateSelect(IsTripCountZero, Zero, OrigUpperBound);
6419 Builder.CreateStore(UpperBound, PUpperBound);
6420 Builder.CreateStore(One, PStride);
6421
6422 // Call the "init" function and update the trip count of the loop with the
6423 // value it produced.
6424 uint32_t SrcLocStrSize;
6425 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6426 IdentFlag Flag = OMP_IDENT_FLAG_WORK_LOOP;
6427 if (DistScheduleSchedType != OMPScheduleType::None) {
6428 Flag |= OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6429 }
6430 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize, Flag);
6431 Value *ThreadNum =
6432 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize));
6433 auto BuildInitCall = [StaticInit, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6434 PUpperBound, PStride, One,
6435 this](Value *SchedulingType, Value *ChunkSize,
6436 auto &Builder) {
6438 StaticInit, {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
6439 /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
6440 /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
6441 /*pstride=*/PStride, /*incr=*/One,
6442 /*chunk=*/ChunkSize});
6443 };
6444 BuildInitCall(SchedulingType, CastedChunkSize, Builder);
6445 if (DistScheduleSchedType != OMPScheduleType::None &&
6446 SchedType != OMPScheduleType::OrderedDistributeChunked &&
6447 SchedType != OMPScheduleType::OrderedDistribute) {
6448 // We want to emit a second init function call for the dist_schedule clause
6449 // to the Distribute construct. This should only be done however if a
6450 // Workshare Loop is nested within a Distribute Construct
6451 BuildInitCall(DistSchedulingType, CastedDistScheduleChunkSize, Builder);
6452 }
6453
6454 // Load values written by the "init" function.
6455 Value *FirstChunkStart =
6456 Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
6457 Value *FirstChunkStop =
6458 Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
6459 Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
6460 Value *ChunkRange =
6461 Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
6462 Value *NextChunkStride =
6463 Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
6464
6465 // Create outer "dispatch" loop for enumerating the chunks.
6466 BasicBlock *DispatchEnter = splitBB(Builder, true);
6467 Value *DispatchCounter;
6468
6469 // It is safe to assume this didn't return an error because the callback
6470 // passed into createCanonicalLoop is the only possible error source, and it
6471 // always returns success.
6472 CanonicalLoopInfo *DispatchCLI = cantFail(createCanonicalLoop(
6473 {Builder.saveIP(), DL},
6474 [&](InsertPointTy BodyIP, Value *Counter) {
6475 DispatchCounter = Counter;
6476 return Error::success();
6477 },
6478 FirstChunkStart, CastedTripCount, NextChunkStride,
6479 /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
6480 "dispatch"));
6481
6482 // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
6483 // not have to preserve the canonical invariant.
6484 BasicBlock *DispatchBody = DispatchCLI->getBody();
6485 BasicBlock *DispatchLatch = DispatchCLI->getLatch();
6486 BasicBlock *DispatchExit = DispatchCLI->getExit();
6487 BasicBlock *DispatchAfter = DispatchCLI->getAfter();
6488 DispatchCLI->invalidate();
6489
6490 // Rewire the original loop to become the chunk loop inside the dispatch loop.
6491 redirectTo(DispatchAfter, CLI->getAfter(), DL);
6492 redirectTo(CLI->getExit(), DispatchLatch, DL);
6493 redirectTo(DispatchBody, DispatchEnter, DL);
6494
6495 // Prepare the prolog of the chunk loop.
6496 Builder.restoreIP(CLI->getPreheaderIP());
6497 Builder.SetCurrentDebugLocation(DL);
6498
6499 // Compute the number of iterations of the chunk loop.
6500 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
6501 Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
6502 Value *IsLastChunk =
6503 Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
6504 Value *CountUntilOrigTripCount =
6505 Builder.CreateSub(CastedTripCount, DispatchCounter);
6506 Value *ChunkTripCount = Builder.CreateSelect(
6507 IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
6508 Value *BackcastedChunkTC =
6509 Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
6510 CLI->setTripCount(BackcastedChunkTC);
6511
6512 // Update all uses of the induction variable except the one in the condition
6513 // block that compares it with the actual upper bound, and the increment in
6514 // the latch block.
6515 Value *BackcastedDispatchCounter =
6516 Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
6517 CLI->mapIndVar([&](Instruction *) -> Value * {
6518 Builder.restoreIP(CLI->getBodyIP());
6519 return Builder.CreateAdd(IV, BackcastedDispatchCounter);
6520 });
6521
6522 // In the "exit" block, call the "fini" function.
6523 Builder.SetInsertPoint(DispatchExit->getFirstInsertionPt());
6524 createRuntimeFunctionCall(StaticFini, {SrcLoc, ThreadNum});
6525
6526 // Add the barrier if requested.
6527 if (NeedsBarrier) {
6528 InsertPointOrErrorTy AfterIP =
6529 createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
6530 /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
6531 if (!AfterIP)
6532 return AfterIP.takeError();
6533 }
6534
6535#ifndef NDEBUG
6536 // Even though we currently do not support applying additional methods to it,
6537 // the chunk loop should remain a canonical loop.
6538 CLI->assertOK();
6539#endif
6540
6541 return DispatchAfter->getFirstInsertionPt();
6542}
6543
6544// Returns an LLVM function to call for executing an OpenMP static worksharing
6545// for loop depending on `type`. Only i32 and i64 are supported by the runtime.
6546// Always interpret integers as unsigned similarly to CanonicalLoopInfo.
6547static FunctionCallee
6549 WorksharingLoopType LoopType) {
6550 unsigned Bitwidth = Ty->getIntegerBitWidth();
6551 Module &M = OMPBuilder->M;
6552 switch (LoopType) {
6553 case WorksharingLoopType::ForStaticLoop:
6554 if (Bitwidth == 32)
6555 return OMPBuilder->getOrCreateRuntimeFunction(
6556 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_4u);
6557 if (Bitwidth == 64)
6558 return OMPBuilder->getOrCreateRuntimeFunction(
6559 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_8u);
6560 break;
6561 case WorksharingLoopType::DistributeStaticLoop:
6562 if (Bitwidth == 32)
6563 return OMPBuilder->getOrCreateRuntimeFunction(
6564 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_4u);
6565 if (Bitwidth == 64)
6566 return OMPBuilder->getOrCreateRuntimeFunction(
6567 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_8u);
6568 break;
6569 case WorksharingLoopType::DistributeForStaticLoop:
6570 if (Bitwidth == 32)
6571 return OMPBuilder->getOrCreateRuntimeFunction(
6572 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_4u);
6573 if (Bitwidth == 64)
6574 return OMPBuilder->getOrCreateRuntimeFunction(
6575 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_8u);
6576 break;
6577 }
6578 if (Bitwidth != 32 && Bitwidth != 64) {
6579 llvm_unreachable("Unknown OpenMP loop iterator bitwidth");
6580 }
6581 llvm_unreachable("Unknown type of OpenMP worksharing loop");
6582}
6583
6584// Inserts a call to proper OpenMP Device RTL function which handles
6585// loop worksharing.
6587 WorksharingLoopType LoopType,
6588 BasicBlock *InsertBlock, Value *Ident,
6589 Value *LoopBodyArg, Value *TripCount,
6590 Function &LoopBodyFn, bool NoLoop) {
6591 Type *TripCountTy = TripCount->getType();
6592 Module &M = OMPBuilder->M;
6593 IRBuilder<> &Builder = OMPBuilder->Builder;
6594 FunctionCallee RTLFn =
6595 getKmpcForStaticLoopForType(TripCountTy, OMPBuilder, LoopType);
6596 SmallVector<Value *, 8> RealArgs;
6597 RealArgs.push_back(Ident);
6598 RealArgs.push_back(&LoopBodyFn);
6599 RealArgs.push_back(LoopBodyArg);
6600 RealArgs.push_back(TripCount);
6601 if (LoopType == WorksharingLoopType::DistributeStaticLoop) {
6602 RealArgs.push_back(ConstantInt::get(TripCountTy, 0));
6603 RealArgs.push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6604 Builder.restoreIP(std::prev(InsertBlock->end()));
6605 OMPBuilder->createRuntimeFunctionCall(RTLFn, RealArgs);
6606 return;
6607 }
6608 FunctionCallee RTLNumThreads = OMPBuilder->getOrCreateRuntimeFunction(
6609 M, omp::RuntimeFunction::OMPRTL_omp_get_num_threads);
6610 Builder.restoreIP(std::prev(InsertBlock->end()));
6611 Value *NumThreads = OMPBuilder->createRuntimeFunctionCall(RTLNumThreads, {});
6612
6613 RealArgs.push_back(
6614 Builder.CreateZExtOrTrunc(NumThreads, TripCountTy, "num.threads.cast"));
6615 RealArgs.push_back(ConstantInt::get(TripCountTy, 0));
6616 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6617 RealArgs.push_back(ConstantInt::get(TripCountTy, 0));
6618 RealArgs.push_back(ConstantInt::get(Builder.getInt8Ty(), NoLoop));
6619 } else {
6620 RealArgs.push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6621 }
6622
6623 OMPBuilder->createRuntimeFunctionCall(RTLFn, RealArgs);
6624}
6625
6627 OpenMPIRBuilder *OMPIRBuilder, CanonicalLoopInfo *CLI, Value *Ident,
6628 Function &OutlinedFn, const SmallVector<Instruction *, 4> &ToBeDeleted,
6629 WorksharingLoopType LoopType, bool NoLoop) {
6630 IRBuilder<> &Builder = OMPIRBuilder->Builder;
6631 BasicBlock *Preheader = CLI->getPreheader();
6632 Value *TripCount = CLI->getTripCount();
6633
6634 // After loop body outling, the loop body contains only set up
6635 // of loop body argument structure and the call to the outlined
6636 // loop body function. Firstly, we need to move setup of loop body args
6637 // into loop preheader.
6638 Preheader->splice(std::prev(Preheader->end()), CLI->getBody(),
6639 CLI->getBody()->begin(), std::prev(CLI->getBody()->end()));
6640
6641 // The next step is to remove the whole loop. We do not it need anymore.
6642 // That's why make an unconditional branch from loop preheader to loop
6643 // exit block
6644 Builder.restoreIP(Preheader->end());
6645 Builder.SetCurrentDebugLocation(Preheader->getTerminator()->getDebugLoc());
6646 Preheader->getTerminator()->eraseFromParent();
6647 Builder.CreateBr(CLI->getExit());
6648
6649 // Delete dead loop blocks
6650 OpenMPIRBuilder::OutlineInfo CleanUpInfo;
6651 SmallPtrSet<BasicBlock *, 32> RegionBlockSet;
6652 SmallVector<BasicBlock *, 32> BlocksToBeRemoved;
6653 CleanUpInfo.EntryBB = CLI->getHeader();
6654 CleanUpInfo.ExitBB = CLI->getExit();
6655 CleanUpInfo.collectBlocks(RegionBlockSet, BlocksToBeRemoved);
6656 DeleteDeadBlocks(BlocksToBeRemoved);
6657
6658 // Find the instruction which corresponds to loop body argument structure
6659 // and remove the call to loop body function instruction.
6660 Value *LoopBodyArg;
6661 User *OutlinedFnUser = OutlinedFn.getUniqueUndroppableUser();
6662 assert(OutlinedFnUser &&
6663 "Expected unique undroppable user of outlined function");
6664 CallInst *OutlinedFnCallInstruction = dyn_cast<CallInst>(OutlinedFnUser);
6665 assert(OutlinedFnCallInstruction && "Expected outlined function call");
6666 assert((OutlinedFnCallInstruction->getParent() == Preheader) &&
6667 "Expected outlined function call to be located in loop preheader");
6668 // Check in case no argument structure has been passed.
6669 if (OutlinedFnCallInstruction->arg_size() > 1)
6670 LoopBodyArg = OutlinedFnCallInstruction->getArgOperand(1);
6671 else
6672 LoopBodyArg = Constant::getNullValue(Builder.getPtrTy());
6673 OutlinedFnCallInstruction->eraseFromParent();
6674
6675 createTargetLoopWorkshareCall(OMPIRBuilder, LoopType, Preheader, Ident,
6676 LoopBodyArg, TripCount, OutlinedFn, NoLoop);
6677
6678 for (auto &ToBeDeletedItem : ToBeDeleted)
6679 ToBeDeletedItem->eraseFromParent();
6680 CLI->invalidate();
6681}
6682
6683OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::applyWorkshareLoopTarget(
6684 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
6685 WorksharingLoopType LoopType, bool NeedsBarrier, bool NoLoop,
6686 bool NeedsLastIter) {
6687 uint32_t SrcLocStrSize;
6688 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6689
6690 // Mirrors host runtime reporting of last iteration by in-body computation.
6691 if (NeedsLastIter) {
6692 Type *I32Type = Type::getInt32Ty(M.getContext());
6693 Builder.restoreIP(AllocaIP);
6694 AllocaInst *PLastIter =
6695 Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6696 CLI->setLastIter(PLastIter);
6697
6698 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
6699 Builder.CreateStore(ConstantInt::get(I32Type, 0), PLastIter);
6700
6701 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
6702 Value *TripCount = CLI->getTripCount();
6703 Value *LastIter =
6704 Builder.CreateSub(TripCount, ConstantInt::get(TripCount->getType(), 1));
6705 Value *IsLast =
6706 Builder.CreateICmpEQ(CLI->getIndVar(), LastIter, "omp.is_last_iter");
6707 Builder.CreateStore(Builder.CreateZExt(IsLast, I32Type), PLastIter);
6708 }
6709
6711 switch (LoopType) {
6712 case WorksharingLoopType::ForStaticLoop:
6713 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6714 break;
6715 case WorksharingLoopType::DistributeStaticLoop:
6716 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6717 break;
6718 case WorksharingLoopType::DistributeForStaticLoop:
6719 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6720 break;
6721 }
6722 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize, Flag);
6723
6724 auto OI = std::make_unique<OutlineInfo>();
6725 OI->OuterAllocBB = CLI->getPreheader();
6726 Function *OuterFn = CLI->getPreheader()->getParent();
6727
6728 // Instructions which need to be deleted at the end of code generation
6729 SmallVector<Instruction *, 4> ToBeDeleted;
6730
6731 OI->OuterAllocBB = AllocaIP.getNodeParent();
6732
6733 // Mark the body loop as region which needs to be extracted
6734 OI->EntryBB = CLI->getBody();
6735 OI->ExitBB = CLI->getLatch()->splitBasicBlockBefore(CLI->getLatch()->begin(),
6736 "omp.prelatch");
6737
6738 // Prepare loop body for extraction
6739 Builder.restoreIP(CLI->getPreheader()->begin());
6740
6741 // Insert new loop counter variable which will be used only in loop
6742 // body.
6743 AllocaInst *NewLoopCnt = Builder.CreateAlloca(CLI->getIndVarType(), 0, "");
6744 Instruction *NewLoopCntLoad =
6745 Builder.CreateLoad(CLI->getIndVarType(), NewLoopCnt);
6746 // New loop counter instructions are redundant in the loop preheader when
6747 // code generation for workshare loop is finshed. That's why mark them as
6748 // ready for deletion.
6749 ToBeDeleted.push_back(NewLoopCntLoad);
6750 ToBeDeleted.push_back(NewLoopCnt);
6751
6752 // Analyse loop body region. Find all input variables which are used inside
6753 // loop body region.
6754 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
6756 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
6757
6758 CodeExtractorAnalysisCache CEAC(*OuterFn);
6759 CodeExtractor Extractor(Blocks,
6760 /* DominatorTree */ nullptr,
6761 /* AggregateArgs */ true,
6762 /* BlockFrequencyInfo */ nullptr,
6763 /* BranchProbabilityInfo */ nullptr,
6764 /* AssumptionCache */ nullptr,
6765 /* AllowVarArgs */ true,
6766 /* AllowAlloca */ true,
6767 /* AllocationBlock */ CLI->getPreheader(),
6768 /* DeallocationBlocks */ {},
6769 /* Suffix */ ".omp_wsloop",
6770 /* AggrArgsIn0AddrSpace */ true);
6771
6772 BasicBlock *CommonExit = nullptr;
6773 SetVector<Value *> SinkingCands, HoistingCands;
6774
6775 // Find allocas outside the loop body region which are used inside loop
6776 // body
6777 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
6778
6779 // We need to model loop body region as the function f(cnt, loop_arg).
6780 // That's why we replace loop induction variable by the new counter
6781 // which will be one of loop body function argument
6783 CLI->getIndVar()->user_end());
6784 for (auto Use : Users) {
6785 if (Instruction *Inst = dyn_cast<Instruction>(Use)) {
6786 if (ParallelRegionBlockSet.count(Inst->getParent())) {
6787 Inst->replaceUsesOfWith(CLI->getIndVar(), NewLoopCntLoad);
6788 }
6789 }
6790 }
6791 // Make sure that loop counter variable is not merged into loop body
6792 // function argument structure and it is passed as separate variable
6793 OI->ExcludeArgsFromAggregate.push_back(NewLoopCntLoad);
6794
6795 // PostOutline CB is invoked when loop body function is outlined and
6796 // loop body is replaced by call to outlined function. We need to add
6797 // call to OpenMP device rtl inside loop preheader. OpenMP device rtl
6798 // function will handle loop control logic.
6799 //
6800 OI->PostOutlineCB = [=, ToBeDeletedVec =
6801 std::move(ToBeDeleted)](Function &OutlinedFn) {
6802 workshareLoopTargetCallback(this, CLI, Ident, OutlinedFn, ToBeDeletedVec,
6803 LoopType, NoLoop);
6804 };
6805 addOutlineInfo(std::move(OI));
6806
6807 // Keep the barrier outside the outlined loop body so that every thread
6808 // encounters it, including threads that execute no iterations.
6809 if (NeedsBarrier) {
6810 Builder.SetInsertPoint(CLI->getExit()->getTerminator());
6811 // Standalone distribute loops never request a barrier. For both regular
6812 // worksharing loops and combined distribute/for loops, the barrier is
6813 // associated with the worksharing loop, hence OMPD_for.
6814 InsertPointOrErrorTy BarrierIP =
6815 createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
6816 /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
6817 if (!BarrierIP)
6818 return BarrierIP.takeError();
6819 }
6820 return CLI->getAfterIP();
6821}
6822
6825 bool NeedsBarrier, omp::ScheduleKind SchedKind, Value *ChunkSize,
6826 bool HasSimdModifier, bool HasMonotonicModifier,
6827 bool HasNonmonotonicModifier, bool HasOrderedClause,
6828 WorksharingLoopType LoopType, bool NoLoop, bool HasDistSchedule,
6829 Value *DistScheduleChunkSize, bool NeedsLastIter) {
6830 if (CLI->VirtualCollapse &&
6831 (Config.isTargetDevice() ||
6832 (SchedKind != omp::OMP_SCHEDULE_Static &&
6833 SchedKind != omp::OMP_SCHEDULE_Default) ||
6834 ChunkSize || HasOrderedClause || HasDistSchedule ||
6835 DistScheduleChunkSize || LoopType != WorksharingLoopType::ForStaticLoop))
6837 "Virtual collapse requires unchunked static worksharing");
6838 if (Config.isTargetDevice())
6839 return applyWorkshareLoopTarget(DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6840 NoLoop, NeedsLastIter);
6841 OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(
6842 SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
6843 HasNonmonotonicModifier, HasOrderedClause, DistScheduleChunkSize);
6844
6845 bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
6846 OMPScheduleType::ModifierOrdered;
6847 OMPScheduleType DistScheduleSchedType = OMPScheduleType::None;
6848 if (HasDistSchedule) {
6849 DistScheduleSchedType = DistScheduleChunkSize
6850 ? OMPScheduleType::OrderedDistributeChunked
6851 : OMPScheduleType::OrderedDistribute;
6852 }
6853 switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
6854 case OMPScheduleType::BaseStatic:
6855 case OMPScheduleType::BaseDistribute:
6856 assert((!ChunkSize || !DistScheduleChunkSize) &&
6857 "No chunk size with static-chunked schedule");
6858 if (IsOrdered && !HasDistSchedule)
6859 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
6860 NeedsBarrier, ChunkSize);
6861 // FIXME: Monotonicity ignored?
6862 if (DistScheduleChunkSize)
6863 return applyStaticChunkedWorkshareLoop(
6864 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6865 DistScheduleChunkSize, DistScheduleSchedType);
6866 return applyStaticWorkshareLoop(DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6867 HasDistSchedule);
6868
6869 case OMPScheduleType::BaseStaticChunked:
6870 case OMPScheduleType::BaseDistributeChunked:
6871 if (IsOrdered && !HasDistSchedule)
6872 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
6873 NeedsBarrier, ChunkSize);
6874 // FIXME: Monotonicity ignored?
6875 return applyStaticChunkedWorkshareLoop(
6876 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6877 DistScheduleChunkSize, DistScheduleSchedType);
6878
6879 case OMPScheduleType::BaseRuntime:
6880 case OMPScheduleType::BaseAuto:
6881 case OMPScheduleType::BaseGreedy:
6882 case OMPScheduleType::BaseBalanced:
6883 case OMPScheduleType::BaseSteal:
6884 case OMPScheduleType::BaseRuntimeSimd:
6885 assert(!ChunkSize &&
6886 "schedule type does not support user-defined chunk sizes");
6887 [[fallthrough]];
6888 case OMPScheduleType::BaseGuidedSimd:
6889 case OMPScheduleType::BaseDynamicChunked:
6890 case OMPScheduleType::BaseGuidedChunked:
6891 case OMPScheduleType::BaseGuidedIterativeChunked:
6892 case OMPScheduleType::BaseGuidedAnalyticalChunked:
6893 case OMPScheduleType::BaseStaticBalancedChunked:
6894 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
6895 NeedsBarrier, ChunkSize);
6896
6897 default:
6898 llvm_unreachable("Unknown/unimplemented schedule kind");
6899 }
6900}
6901
6902/// Returns an LLVM function to call for initializing loop bounds using OpenMP
6903/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
6904/// the runtime. Always interpret integers as unsigned similarly to
6905/// CanonicalLoopInfo.
6906static FunctionCallee
6908 unsigned Bitwidth = Ty->getIntegerBitWidth();
6909 if (Bitwidth == 32)
6910 return OMPBuilder.getOrCreateRuntimeFunction(
6911 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
6912 if (Bitwidth == 64)
6913 return OMPBuilder.getOrCreateRuntimeFunction(
6914 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
6915 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6916}
6917
6918/// Returns an LLVM function to call for updating the next loop using OpenMP
6919/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
6920/// the runtime. Always interpret integers as unsigned similarly to
6921/// CanonicalLoopInfo.
6922static FunctionCallee
6924 unsigned Bitwidth = Ty->getIntegerBitWidth();
6925 if (Bitwidth == 32)
6926 return OMPBuilder.getOrCreateRuntimeFunction(
6927 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
6928 if (Bitwidth == 64)
6929 return OMPBuilder.getOrCreateRuntimeFunction(
6930 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
6931 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6932}
6933
6934/// Returns an LLVM function to call for finalizing the dynamic loop using
6935/// depending on `type`. Only i32 and i64 are supported by the runtime. Always
6936/// interpret integers as unsigned similarly to CanonicalLoopInfo.
6937static FunctionCallee
6939 unsigned Bitwidth = Ty->getIntegerBitWidth();
6940 if (Bitwidth == 32)
6941 return OMPBuilder.getOrCreateRuntimeFunction(
6942 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
6943 if (Bitwidth == 64)
6944 return OMPBuilder.getOrCreateRuntimeFunction(
6945 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
6946 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6947}
6948
6950OpenMPIRBuilder::applyDynamicWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
6951 InsertPointTy AllocaIP,
6952 OMPScheduleType SchedType,
6953 bool NeedsBarrier, Value *Chunk) {
6954 assert(CLI->isValid() && "Requires a valid canonical loop");
6955 assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
6956 "Require dedicated allocate IP");
6958 "Require valid schedule type");
6959
6960 bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
6961 OMPScheduleType::ModifierOrdered;
6962
6963 // Set up the source location value for OpenMP runtime.
6964 Builder.SetCurrentDebugLocation(DL);
6965
6966 uint32_t SrcLocStrSize;
6967 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6968 Value *SrcLoc =
6969 getOrCreateIdent(SrcLocStr, SrcLocStrSize, OMP_IDENT_FLAG_WORK_LOOP);
6970
6971 // Declare useful OpenMP runtime functions.
6972 Value *IV = CLI->getIndVar();
6973 Type *IVTy = IV->getType();
6974 FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
6975 FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
6976
6977 // Allocate space for computed loop bounds as expected by the "init" function.
6978 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6979 Type *I32Type = Type::getInt32Ty(M.getContext());
6980 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6981 Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
6982 Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
6983 Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
6984 CLI->setLastIter(PLastIter);
6985
6986 // At the end of the preheader, prepare for calling the "init" function by
6987 // storing the current loop bounds into the allocated space. A canonical loop
6988 // always iterates from 0 to trip-count with step 1. Note that "init" expects
6989 // and produces an inclusive upper bound.
6990 BasicBlock *PreHeader = CLI->getPreheader();
6991 Builder.SetInsertPoint(PreHeader->getTerminator());
6992 Constant *One = ConstantInt::get(IVTy, 1);
6993 Builder.CreateStore(One, PLowerBound);
6994 Value *UpperBound = CLI->getTripCount();
6995 Builder.CreateStore(UpperBound, PUpperBound);
6996 Builder.CreateStore(One, PStride);
6997
6998 BasicBlock *Header = CLI->getHeader();
6999 BasicBlock *Exit = CLI->getExit();
7000 BasicBlock *Cond = CLI->getCond();
7001 BasicBlock *Latch = CLI->getLatch();
7002 InsertPointTy AfterIP = CLI->getAfterIP();
7003
7004 // The CLI will be "broken" in the code below, as the loop is no longer
7005 // a valid canonical loop.
7006
7007 if (!Chunk)
7008 Chunk = One;
7009
7010 Value *ThreadNum =
7011 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize));
7012
7013 Constant *SchedulingType =
7014 ConstantInt::get(I32Type, static_cast<int>(SchedType));
7015
7016 // Call the "init" function.
7017 createRuntimeFunctionCall(DynamicInit, {SrcLoc, ThreadNum, SchedulingType,
7018 /* LowerBound */ One, UpperBound,
7019 /* step */ One, Chunk});
7020
7021 // An outer loop around the existing one.
7022 BasicBlock *OuterCond = BasicBlock::Create(
7023 PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
7024 PreHeader->getParent());
7025 // This needs to be 32-bit always, so can't use the IVTy Zero above.
7026 Builder.SetInsertPoint(OuterCond->getFirstInsertionPt());
7028 DynamicNext,
7029 {SrcLoc, ThreadNum, PLastIter, PLowerBound, PUpperBound, PStride});
7030 Constant *Zero32 = ConstantInt::get(I32Type, 0);
7031 Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
7032 Value *LowerBound =
7033 Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
7034 Builder.CreateCondBr(MoreWork, Header, Exit);
7035
7036 // Change PHI-node in loop header to use outer cond rather than preheader,
7037 // and set IV to the LowerBound.
7038 Instruction *Phi = &Header->front();
7039 auto *PI = cast<PHINode>(Phi);
7040 PI->setIncomingBlock(0, OuterCond);
7041 PI->setIncomingValue(0, LowerBound);
7042
7043 // Then set the pre-header to jump to the OuterCond
7044 Instruction *Term = PreHeader->getTerminator();
7045 auto *Br = cast<UncondBrInst>(Term);
7046 Br->setSuccessor(OuterCond);
7047
7048 // Modify the inner condition:
7049 // * Use the UpperBound returned from the DynamicNext call.
7050 // * jump to the loop outer loop when done with one of the inner loops.
7051 Builder.SetInsertPoint(Cond->getFirstInsertionPt());
7052 UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
7053 Instruction *Comp = &*Builder.GetInsertPoint();
7054 auto *CI = cast<CmpInst>(Comp);
7055 CI->setOperand(1, UpperBound);
7056 // Redirect the inner exit to branch to outer condition.
7057 Instruction *Branch = &Cond->back();
7058 auto *BI = cast<CondBrInst>(Branch);
7059 assert(BI->getSuccessor(1) == Exit);
7060 BI->setSuccessor(1, OuterCond);
7061
7062 // Call the "fini" function if "ordered" is present in wsloop directive.
7063 if (Ordered) {
7064 Builder.SetInsertPoint(&Latch->back());
7065 FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
7066 createRuntimeFunctionCall(DynamicFini, {SrcLoc, ThreadNum});
7067 }
7068
7069 // Add the barrier if requested.
7070 if (NeedsBarrier) {
7071 Builder.SetInsertPoint(&Exit->back());
7072 InsertPointOrErrorTy BarrierIP =
7074 omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
7075 /* CheckCancelFlag */ false);
7076 if (!BarrierIP)
7077 return BarrierIP.takeError();
7078 }
7079
7080 CLI->invalidate();
7081 return AfterIP;
7082}
7083
7084/// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
7085/// after this \p OldTarget will be orphaned.
7087 BasicBlock *NewTarget, DebugLoc DL) {
7089 redirectTo(Pred, NewTarget, DL);
7090}
7091
7093 SmallPtrSet<BasicBlock *, 8> InternalBBs(from_range, BBs);
7094 // We add a block to BBsToKeep iff we have proven it has an external use.
7096
7097 while (true) {
7098 bool Changed = false;
7099
7100 for (BasicBlock *BB : BBs) {
7101 if (BBsToKeep.contains(BB))
7102 continue;
7103
7104 for (Use &U : BB->uses()) {
7105 auto *UseInst = dyn_cast<Instruction>(U.getUser());
7106 if (!UseInst)
7107 continue;
7108 BasicBlock *UseBB = UseInst->getParent();
7109 if (!InternalBBs.contains(UseBB) || BBsToKeep.contains(UseBB)) {
7110 BBsToKeep.insert(BB);
7111 Changed = true;
7112 break;
7113 }
7114 }
7115 }
7116
7117 if (!Changed)
7118 break;
7119 }
7120
7122 BBs, [&BBsToKeep](BasicBlock *BB) { return !BBsToKeep.contains(BB); });
7123 DeleteDeadBlocks(BBsToDelete);
7124}
7125
7126/// Physical handles captured before the source descriptors are invalidated.
7133
7135OpenMPIRBuilder::planVirtualRowLoop(ArrayRef<CanonicalLoopInfo *> Loops) {
7136 // The executor inserts a guard before the outer latch. An indirect jump
7137 // by block address could bypass that guard.
7138 if (isa<IndirectBrInst>(Loops.back()->getAfter()->getTerminator()))
7140 "Virtual collapse requires unobserved canonical loop controls");
7141 // Save the original blocks and IVs before the executor changes the CFG.
7142 VirtualRowPlan Plan;
7143 Plan.Latches.push_back(Loops.front()->getLatch());
7144 for (CanonicalLoopInfo *Loop : Loops) {
7145 Plan.IndVars.push_back(cast<PHINode>(Loop->getIndVar()));
7146 Plan.Preheaders.push_back(Loop->getPreheader());
7147 }
7148 // The inner loop must return directly to the latch where the guard is added.
7149 if (Loops.front()->getBody()->getUniqueSuccessor() !=
7150 Plan.Preheaders.back() ||
7151 Loops.back()->getAfter()->getSingleSuccessor() != Plan.Latches.front())
7152 reportFatalInternalError("Virtual collapse requires direct nesting");
7153 Plan.InnerCmp = cast<CmpInst>(&Loops.back()->getCond()->front());
7154 return Plan;
7155}
7156
7157void OpenMPIRBuilder::createVirtualRowExecutor(CanonicalLoopInfo *Result,
7158 const VirtualRowPlan &Plan,
7159 ArrayRef<Value *> TripCounts,
7160 Value *Begin, Value *Count,
7161 BasicBlock *Entry) {
7162 DebugLoc DL = Builder.getCurrentDebugLocation();
7163 BasicBlock *OuterHeader = Plan.IndVars.front()->getParent();
7164 Type *IVType = Begin->getType();
7165 Constant *Zero = ConstantInt::get(IVType, 0);
7166 // A row is one invocation of the inner loop. Decode the first logical
7167 // iteration once, before entering the original loop nest.
7168 Builder.SetInsertPoint(Entry);
7169 Value *InnerBegin =
7170 Builder.CreateURem(Begin, TripCounts.back(), "omp_collapsed.begin.1");
7171 Value *OuterBegin =
7172 Builder.CreateUDiv(Begin, TripCounts.back(), "omp_collapsed.begin.0");
7173 // Include the skipped prefix of the first row so each completed row
7174 // removes one full inner trip count from Remaining.
7175 Value *InitialRemaining =
7176 Builder.CreateAdd(Count, InnerBegin, "omp_collapsed.row.remaining");
7177 Builder.CreateBr(OuterHeader);
7178
7179 Builder.SetInsertPoint(OuterHeader->getFirstNonPHIIt());
7180 Builder.SetCurrentDebugLocation(DL);
7181 PHINode *Remaining =
7182 Builder.CreatePHI(IVType, 2, "omp_collapsed.row.remaining.0");
7183 Remaining->addIncoming(InitialRemaining, Entry);
7184 // Only the first row starts at InnerBegin; subsequent rows start at zero.
7185 // For an inner trip count of one, the existing zero start is sufficient.
7186 auto *InnerCount = dyn_cast<ConstantInt>(TripCounts.back());
7187 if (!InnerCount || !InnerCount->isOne()) {
7188 PHINode *Start =
7189 Builder.CreatePHI(IVType, 2, "omp_collapsed.row.start.1.0");
7190 Start->addIncoming(InnerBegin, Entry);
7191 Start->addIncoming(Zero, Plan.Latches.front());
7192 Plan.IndVars.back()->setIncomingValue(0, Start);
7193 }
7194 // Saved inner-preheader insertions must not change the IV PHI's entry edge.
7195 // Keep the original branch as their anchor and give it a PHI-free successor.
7196 auto *InnerBr = cast<UncondBrInst>(Plan.Preheaders.back()->getTerminator());
7197 BasicBlock *InnerHeader = Plan.IndVars.back()->getParent();
7198 BasicBlock *InnerEntry =
7199 BasicBlock::Create(M.getContext(), "omp_collapsed.row.preheader",
7200 InnerHeader->getParent(), InnerHeader);
7201 Builder.SetInsertPoint(InnerEntry);
7202 Builder.SetCurrentDebugLocation(DL);
7203 Builder.CreateBr(InnerHeader);
7204 InnerBr->setSuccessor(InnerEntry);
7205 Plan.IndVars.back()->setIncomingBlock(0, InnerEntry);
7206 // The final row ends at Remaining; earlier rows keep their original bound.
7207 Builder.SetInsertPoint(Plan.Preheaders.back()->getTerminator());
7208 Builder.SetCurrentDebugLocation(DL);
7209 Value *IsFinalRow = Builder.CreateICmpULE(Remaining, TripCounts.back(),
7210 "omp_collapsed.row.is_final");
7211 Value *InnerStop = Builder.CreateSelect(
7212 IsFinalRow, Remaining, TripCounts.back(), "omp_collapsed.row.stop");
7213 Plan.InnerCmp->setOperand(1, InnerStop);
7214
7215 // Only non-final rows reach the outer latch, so Remaining is greater than
7216 // the inner trip count and this subtraction cannot underflow.
7217 BasicBlock *Latch = Plan.Latches.front();
7218 Builder.SetInsertPoint(Latch->getTerminator());
7219 Builder.SetCurrentDebugLocation(DL);
7220 Value *RemainingNext = Builder.CreateSub(Remaining, TripCounts.back(),
7221 "omp_collapsed.row.remaining.next",
7222 /*HasNUW=*/true);
7223 Remaining->addIncoming(RemainingNext, Latch);
7224 // Check completion after the inner loop and its continuation, before
7225 // incrementing the outer IV. The final row exits the whole nest.
7226 BasicBlock *Guard =
7227 Latch->splitBasicBlockBefore(Latch->begin(), "omp_collapsed.row.done");
7228 Guard->getTerminator()->eraseFromParent();
7229 Builder.SetInsertPoint(Guard);
7230 Builder.CreateCondBr(IsFinalRow, Result->getExit(), Latch);
7231 // Match the retained outer bound to the count used in the total product.
7232 cast<CmpInst>(&Result->getCond()->front())->setOperand(1, TripCounts.front());
7233
7234 // Trip counts are unsigned and may exceed the IV's signed range.
7235 // TODO: Preserve nsw when the trip count is known to fit the signed range.
7236 for (auto [IV, TripCount] : zip(Plan.IndVars, TripCounts))
7237 if (!isa<ConstantInt>(TripCount))
7238 cast<BinaryOperator>(IV->getIncomingValue(1))->setHasNoSignedWrap(false);
7239
7240 Plan.IndVars.front()->setIncomingValue(0, OuterBegin);
7241 Plan.IndVars.front()->setIncomingBlock(0, Entry);
7242}
7243
7244CanonicalLoopInfo *OpenMPIRBuilder::createVirtualCollapsedLoop(
7246 const VirtualRowPlan &Plan, ArrayRef<Value *> TripCounts,
7247 Value *CollapsedTripCount) {
7248 // Reuse the outer loop's control blocks; the physical nest stays in place.
7249 LoopInfos.emplace_front();
7250 CanonicalLoopInfo *Result = &LoopInfos.front();
7251 Result->Header = Loops.front()->getHeader();
7252 Result->Cond = Loops.front()->getCond();
7253 Result->Latch = Loops.front()->getLatch();
7254 Result->Exit = Loops.front()->getExit();
7255 BasicBlock *Preheader = Plan.Preheaders.front();
7256 Function *F = Result->getFunction();
7257 Type *IVType = CollapsedTripCount->getType();
7258 Constant *Zero = ConstantInt::get(IVType, 0);
7259 // Keep initialization separate from decoding so an empty range skips both
7260 // division and the loop nest.
7261 BasicBlock *Init = BasicBlock::Create(M.getContext(), "omp_collapsed.init", F,
7262 Result->getHeader());
7263 BasicBlock *Entry = BasicBlock::Create(M.getContext(), "omp_collapsed.decode",
7264 F, Result->getHeader());
7265 Builder.SetCurrentDebugLocation(DL);
7266 Builder.SetInsertPoint(Init);
7267 // Keep explicit range copies until scheduling replaces operand zero. Create
7268 // the instructions directly so the initial constants are not folded away.
7269 auto *Begin = Builder.Insert(BinaryOperator::CreateAdd(Zero, Zero),
7270 "omp_collapsed.range.begin");
7271 auto *Count =
7272 Builder.Insert(BinaryOperator::CreateAdd(CollapsedTripCount, Zero),
7273 "omp_collapsed.range.count");
7274 Builder.CreateCondBr(Builder.CreateICmpNE(Count, Zero), Entry,
7275 Result->getExit());
7276 Result->VirtualCollapse =
7277 CanonicalLoopInfo::VirtualCollapseInfo{Begin, Count};
7278 // Route the preheader through Init. The executor reconnects the outer IV
7279 // PHI to the decode block.
7280 cast<UncondBrInst>(Preheader->getTerminator())->setSuccessor(Init);
7281 createVirtualRowExecutor(Result, Plan, TripCounts, Begin, Count, Entry);
7282 // The transformed nest is now represented by Result, not the input loops.
7283 for (CanonicalLoopInfo *Loop : Loops)
7284 Loop->invalidate();
7285#ifndef NDEBUG
7286 Result->assertOK();
7287#endif
7288 return Result;
7289}
7290
7291void OpenMPIRBuilder::bindCollapsedRange(CanonicalLoopInfo *Loop, Value *Begin,
7292 Value *Count) {
7293 // Update only the copied values; the range has no PHI predecessor to rebind.
7294 Loop->VirtualCollapse->Begin->setOperand(0, Begin);
7295 Loop->VirtualCollapse->Count->setOperand(0, Count);
7296}
7297
7298CanonicalLoopInfo *
7300 InsertPointTy ComputeIP) {
7301 assert(Loops.size() >= 1 && "At least one loop required");
7302 size_t NumLoops = Loops.size();
7303
7304 // Nothing to do if there is already just one loop.
7305 if (NumLoops == 1)
7306 return Loops.front();
7307
7308 if (Config.CollapseMapping == CollapseIVMapping::Virtual) {
7309 if (Loops.size() != 2)
7310 reportFatalInternalError("Virtual collapse requires two loops");
7311 SmallVector<Value *, 4> TripCounts;
7312 for (CanonicalLoopInfo *Loop : Loops) {
7313 if (Loop->VirtualCollapse)
7314 Loop->reportUnsupportedVirtualCollapse();
7315 Value *TC = Loop->getTripCount();
7316 TripCounts.push_back(TC);
7317 }
7318 VirtualRowPlan Plan = planVirtualRowLoop(Loops);
7319 if (ComputeIP.isValid())
7320 Builder.restoreIP(ComputeIP);
7321 else
7322 Builder.restoreIP(Loops.front()->getPreheaderIP());
7323 Builder.SetCurrentDebugLocation(DL);
7324
7325 // Freeze each count once so the product, decoding and bounds agree even
7326 // for undef or poison inputs.
7328 for (Value *&TripCount : TripCounts) {
7329 if (isa<ConstantInt, FreezeInst>(TripCount))
7330 continue;
7331 auto [It, Inserted] = Counts.try_emplace(TripCount, TripCount);
7332 if (Inserted)
7333 It->second = Builder.CreateFreeze(TripCount, "omp_collapsed.tripcount");
7334 TripCount = It->second;
7335 }
7336 Value *CollapsedTripCount =
7337 Builder.CreateNUWMul(TripCounts.front(), TripCounts.back());
7338 return createVirtualCollapsedLoop(DL, Loops, Plan, TripCounts,
7339 CollapsedTripCount);
7340 }
7341
7342 CanonicalLoopInfo *Outermost = Loops.front();
7343 CanonicalLoopInfo *Innermost = Loops.back();
7344 BasicBlock *OrigPreheader = Outermost->getPreheader();
7345 BasicBlock *OrigAfter = Outermost->getAfter();
7346 Function *F = OrigPreheader->getParent();
7347
7348 // Loop control blocks that may become orphaned later.
7349 SmallVector<BasicBlock *, 12> OldControlBBs;
7350 OldControlBBs.reserve(6 * Loops.size());
7352 Loop->collectControlBlocks(OldControlBBs);
7353
7354 // Setup the IRBuilder for inserting the trip count computation.
7355 Builder.SetCurrentDebugLocation(DL);
7356 if (ComputeIP.isValid())
7357 Builder.restoreIP(ComputeIP);
7358 else
7359 Builder.restoreIP(Outermost->getPreheaderIP());
7360
7361 // Derive the collapsed' loop trip count.
7362 // TODO: Find common/largest indvar type.
7363 Value *CollapsedTripCount = nullptr;
7364 for (CanonicalLoopInfo *L : Loops) {
7365 assert(L->isValid() &&
7366 "All loops to collapse must be valid canonical loops");
7367 Value *OrigTripCount = L->getTripCount();
7368 if (!CollapsedTripCount) {
7369 CollapsedTripCount = OrigTripCount;
7370 continue;
7371 }
7372
7373 // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
7374 CollapsedTripCount =
7375 Builder.CreateNUWMul(CollapsedTripCount, OrigTripCount);
7376 }
7377
7378 // Create the collapsed loop control flow.
7379 CanonicalLoopInfo *Result =
7380 createLoopSkeleton(DL, CollapsedTripCount, F,
7381 OrigPreheader->getNextNode(), OrigAfter, "collapsed",
7382 /*IsCollapsed=*/true);
7383
7384 // Build the collapsed loop body code.
7385 // Start with deriving the input loop induction variables from the collapsed
7386 // one, using a divmod scheme. To preserve the original loops' order, the
7387 // innermost loop use the least significant bits.
7388 Builder.restoreIP(Result->getBodyIP());
7389
7390 Value *Leftover = Result->getIndVar();
7391 SmallVector<Value *> NewIndVars;
7392 NewIndVars.resize(NumLoops);
7393 for (int i = NumLoops - 1; i >= 1; --i) {
7394 Value *OrigTripCount = Loops[i]->getTripCount();
7395
7396 Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
7397 NewIndVars[i] = NewIndVar;
7398
7399 Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
7400 }
7401 // Outermost loop gets all the remaining bits.
7402 NewIndVars[0] = Leftover;
7403
7404 // Construct the loop body control flow.
7405 // We progressively construct the branch structure following in direction of
7406 // the control flow, from the leading in-between code, the loop nest body, the
7407 // trailing in-between code, and rejoining the collapsed loop's latch.
7408 // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
7409 // the ContinueBlock is set, continue with that block. If ContinuePred, use
7410 // its predecessors as sources.
7411 BasicBlock *ContinueBlock = Result->getBody();
7412 BasicBlock *ContinuePred = nullptr;
7413 auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
7414 BasicBlock *NextSrc) {
7415 if (ContinueBlock)
7416 redirectTo(ContinueBlock, Dest, DL);
7417 else
7418 redirectAllPredecessorsTo(ContinuePred, Dest, DL);
7419
7420 ContinueBlock = nullptr;
7421 ContinuePred = NextSrc;
7422 };
7423
7424 // The code before the nested loop of each level.
7425 // Because we are sinking it into the nest, it will be executed more often
7426 // that the original loop. More sophisticated schemes could keep track of what
7427 // the in-between code is and instantiate it only once per thread.
7428 for (size_t i = 0; i < NumLoops - 1; ++i)
7429 ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
7430
7431 // Connect the loop nest body.
7432 ContinueWith(Innermost->getBody(), Innermost->getLatch());
7433
7434 // The code after the nested loop at each level.
7435 for (size_t i = NumLoops - 1; i > 0; --i)
7436 ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
7437
7438 // Connect the finished loop to the collapsed loop latch.
7439 ContinueWith(Result->getLatch(), nullptr);
7440
7441 // Replace the input loops with the new collapsed loop.
7442 redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
7443 redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
7444
7445 // Replace the input loop indvars with the derived ones.
7446 for (size_t i = 0; i < NumLoops; ++i)
7447 Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
7448
7449 // Remove unused parts of the input loops.
7450 removeUnusedBlocksFromParent(OldControlBBs);
7451
7452 for (CanonicalLoopInfo *L : Loops)
7453 L->invalidate();
7454
7455#ifndef NDEBUG
7456 Result->assertOK();
7457#endif
7458 return Result;
7459}
7460
7461std::vector<CanonicalLoopInfo *>
7463 ArrayRef<Value *> TileSizes) {
7464 assert(TileSizes.size() == Loops.size() &&
7465 "Must pass as many tile sizes as there are loops");
7466 int NumLoops = Loops.size();
7467 assert(NumLoops >= 1 && "At least one loop to tile required");
7468
7469 CanonicalLoopInfo *OutermostLoop = Loops.front();
7470 CanonicalLoopInfo *InnermostLoop = Loops.back();
7471 Function *F = OutermostLoop->getBody()->getParent();
7472 BasicBlock *InnerEnter = InnermostLoop->getBody();
7473 BasicBlock *InnerLatch = InnermostLoop->getLatch();
7474
7475 // Loop control blocks that may become orphaned later.
7476 SmallVector<BasicBlock *, 12> OldControlBBs;
7477 OldControlBBs.reserve(6 * Loops.size());
7479 Loop->collectControlBlocks(OldControlBBs);
7480
7481 // Collect original trip counts and induction variable to be accessible by
7482 // index. Also, the structure of the original loops is not preserved during
7483 // the construction of the tiled loops, so do it before we scavenge the BBs of
7484 // any original CanonicalLoopInfo.
7485 SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
7486 for (CanonicalLoopInfo *L : Loops) {
7487 assert(L->isValid() && "All input loops must be valid canonical loops");
7488 OrigTripCounts.push_back(L->getTripCount());
7489 OrigIndVars.push_back(L->getIndVar());
7490 }
7491
7492 // Collect the code between loop headers. These may contain SSA definitions
7493 // that are used in the loop nest body. To be usable with in the innermost
7494 // body, these BasicBlocks will be sunk into the loop nest body. That is,
7495 // these instructions may be executed more often than before the tiling.
7496 // TODO: It would be sufficient to only sink them into body of the
7497 // corresponding tile loop.
7499 for (int i = 0; i < NumLoops - 1; ++i) {
7500 CanonicalLoopInfo *Surrounding = Loops[i];
7501 CanonicalLoopInfo *Nested = Loops[i + 1];
7502
7503 BasicBlock *EnterBB = Surrounding->getBody();
7504 BasicBlock *ExitBB = Nested->getHeader();
7505 InbetweenCode.emplace_back(EnterBB, ExitBB);
7506 }
7507
7508 // Compute the trip counts of the floor loops.
7509 Builder.SetCurrentDebugLocation(DL);
7510 Builder.restoreIP(OutermostLoop->getPreheaderIP());
7511 SmallVector<Value *, 4> FloorCompleteCount, FloorCount, FloorRems;
7512 for (int i = 0; i < NumLoops; ++i) {
7513 Value *TileSize = TileSizes[i];
7514 Value *OrigTripCount = OrigTripCounts[i];
7515 Type *IVType = OrigTripCount->getType();
7516
7517 Value *FloorCompleteTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
7518 Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
7519
7520 // 0 if tripcount divides the tilesize, 1 otherwise.
7521 // 1 means we need an additional iteration for a partial tile.
7522 //
7523 // Unfortunately we cannot just use the roundup-formula
7524 // (tripcount + tilesize - 1)/tilesize
7525 // because the summation might overflow. We do not want introduce undefined
7526 // behavior when the untiled loop nest did not.
7527 Value *FloorTripOverflow =
7528 Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
7529
7530 FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
7531 Value *FloorTripCount =
7532 Builder.CreateAdd(FloorCompleteTripCount, FloorTripOverflow,
7533 "omp_floor" + Twine(i) + ".tripcount", true);
7534
7535 // Remember some values for later use.
7536 FloorCompleteCount.push_back(FloorCompleteTripCount);
7537 FloorCount.push_back(FloorTripCount);
7538 FloorRems.push_back(FloorTripRem);
7539 }
7540
7541 // Generate the new loop nest, from the outermost to the innermost.
7542 std::vector<CanonicalLoopInfo *> Result;
7543 Result.reserve(NumLoops * 2);
7544
7545 // The basic block of the surrounding loop that enters the nest generated
7546 // loop.
7547 BasicBlock *Enter = OutermostLoop->getPreheader();
7548
7549 // The basic block of the surrounding loop where the inner code should
7550 // continue.
7551 BasicBlock *Continue = OutermostLoop->getAfter();
7552
7553 // Where the next loop basic block should be inserted.
7554 BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
7555
7556 auto EmbeddNewLoop =
7557 [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
7558 Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
7559 CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
7560 DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
7561 redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
7562 redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
7563
7564 // Setup the position where the next embedded loop connects to this loop.
7565 Enter = EmbeddedLoop->getBody();
7566 Continue = EmbeddedLoop->getLatch();
7567 OutroInsertBefore = EmbeddedLoop->getLatch();
7568 return EmbeddedLoop;
7569 };
7570
7571 auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
7572 const Twine &NameBase) {
7573 for (auto P : enumerate(TripCounts)) {
7574 CanonicalLoopInfo *EmbeddedLoop =
7575 EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
7576 Result.push_back(EmbeddedLoop);
7577 }
7578 };
7579
7580 EmbeddNewLoops(FloorCount, "floor");
7581
7582 // Within the innermost floor loop, emit the code that computes the tile
7583 // sizes.
7584 Builder.SetInsertPoint(Enter->getTerminator());
7585 SmallVector<Value *, 4> TileCounts;
7586 for (int i = 0; i < NumLoops; ++i) {
7587 CanonicalLoopInfo *FloorLoop = Result[i];
7588 Value *TileSize = TileSizes[i];
7589
7590 Value *FloorIsEpilogue =
7591 Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCompleteCount[i]);
7592 Value *TileTripCount =
7593 Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
7594
7595 TileCounts.push_back(TileTripCount);
7596 }
7597
7598 // Create the tile loops.
7599 EmbeddNewLoops(TileCounts, "tile");
7600
7601 // Insert the inbetween code into the body.
7602 BasicBlock *BodyEnter = Enter;
7603 BasicBlock *BodyEntered = nullptr;
7604 for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
7605 BasicBlock *EnterBB = P.first;
7606 BasicBlock *ExitBB = P.second;
7607
7608 if (BodyEnter)
7609 redirectTo(BodyEnter, EnterBB, DL);
7610 else
7611 redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
7612
7613 BodyEnter = nullptr;
7614 BodyEntered = ExitBB;
7615 }
7616
7617 // Append the original loop nest body into the generated loop nest body.
7618 if (BodyEnter)
7619 redirectTo(BodyEnter, InnerEnter, DL);
7620 else
7621 redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
7623
7624 // Replace the original induction variable with an induction variable computed
7625 // from the tile and floor induction variables.
7626 Builder.restoreIP(Result.back()->getBodyIP());
7627 for (int i = 0; i < NumLoops; ++i) {
7628 CanonicalLoopInfo *FloorLoop = Result[i];
7629 CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
7630 Value *OrigIndVar = OrigIndVars[i];
7631 Value *Size = TileSizes[i];
7632
7633 Value *Scale =
7634 Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
7635 Value *Shift =
7636 Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
7637 OrigIndVar->replaceAllUsesWith(Shift);
7638 }
7639
7640 // Remove unused parts of the original loops.
7641 removeUnusedBlocksFromParent(OldControlBBs);
7642
7643 for (CanonicalLoopInfo *L : Loops)
7644 L->invalidate();
7645
7646#ifndef NDEBUG
7647 for (CanonicalLoopInfo *GenL : Result)
7648 GenL->assertOK();
7649#endif
7650 return Result;
7651}
7652
7653/// Attach metadata \p Properties to the basic block described by \p BB. If the
7654/// basic block already has metadata, the basic block properties are appended.
7657 // Nothing to do if no property to attach.
7658 if (Properties.empty())
7659 return;
7660
7661 LLVMContext &Ctx = BB->getContext();
7662 SmallVector<Metadata *> NewProperties;
7663 NewProperties.push_back(nullptr);
7664
7665 // If the basic block already has metadata, prepend it to the new metadata.
7666 MDNode *Existing = BB->getTerminator()->getMetadata(LLVMContext::MD_loop);
7667 if (Existing)
7668 append_range(NewProperties, drop_begin(Existing->operands(), 1));
7669
7670 append_range(NewProperties, Properties);
7671 MDNode *BasicBlockID = MDNode::getDistinct(Ctx, NewProperties);
7672 BasicBlockID->replaceOperandWith(0, BasicBlockID);
7673
7674 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, BasicBlockID);
7675}
7676
7677/// Attach loop metadata \p Properties to the loop described by \p Loop. If the
7678/// loop already has metadata, the loop properties are appended.
7681 assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
7682
7683 // Attach metadata to the loop's latch
7684 BasicBlock *Latch = Loop->getLatch();
7685 assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
7687}
7688
7689/// Attach llvm.access.group metadata to the memref instructions of \p Block
7691 LoopInfo &LI) {
7692 for (Instruction &I : *Block) {
7693 if (I.mayReadOrWriteMemory()) {
7694 // TODO: This instruction may already have access group from
7695 // other pragmas e.g. #pragma clang loop vectorize. Append
7696 // so that the existing metadata is not overwritten.
7697 I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
7698 }
7699 }
7700}
7701
7702CanonicalLoopInfo *
7704 CanonicalLoopInfo *firstLoop = Loops.front();
7705 CanonicalLoopInfo *lastLoop = Loops.back();
7706 Function *F = firstLoop->getPreheader()->getParent();
7707
7708 // Loop control blocks that will become orphaned later
7709 SmallVector<BasicBlock *> oldControlBBs;
7711 Loop->collectControlBlocks(oldControlBBs);
7712
7713 // Collect original trip counts
7714 SmallVector<Value *> origTripCounts;
7715 for (CanonicalLoopInfo *L : Loops) {
7716 assert(L->isValid() && "All input loops must be valid canonical loops");
7717 origTripCounts.push_back(L->getTripCount());
7718 }
7719
7720 Builder.SetCurrentDebugLocation(DL);
7721
7722 // Compute max trip count.
7723 // The fused loop will be from 0 to max(origTripCounts)
7724 BasicBlock *TCBlock = BasicBlock::Create(F->getContext(), "omp.fuse.comp.tc",
7725 F, firstLoop->getHeader());
7726 Builder.SetInsertPoint(TCBlock);
7727 Value *fusedTripCount = nullptr;
7728 for (CanonicalLoopInfo *L : Loops) {
7729 assert(L->isValid() && "All loops to fuse must be valid canonical loops");
7730 Value *origTripCount = L->getTripCount();
7731 if (!fusedTripCount) {
7732 fusedTripCount = origTripCount;
7733 continue;
7734 }
7735 Value *condTP = Builder.CreateICmpSGT(fusedTripCount, origTripCount);
7736 fusedTripCount = Builder.CreateSelect(condTP, fusedTripCount, origTripCount,
7737 ".omp.fuse.tc");
7738 }
7739
7740 // Generate new loop
7741 CanonicalLoopInfo *fused =
7742 createLoopSkeleton(DL, fusedTripCount, F, firstLoop->getBody(),
7743 lastLoop->getLatch(), "fused");
7744
7745 // Replace original loops with the fused loop
7746 // Preheader and After are not considered inside the CLI.
7747 // These are used to compute the individual TCs of the loops
7748 // so they have to be put before the resulting fused loop.
7749 // Moving them up for readability.
7750 for (size_t i = 0; i < Loops.size() - 1; ++i) {
7751 Loops[i]->getPreheader()->moveBefore(TCBlock);
7752 Loops[i]->getAfter()->moveBefore(TCBlock);
7753 }
7754 lastLoop->getPreheader()->moveBefore(TCBlock);
7755
7756 for (size_t i = 0; i < Loops.size() - 1; ++i) {
7757 redirectTo(Loops[i]->getPreheader(), Loops[i]->getAfter(), DL);
7758 redirectTo(Loops[i]->getAfter(), Loops[i + 1]->getPreheader(), DL);
7759 }
7760 redirectTo(lastLoop->getPreheader(), TCBlock, DL);
7761 redirectTo(TCBlock, fused->getPreheader(), DL);
7762 redirectTo(fused->getAfter(), lastLoop->getAfter(), DL);
7763
7764 // Build the fused body
7765 // Create new Blocks with conditions that jump to the original loop bodies
7767 SmallVector<Value *> condValues;
7768 for (size_t i = 0; i < Loops.size(); ++i) {
7769 BasicBlock *condBlock = BasicBlock::Create(
7770 F->getContext(), "omp.fused.inner.cond", F, Loops[i]->getBody());
7771 Builder.SetInsertPoint(condBlock);
7772 Value *condValue =
7773 Builder.CreateICmpSLT(fused->getIndVar(), origTripCounts[i]);
7774 condBBs.push_back(condBlock);
7775 condValues.push_back(condValue);
7776 }
7777 // Join the condition blocks with the bodies of the original loops
7778 redirectTo(fused->getBody(), condBBs[0], DL);
7779 for (size_t i = 0; i < Loops.size() - 1; ++i) {
7780 Builder.SetInsertPoint(condBBs[i]);
7781 Builder.CreateCondBr(condValues[i], Loops[i]->getBody(), condBBs[i + 1]);
7782 redirectAllPredecessorsTo(Loops[i]->getLatch(), condBBs[i + 1], DL);
7783 // Replace the IV with the fused IV
7784 Loops[i]->getIndVar()->replaceAllUsesWith(fused->getIndVar());
7785 }
7786 // Last body jumps to the created end body block
7787 Builder.SetInsertPoint(condBBs.back());
7788 Builder.CreateCondBr(condValues.back(), lastLoop->getBody(),
7789 fused->getLatch());
7790 redirectAllPredecessorsTo(lastLoop->getLatch(), fused->getLatch(), DL);
7791 // Replace the IV with the fused IV
7792 lastLoop->getIndVar()->replaceAllUsesWith(fused->getIndVar());
7793
7794 // The loop latch must have only one predecessor. Currently it is branched to
7795 // from both the last condition block and the last loop body
7796 fused->getLatch()->splitBasicBlockBefore(fused->getLatch()->begin(),
7797 "omp.fused.pre_latch");
7798
7799 // Remove unused parts
7800 removeUnusedBlocksFromParent(oldControlBBs);
7801
7802 // Invalidate old CLIs
7803 for (CanonicalLoopInfo *L : Loops)
7804 L->invalidate();
7805
7806#ifndef NDEBUG
7807 fused->assertOK();
7808#endif
7809 return fused;
7810}
7811
7812void OpenMPIRBuilder::addUnrollMetadata(CanonicalLoopInfo *Loop,
7814 assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
7815 if (Loop->VirtualCollapse)
7816 reportFatalInternalError("unrolling must precede Virtual collapse");
7818}
7819
7821 LLVMContext &Ctx = Builder.getContext();
7822 addUnrollMetadata(
7823 Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
7824 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
7825}
7826
7828 LLVMContext &Ctx = Builder.getContext();
7829 addUnrollMetadata(
7830 Loop, {
7831 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
7832 });
7833}
7834
7835void OpenMPIRBuilder::createIfVersion(CanonicalLoopInfo *CanonicalLoop,
7836 Value *IfCond, ValueToValueMapTy &VMap,
7837 LoopAnalysis &LIA, LoopInfo &LI, Loop *L,
7838 const Twine &NamePrefix) {
7839 Function *F = CanonicalLoop->getFunction();
7840
7841 // We can't do
7842 // if (cond) {
7843 // simd_loop;
7844 // } else {
7845 // non_simd_loop;
7846 // }
7847 // because then the CanonicalLoopInfo would only point to one of the loops:
7848 // leading to other constructs operating on the same loop to malfunction.
7849 // Instead generate
7850 // while (...) {
7851 // if (cond) {
7852 // simd_body;
7853 // } else {
7854 // not_simd_body;
7855 // }
7856 // }
7857 // At least for simple loops, LLVM seems able to hoist the if out of the loop
7858 // body at -O3
7859
7860 // Define where if branch should be inserted
7861 auto SplitBeforeIt = CanonicalLoop->getBody()->getFirstNonPHIIt();
7862
7863 // Create additional blocks for the if statement
7864 BasicBlock *Cond = SplitBeforeIt->getParent();
7865 llvm::LLVMContext &C = Cond->getContext();
7867 C, NamePrefix + ".if.then", Cond->getParent(), Cond->getNextNode());
7869 C, NamePrefix + ".if.else", Cond->getParent(), CanonicalLoop->getExit());
7870
7871 // Create if condition branch.
7872 Builder.SetInsertPoint(SplitBeforeIt);
7873 Instruction *BrInstr =
7874 Builder.CreateCondBr(IfCond, ThenBlock, /*ifFalse*/ ElseBlock);
7875 InsertPointTy IP(++BrInstr->getIterator());
7876 // Then block contains branch to omp loop body which needs to be vectorized
7877 spliceBB(IP, ThenBlock, false, Builder.getCurrentDebugLocation());
7878 ThenBlock->replaceSuccessorsPhiUsesWith(Cond, ThenBlock);
7879
7880 Builder.SetInsertPoint(ElseBlock);
7881
7882 // Clone loop for the else branch
7884
7885 SmallVector<BasicBlock *, 8> ExistingBlocks;
7886 ExistingBlocks.reserve(L->getNumBlocks() + 1);
7887 ExistingBlocks.push_back(ThenBlock);
7888 ExistingBlocks.append(L->block_begin(), L->block_end());
7889 // Cond is the block that has the if clause condition
7890 // LoopCond is omp_loop.cond
7891 // LoopHeader is omp_loop.header
7892 BasicBlock *LoopCond = Cond->getUniquePredecessor();
7893 BasicBlock *LoopHeader = LoopCond->getUniquePredecessor();
7894 assert(LoopCond && LoopHeader && "Invalid loop structure");
7895 for (BasicBlock *Block : ExistingBlocks) {
7896 if (Block == L->getLoopPreheader() || Block == L->getLoopLatch() ||
7897 Block == LoopHeader || Block == LoopCond || Block == Cond) {
7898 continue;
7899 }
7900 BasicBlock *NewBB = CloneBasicBlock(Block, VMap, "", F);
7901
7902 // fix name not to be omp.if.then
7903 if (Block == ThenBlock)
7904 NewBB->setName(NamePrefix + ".if.else");
7905
7906 NewBB->moveBefore(CanonicalLoop->getExit());
7907 VMap[Block] = NewBB;
7908 NewBlocks.push_back(NewBB);
7909 }
7910 remapInstructionsInBlocks(NewBlocks, VMap);
7911 Builder.CreateBr(NewBlocks.front());
7912
7913 // The loop latch must have only one predecessor. Currently it is branched to
7914 // from both the 'then' and 'else' branches.
7915 L->getLoopLatch()->splitBasicBlockBefore(L->getLoopLatch()->begin(),
7916 NamePrefix + ".pre_latch");
7917
7918 // Ensure that the then block is added to the loop so we add the attributes in
7919 // the next step
7920 L->addBasicBlockToLoop(ThenBlock, LI);
7921}
7922
7923unsigned
7925 const StringMap<bool> &Features) {
7926 if (TargetTriple.isX86()) {
7927 if (Features.lookup("avx512f"))
7928 return 512;
7929 else if (Features.lookup("avx"))
7930 return 256;
7931 return 128;
7932 }
7933 if (TargetTriple.isPPC())
7934 return 128;
7935 if (TargetTriple.isWasm())
7936 return 128;
7937 if (TargetTriple.isSystemZ())
7938 return 64;
7939 return 0;
7940}
7941
7943 MapVector<Value *, Value *> AlignedVars,
7944 Value *IfCond, OrderKind Order,
7945 ConstantInt *Simdlen, ConstantInt *Safelen) {
7946 if (CanonicalLoop->VirtualCollapse)
7947 CanonicalLoop->reportUnsupportedVirtualCollapse();
7948 LLVMContext &Ctx = Builder.getContext();
7949
7950 Function *F = CanonicalLoop->getFunction();
7951
7952 // Blocks must have terminators.
7953 // FIXME: Don't run analyses on incomplete/invalid IR.
7955 for (BasicBlock &BB : *F)
7956 if (!BB.hasTerminator())
7957 UIs.push_back(new UnreachableInst(F->getContext(), &BB));
7958
7959 // TODO: We should not rely on pass manager. Currently we use pass manager
7960 // only for getting llvm::Loop which corresponds to given CanonicalLoopInfo
7961 // object. We should have a method which returns all blocks between
7962 // CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()
7964 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
7965 FAM.registerPass([]() { return LoopAnalysis(); });
7966 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
7967
7968 LoopAnalysis LIA;
7969 LoopInfo &&LI = LIA.run(*F, FAM);
7970
7971 for (Instruction *I : UIs)
7972 I->eraseFromParent();
7973
7974 Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
7975 if (AlignedVars.size()) {
7976 InsertPointTy IP = Builder.saveIP();
7977 for (auto &AlignedItem : AlignedVars) {
7978 Value *AlignedPtr = AlignedItem.first;
7979 Value *Alignment = AlignedItem.second;
7980 Instruction *loadInst = dyn_cast<Instruction>(AlignedPtr);
7981 Builder.SetInsertPoint(loadInst->getNextNode());
7982 Builder.CreateAlignmentAssumption(F->getDataLayout(), AlignedPtr,
7983 Alignment);
7984 }
7985 Builder.restoreIP(IP);
7986 }
7987
7988 if (IfCond) {
7989 ValueToValueMapTy VMap;
7990 createIfVersion(CanonicalLoop, IfCond, VMap, LIA, LI, L, "simd");
7991 }
7992
7994
7995 // Get the basic blocks from the loop in which memref instructions
7996 // can be found.
7997 // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
7998 // preferably without running any passes.
7999 for (BasicBlock *Block : L->getBlocks()) {
8000 if (Block == CanonicalLoop->getCond() ||
8001 Block == CanonicalLoop->getHeader())
8002 continue;
8003 Reachable.insert(Block);
8004 }
8005
8006 SmallVector<Metadata *> LoopMDList;
8007
8008 // In presence of finite 'safelen', it may be unsafe to mark all
8009 // the memory instructions parallel, because loop-carried
8010 // dependences of 'safelen' iterations are possible.
8011 // If clause order(concurrent) is specified then the memory instructions
8012 // are marked parallel even if 'safelen' is finite.
8013 if ((Safelen == nullptr) || (Order == OrderKind::OMP_ORDER_concurrent))
8014 applyParallelAccessesMetadata(CanonicalLoop, Ctx, L, LI, LoopMDList);
8015
8016 // FIXME: the IF clause shares a loop backedge for the SIMD and non-SIMD
8017 // versions so we can't add the loop attributes in that case.
8018 if (IfCond) {
8019 // we can still add llvm.loop.parallel_access
8020 addLoopMetadata(CanonicalLoop, LoopMDList);
8021 return;
8022 }
8023
8024 // Use the above access group metadata to create loop level
8025 // metadata, which should be distinct for each loop.
8026 LoopMDList.push_back(
8027 MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable")}));
8028
8029 if (Simdlen || Safelen) {
8030 // If both simdlen and safelen clauses are specified, the value of the
8031 // simdlen parameter must be less than or equal to the value of the safelen
8032 // parameter. Therefore, use safelen only in the absence of simdlen.
8033 ConstantInt *VectorizeWidth = Simdlen == nullptr ? Safelen : Simdlen;
8034 LoopMDList.push_back(
8035 MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.width"),
8036 ConstantAsMetadata::get(VectorizeWidth)}));
8037 }
8038
8039 addLoopMetadata(CanonicalLoop, LoopMDList);
8040}
8041
8043 int32_t Factor,
8044 CanonicalLoopInfo **UnrolledCLI) {
8045 assert(Factor >= 0 && "Unroll factor must not be negative");
8046
8047 Function *F = Loop->getFunction();
8048 LLVMContext &Ctx = F->getContext();
8049
8050 // If the unrolled loop is not used for another loop-associated directive, it
8051 // is sufficient to add metadata for the LoopUnrollPass.
8052 if (!UnrolledCLI) {
8053 SmallVector<Metadata *, 2> LoopMetadata;
8054 LoopMetadata.push_back(
8055 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
8056
8057 if (Factor >= 1) {
8059 ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
8060 LoopMetadata.push_back(MDNode::get(
8061 Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
8062 }
8063
8064 addUnrollMetadata(Loop, LoopMetadata);
8065 return;
8066 }
8067
8068 if (Factor == 0) {
8069 if (Loop->VirtualCollapse)
8070 Loop->reportUnsupportedVirtualCollapse();
8072 }
8073
8074 // No change required with unroll factor 1.
8075 if (Factor == 1) {
8076 *UnrolledCLI = Loop;
8077 return;
8078 }
8079
8080 assert(Factor >= 2 &&
8081 "unrolling only makes sense with a factor of 2 or larger");
8082
8083 Type *IndVarTy = Loop->getIndVarType();
8084
8085 // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
8086 // unroll the inner loop.
8087 Value *FactorVal =
8088 ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
8089 /*isSigned=*/false));
8090 std::vector<CanonicalLoopInfo *> LoopNest =
8091 tileLoops(DL, {Loop}, {FactorVal});
8092 assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
8093 *UnrolledCLI = LoopNest[0];
8094 CanonicalLoopInfo *InnerLoop = LoopNest[1];
8095
8096 // LoopUnrollPass can only fully unroll loops with constant trip count.
8097 // Unroll by the unroll factor with a fallback epilog for the remainder
8098 // iterations if necessary.
8100 ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
8102 InnerLoop,
8103 {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
8105 Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
8106
8107#ifndef NDEBUG
8108 (*UnrolledCLI)->assertOK();
8109#endif
8110}
8111
8114 llvm::Value *BufSize, llvm::Value *CpyBuf,
8115 llvm::Value *CpyFn, llvm::Value *DidIt) {
8116 if (!updateToLocation(Loc))
8117 return Loc.IP;
8118
8119 uint32_t SrcLocStrSize;
8120 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8121 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8122 Value *ThreadId = getOrCreateThreadID(Ident);
8123
8124 llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
8125
8126 Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
8127
8128 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
8129 createRuntimeFunctionCall(Fn, Args);
8130
8131 return Builder.saveIP();
8132}
8133
8135 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
8136 FinalizeCallbackTy FiniCB, bool IsNowait, ArrayRef<llvm::Value *> CPVars,
8138
8139 if (!updateToLocation(Loc))
8140 return Loc.IP;
8141
8142 // If needed allocate and initialize `DidIt` with 0.
8143 // DidIt: flag variable: 1=single thread; 0=not single thread.
8144 llvm::Value *DidIt = nullptr;
8145 if (!CPVars.empty()) {
8146 DidIt = Builder.CreateAlloca(llvm::Type::getInt32Ty(Builder.getContext()));
8147 Builder.CreateStore(Builder.getInt32(0), DidIt);
8148 }
8149
8150 Directive OMPD = Directive::OMPD_single;
8151 uint32_t SrcLocStrSize;
8152 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8153 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8154 Value *ThreadId = getOrCreateThreadID(Ident);
8155 Value *Args[] = {Ident, ThreadId};
8156
8157 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
8158 Instruction *EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
8159
8160 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
8161 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
8162
8163 auto FiniCBWrapper = [&](InsertPointTy IP) -> Error {
8164 if (Error Err = FiniCB(IP))
8165 return Err;
8166
8167 // The thread that executes the single region must set `DidIt` to 1.
8168 // This is used by __kmpc_copyprivate, to know if the caller is the
8169 // single thread or not.
8170 if (DidIt)
8171 Builder.CreateStore(Builder.getInt32(1), DidIt);
8172
8173 return Error::success();
8174 };
8175
8176 // generates the following:
8177 // if (__kmpc_single()) {
8178 // .... single region ...
8179 // __kmpc_end_single
8180 // }
8181 // __kmpc_copyprivate
8182 // __kmpc_barrier
8183
8184 InsertPointOrErrorTy AfterIP =
8185 EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCBWrapper,
8186 /*Conditional*/ true,
8187 /*hasFinalize*/ true);
8188 if (!AfterIP)
8189 return AfterIP.takeError();
8190
8191 if (DidIt) {
8192 for (size_t I = 0, E = CPVars.size(); I < E; ++I)
8193 // NOTE BufSize is currently unused, so just pass 0.
8195 /*BufSize=*/ConstantInt::get(Int64, 0), CPVars[I],
8196 CPFuncs[I], DidIt);
8197 // NOTE __kmpc_copyprivate already inserts a barrier
8198 } else if (!IsNowait) {
8199 InsertPointOrErrorTy AfterIP =
8201 omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
8202 /* CheckCancelFlag */ false);
8203 if (!AfterIP)
8204 return AfterIP.takeError();
8205 }
8206 return Builder.saveIP();
8207}
8208
8211 BodyGenCallbackTy BodyGenCB,
8212 FinalizeCallbackTy FiniCB, bool IsNowait) {
8213
8214 if (!updateToLocation(Loc))
8215 return Loc.IP;
8216
8217 // All threads execute the scope body — no conditional entry.
8218 InsertPointOrErrorTy AfterIP = EmitOMPInlinedRegion(
8219 Directive::OMPD_scope, /*EntryCall=*/nullptr, /*ExitCall=*/nullptr,
8220 BodyGenCB, FiniCB, /*Conditional=*/false, /*HasFinalize=*/true,
8221 /*IsCancellable=*/false);
8222 if (!AfterIP)
8223 return AfterIP.takeError();
8224
8225 Builder.restoreIP(*AfterIP);
8226 if (!IsNowait) {
8227 AfterIP = createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
8228 omp::Directive::OMPD_unknown,
8229 /*ForceSimpleCall=*/false,
8230 /*CheckCancelFlag=*/false);
8231 if (!AfterIP)
8232 return AfterIP.takeError();
8233 }
8234 return Builder.saveIP();
8235}
8236
8238 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
8239 FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
8240
8241 if (!updateToLocation(Loc))
8242 return Loc.IP;
8243
8244 Directive OMPD = Directive::OMPD_critical;
8245 uint32_t SrcLocStrSize;
8246 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8247 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8248 Value *ThreadId = getOrCreateThreadID(Ident);
8249 Value *LockVar = getOMPCriticalRegionLock(CriticalName);
8250 Value *Args[] = {Ident, ThreadId, LockVar};
8251
8252 SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
8253 Function *RTFn = nullptr;
8254 if (HintInst) {
8255 // Add Hint to entry Args and create call
8256 EnterArgs.push_back(HintInst);
8257 RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
8258 } else {
8259 RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
8260 }
8261 Instruction *EntryCall = createRuntimeFunctionCall(RTFn, EnterArgs);
8262
8263 Function *ExitRTLFn =
8264 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
8265 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
8266
8267 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8268 /*Conditional*/ false, /*hasFinalize*/ true);
8269}
8270
8273 InsertPointTy AllocaIP, unsigned NumLoops,
8274 ArrayRef<llvm::Value *> StoreValues,
8275 const Twine &Name, bool IsDependSource) {
8276 assert(
8277 llvm::all_of(StoreValues,
8278 [](Value *SV) { return SV->getType()->isIntegerTy(64); }) &&
8279 "OpenMP runtime requires depend vec with i64 type");
8280
8281 if (!updateToLocation(Loc))
8282 return Loc.IP;
8283
8284 // Allocate space for vector and generate alloc instruction.
8285 auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
8286 Builder.restoreIP(AllocaIP);
8287 AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
8288 ArgsBase->setAlignment(Align(8));
8290
8291 // Store the index value with offset in depend vector.
8292 for (unsigned I = 0; I < NumLoops; ++I) {
8293 Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
8294 ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
8295 StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
8296 STInst->setAlignment(Align(8));
8297 }
8298
8299 Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
8300 ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
8301
8302 uint32_t SrcLocStrSize;
8303 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8304 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8305 Value *ThreadId = getOrCreateThreadID(Ident);
8306 Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
8307
8308 Function *RTLFn = nullptr;
8309 if (IsDependSource)
8310 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
8311 else
8312 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
8313 createRuntimeFunctionCall(RTLFn, Args);
8314
8315 return Builder.saveIP();
8316}
8317
8319 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
8320 FinalizeCallbackTy FiniCB, bool IsThreads) {
8321 if (!updateToLocation(Loc))
8322 return Loc.IP;
8323
8324 Directive OMPD = Directive::OMPD_ordered_blockassoc;
8325 Instruction *EntryCall = nullptr;
8326 Instruction *ExitCall = nullptr;
8327
8328 if (IsThreads) {
8329 uint32_t SrcLocStrSize;
8330 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8331 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8332 Value *ThreadId = getOrCreateThreadID(Ident);
8333 Value *Args[] = {Ident, ThreadId};
8334
8335 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
8336 EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
8337
8338 Function *ExitRTLFn =
8339 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
8340 ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
8341 }
8342
8343 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8344 /*Conditional*/ false, /*hasFinalize*/ true);
8345}
8346
8347OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::EmitOMPInlinedRegion(
8348 Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
8349 BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
8350 bool HasFinalize, bool IsCancellable) {
8351
8352 if (HasFinalize)
8353 FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
8354
8355 // Create inlined region's entry and body blocks, in preparation
8356 // for conditional creation
8357 BasicBlock *EntryBB = Builder.GetInsertBlock();
8358 Instruction *SplitPos = EntryBB->getTerminatorOrNull();
8360 SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
8361 SplitPos->setDebugLoc(Builder.getCurrentDebugLocation());
8362 }
8363 BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
8364 BasicBlock *FiniBB =
8365 EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
8366
8367 Builder.SetInsertPoint(EntryBB->getTerminator());
8368 emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
8369
8370 // generate body
8371 if (Error Err =
8372 BodyGenCB(/* AllocaIP */ InsertPointTy(),
8373 /* CodeGenIP */ Builder.saveIP(), /* DeallocBlocks */ {}))
8374 return Err;
8375
8376 // emit exit call and do any needed finalization.
8377 auto FinIP = FiniBB->getFirstInsertionPt();
8378 assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
8379 FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
8380 "Unexpected control flow graph state!!");
8381 InsertPointOrErrorTy AfterIP =
8382 emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
8383 if (!AfterIP)
8384 return AfterIP.takeError();
8385
8386 // If we are skipping the region of a non conditional, remove the exit
8387 // block, and clear the builder's insertion point.
8388 assert(SplitPos->getParent() == ExitBB &&
8389 "Unexpected Insertion point location!");
8390 auto merged = MergeBlockIntoPredecessor(ExitBB);
8391 BasicBlock *ExitPredBB = SplitPos->getParent();
8392 auto InsertBB = merged ? ExitPredBB : ExitBB;
8394 SplitPos->eraseFromParent();
8395 Builder.SetInsertPoint(InsertBB);
8396
8397 return Builder.saveIP();
8398}
8399
8400OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
8401 Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
8402 // if nothing to do, Return current insertion point.
8403 if (!Conditional || !EntryCall)
8404 return Builder.saveIP();
8405
8406 BasicBlock *EntryBB = Builder.GetInsertBlock();
8407 Value *CallBool = Builder.CreateIsNotNull(EntryCall);
8408 auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
8409 auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
8410
8411 // Emit thenBB and set the Builder's insertion point there for
8412 // body generation next. Place the block after the current block.
8413 Function *CurFn = EntryBB->getParent();
8414 CurFn->insert(std::next(EntryBB->getIterator()), ThenBB);
8415
8416 // Move Entry branch to end of ThenBB, and replace with conditional
8417 // branch (If-stmt)
8418 Instruction *EntryBBTI = EntryBB->getTerminator();
8419 Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
8420 EntryBBTI->removeFromParent();
8421 Builder.SetInsertPoint(UI);
8422 Builder.Insert(EntryBBTI);
8423 UI->eraseFromParent();
8424 Builder.SetInsertPoint(ThenBB->getTerminator());
8425
8426 // return an insertion point to ExitBB.
8427 return ExitBB->getFirstInsertionPt();
8428}
8429
8430OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::emitCommonDirectiveExit(
8431 omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
8432 bool HasFinalize) {
8433
8434 Builder.restoreIP(FinIP);
8435
8436 // If there is finalization to do, emit it before the exit call
8437 if (HasFinalize) {
8438 assert(!FinalizationStack.empty() &&
8439 "Unexpected finalization stack state!");
8440
8441 FinalizationInfo Fi = FinalizationStack.pop_back_val();
8442 assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
8443
8444 BasicBlock *FinBB = FinIP.getNodeParent();
8445 if (Error Err = Fi.mergeFiniBB(Builder, FinBB))
8446 return std::move(Err);
8447
8448 // Exit condition: insertion point is before the terminator of the new Fini
8449 // block
8450 Builder.SetInsertPoint(FinBB->getTerminator());
8451 }
8452
8453 if (!ExitCall)
8454 return Builder.saveIP();
8455
8456 // place the Exitcall as last instruction before Finalization block terminator
8457 ExitCall->removeFromParent();
8458 Builder.Insert(ExitCall);
8459
8460 return ExitCall->getIterator();
8461}
8462
8464 InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
8465 llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
8466 if (!IP.isValid())
8467 return IP;
8468
8470
8471 // creates the following CFG structure
8472 // OMP_Entry : (MasterAddr != PrivateAddr)?
8473 // F T
8474 // | \
8475 // | copin.not.master
8476 // | /
8477 // v /
8478 // copyin.not.master.end
8479 // |
8480 // v
8481 // OMP.Entry.Next
8482
8483 BasicBlock *OMP_Entry = IP.getNodeParent();
8484 Function *CurFn = OMP_Entry->getParent();
8485 BasicBlock *CopyBegin =
8486 BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
8487 BasicBlock *CopyEnd = nullptr;
8488
8489 // If entry block is terminated, split to preserve the branch to following
8490 // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
8492 CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
8493 "copyin.not.master.end");
8494 OMP_Entry->getTerminator()->eraseFromParent();
8495 } else {
8496 CopyEnd =
8497 BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
8498 }
8499
8500 Builder.SetInsertPoint(OMP_Entry);
8501 Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
8502 Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
8503 Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
8504 Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
8505
8506 Builder.SetInsertPoint(CopyBegin);
8507 if (BranchtoEnd)
8508 Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
8509
8510 return Builder.saveIP();
8511}
8512
8514 Value *Size, Value *Allocator,
8515 std::string Name) {
8517 if (!updateToLocation(Loc))
8518 return nullptr;
8519
8520 uint32_t SrcLocStrSize;
8521 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8522 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8523 Value *ThreadId = getOrCreateThreadID(Ident);
8524 Value *Args[] = {ThreadId, Size, Allocator};
8525
8526 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
8527
8528 return createRuntimeFunctionCall(Fn, Args, Name);
8529}
8530
8532 Value *Align, Value *Size,
8533 Value *Allocator,
8534 std::string Name) {
8536 if (!updateToLocation(Loc))
8537 return nullptr;
8538
8539 uint32_t SrcLocStrSize;
8540 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8541 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8542 Value *ThreadId = getOrCreateThreadID(Ident);
8543 Value *Args[] = {ThreadId, Align, Size, Allocator};
8544
8545 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_aligned_alloc);
8546
8547 return createRuntimeFunctionCall(Fn, Args, Name);
8548}
8549
8551 Value *Addr, Value *Allocator,
8552 std::string Name) {
8554 if (!updateToLocation(Loc))
8555 return nullptr;
8556
8557 uint32_t SrcLocStrSize;
8558 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8559 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8560 Value *ThreadId = getOrCreateThreadID(Ident);
8561 Value *Args[] = {ThreadId, Addr, Allocator};
8562 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
8563 return createRuntimeFunctionCall(Fn, Args, Name);
8564}
8565
8567 Value *Size,
8568 const Twine &Name) {
8571
8572 Value *Args[] = {Size};
8573 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc_shared);
8574 CallInst *Call = createRuntimeFunctionCall(Fn, Args, Name);
8576 M.getContext(), M.getDataLayout().getPrefTypeAlign(Int64)));
8577 return Call;
8578}
8579
8581 Type *VarType,
8582 const Twine &Name) {
8583 return createOMPAllocShared(
8584 Loc, Builder.getInt64(M.getDataLayout().getTypeAllocSize(VarType)), Name);
8585}
8586
8588 Value *Addr, Value *Size,
8589 const Twine &Name) {
8592
8593 Value *Args[] = {Addr, Size};
8594 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free_shared);
8595 return createRuntimeFunctionCall(Fn, Args, Name);
8596}
8597
8599 Value *Addr, Type *VarType,
8600 const Twine &Name) {
8601 return createOMPFreeShared(
8602 Loc, Addr, Builder.getInt64(M.getDataLayout().getTypeAllocSize(VarType)),
8603 Name);
8604}
8605
8607 const LocationDescription &Loc, Value *InteropVar,
8609 Value *DependenceAddress, bool HaveNowaitClause) {
8612
8613 uint32_t SrcLocStrSize;
8614 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8615 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8616 Value *ThreadId = getOrCreateThreadID(Ident);
8617 if (Device == nullptr)
8619 else if (Device->getType() != Int32)
8620 Device = Builder.CreateIntCast(Device, Int32, /*isSigned=*/true);
8621 Constant *InteropTypeVal = ConstantInt::get(Int32, (int)InteropType);
8622 if (NumDependences == nullptr) {
8623 NumDependences = ConstantInt::get(Int32, 0);
8624 PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());
8625 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
8626 }
8627 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8628 Value *Args[] = {
8629 Ident, ThreadId, InteropVar, InteropTypeVal,
8630 Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
8631
8632 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
8633
8634 return createRuntimeFunctionCall(Fn, Args);
8635}
8636
8638 const LocationDescription &Loc, Value *InteropVar, Value *Device,
8639 Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
8642
8643 uint32_t SrcLocStrSize;
8644 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8645 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8646 Value *ThreadId = getOrCreateThreadID(Ident);
8647 if (Device == nullptr)
8649 else if (Device->getType() != Int32)
8650 Device = Builder.CreateIntCast(Device, Int32, /*isSigned=*/true);
8651 if (NumDependences == nullptr) {
8652 NumDependences = ConstantInt::get(Int32, 0);
8653 PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());
8654 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
8655 }
8656 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8657 Value *Args[] = {
8658 Ident, ThreadId, InteropVar, Device,
8659 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8660
8661 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
8662
8663 return createRuntimeFunctionCall(Fn, Args);
8664}
8665
8667 Value *InteropVar, Value *Device,
8668 Value *NumDependences,
8669 Value *DependenceAddress,
8670 bool HaveNowaitClause) {
8673 uint32_t SrcLocStrSize;
8674 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8675 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8676 Value *ThreadId = getOrCreateThreadID(Ident);
8677 if (Device == nullptr)
8679 else if (Device->getType() != Int32)
8680 Device = Builder.CreateIntCast(Device, Int32, /*isSigned=*/true);
8681 if (NumDependences == nullptr) {
8682 NumDependences = ConstantInt::get(Int32, 0);
8683 PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());
8684 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
8685 }
8686 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8687 Value *Args[] = {
8688 Ident, ThreadId, InteropVar, Device,
8689 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8690
8691 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
8692
8693 return createRuntimeFunctionCall(Fn, Args);
8694}
8695
8698 llvm::ConstantInt *Size, const llvm::Twine &Name) {
8701
8702 uint32_t SrcLocStrSize;
8703 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8704 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8705 Value *ThreadId = getOrCreateThreadID(Ident);
8706 Constant *ThreadPrivateCache =
8707 getOrCreateInternalVariable(Int8PtrPtr, Name.str());
8708 llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
8709
8710 Function *Fn =
8711 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
8712
8713 return createRuntimeFunctionCall(Fn, Args);
8714}
8715
8717 const LocationDescription &Loc,
8719 assert(!Attrs.MaxThreads.empty() && !Attrs.MaxTeams.empty() &&
8720 "expected num_threads and num_teams to be specified");
8721
8722 if (!updateToLocation(Loc))
8723 return nullptr;
8724
8725 uint32_t SrcLocStrSize;
8726 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8727 Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8728 Constant *IsSPMDVal = ConstantInt::getSigned(Int8, Attrs.ExecFlags);
8729 Constant *UseGenericStateMachineVal = ConstantInt::getSigned(
8730 Int8, Attrs.ExecFlags != omp::OMP_TGT_EXEC_MODE_SPMD &&
8731 Attrs.ExecFlags != omp::OMP_TGT_EXEC_MODE_SPMD_NO_LOOP);
8732 Constant *MayUseNestedParallelismVal = ConstantInt::getSigned(Int8, true);
8733 Constant *DebugIndentionLevelVal = ConstantInt::getSigned(Int16, 0);
8734
8735 Function *DebugKernelWrapper = Builder.GetInsertBlock()->getParent();
8736 Function *Kernel = DebugKernelWrapper;
8737
8738 // We need to strip the debug prefix to get the correct kernel name.
8739 StringRef KernelName = Kernel->getName();
8740 const std::string DebugPrefix = "_debug__";
8741 if (KernelName.ends_with(DebugPrefix)) {
8742 KernelName = KernelName.drop_back(DebugPrefix.length());
8743 Kernel = M.getFunction(KernelName);
8744 assert(Kernel && "Expected the real kernel to exist");
8745 }
8746
8747 // Manifest the launch configuration in the metadata matching the kernel
8748 // environment.
8749 if (Attrs.MinTeams.front() > 1 || Attrs.MaxTeams.front() > 0)
8750 writeTeamsForKernel(T, *Kernel, Attrs.MinTeams.front(),
8751 Attrs.MaxTeams.front());
8752
8753 // Don't derive or write thread bounds for Bare kernels.
8754 int32_t MaxThreadsVal = Attrs.MaxThreads.front();
8755 if (Attrs.ExecFlags != omp::OMP_TGT_EXEC_MODE_BARE) {
8756 // If MaxThreads is not set and needs adjustment, select the maximum
8757 // between the default workgroup size and the MinThreads value. This is
8758 // only meaningful for targets with a known grid value (i.e. GPUs); for
8759 // other targets (e.g. host kernels) leave it unset so the runtime falls
8760 // back to its own device-specific default.
8761 if (MaxThreadsVal < 0 && UseDefaultMaxThreads && hasGridValue(T))
8762 MaxThreadsVal =
8763 std::max(int32_t(getGridValue(T, Kernel).GV_Default_WG_Size),
8764 Attrs.MinThreads.front());
8765
8766 // Generic mode runs the main thread on a warp of its own, past
8767 // thread_limit. Reserve the widest warp any target has. Not on SPIR-V,
8768 // causes problems with Level Zero.
8769 if (MaxThreadsVal > 0 &&
8770 Attrs.ExecFlags == omp::OMP_TGT_EXEC_MODE_GENERIC && hasGridValue(T) &&
8771 !T.isSPIRV())
8772 MaxThreadsVal = int32_t(
8773 std::min<int64_t>(int64_t(MaxThreadsVal) + 64,
8774 int64_t(getGridValue(T, Kernel).GV_Max_WG_Size)));
8775
8776 if (MaxThreadsVal > 0)
8777 writeThreadBoundsForKernel(T, *Kernel, Attrs.MinThreads.front(),
8778 MaxThreadsVal);
8779 }
8780
8781 Constant *MinThreads =
8782 ConstantInt::getSigned(Int32, Attrs.MinThreads.front());
8783 Constant *MaxThreads = ConstantInt::getSigned(Int32, MaxThreadsVal);
8784 Constant *MinTeams = ConstantInt::getSigned(Int32, Attrs.MinTeams.front());
8785 Constant *MaxTeams = ConstantInt::getSigned(Int32, Attrs.MaxTeams.front());
8786 Constant *ReductionDataSize =
8787 ConstantInt::getSigned(Int32, Attrs.ReductionDataSize);
8788
8789 const DataLayout &DL = M.getDataLayout();
8790
8791 Twine DynamicEnvironmentName = KernelName + "_dynamic_environment";
8792 Constant *DynamicEnvironmentInitializer =
8793 ConstantStruct::get(DynamicEnvironment, {DebugIndentionLevelVal});
8794 GlobalVariable *DynamicEnvironmentGV = new GlobalVariable(
8795 M, DynamicEnvironment, /*IsConstant=*/false, GlobalValue::WeakODRLinkage,
8796 DynamicEnvironmentInitializer, DynamicEnvironmentName,
8797 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
8798 DL.getDefaultGlobalsAddressSpace());
8799 DynamicEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);
8800
8801 Constant *DynamicEnvironment =
8802 DynamicEnvironmentGV->getType() == DynamicEnvironmentPtr
8803 ? DynamicEnvironmentGV
8804 : ConstantExpr::getAddrSpaceCast(DynamicEnvironmentGV,
8805 DynamicEnvironmentPtr);
8806
8807 Constant *ConfigurationEnvironmentInitializer = ConstantStruct::get(
8808 ConfigurationEnvironment, {
8809 UseGenericStateMachineVal,
8810 MayUseNestedParallelismVal,
8811 IsSPMDVal,
8812 MinThreads,
8813 MaxThreads,
8814 MinTeams,
8815 MaxTeams,
8816 ReductionDataSize,
8817 });
8818 Constant *KernelEnvironmentInitializer = ConstantStruct::get(
8819 KernelEnvironment, {
8820 ConfigurationEnvironmentInitializer,
8821 Ident,
8822 DynamicEnvironment,
8823 });
8824 std::string KernelEnvironmentName =
8825 (KernelName + "_kernel_environment").str();
8826 GlobalVariable *KernelEnvironmentGV = new GlobalVariable(
8827 M, KernelEnvironment, /*IsConstant=*/true, GlobalValue::WeakODRLinkage,
8828 KernelEnvironmentInitializer, KernelEnvironmentName,
8829 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
8830 DL.getDefaultGlobalsAddressSpace());
8831 KernelEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);
8832
8833 return KernelEnvironmentGV->getType() == KernelEnvironmentPtr
8834 ? KernelEnvironmentGV
8835 : ConstantExpr::getAddrSpaceCast(KernelEnvironmentGV,
8836 KernelEnvironmentPtr);
8837}
8838
8840 const LocationDescription &Loc,
8842 Constant *KernelEnvironment = emitKernelEnvironment(Loc, Attrs);
8843 if (!KernelEnvironment)
8844 return Loc.IP;
8845
8846 if (!updateToLocation(Loc))
8847 return Loc.IP;
8848
8849 Function *DebugKernelWrapper = Builder.GetInsertBlock()->getParent();
8851 omp::RuntimeFunction::OMPRTL___kmpc_target_init);
8852
8853 Value *KernelLaunchEnvironment =
8854 DebugKernelWrapper->getArg(DebugKernelWrapper->arg_size() - 1);
8855 Type *KernelLaunchEnvParamTy = Fn->getFunctionType()->getParamType(1);
8856 KernelLaunchEnvironment =
8857 KernelLaunchEnvironment->getType() == KernelLaunchEnvParamTy
8858 ? KernelLaunchEnvironment
8859 : Builder.CreateAddrSpaceCast(KernelLaunchEnvironment,
8860 KernelLaunchEnvParamTy);
8861 CallInst *ThreadKind = createRuntimeFunctionCall(
8862 Fn, {KernelEnvironment, KernelLaunchEnvironment});
8863
8864 Value *ExecUserCode = Builder.CreateICmpEQ(
8865 ThreadKind, Constant::getAllOnesValue(ThreadKind->getType()),
8866 "exec_user_code");
8867
8868 // ThreadKind = __kmpc_target_init(...)
8869 // if (ThreadKind == -1)
8870 // user_code
8871 // else
8872 // return;
8873
8874 auto *UI = Builder.CreateUnreachable();
8875 BasicBlock *CheckBB = UI->getParent();
8876 BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
8877
8878 BasicBlock *WorkerExitBB = BasicBlock::Create(
8879 CheckBB->getContext(), "worker.exit", CheckBB->getParent());
8880 Builder.SetInsertPoint(WorkerExitBB);
8881 Builder.CreateRetVoid();
8882
8883 auto *CheckBBTI = CheckBB->getTerminator();
8884 Builder.SetInsertPoint(CheckBBTI);
8885 Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
8886
8887 CheckBBTI->eraseFromParent();
8888 UI->eraseFromParent();
8889
8890 // Continue in the "user_code" block, see diagram above and in
8891 // openmp/libomptarget/deviceRTLs/common/include/target.h .
8892 return UserCodeEntryBB->getFirstInsertionPt();
8893}
8894
8896 int32_t TeamsReductionDataSize) {
8897 if (!updateToLocation(Loc))
8898 return;
8899
8901 omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
8902
8904
8905 if (!TeamsReductionDataSize)
8906 return;
8907
8908 Function *Kernel = Builder.GetInsertBlock()->getParent();
8909 // We need to strip the debug prefix to get the correct kernel name.
8910 StringRef KernelName = Kernel->getName();
8911 const std::string DebugPrefix = "_debug__";
8912 if (KernelName.ends_with(DebugPrefix))
8913 KernelName = KernelName.drop_back(DebugPrefix.length());
8914 auto *KernelEnvironmentGV =
8915 M.getNamedGlobal((KernelName + "_kernel_environment").str());
8916 assert(KernelEnvironmentGV && "Expected kernel environment global\n");
8917 auto *KernelEnvironmentInitializer = KernelEnvironmentGV->getInitializer();
8918 auto *NewInitializer = ConstantFoldInsertValueInstruction(
8919 KernelEnvironmentInitializer,
8920 ConstantInt::get(Int32, TeamsReductionDataSize), {0, 7});
8921 KernelEnvironmentGV->setInitializer(NewInitializer);
8922}
8923
8924static void updateNVPTXAttr(Function &Kernel, StringRef Name, int32_t Value,
8925 bool Min) {
8926 if (Kernel.hasFnAttribute(Name)) {
8927 int32_t OldLimit = Kernel.getFnAttributeAsParsedInteger(Name);
8928 Value = Min ? std::min(OldLimit, Value) : std::max(OldLimit, Value);
8929 }
8930 Kernel.addFnAttr(Name, llvm::utostr(Value));
8931}
8932
8933std::pair<int32_t, int32_t>
8935 int32_t ThreadLimit =
8936 Kernel.getFnAttributeAsParsedInteger("omp_target_thread_limit");
8937
8938 if (T.isAMDGPU()) {
8939 const auto &Attr = Kernel.getFnAttribute("amdgpu-flat-work-group-size");
8940 if (!Attr.isValid() || !Attr.isStringAttribute())
8941 return {0, ThreadLimit};
8942 auto [LBStr, UBStr] = Attr.getValueAsString().split(',');
8943 int32_t LB, UB;
8944 if (!llvm::to_integer(UBStr, UB, 10))
8945 return {0, ThreadLimit};
8946 UB = ThreadLimit ? std::min(ThreadLimit, UB) : UB;
8947 if (!llvm::to_integer(LBStr, LB, 10))
8948 return {0, UB};
8949 return {LB, UB};
8950 }
8951
8952 if (Kernel.hasFnAttribute(NVVMAttr::MaxNTID)) {
8953 int32_t UB = Kernel.getFnAttributeAsParsedInteger(NVVMAttr::MaxNTID);
8954 return {0, ThreadLimit ? std::min(ThreadLimit, UB) : UB};
8955 }
8956 return {0, ThreadLimit};
8957}
8958
8960 Function &Kernel, int32_t LB,
8961 int32_t UB) {
8962 Kernel.addFnAttr("omp_target_thread_limit", std::to_string(UB));
8963
8964 if (T.isAMDGPU()) {
8965 Kernel.addFnAttr("amdgpu-flat-work-group-size",
8966 llvm::utostr(LB) + "," + llvm::utostr(UB));
8967 return;
8968 }
8969
8971}
8972
8973std::pair<int32_t, int32_t>
8975 // TODO: Read from backend annotations if available.
8976 return {0, Kernel.getFnAttributeAsParsedInteger("omp_target_num_teams")};
8977}
8978
8980 int32_t LB, int32_t UB) {
8981 if (UB > 0) {
8982 if (T.isNVPTX())
8984 if (T.isAMDGPU())
8985 Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(UB) + ",1,1");
8986 }
8987
8988 Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));
8989}
8990
8991void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
8992 Function *OutlinedFn) {
8993 if (Config.isTargetDevice()) {
8995 // TODO: Determine if DSO local can be set to true.
8996 OutlinedFn->setDSOLocal(false);
8998 if (T.isAMDGCN())
9000 else if (T.isNVPTX())
9002 else if (T.isSPIRV())
9004 }
9005}
9006
9007Constant *OpenMPIRBuilder::createOutlinedFunctionID(Function *OutlinedFn,
9008 StringRef EntryFnIDName) {
9009 if (Config.isTargetDevice()) {
9010 assert(OutlinedFn && "The outlined function must exist if embedded");
9011 return OutlinedFn;
9012 }
9013
9014 return new GlobalVariable(
9015 M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::WeakAnyLinkage,
9016 Constant::getNullValue(Builder.getInt8Ty()), EntryFnIDName);
9017}
9018
9019Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(Function *OutlinedFn,
9020 StringRef EntryFnName) {
9021 if (OutlinedFn)
9022 return OutlinedFn;
9023
9024 assert(!M.getGlobalVariable(EntryFnName, true) &&
9025 "Named kernel already exists?");
9026 return new GlobalVariable(
9027 M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::InternalLinkage,
9028 Constant::getNullValue(Builder.getInt8Ty()), EntryFnName);
9029}
9030
9032 TargetRegionEntryInfo &EntryInfo,
9033 FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,
9034 Function *&OutlinedFn, Constant *&OutlinedFnID) {
9035
9036 SmallString<64> EntryFnName;
9037 OffloadInfoManager.getTargetRegionEntryFnName(EntryFnName, EntryInfo);
9038
9039 if (Config.isTargetDevice() || !Config.openMPOffloadMandatory()) {
9040 Expected<Function *> CBResult = GenerateFunctionCallback(EntryFnName);
9041 if (!CBResult)
9042 return CBResult.takeError();
9043 OutlinedFn = *CBResult;
9044 } else {
9045 OutlinedFn = nullptr;
9046 }
9047
9048 // If this target outline function is not an offload entry, we don't need to
9049 // register it. This may be in the case of a false if clause, or if there are
9050 // no OpenMP targets.
9051 if (!IsOffloadEntry)
9052 return Error::success();
9053
9054 std::string EntryFnIDName =
9055 Config.isTargetDevice()
9056 ? std::string(EntryFnName)
9057 : createPlatformSpecificName({EntryFnName, "region_id"});
9058
9059 OutlinedFnID = registerTargetRegionFunction(EntryInfo, OutlinedFn,
9060 EntryFnName, EntryFnIDName);
9061 return Error::success();
9062}
9063
9065 TargetRegionEntryInfo &EntryInfo, Function *OutlinedFn,
9066 StringRef EntryFnName, StringRef EntryFnIDName) {
9067 if (OutlinedFn)
9068 setOutlinedTargetRegionFunctionAttributes(OutlinedFn);
9069 auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
9070 auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
9071 OffloadInfoManager.registerTargetRegionEntryInfo(
9072 EntryInfo, EntryAddr, OutlinedFnID,
9074 return OutlinedFnID;
9075}
9076
9078 const LocationDescription &Loc, InsertPointTy AllocaIP,
9079 InsertPointTy CodeGenIP, ArrayRef<BasicBlock *> DeallocBlocks,
9080 Value *DeviceID, Value *IfCond, TargetDataInfo &Info,
9081 GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB,
9082 omp::RuntimeFunction *MapperFunc,
9084 BodyGenTy BodyGenType)>
9085 BodyGenCB,
9086 function_ref<void(unsigned int, Value *)> DeviceAddrCB, Value *SrcLocInfo) {
9087 if (!updateToLocation(Loc))
9088 return InsertPointTy();
9089
9090 Builder.restoreIP(CodeGenIP);
9091
9092 bool IsStandAlone = !BodyGenCB;
9093 MapInfosTy *MapInfo;
9094 // Generate the code for the opening of the data environment. Capture all the
9095 // arguments of the runtime call by reference because they are used in the
9096 // closing of the region.
9097 auto BeginThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9098 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
9099 MapInfo = &GenMapInfoCB(Builder.saveIP());
9100 if (Error Err = emitOffloadingArrays(
9101 AllocaIP, Builder.saveIP(), *MapInfo, Info, CustomMapperCB,
9102 /*IsNonContiguous=*/true, DeviceAddrCB))
9103 return Err;
9104
9105 TargetDataRTArgs RTArgs;
9107
9108 // Emit the number of elements in the offloading arrays.
9109 Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
9110
9111 // Source location for the ident struct
9112 if (!SrcLocInfo) {
9113 uint32_t SrcLocStrSize;
9114 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
9115 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
9116 }
9117
9118 SmallVector<llvm::Value *, 13> OffloadingArgs = {
9119 SrcLocInfo, DeviceID,
9120 PointerNum, RTArgs.BasePointersArray,
9121 RTArgs.PointersArray, RTArgs.SizesArray,
9122 RTArgs.MapTypesArray, RTArgs.MapNamesArray,
9123 RTArgs.MappersArray};
9124
9125 if (IsStandAlone) {
9126 assert(MapperFunc && "MapperFunc missing for standalone target data");
9127
9128 auto TaskBodyCB = [&](Value *, Value *,
9130 if (Info.HasNoWait) {
9131 OffloadingArgs.append({llvm::Constant::getNullValue(Int32),
9135 }
9136
9138 OffloadingArgs);
9139
9140 if (Info.HasNoWait) {
9141 BasicBlock *OffloadContBlock =
9142 BasicBlock::Create(Builder.getContext(), "omp_offload.cont");
9143 Function *CurFn = Builder.GetInsertBlock()->getParent();
9144 emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);
9145 Builder.restoreIP(Builder.saveIP());
9146 }
9147 return Error::success();
9148 };
9149
9150 bool RequiresOuterTargetTask = Info.HasNoWait;
9151 if (!RequiresOuterTargetTask)
9152 cantFail(TaskBodyCB(/*DeviceID=*/nullptr, /*RTLoc=*/nullptr,
9153 /*TargetTaskAllocaIP=*/{}));
9154 else
9155 cantFail(emitTargetTask(TaskBodyCB, DeviceID, SrcLocInfo, AllocaIP,
9156 /*Dependencies=*/{}, RTArgs, Info.HasNoWait));
9157 } else {
9158 Function *BeginMapperFunc = getOrCreateRuntimeFunctionPtr(
9159 omp::OMPRTL___tgt_target_data_begin_mapper);
9160
9161 createRuntimeFunctionCall(BeginMapperFunc, OffloadingArgs);
9162
9163 for (auto DeviceMap : Info.DevicePtrInfoMap) {
9164 if (isa<AllocaInst>(DeviceMap.second.second)) {
9165 auto *LI =
9166 Builder.CreateLoad(Builder.getPtrTy(), DeviceMap.second.first);
9167 Builder.CreateStore(LI, DeviceMap.second.second);
9168 }
9169 }
9170
9171 // If device pointer privatization is required, emit the body of the
9172 // region here. It will have to be duplicated: with and without
9173 // privatization.
9174 InsertPointOrErrorTy AfterIP =
9175 BodyGenCB(Builder.saveIP(), BodyGenTy::Priv);
9176 if (!AfterIP)
9177 return AfterIP.takeError();
9178 Builder.restoreIP(*AfterIP);
9179 }
9180 return Error::success();
9181 };
9182
9183 // If we need device pointer privatization, we need to emit the body of the
9184 // region with no privatization in the 'else' branch of the conditional.
9185 // Otherwise, we don't have to do anything.
9186 auto BeginElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9187 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
9188 InsertPointOrErrorTy AfterIP =
9189 BodyGenCB(Builder.saveIP(), BodyGenTy::DupNoPriv);
9190 if (!AfterIP)
9191 return AfterIP.takeError();
9192 Builder.restoreIP(*AfterIP);
9193 return Error::success();
9194 };
9195
9196 // Generate code for the closing of the data region.
9197 auto EndThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9198 ArrayRef<BasicBlock *> DeallocBlocks) {
9199 TargetDataRTArgs RTArgs;
9200 Info.EmitDebug = !MapInfo->Names.empty();
9201 emitOffloadingArraysArgument(Builder, RTArgs, Info, /*ForEndCall=*/true);
9202
9203 // Emit the number of elements in the offloading arrays.
9204 Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
9205
9206 // Source location for the ident struct
9207 if (!SrcLocInfo) {
9208 uint32_t SrcLocStrSize;
9209 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
9210 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
9211 }
9212
9213 Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,
9214 PointerNum, RTArgs.BasePointersArray,
9215 RTArgs.PointersArray, RTArgs.SizesArray,
9216 RTArgs.MapTypesArray, RTArgs.MapNamesArray,
9217 RTArgs.MappersArray};
9218 Function *EndMapperFunc =
9219 getOrCreateRuntimeFunctionPtr(omp::OMPRTL___tgt_target_data_end_mapper);
9220
9221 createRuntimeFunctionCall(EndMapperFunc, OffloadingArgs);
9222 return Error::success();
9223 };
9224
9225 // We don't have to do anything to close the region if the if clause evaluates
9226 // to false.
9227 auto EndElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9228 ArrayRef<BasicBlock *> DeallocBlocks) {
9229 return Error::success();
9230 };
9231
9232 Error Err = [&]() -> Error {
9233 if (BodyGenCB) {
9234 Error Err = [&]() {
9235 if (IfCond)
9236 return emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);
9237 return BeginThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
9238 }();
9239
9240 if (Err)
9241 return Err;
9242
9243 // If we don't require privatization of device pointers, we emit the body
9244 // in between the runtime calls. This avoids duplicating the body code.
9245 InsertPointOrErrorTy AfterIP =
9246 BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv);
9247 if (!AfterIP)
9248 return AfterIP.takeError();
9249 restoreIPandDebugLoc(Builder, *AfterIP);
9250
9251 if (IfCond)
9252 return emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);
9253 return EndThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
9254 }
9255 if (IfCond)
9256 return emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);
9257 return BeginThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
9258 }();
9259
9260 if (Err)
9261 return Err;
9262
9263 return Builder.saveIP();
9264}
9265
9268 bool IsGPUDistribute) {
9269 assert((IVSize == 32 || IVSize == 64) &&
9270 "IV size is not compatible with the omp runtime");
9271 RuntimeFunction Name;
9272 if (IsGPUDistribute)
9273 Name = IVSize == 32
9274 ? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_4
9275 : omp::OMPRTL___kmpc_distribute_static_init_4u)
9276 : (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_8
9277 : omp::OMPRTL___kmpc_distribute_static_init_8u);
9278 else
9279 Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_4
9280 : omp::OMPRTL___kmpc_for_static_init_4u)
9281 : (IVSigned ? omp::OMPRTL___kmpc_for_static_init_8
9282 : omp::OMPRTL___kmpc_for_static_init_8u);
9283
9284 return getOrCreateRuntimeFunction(M, Name);
9285}
9286
9288 bool IVSigned) {
9289 assert((IVSize == 32 || IVSize == 64) &&
9290 "IV size is not compatible with the omp runtime");
9291 RuntimeFunction Name = IVSize == 32
9292 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_4
9293 : omp::OMPRTL___kmpc_dispatch_init_4u)
9294 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_8
9295 : omp::OMPRTL___kmpc_dispatch_init_8u);
9296
9297 return getOrCreateRuntimeFunction(M, Name);
9298}
9299
9301 bool IVSigned) {
9302 assert((IVSize == 32 || IVSize == 64) &&
9303 "IV size is not compatible with the omp runtime");
9304 RuntimeFunction Name = IVSize == 32
9305 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_4
9306 : omp::OMPRTL___kmpc_dispatch_next_4u)
9307 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_8
9308 : omp::OMPRTL___kmpc_dispatch_next_8u);
9309
9310 return getOrCreateRuntimeFunction(M, Name);
9311}
9312
9314 bool IVSigned) {
9315 assert((IVSize == 32 || IVSize == 64) &&
9316 "IV size is not compatible with the omp runtime");
9317 RuntimeFunction Name = IVSize == 32
9318 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_4
9319 : omp::OMPRTL___kmpc_dispatch_fini_4u)
9320 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_8
9321 : omp::OMPRTL___kmpc_dispatch_fini_8u);
9322
9323 return getOrCreateRuntimeFunction(M, Name);
9324}
9325
9327 return getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_dispatch_deinit);
9328}
9329
9331 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Function *Func,
9332 DenseMap<Value *, std::tuple<Value *, unsigned>> &ValueReplacementMap) {
9333
9334 DISubprogram *NewSP = Func->getSubprogram();
9335 if (!NewSP)
9336 return;
9337
9339
9340 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar, unsigned arg) {
9341 DILocalVariable *&NewVar = RemappedVariables[OldVar];
9342 // Only use cached variable if the arg number matches. This is important
9343 // so that DIVariable created for privatized variables are not discarded.
9344 if (NewVar && (arg == NewVar->getArg()))
9345 return NewVar;
9346
9348 Builder.getContext(), OldVar->getScope(), OldVar->getName(),
9349 OldVar->getFile(), OldVar->getLine(), OldVar->getType(), arg,
9350 OldVar->getFlags(), OldVar->getAlignInBits(), OldVar->getAnnotations());
9351 return NewVar;
9352 };
9353
9354 auto UpdateDebugRecord = [&](auto *DR) {
9355 DILocalVariable *OldVar = DR->getVariable();
9356 unsigned ArgNo = 0;
9357 for (auto Loc : DR->location_ops()) {
9358 auto Iter = ValueReplacementMap.find(Loc);
9359 if (Iter != ValueReplacementMap.end()) {
9360 DR->replaceVariableLocationOp(Loc, std::get<0>(Iter->second));
9361 ArgNo = std::get<1>(Iter->second) + 1;
9362 }
9363 }
9364 if (ArgNo != 0)
9365 DR->setVariable(GetUpdatedDIVariable(OldVar, ArgNo));
9366 };
9367
9369 auto MoveDebugRecordToCorrectBlock = [&](DbgVariableRecord *DVR) {
9370 if (DVR->getNumVariableLocationOps() != 1u) {
9371 DVR->setKillLocation();
9372 return;
9373 }
9374 Value *Loc = DVR->getVariableLocationOp(0u);
9375 BasicBlock *CurBB = DVR->getParent();
9376 BasicBlock *RequiredBB = nullptr;
9377
9378 if (Instruction *LocInst = dyn_cast<Instruction>(Loc))
9379 RequiredBB = LocInst->getParent();
9380 else if (isa<llvm::Argument>(Loc))
9381 RequiredBB = &DVR->getFunction()->getEntryBlock();
9382
9383 if (RequiredBB && RequiredBB != CurBB) {
9384 assert(!RequiredBB->empty());
9385 RequiredBB->insertDbgRecordBefore(DVR->clone(),
9386 RequiredBB->back().getIterator());
9387 DVRsToDelete.push_back(DVR);
9388 }
9389 };
9390
9391 // The location and scope of variable records still point to
9392 // the parent function of the target region. Update them.
9393 for (Instruction &I : instructions(Func)) {
9394 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
9395 UpdateDebugRecord(&DVR);
9396 MoveDebugRecordToCorrectBlock(&DVR);
9397 }
9398 }
9399 for (auto *DVR : DVRsToDelete)
9400 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);
9401 // An extra argument is passed to the device. Create the debug data for it.
9402 if (OMPBuilder.Config.isTargetDevice()) {
9403 DICompileUnit *CU = NewSP->getUnit();
9404 Module *M = Func->getParent();
9405 DIBuilder DB(*M, true, CU);
9406 DIType *VoidPtrTy =
9407 DB.createQualifiedType(dwarf::DW_TAG_pointer_type, nullptr);
9408 unsigned ArgNo = Func->arg_size();
9409 DILocalVariable *Var = DB.createParameterVariable(
9410 NewSP, "dyn_ptr", ArgNo, NewSP->getFile(), /*LineNo=*/0, VoidPtrTy,
9411 /*AlwaysPreserve=*/false, DINode::DIFlags::FlagArtificial);
9412 auto Loc = DILocation::get(Func->getContext(), 0, 0, NewSP, 0);
9413 Argument *LastArg = Func->getArg(Func->arg_size() - 1);
9414 DB.insertDeclare(LastArg, Var, DB.createExpression(), Loc,
9415 &(*Func->begin()));
9416 }
9417}
9418
9420 if (Operator::getOpcode(V) == Instruction::AddrSpaceCast)
9421 return cast<Operator>(V)->getOperand(0);
9422 return V;
9423}
9424
9426 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder,
9428 StringRef FuncName, SmallVectorImpl<Value *> &Inputs,
9431 DebugLoc OutlinedFnLoc) {
9432 SmallVector<Type *> ParameterTypes;
9433 if (OMPBuilder.Config.isTargetDevice()) {
9434 // All parameters to target devices are passed as pointers
9435 // or i64. This assumes 64-bit address spaces/pointers.
9436 for (auto &Arg : Inputs)
9437 ParameterTypes.push_back(Arg->getType()->isPointerTy()
9438 ? Arg->getType()
9439 : Type::getInt64Ty(Builder.getContext()));
9440 } else {
9441 for (auto &Arg : Inputs)
9442 ParameterTypes.push_back(Arg->getType());
9443 }
9444
9445 // The implicit dyn_ptr argument is always the last parameter on both host
9446 // and device so the argument counts match without runtime manipulation.
9447 auto *PtrTy = PointerType::getUnqual(Builder.getContext());
9448 ParameterTypes.push_back(PtrTy);
9449
9450 auto BB = Builder.GetInsertBlock();
9451 auto M = BB->getModule();
9452 auto FuncType = FunctionType::get(Builder.getVoidTy(), ParameterTypes,
9453 /*isVarArg*/ false);
9454 auto Func =
9455 Function::Create(FuncType, GlobalValue::InternalLinkage, FuncName, M);
9456
9457 // Forward target-cpu and target-features function attributes from the
9458 // original function to the new outlined function.
9459 Function *ParentFn = Builder.GetInsertBlock()->getParent();
9460
9461 auto TargetCpuAttr = ParentFn->getFnAttribute("target-cpu");
9462 if (TargetCpuAttr.isStringAttribute())
9463 Func->addFnAttr(TargetCpuAttr);
9464
9465 auto TargetFeaturesAttr = ParentFn->getFnAttribute("target-features");
9466 if (TargetFeaturesAttr.isStringAttribute())
9467 Func->addFnAttr(TargetFeaturesAttr);
9468
9469 if (OMPBuilder.Config.isTargetDevice()) {
9470 Value *ExecMode =
9471 OMPBuilder.emitKernelExecutionMode(FuncName, DefaultAttrs.ExecFlags);
9472 OMPBuilder.emitUsed("llvm.compiler.used", {ExecMode});
9473 }
9474
9475 // Save insert point.
9476 IRBuilder<>::InsertPointGuard IPG(Builder);
9477 // We will generate the entries in the outlined function but the debug
9478 // location is still pointing to the parent function, which is the wrong
9479 // scope. OutlinedFnLoc, when the caller provides one, is the same source
9480 // position scoped to the subprogram that will be attached to the outlined
9481 // function, so it is what everything emitted below needs.
9482 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9483
9484 // Generate the region into the function.
9485 BasicBlock *EntryBB = BasicBlock::Create(Builder.getContext(), "entry", Func);
9486 Builder.SetInsertPoint(EntryBB);
9487
9488 // Insert target init call in the device compilation pass. On the host
9489 // (e.g. a non-GPU offload target), there is no runtime init/deinit
9490 // sequence, but the runtime still needs a '<kernel>_kernel_environment'
9491 // global to know how the kernel was configured, so emit it directly.
9492 if (OMPBuilder.Config.isTargetDevice())
9493 Builder.restoreIP(OMPBuilder.createTargetInit(Builder, DefaultAttrs));
9494 else
9495 OMPBuilder.emitKernelEnvironment(Builder, DefaultAttrs);
9496
9497 BasicBlock *UserCodeEntryBB = Builder.GetInsertBlock();
9498
9499 // As we embed the user code in the middle of our target region after we
9500 // generate entry code, we must move what allocas we can into the entry
9501 // block to avoid possible breaking optimisations
9503
9504 BasicBlock *ExitBB = splitBB(Builder, /*CreateBranch=*/true, "target.exit");
9505 BasicBlock *OutlinedBodyBB =
9506 splitBB(Builder, /*CreateBranch=*/true, "outlined.body");
9508 CBFunc(Builder.saveIP(), OutlinedBodyBB->begin(), ExitBB);
9509 if (!AfterIP)
9510 return AfterIP.takeError();
9511 Builder.SetInsertPoint(ExitBB);
9512 // The body callback builds the body with its own IRBuilder and cannot reach
9513 // this one directly. But a body holding another OpenMP construct, a nested
9514 // parallel say, calls OpenMPIRBuilder::createParallel, and that can leave
9515 // this Builder pointing at the wrong debug location, or at none at all. The
9516 // epilogue below belongs to the target construct rather than to whatever the
9517 // body emitted last, so re-establish the location the prologue was emitted
9518 // with.
9519 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9520
9521 // Insert target deinit call in the device compilation pass.
9522 if (OMPBuilder.Config.isTargetDevice())
9523 OMPBuilder.createTargetDeinit(Builder);
9524
9525 // Insert return instruction.
9526 Builder.CreateRetVoid();
9527
9528 // New Alloca IP at entry point of created device function.
9529 Builder.SetInsertPoint(EntryBB->getFirstNonPHIIt());
9530 auto AllocaIP = Builder.saveIP();
9531
9532 Builder.SetInsertPoint(UserCodeEntryBB->getFirstNonPHIOrPseudoProbe());
9533
9534 // Do not include the artificial dyn_ptr argument.
9535 const auto &ArgRange = make_range(Func->arg_begin(), Func->arg_end() - 1);
9536
9538
9539 auto ReplaceValue = [](Value *Input, Value *InputCopy, Function *Func) {
9540 // Things like GEP's can come in the form of Constants. Constants and
9541 // ConstantExpr's do not have access to the knowledge of what they're
9542 // contained in, so we must dig a little to find an instruction so we
9543 // can tell if they're used inside of the function we're outlining. We
9544 // also replace the original constant expression with a new instruction
9545 // equivalent; an instruction as it allows easy modification in the
9546 // following loop, as we can now know the constant (instruction) is
9547 // owned by our target function and replaceUsesOfWith can now be invoked
9548 // on it (cannot do this with constants it seems). A brand new one also
9549 // allows us to be cautious as it is perhaps possible the old expression
9550 // was used inside of the function but exists and is used externally
9551 // (unlikely by the nature of a Constant, but still).
9552 // NOTE: We cannot remove dead constants that have been rewritten to
9553 // instructions at this stage, we run the risk of breaking later lowering
9554 // by doing so as we could still be in the process of lowering the module
9555 // from MLIR to LLVM-IR and the MLIR lowering may still require the original
9556 // constants we have created rewritten versions of.
9557 if (auto *Const = dyn_cast<Constant>(Input))
9558 convertUsersOfConstantsToInstructions(Const, Func, false);
9559
9560 // Collect users before iterating over them to avoid invalidating the
9561 // iteration in case a user uses Input more than once (e.g. a call
9562 // instruction).
9563 SetVector<User *> Users(Input->users().begin(), Input->users().end());
9564 // Collect all the instructions
9566 if (auto *Instr = dyn_cast<Instruction>(User))
9567 if (Instr->getFunction() == Func)
9568 Instr->replaceUsesOfWith(Input, InputCopy);
9569 };
9570
9571 SmallVector<std::pair<Value *, Value *>> DeferredReplacement;
9572
9573 // Rewrite uses of input valus to parameters.
9574 for (auto InArg : zip(Inputs, ArgRange)) {
9575 Value *Input = std::get<0>(InArg);
9576 Argument &Arg = std::get<1>(InArg);
9577 Value *InputCopy = nullptr;
9578
9579 llvm::OpenMPIRBuilder::InsertPointOrErrorTy AfterIP = ArgAccessorFuncCB(
9580 Arg, Input, InputCopy, AllocaIP, Builder.saveIP(), ExitBB->begin());
9581 if (!AfterIP)
9582 return AfterIP.takeError();
9583 Builder.restoreIP(*AfterIP);
9584 ValueReplacementMap[Input] = std::make_tuple(InputCopy, Arg.getArgNo());
9585
9586 // In certain cases a Global may be set up for replacement, however, this
9587 // Global may be used in multiple arguments to the kernel, just segmented
9588 // apart, for example, if we have a global array, that is sectioned into
9589 // multiple mappings (technically not legal in OpenMP, but there is a case
9590 // in Fortran for Common Blocks where this is neccesary), we will end up
9591 // with GEP's into this array inside the kernel, that refer to the Global
9592 // but are technically separate arguments to the kernel for all intents and
9593 // purposes. If we have mapped a segment that requires a GEP into the 0-th
9594 // index, it will fold into an referal to the Global, if we then encounter
9595 // this folded GEP during replacement all of the references to the
9596 // Global in the kernel will be replaced with the argument we have generated
9597 // that corresponds to it, including any other GEP's that refer to the
9598 // Global that may be other arguments. This will invalidate all of the other
9599 // preceding mapped arguments that refer to the same global that may be
9600 // separate segments. To prevent this, we defer global processing until all
9601 // other processing has been performed.
9604 DeferredReplacement.push_back(std::make_pair(Input, InputCopy));
9605 continue;
9606 }
9607
9609 continue;
9610
9611 ReplaceValue(Input, InputCopy, Func);
9612 }
9613
9614 // Replace all of our deferred Input values, currently just Globals.
9615 for (auto Deferred : DeferredReplacement)
9616 ReplaceValue(std::get<0>(Deferred), std::get<1>(Deferred), Func);
9617
9618 FixupDebugInfoForOutlinedFunction(OMPBuilder, Builder, Func,
9619 ValueReplacementMap);
9620 return Func;
9621}
9622/// Given a task descriptor, TaskWithPrivates, return the pointer to the block
9623/// of pointers containing shared data between the parent task and the created
9624/// task.
9626 Value *TaskWithPrivates) {
9627 LLVMContext &Ctx = Builder.getContext();
9628 return Builder.CreateLoad(PointerType::getUnqual(Ctx), TaskWithPrivates);
9629}
9630/// Create an entry point for a target task with the following.
9631/// It'll have the following signature
9632/// void @.omp_target_task_proxy_func(i32 %thread.id, ptr %task)
9633/// This function is called from emitTargetTask once the
9634/// code to launch the target kernel has been outlined already.
9635/// NumOffloadingArrays is the number of offloading arrays that we need to copy
9636/// into the task structure so that the deferred target task can access this
9637/// data even after the stack frame of the generating task has been rolled
9638/// back. Offloading arrays contain base pointers, pointers, sizes etc
9639/// of the data that the target kernel will access. These in effect are the
9640/// non-empty arrays of pointers held by OpenMPIRBuilder::TargetDataRTArgs.
9642 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, CallInst *StaleCI,
9643 StructType *PrivatesTy, StructType *TaskWithPrivatesTy,
9644 const size_t NumOffloadingArrays, const int SharedArgsOperandNo) {
9645
9646 // If NumOffloadingArrays is non-zero, PrivatesTy better not be nullptr.
9647 // This is because PrivatesTy is the type of the structure in which
9648 // we pass the offloading arrays to the deferred target task.
9649 assert((!NumOffloadingArrays || PrivatesTy) &&
9650 "PrivatesTy cannot be nullptr when there are offloadingArrays"
9651 "to privatize");
9652
9653 Module &M = OMPBuilder.M;
9654 // KernelLaunchFunction is the target launch function, i.e.
9655 // the function that sets up kernel arguments and calls
9656 // __tgt_target_kernel to launch the kernel on the device.
9657 //
9658 Function *KernelLaunchFunction = StaleCI->getCalledFunction();
9659
9660 // StaleCI is the CallInst which is the call to the outlined
9661 // target kernel launch function. If there are local live-in values
9662 // that the outlined function uses then these are aggregated into a structure
9663 // which is passed as the second argument. If there are no local live-in
9664 // values or if all values used by the outlined kernel are global variables,
9665 // then there's only one argument, the threadID. So, StaleCI can be
9666 //
9667 // %structArg = alloca { ptr, ptr }, align 8
9668 // %gep_ = getelementptr { ptr, ptr }, ptr %structArg, i32 0, i32 0
9669 // store ptr %20, ptr %gep_, align 8
9670 // %gep_8 = getelementptr { ptr, ptr }, ptr %structArg, i32 0, i32 1
9671 // store ptr %21, ptr %gep_8, align 8
9672 // call void @_QQmain..omp_par.1(i32 %global.tid.val6, ptr %structArg)
9673 //
9674 // OR
9675 //
9676 // call void @_QQmain..omp_par.1(i32 %global.tid.val6)
9677 LLVMContext &Ctx = StaleCI->getParent()->getContext();
9678
9679 Type *ThreadIDTy = Type::getInt32Ty(Ctx);
9680 Type *TaskPtrTy = OMPBuilder.TaskPtr;
9681 [[maybe_unused]] Type *TaskTy = OMPBuilder.Task;
9682
9683 auto ProxyFnTy =
9684 FunctionType::get(Builder.getVoidTy(), {ThreadIDTy, TaskPtrTy},
9685 /* isVarArg */ false);
9686 auto ProxyFn = Function::Create(ProxyFnTy, GlobalValue::InternalLinkage,
9687 ".omp_target_task_proxy_func", M);
9688 Value *ThreadId = ProxyFn->getArg(0);
9689 Value *TaskWithPrivates = ProxyFn->getArg(1);
9690 ThreadId->setName("thread.id");
9691 TaskWithPrivates->setName("task");
9692
9693 bool HasShareds = SharedArgsOperandNo > 0;
9694 bool HasOffloadingArrays = NumOffloadingArrays > 0;
9695 IRBuilder<>::InsertPointGuard IPG(Builder);
9696 BasicBlock *EntryBB =
9697 BasicBlock::Create(Builder.getContext(), "entry", ProxyFn);
9698 Builder.SetInsertPoint(EntryBB);
9699 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
9700
9701 SmallVector<Value *> KernelLaunchArgs;
9702 KernelLaunchArgs.reserve(StaleCI->arg_size());
9703 KernelLaunchArgs.push_back(ThreadId);
9704
9705 if (HasOffloadingArrays) {
9706 assert(TaskTy != TaskWithPrivatesTy &&
9707 "If there are offloading arrays to pass to the target"
9708 "TaskTy cannot be the same as TaskWithPrivatesTy");
9709 (void)TaskTy;
9710 Value *Privates =
9711 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskWithPrivates, 1);
9712 for (unsigned int i = 0; i < NumOffloadingArrays; ++i)
9713 KernelLaunchArgs.push_back(
9714 Builder.CreateStructGEP(PrivatesTy, Privates, i));
9715 }
9716
9717 if (HasShareds) {
9718 auto *ArgStructAlloca =
9719 dyn_cast<AllocaInst>(StaleCI->getArgOperand(SharedArgsOperandNo));
9720 assert(ArgStructAlloca &&
9721 "Unable to find the alloca instruction corresponding to arguments "
9722 "for extracted function");
9723 auto *ArgStructType = cast<StructType>(ArgStructAlloca->getAllocatedType());
9724 std::optional<TypeSize> ArgAllocSize =
9725 ArgStructAlloca->getAllocationSize(M.getDataLayout());
9726 assert(ArgStructType && ArgAllocSize &&
9727 "Unable to determine size of arguments for extracted function");
9728 uint64_t StructSize = ArgAllocSize->getFixedValue();
9729
9730 AllocaInst *NewArgStructAlloca =
9731 Builder.CreateAlloca(ArgStructType, nullptr, "structArg");
9732
9733 Value *SharedsSize = Builder.getInt64(StructSize);
9734
9735 LoadInst *LoadShared =
9736 loadSharedDataFromTaskDescriptor(Builder, TaskWithPrivates);
9737
9738 Builder.CreateMemCpy(
9739 NewArgStructAlloca, NewArgStructAlloca->getAlign(), LoadShared,
9740 LoadShared->getPointerAlignment(M.getDataLayout()), SharedsSize);
9741 KernelLaunchArgs.push_back(NewArgStructAlloca);
9742 }
9743 OMPBuilder.createRuntimeFunctionCall(KernelLaunchFunction, KernelLaunchArgs);
9744 Builder.CreateRetVoid();
9745 return ProxyFn;
9746}
9748
9749 if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
9750 return GEP->getSourceElementType();
9751 if (auto *Alloca = dyn_cast<AllocaInst>(V))
9752 return Alloca->getAllocatedType();
9753
9754 llvm_unreachable("Unhandled Instruction type");
9755 return nullptr;
9756}
9757// This function returns a struct that has at most two members.
9758// The first member is always %struct.kmp_task_ompbuilder_t, that is the task
9759// descriptor. The second member, if needed, is a struct containing arrays
9760// that need to be passed to the offloaded target kernel. For example,
9761// if .offload_baseptrs, .offload_ptrs and .offload_sizes have to be passed to
9762// the target kernel and their types are [3 x ptr], [3 x ptr] and [3 x i64]
9763// respectively, then the types created by this function are
9764//
9765// %struct.privates = type { [3 x ptr], [3 x ptr], [3 x i64] }
9766// %struct.task_with_privates = type { %struct.kmp_task_ompbuilder_t,
9767// %struct.privates }
9768// %struct.task_with_privates is returned by this function.
9769// If there aren't any offloading arrays to pass to the target kernel,
9770// %struct.kmp_task_ompbuilder_t is returned.
9771static StructType *
9773 ArrayRef<Value *> OffloadingArraysToPrivatize,
9774 ArrayRef<Type *> DescriptorTypes) {
9775
9776 if (OffloadingArraysToPrivatize.empty() && DescriptorTypes.empty())
9777 return OMPIRBuilder.Task;
9778
9779 SmallVector<Type *, 4> StructFieldTypes;
9780 for (Value *V : OffloadingArraysToPrivatize) {
9781 assert(V->getType()->isPointerTy() &&
9782 "Expected pointer to array to privatize. Got a non-pointer value "
9783 "instead");
9784 Type *ArrayTy = getOffloadingArrayType(V);
9785 assert(ArrayTy && "ArrayType cannot be nullptr");
9786 StructFieldTypes.push_back(ArrayTy);
9787 }
9788 llvm::append_range(StructFieldTypes, DescriptorTypes);
9789 StructType *PrivatesStructTy =
9790 StructType::create(StructFieldTypes, "struct.privates");
9791 return StructType::create({OMPIRBuilder.Task, PrivatesStructTy},
9792 "struct.task_with_privates");
9793}
9795 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, bool IsOffloadEntry,
9796 TargetRegionEntryInfo &EntryInfo,
9798 Function *&OutlinedFn, Constant *&OutlinedFnID,
9802 DebugLoc OutlinedFnLoc) {
9803
9804 OpenMPIRBuilder::FunctionGenCallback &&GenerateOutlinedFunction =
9805 [&](StringRef EntryFnName) {
9806 return createOutlinedFunction(OMPBuilder, Builder, DefaultAttrs,
9807 EntryFnName, Inputs, CBFunc,
9808 ArgAccessorFuncCB, OutlinedFnLoc);
9809 };
9810
9811 return OMPBuilder.emitTargetRegionFunction(
9812 EntryInfo, GenerateOutlinedFunction, IsOffloadEntry, OutlinedFn,
9813 OutlinedFnID);
9814}
9815
9817 TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc,
9819 const DependenciesInfo &Dependencies, const TargetDataRTArgs &RTArgs,
9820 bool HasNoWait) {
9821
9822 // The following explains the code-gen scenario for the `target` directive. A
9823 // similar scneario is followed for other device-related directives (e.g.
9824 // `target enter data`) but in similar fashion since we only need to emit task
9825 // that encapsulates the proper runtime call.
9826 //
9827 // When we arrive at this function, the target region itself has been
9828 // outlined into the function OutlinedFn.
9829 // So at ths point, for
9830 // --------------------------------------------------------------
9831 // void user_code_that_offloads(...) {
9832 // omp target depend(..) map(from:a) map(to:b) private(i)
9833 // do i = 1, 10
9834 // a(i) = b(i) + n
9835 // }
9836 //
9837 // --------------------------------------------------------------
9838 //
9839 // we have
9840 //
9841 // --------------------------------------------------------------
9842 //
9843 // void user_code_that_offloads(...) {
9844 // %.offload_baseptrs = alloca [2 x ptr], align 8
9845 // %.offload_ptrs = alloca [2 x ptr], align 8
9846 // %.offload_mappers = alloca [2 x ptr], align 8
9847 // ;; target region has been outlined and now we need to
9848 // ;; offload to it via a target task.
9849 // }
9850 // void outlined_device_function(ptr a, ptr b, ptr n) {
9851 // n = *n_ptr;
9852 // do i = 1, 10
9853 // a(i) = b(i) + n
9854 // }
9855 //
9856 // We have to now do the following
9857 // (i) Make an offloading call to outlined_device_function using the OpenMP
9858 // RTL. See 'kernel_launch_function' in the pseudo code below. This is
9859 // emitted by emitKernelLaunch
9860 // (ii) Create a task entry point function that calls kernel_launch_function
9861 // and is the entry point for the target task. See
9862 // '@.omp_target_task_proxy_func in the pseudocode below.
9863 // (iii) Create a task with the task entry point created in (ii)
9864 //
9865 // That is we create the following
9866 // struct task_with_privates {
9867 // struct kmp_task_ompbuilder_t task_struct;
9868 // struct privates {
9869 // [2 x ptr] ; baseptrs
9870 // [2 x ptr] ; ptrs
9871 // [2 x i64] ; sizes
9872 // }
9873 // }
9874 // void user_code_that_offloads(...) {
9875 // %.offload_baseptrs = alloca [2 x ptr], align 8
9876 // %.offload_ptrs = alloca [2 x ptr], align 8
9877 // %.offload_sizes = alloca [2 x i64], align 8
9878 //
9879 // %structArg = alloca { ptr, ptr, ptr }, align 8
9880 // %strucArg[0] = a
9881 // %strucArg[1] = b
9882 // %strucArg[2] = &n
9883 //
9884 // target_task_with_privates = @__kmpc_omp_target_task_alloc(...,
9885 // sizeof(kmp_task_ompbuilder_t),
9886 // sizeof(structArg),
9887 // @.omp_target_task_proxy_func,
9888 // ...)
9889 // memcpy(target_task_with_privates->task_struct->shareds, %structArg,
9890 // sizeof(structArg))
9891 // memcpy(target_task_with_privates->privates->baseptrs,
9892 // offload_baseptrs, sizeof(offload_baseptrs)
9893 // memcpy(target_task_with_privates->privates->ptrs,
9894 // offload_ptrs, sizeof(offload_ptrs)
9895 // memcpy(target_task_with_privates->privates->sizes,
9896 // offload_sizes, sizeof(offload_sizes)
9897 // dependencies_array = ...
9898 // ;; if nowait not present
9899 // call @__kmpc_omp_wait_deps(..., dependencies_array)
9900 // call @__kmpc_omp_task_begin_if0(...)
9901 // call @ @.omp_target_task_proxy_func(i32 thread_id, ptr
9902 // %target_task_with_privates)
9903 // call @__kmpc_omp_task_complete_if0(...)
9904 // }
9905 //
9906 // define internal void @.omp_target_task_proxy_func(i32 %thread.id,
9907 // ptr %task) {
9908 // %structArg = alloca {ptr, ptr, ptr}
9909 // %task_ptr = getelementptr(%task, 0, 0)
9910 // %shared_data = load (getelementptr %task_ptr, 0, 0)
9911 // mempcy(%structArg, %shared_data, sizeof(%structArg))
9912 //
9913 // %offloading_arrays = getelementptr(%task, 0, 1)
9914 // %offload_baseptrs = getelementptr(%offloading_arrays, 0, 0)
9915 // %offload_ptrs = getelementptr(%offloading_arrays, 0, 1)
9916 // %offload_sizes = getelementptr(%offloading_arrays, 0, 2)
9917 // kernel_launch_function(%thread.id, %offload_baseptrs, %offload_ptrs,
9918 // %offload_sizes, %structArg)
9919 // }
9920 //
9921 // We need the proxy function because the signature of the task entry point
9922 // expected by kmpc_omp_task is always the same and will be different from
9923 // that of the kernel_launch function.
9924 //
9925 // kernel_launch_function is generated by emitKernelLaunch and has the
9926 // always_inline attribute. For this example, it'll look like so:
9927 // void kernel_launch_function(%thread_id, %offload_baseptrs, %offload_ptrs,
9928 // %offload_sizes, %structArg) alwaysinline {
9929 // %kernel_args = alloca %struct.__tgt_kernel_arguments, align 8
9930 // ; load aggregated data from %structArg
9931 // ; setup kernel_args using offload_baseptrs, offload_ptrs and
9932 // ; offload_sizes
9933 // call i32 @__tgt_target_kernel(...,
9934 // outlined_device_function,
9935 // ptr %kernel_args)
9936 // }
9937 // void outlined_device_function(ptr a, ptr b, ptr n) {
9938 // n = *n_ptr;
9939 // do i = 1, 10
9940 // a(i) = b(i) + n
9941 // }
9942 //
9943 BasicBlock *TargetTaskBodyBB =
9944 splitBB(Builder, /*CreateBranch=*/true, "target.task.body");
9945 BasicBlock *TargetTaskAllocaBB =
9946 splitBB(Builder, /*CreateBranch=*/true, "target.task.alloca");
9947
9948 InsertPointTy TargetTaskAllocaIP(TargetTaskAllocaBB->begin());
9949 InsertPointTy TargetTaskBodyIP(TargetTaskBodyBB->begin());
9950
9951 auto OI = std::make_unique<OutlineInfo>();
9952 OI->EntryBB = TargetTaskAllocaBB;
9953 OI->OuterAllocBB = AllocaIP.getNodeParent();
9954
9955 // Add the thread ID argument.
9957 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
9958 Builder, AllocaIP, ToBeDeleted, TargetTaskAllocaIP, "global.tid", false));
9959
9960 // Generate the task body which will subsequently be outlined.
9961 Builder.restoreIP(TargetTaskBodyIP);
9962 if (Error Err = TaskBodyCB(DeviceID, RTLoc, TargetTaskAllocaIP))
9963 return Err;
9964
9965 // The outliner (CodeExtractor) extract a sequence or vector of blocks that
9966 // it is given. These blocks are enumerated by
9967 // OpenMPIRBuilder::OutlineInfo::collectBlocks which expects the OI.ExitBlock
9968 // to be outside the region. In other words, OI.ExitBlock is expected to be
9969 // the start of the region after the outlining. We used to set OI.ExitBlock
9970 // to the InsertBlock after TaskBodyCB is done. This is fine in most cases
9971 // except when the task body is a single basic block. In that case,
9972 // OI.ExitBlock is set to the single task body block and will get left out of
9973 // the outlining process. So, simply create a new empty block to which we
9974 // uncoditionally branch from where TaskBodyCB left off
9975 OI->ExitBB = BasicBlock::Create(Builder.getContext(), "target.task.cont");
9976 emitBlock(OI->ExitBB, Builder.GetInsertBlock()->getParent(),
9977 /*IsFinished=*/true);
9978
9979 SmallVector<Value *, 2> OffloadingArraysToPrivatize;
9980 bool NeedsTargetTask = HasNoWait && DeviceID;
9981 if (NeedsTargetTask) {
9982 for (auto *V :
9983 {RTArgs.BasePointersArray, RTArgs.PointersArray, RTArgs.MappersArray,
9984 RTArgs.MapNamesArray, RTArgs.MapTypesArray, RTArgs.MapTypesArrayEnd,
9985 RTArgs.SizesArray}) {
9987 OffloadingArraysToPrivatize.push_back(V);
9988 OI->ExcludeArgsFromAggregate.push_back(V);
9989 }
9990 }
9991 }
9992 auto NonContiguousDescriptors = RTArgs.NonContiguousDescriptors;
9993 if (!NeedsTargetTask)
9994 NonContiguousDescriptors.clear();
9995 OI->PostOutlineCB = [this, ToBeDeleted, Dependencies, NeedsTargetTask,
9996 DeviceID, OffloadingArraysToPrivatize,
9997 NonContiguousDescriptors,
9998 PointersArray =
9999 RTArgs.PointersArray](Function &OutlinedFn) mutable {
10000 assert(OutlinedFn.hasOneUse() &&
10001 "there must be a single user for the outlined function");
10002
10003 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
10004
10005 // The first argument of StaleCI is always the thread id.
10006 // The next few arguments are the pointers to offloading arrays
10007 // if any. (see OffloadingArraysToPrivatize)
10008 // Finally, all other local values that are live-in into the outlined region
10009 // end up in a structure whose pointer is passed as the last argument. This
10010 // piece of data is passed in the "shared" field of the task structure. So,
10011 // we know we have to pass shareds to the task if the number of arguments is
10012 // greater than OffloadingArraysToPrivatize.size() + 1 The 1 is for the
10013 // thread id. Further, for safety, we assert that the number of arguments of
10014 // StaleCI is exactly OffloadingArraysToPrivatize.size() + 2
10015 const unsigned int NumStaleCIArgs = StaleCI->arg_size();
10016 bool HasShareds = NumStaleCIArgs > OffloadingArraysToPrivatize.size() + 1;
10017 assert((!HasShareds ||
10018 NumStaleCIArgs == (OffloadingArraysToPrivatize.size() + 2)) &&
10019 "Wrong number of arguments for StaleCI when shareds are present");
10020 int SharedArgOperandNo =
10021 HasShareds ? OffloadingArraysToPrivatize.size() + 1 : 0;
10022
10023 // Descriptor storage is not an argument to the outlined function. It is
10024 // reached indirectly through the task-private pointer array.
10025 SmallVector<Type *, 2> DescriptorTypes;
10026 for (const auto &Descriptor : NonContiguousDescriptors)
10027 DescriptorTypes.push_back(Descriptor.Storage->getAllocatedType());
10028 StructType *TaskWithPrivatesTy = createTaskWithPrivatesTy(
10029 *this, OffloadingArraysToPrivatize, DescriptorTypes);
10030 StructType *PrivatesTy = nullptr;
10031
10032 if (!OffloadingArraysToPrivatize.empty())
10033 PrivatesTy =
10034 static_cast<StructType *>(TaskWithPrivatesTy->getElementType(1));
10035
10037 *this, Builder, StaleCI, PrivatesTy, TaskWithPrivatesTy,
10038 OffloadingArraysToPrivatize.size(), SharedArgOperandNo);
10039
10040 LLVM_DEBUG(dbgs() << "Proxy task entry function created: " << *ProxyFn
10041 << "\n");
10042
10043 Builder.SetInsertPoint(StaleCI);
10044
10045 // Gather the arguments for emitting the runtime call.
10046 uint32_t SrcLocStrSize;
10047 Constant *SrcLocStr =
10049 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
10050
10051 // @__kmpc_omp_task_alloc or @__kmpc_omp_target_task_alloc
10052 //
10053 // If `HasNoWait == true`, we call @__kmpc_omp_target_task_alloc to provide
10054 // the DeviceID to the deferred task and also since
10055 // @__kmpc_omp_target_task_alloc creates an untied/async task.
10056 Function *TaskAllocFn =
10057 !NeedsTargetTask
10058 ? getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc)
10060 OMPRTL___kmpc_omp_target_task_alloc);
10061
10062 // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
10063 // call.
10064 Value *ThreadID = getOrCreateThreadID(Ident);
10065
10066 // Argument - `sizeof_kmp_task_t` (TaskSize)
10067 // Tasksize refers to the size in bytes of kmp_task_t data structure
10068 // plus any other data to be passed to the target task, if any, which
10069 // is packed into a struct. kmp_task_t and the struct so created are
10070 // packed into a wrapper struct whose type is TaskWithPrivatesTy.
10071 Value *TaskSize = Builder.getInt64(
10072 M.getDataLayout().getTypeStoreSize(TaskWithPrivatesTy));
10073
10074 // Argument - `sizeof_shareds` (SharedsSize)
10075 // SharedsSize refers to the shareds array size in the kmp_task_t data
10076 // structure.
10077 Value *SharedsSize = Builder.getInt64(0);
10078 if (HasShareds) {
10079 auto *ArgStructAlloca =
10080 dyn_cast<AllocaInst>(StaleCI->getArgOperand(SharedArgOperandNo));
10081 assert(ArgStructAlloca &&
10082 "Unable to find the alloca instruction corresponding to arguments "
10083 "for extracted function");
10084 std::optional<TypeSize> ArgAllocSize =
10085 ArgStructAlloca->getAllocationSize(M.getDataLayout());
10086 assert(ArgAllocSize &&
10087 "Unable to determine size of arguments for extracted function");
10088 SharedsSize = Builder.getInt64(ArgAllocSize->getFixedValue());
10089 }
10090
10091 // Argument - `flags`
10092 // Task is tied iff (Flags & 1) == 1.
10093 // Task is untied iff (Flags & 1) == 0.
10094 // Task is final iff (Flags & 2) == 2.
10095 // Task is not final iff (Flags & 2) == 0.
10096 // A target task is not final and is untied.
10097 Value *Flags = Builder.getInt32(0);
10098
10099 // Emit the @__kmpc_omp_task_alloc runtime call
10100 // The runtime call returns a pointer to an area where the task captured
10101 // variables must be copied before the task is run (TaskData)
10102 CallInst *TaskData = nullptr;
10103
10104 SmallVector<llvm::Value *> TaskAllocArgs = {
10105 /*loc_ref=*/Ident, /*gtid=*/ThreadID,
10106 /*flags=*/Flags,
10107 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
10108 /*task_func=*/ProxyFn};
10109
10110 if (NeedsTargetTask) {
10111 assert(DeviceID && "Expected non-empty device ID.");
10112 TaskAllocArgs.push_back(DeviceID);
10113 }
10114
10115 TaskData = createRuntimeFunctionCall(TaskAllocFn, TaskAllocArgs);
10116
10117 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
10118 if (HasShareds) {
10119 Value *Shareds = StaleCI->getArgOperand(SharedArgOperandNo);
10120 Value *TaskShareds = loadSharedDataFromTaskDescriptor(Builder, TaskData);
10121 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
10122 SharedsSize);
10123 }
10124 if (!OffloadingArraysToPrivatize.empty()) {
10125 Value *Privates =
10126 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskData, 1);
10127 Value *PrivatePointersArray = nullptr;
10128 for (unsigned int i = 0; i < OffloadingArraysToPrivatize.size(); ++i) {
10129 Value *PtrToPrivatize = OffloadingArraysToPrivatize[i];
10130 [[maybe_unused]] Type *ArrayType =
10131 getOffloadingArrayType(PtrToPrivatize);
10132 assert(ArrayType && "ArrayType cannot be nullptr");
10133
10134 Type *ElementType = PrivatesTy->getElementType(i);
10135 assert(ElementType == ArrayType &&
10136 "ElementType should match ArrayType");
10137 (void)ArrayType;
10138
10139 Value *Dst = Builder.CreateStructGEP(PrivatesTy, Privates, i);
10140 Builder.CreateMemCpy(
10141 Dst, Alignment, PtrToPrivatize, Alignment,
10142 Builder.getInt64(M.getDataLayout().getTypeStoreSize(ElementType)));
10143 if (PtrToPrivatize == PointersArray)
10144 PrivatePointersArray = Dst;
10145 }
10146 // Snapshot the encounter-time bounds before enqueueing the task, then
10147 // redirect its pointer entries to descriptors owned by that task.
10148 for (auto [I, Descriptor] : llvm::enumerate(NonContiguousDescriptors)) {
10149 assert(PrivatePointersArray && "missing task-private pointer array");
10150 Value *Dst = Builder.CreateStructGEP(
10151 PrivatesTy, Privates, OffloadingArraysToPrivatize.size() + I);
10152 Builder.CreateMemCpy(
10153 Dst, Alignment, Descriptor.Storage, Descriptor.Storage->getAlign(),
10154 Builder.getInt64(M.getDataLayout().getTypeStoreSize(
10155 Descriptor.Storage->getAllocatedType())));
10156 Value *Entry = Builder.CreateConstInBoundsGEP2_32(
10157 getOffloadingArrayType(PointersArray), PrivatePointersArray, 0,
10158 Descriptor.MapIndex);
10159 Builder.CreateAlignedStore(Dst, Entry, Alignment);
10160 }
10161 }
10162
10163 Value *DepArray = nullptr;
10164 Value *NumDeps = nullptr;
10165 if (Dependencies.DepArray) {
10166 DepArray = Dependencies.DepArray;
10167 NumDeps = Dependencies.NumDeps;
10168 } else if (!Dependencies.Deps.empty()) {
10169 DepArray = emitTaskDependencies(*this, Dependencies.Deps);
10170 NumDeps = Builder.getInt32(Dependencies.Deps.size());
10171 }
10172
10173 // ---------------------------------------------------------------
10174 // V5.2 13.8 target construct
10175 // If the nowait clause is present, execution of the target task
10176 // may be deferred. If the nowait clause is not present, the target task is
10177 // an included task.
10178 // ---------------------------------------------------------------
10179 // The above means that the lack of a nowait on the target construct
10180 // translates to '#pragma omp task if(0)'
10181 if (!NeedsTargetTask) {
10182 if (DepArray) {
10183 Function *TaskWaitFn =
10184 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_wait_deps);
10186 TaskWaitFn,
10187 {/*loc_ref=*/Ident, /*gtid=*/ThreadID,
10188 /*ndeps=*/NumDeps,
10189 /*dep_list=*/DepArray,
10190 /*ndeps_noalias=*/ConstantInt::get(Builder.getInt32Ty(), 0),
10191 /*noalias_dep_list=*/
10193 }
10194 // Included task.
10195 Function *TaskBeginFn =
10196 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);
10197 Function *TaskCompleteFn =
10198 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);
10199 createRuntimeFunctionCall(TaskBeginFn, {Ident, ThreadID, TaskData});
10200 CallInst *CI = createRuntimeFunctionCall(ProxyFn, {ThreadID, TaskData});
10201 CI->setDebugLoc(StaleCI->getDebugLoc());
10202 createRuntimeFunctionCall(TaskCompleteFn, {Ident, ThreadID, TaskData});
10203 } else if (DepArray) {
10204 // HasNoWait - meaning the task may be deferred. Call
10205 // __kmpc_omp_task_with_deps if there are dependencies,
10206 // else call __kmpc_omp_task
10207 Function *TaskFn =
10208 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);
10210 TaskFn,
10211 {Ident, ThreadID, TaskData, NumDeps, DepArray,
10212 ConstantInt::get(Builder.getInt32Ty(), 0),
10214 } else {
10215 // Emit the @__kmpc_omp_task runtime call to spawn the task
10216 Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
10217 createRuntimeFunctionCall(TaskFn, {Ident, ThreadID, TaskData});
10218 }
10219
10220 Builder.ClearInsertionPoint();
10221 StaleCI->eraseFromParent();
10222 for (Instruction *I : llvm::reverse(ToBeDeleted))
10223 I->eraseFromParent();
10224 };
10225 addOutlineInfo(std::move(OI));
10226
10227 LLVM_DEBUG(dbgs() << "Insert block after emitKernelLaunch = \n"
10228 << *(Builder.GetInsertBlock()) << "\n");
10229 LLVM_DEBUG(dbgs() << "Module after emitKernelLaunch = \n"
10230 << *(Builder.getModule()) << "\n");
10231 return Builder.saveIP();
10232}
10233
10235 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
10236 TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
10237 CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous,
10238 bool ForEndCall, function_ref<void(unsigned int, Value *)> DeviceAddrCB) {
10239 if (Error Err =
10240 emitOffloadingArrays(AllocaIP, CodeGenIP, CombinedInfo, Info,
10241 CustomMapperCB, IsNonContiguous, DeviceAddrCB))
10242 return Err;
10243 emitOffloadingArraysArgument(Builder, RTArgs, Info, ForEndCall);
10244 return Error::success();
10245}
10246
10248 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Value *RTLocOverride,
10253 Value *IfCond, Function *OutlinedFn, Constant *OutlinedFnID,
10257 const OpenMPIRBuilder::DependenciesInfo &Dependencies, bool HasNoWait,
10258 Value *DynCGroupMem, OMPDynGroupprivateFallbackType DynCGroupMemFallback) {
10259 // Generate a function call to the host fallback implementation of the target
10260 // region. This is called by the host when no offload entry was generated for
10261 // the target region and when the offloading call fails at runtime.
10262 auto &&EmitTargetCallFallbackCB = [&](OpenMPIRBuilder::InsertPointTy IP)
10264 Builder.restoreIP(IP);
10265 // Ensure the host fallback has the same dyn_ptr ABI as the device.
10266 SmallVector<Value *> FallbackArgs(Args.begin(), Args.end());
10267 FallbackArgs.push_back(
10268 Constant::getNullValue(PointerType::getUnqual(Builder.getContext())));
10269 OMPBuilder.createRuntimeFunctionCall(OutlinedFn, FallbackArgs);
10270 return Builder.saveIP();
10271 };
10272
10273 bool HasDependencies = !Dependencies.empty();
10274 bool RequiresOuterTargetTask = HasNoWait || HasDependencies;
10275
10277
10278 auto TaskBodyCB =
10279 [&](Value *DeviceID, Value *RTLoc,
10280 IRBuilderBase::InsertPoint TargetTaskAllocaIP) -> Error {
10281 // Assume no error was returned because EmitTargetCallFallbackCB doesn't
10282 // produce any.
10284 // emitKernelLaunch makes the necessary runtime call to offload the
10285 // kernel. We then outline all that code into a separate function
10286 // ('kernel_launch_function' in the pseudo code above). This function is
10287 // then called by the target task proxy function (see
10288 // '@.omp_target_task_proxy_func' in the pseudo code above)
10289 // "@.omp_target_task_proxy_func' is generated by
10290 // emitTargetTaskProxyFunction.
10291 if (OutlinedFnID && DeviceID)
10292 return OMPBuilder.emitKernelLaunch(Builder, OutlinedFnID,
10293 EmitTargetCallFallbackCB, KArgs,
10294 DeviceID, RTLoc, TargetTaskAllocaIP);
10295
10296 // We only need to do the outlining if `DeviceID` is set to avoid calling
10297 // `emitKernelLaunch` if we want to code-gen for the host; e.g. if we are
10298 // generating the `else` branch of an `if` clause.
10299 //
10300 // When OutlinedFnID is set to nullptr, then it's not an offloading call.
10301 // In this case, we execute the host implementation directly.
10302 return EmitTargetCallFallbackCB(OMPBuilder.Builder.saveIP());
10303 }());
10304
10305 OMPBuilder.Builder.restoreIP(AfterIP);
10306 return Error::success();
10307 };
10308
10309 auto &&EmitTargetCallElse =
10310 [&](OpenMPIRBuilder::InsertPointTy AllocaIP,
10312 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
10313 // Assume no error was returned because EmitTargetCallFallbackCB doesn't
10314 // produce any.
10316 if (RequiresOuterTargetTask) {
10317 // Arguments that are intended to be directly forwarded to an
10318 // emitKernelLaunch call are pased as nullptr, since
10319 // OutlinedFnID=nullptr results in that call not being done.
10321 return OMPBuilder.emitTargetTask(TaskBodyCB, /*DeviceID=*/nullptr,
10322 /*RTLoc=*/nullptr, AllocaIP,
10323 Dependencies, EmptyRTArgs, HasNoWait);
10324 }
10325 return EmitTargetCallFallbackCB(Builder.saveIP());
10326 }());
10327
10328 Builder.restoreIP(AfterIP);
10329 return Error::success();
10330 };
10331
10332 auto &&EmitTargetCallThen =
10333 [&](OpenMPIRBuilder::InsertPointTy AllocaIP,
10335 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
10336 Info.HasNoWait = HasNoWait;
10337 OpenMPIRBuilder::MapInfosTy &MapInfo = GenMapInfoCB(Builder.saveIP());
10338
10340 if (Error Err = OMPBuilder.emitOffloadingArraysAndArgs(
10341 AllocaIP, Builder.saveIP(), Info, RTArgs, MapInfo, CustomMapperCB,
10342 /*IsNonContiguous=*/true,
10343 /*ForEndCall=*/false))
10344 return Err;
10345
10346 SmallVector<Value *, 3> NumTeamsC;
10347 for (auto [DefaultVal, RuntimeVal] :
10348 zip_equal(DefaultAttrs.MaxTeams, RuntimeAttrs.MaxTeams))
10349 NumTeamsC.push_back(RuntimeVal ? RuntimeVal
10350 : Builder.getInt32(DefaultVal));
10351
10352 // Calculate number of threads: 0 if no clauses specified, otherwise it is
10353 // the minimum between optional THREAD_LIMIT and NUM_THREADS clauses.
10354 auto InitMaxThreadsClause = [&Builder](Value *Clause) {
10355 if (Clause)
10356 Clause = Builder.CreateIntCast(Clause, Builder.getInt32Ty(),
10357 /*isSigned=*/false);
10358 return Clause;
10359 };
10360 auto CombineMaxThreadsClauses = [&Builder](Value *Clause, Value *&Result) {
10361 if (Clause)
10362 Result =
10363 Result ? Builder.CreateSelect(Builder.CreateICmpULT(Result, Clause),
10364 Result, Clause)
10365 : Clause;
10366 };
10367
10368 // If a multi-dimensional THREAD_LIMIT is set, it is the OMPX_BARE case, so
10369 // the NUM_THREADS clause is overriden by THREAD_LIMIT.
10370 SmallVector<Value *, 3> NumThreadsC;
10371 Value *MaxThreadsClause =
10372 RuntimeAttrs.TeamsThreadLimit.size() == 1
10373 ? InitMaxThreadsClause(RuntimeAttrs.MaxThreads.front())
10374 : nullptr;
10375
10376 for (auto [TeamsVal, TargetVal] : zip_equal(
10377 RuntimeAttrs.TeamsThreadLimit, RuntimeAttrs.TargetThreadLimit)) {
10378 Value *TeamsThreadLimitClause = InitMaxThreadsClause(TeamsVal);
10379 Value *NumThreads = InitMaxThreadsClause(TargetVal);
10380
10381 CombineMaxThreadsClauses(TeamsThreadLimitClause, NumThreads);
10382 CombineMaxThreadsClauses(MaxThreadsClause, NumThreads);
10383
10384 NumThreadsC.push_back(NumThreads ? NumThreads : Builder.getInt32(0));
10385 }
10386
10387 unsigned NumTargetItems = Info.NumberOfPtrs;
10388 Value *RTLoc = RTLocOverride;
10389 if (!RTLoc) {
10390 uint32_t SrcLocStrSize;
10391 Constant *SrcLocStr =
10392 OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
10393 RTLoc = OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize,
10394 llvm::omp::IdentFlag(0), 0);
10395 }
10396
10397 Value *TripCount = RuntimeAttrs.LoopTripCount
10398 ? Builder.CreateIntCast(RuntimeAttrs.LoopTripCount,
10399 Builder.getInt64Ty(),
10400 /*isSigned=*/false)
10401 : Builder.getInt64(0);
10402
10403 // Request zero groupprivate bytes by default.
10404 if (!DynCGroupMem)
10405 DynCGroupMem = Builder.getInt32(0);
10406
10408 NumTargetItems, RTArgs, TripCount, NumTeamsC, NumThreadsC, DynCGroupMem,
10409 HasNoWait, /*StrictBlocks=*/false, /*StrictThreads=*/false,
10410 DynCGroupMemFallback);
10411
10412 // Assume no error was returned because TaskBodyCB and
10413 // EmitTargetCallFallbackCB don't produce any.
10415 // The presence of certain clauses on the target directive require the
10416 // explicit generation of the target task.
10417 if (RequiresOuterTargetTask)
10418 return OMPBuilder.emitTargetTask(TaskBodyCB, RuntimeAttrs.DeviceID,
10419 RTLoc, AllocaIP, Dependencies,
10420 KArgs.RTArgs, Info.HasNoWait);
10421
10422 return OMPBuilder.emitKernelLaunch(
10423 Builder, OutlinedFnID, EmitTargetCallFallbackCB, KArgs,
10424 RuntimeAttrs.DeviceID, RTLoc, AllocaIP);
10425 }());
10426
10427 Builder.restoreIP(AfterIP);
10428 return Error::success();
10429 };
10430
10431 // If we don't have an ID for the target region, it means an offload entry
10432 // wasn't created. In this case we just run the host fallback directly and
10433 // ignore any potential 'if' clauses.
10434 if (!OutlinedFnID)
10435 return EmitTargetCallElse(AllocaIP, Builder.saveIP(), DeallocBlocks);
10436
10437 // If there's no 'if' clause, only generate the kernel launch code path.
10438 if (!IfCond)
10439 return EmitTargetCallThen(AllocaIP, Builder.saveIP(), DeallocBlocks);
10440
10441 return OMPBuilder.emitIfClause(IfCond, EmitTargetCallThen, EmitTargetCallElse,
10442 AllocaIP);
10443}
10444
10446 const LocationDescription &Loc, bool IsOffloadEntry, InsertPointTy AllocaIP,
10447 InsertPointTy CodeGenIP, ArrayRef<BasicBlock *> DeallocBlocks,
10448 TargetDataInfo &Info, TargetRegionEntryInfo &EntryInfo,
10449 const TargetKernelDefaultAttrs &DefaultAttrs,
10450 const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond,
10451 SmallVectorImpl<Value *> &Inputs, GenMapInfoCallbackTy GenMapInfoCB,
10454 CustomMapperCallbackTy CustomMapperCB, const DependenciesInfo &Dependencies,
10455 bool HasNowait, Value *DynCGroupMem,
10456 OMPDynGroupprivateFallbackType DynCGroupMemFallback, DebugLoc OutlinedFnLoc,
10457 Value *RTLocOverride) {
10458
10459 if (!updateToLocation(Loc))
10460 return InsertPointTy();
10461
10462 Builder.restoreIP(CodeGenIP);
10463
10464 Function *OutlinedFn;
10465 Constant *OutlinedFnID = nullptr;
10466 // The target region is outlined into its own function. The LLVM IR for
10467 // the target region itself is generated using the callbacks CBFunc
10468 // and ArgAccessorFuncCB
10470 *this, Builder, IsOffloadEntry, EntryInfo, DefaultAttrs, OutlinedFn,
10471 OutlinedFnID, Inputs, CBFunc, ArgAccessorFuncCB, OutlinedFnLoc))
10472 return Err;
10473
10474 // If we are not on the target device, then we need to generate code
10475 // to make a remote call (offload) to the previously outlined function
10476 // that represents the target region. Do that now.
10477 if (!Config.isTargetDevice()) {
10478 if (Error Err = emitTargetCall(
10479 *this, Builder, RTLocOverride, AllocaIP, DeallocBlocks, Info,
10480 DefaultAttrs, RuntimeAttrs, IfCond, OutlinedFn, OutlinedFnID,
10481 Inputs, GenMapInfoCB, CustomMapperCB, Dependencies, HasNowait,
10482 DynCGroupMem, DynCGroupMemFallback))
10483 return Err;
10484 }
10485 return Builder.saveIP();
10486}
10487
10488std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
10489 StringRef FirstSeparator,
10490 StringRef Separator) {
10491 SmallString<128> Buffer;
10492 llvm::raw_svector_ostream OS(Buffer);
10493 StringRef Sep = FirstSeparator;
10494 for (StringRef Part : Parts) {
10495 OS << Sep << Part;
10496 Sep = Separator;
10497 }
10498 return OS.str().str();
10499}
10500
10501std::string
10503 return OpenMPIRBuilder::getNameWithSeparators(Parts, Config.firstSeparator(),
10504 Config.separator());
10505}
10506
10508 Type *Ty, const StringRef &Name, std::optional<unsigned> AddressSpace) {
10509 auto &Elem = *InternalVars.try_emplace(Name, nullptr).first;
10510 if (Elem.second) {
10511 assert(Elem.second->getValueType() == Ty &&
10512 "OMP internal variable has different type than requested");
10513 } else {
10514 // TODO: investigate the appropriate linkage type used for the global
10515 // variable for possibly changing that to internal or private, or maybe
10516 // create different versions of the function for different OMP internal
10517 // variables.
10518 const DataLayout &DL = M.getDataLayout();
10519 // TODO: Investigate why AMDGPU expects AS 0 for globals even though the
10520 // default global AS is 1.
10521 // See double-target-call-with-declare-target.f90 and
10522 // declare-target-vars-in-target-region.f90 libomptarget
10523 // tests.
10524 unsigned AddressSpaceVal = AddressSpace ? *AddressSpace
10525 : M.getTargetTriple().isAMDGPU()
10526 ? 0
10527 : DL.getDefaultGlobalsAddressSpace();
10528 auto Linkage = this->M.getTargetTriple().isWasm()
10531 auto *GV = new GlobalVariable(M, Ty, /*IsConstant=*/false, Linkage,
10532 Constant::getNullValue(Ty), Elem.first(),
10533 /*InsertBefore=*/nullptr,
10534 GlobalValue::NotThreadLocal, AddressSpaceVal);
10535 const llvm::Align TypeAlign = DL.getABITypeAlign(Ty);
10536 const llvm::Align PtrAlign = DL.getPointerABIAlignment(AddressSpaceVal);
10537 GV->setAlignment(std::max(TypeAlign, PtrAlign));
10538 Elem.second = GV;
10539 }
10540
10541 return Elem.second;
10542}
10543
10544Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
10545 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
10546 std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
10547 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
10548}
10549
10551 LLVMContext &Ctx = Builder.getContext();
10552 Value *Null =
10553 Constant::getNullValue(PointerType::getUnqual(BasePtr->getContext()));
10554 Value *SizeGep =
10555 Builder.CreateGEP(BasePtr->getType(), Null, Builder.getInt32(1));
10556 Value *SizePtrToInt = Builder.CreatePtrToInt(SizeGep, Type::getInt64Ty(Ctx));
10557 return SizePtrToInt;
10558}
10559
10562 std::string VarName) {
10563 llvm::Constant *MaptypesArrayInit =
10564 llvm::ConstantDataArray::get(M.getContext(), Mappings);
10565 auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
10566 M, MaptypesArrayInit->getType(),
10567 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
10568 VarName);
10569 MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
10570 return MaptypesArrayGlobal;
10571}
10572
10574 InsertPointTy AllocaIP,
10575 unsigned NumOperands,
10576 struct MapperAllocas &MapperAllocas) {
10577 if (!updateToLocation(Loc))
10578 return;
10579
10580 auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
10581 auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
10582 Builder.restoreIP(AllocaIP);
10583 AllocaInst *ArgsBase = Builder.CreateAlloca(
10584 ArrI8PtrTy, /* ArraySize = */ nullptr, ".offload_baseptrs");
10585 AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy, /* ArraySize = */ nullptr,
10586 ".offload_ptrs");
10587 AllocaInst *ArgSizes = Builder.CreateAlloca(
10588 ArrI64Ty, /* ArraySize = */ nullptr, ".offload_sizes");
10590 MapperAllocas.ArgsBase = ArgsBase;
10591 MapperAllocas.Args = Args;
10592 MapperAllocas.ArgSizes = ArgSizes;
10593}
10594
10596 Function *MapperFunc, Value *SrcLocInfo,
10597 Value *MaptypesArg, Value *MapnamesArg,
10599 int64_t DeviceID, unsigned NumOperands) {
10600 if (!updateToLocation(Loc))
10601 return;
10602
10603 auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
10604 auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
10605 Value *ArgsBaseGEP =
10606 Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
10607 {Builder.getInt32(0), Builder.getInt32(0)});
10608 Value *ArgsGEP =
10609 Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
10610 {Builder.getInt32(0), Builder.getInt32(0)});
10611 Value *ArgSizesGEP =
10612 Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
10613 {Builder.getInt32(0), Builder.getInt32(0)});
10614 Value *NullPtr =
10615 Constant::getNullValue(PointerType::getUnqual(Int8Ptr->getContext()));
10616 createRuntimeFunctionCall(MapperFunc, {SrcLocInfo, Builder.getInt64(DeviceID),
10617 Builder.getInt32(NumOperands),
10618 ArgsBaseGEP, ArgsGEP, ArgSizesGEP,
10619 MaptypesArg, MapnamesArg, NullPtr});
10620}
10621
10623 TargetDataRTArgs &RTArgs,
10624 TargetDataInfo &Info,
10625 bool ForEndCall) {
10626 assert((!ForEndCall || Info.separateBeginEndCalls()) &&
10627 "expected region end call to runtime only when end call is separate");
10628 auto UnqualPtrTy = PointerType::getUnqual(M.getContext());
10629 auto VoidPtrTy = UnqualPtrTy;
10630 auto VoidPtrPtrTy = UnqualPtrTy;
10631 auto Int64Ty = Type::getInt64Ty(M.getContext());
10632 auto Int64PtrTy = UnqualPtrTy;
10633
10634 RTArgs.NonContiguousDescriptors = Info.RTArgs.NonContiguousDescriptors;
10635 if (!Info.NumberOfPtrs) {
10636 RTArgs.BasePointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10637 RTArgs.PointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10638 RTArgs.SizesArray = ConstantPointerNull::get(Int64PtrTy);
10639 RTArgs.MapTypesArray = ConstantPointerNull::get(Int64PtrTy);
10640 RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
10641 RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10642 return;
10643 }
10644
10645 RTArgs.BasePointersArray = Builder.CreateConstInBoundsGEP2_32(
10646 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs),
10647 Info.RTArgs.BasePointersArray,
10648 /*Idx0=*/0, /*Idx1=*/0);
10649 RTArgs.PointersArray = Builder.CreateConstInBoundsGEP2_32(
10650 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
10651 /*Idx0=*/0,
10652 /*Idx1=*/0);
10653 RTArgs.SizesArray = Builder.CreateConstInBoundsGEP2_32(
10654 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
10655 /*Idx0=*/0, /*Idx1=*/0);
10656 RTArgs.MapTypesArray = Builder.CreateConstInBoundsGEP2_32(
10657 ArrayType::get(Int64Ty, Info.NumberOfPtrs),
10658 ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd
10659 : Info.RTArgs.MapTypesArray,
10660 /*Idx0=*/0,
10661 /*Idx1=*/0);
10662
10663 // Only emit the mapper information arrays if debug information is
10664 // requested.
10665 if (!Info.EmitDebug)
10666 RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
10667 else
10668 RTArgs.MapNamesArray = Builder.CreateConstInBoundsGEP2_32(
10669 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,
10670 /*Idx0=*/0,
10671 /*Idx1=*/0);
10672 // If there is no user-defined mapper, set the mapper array to nullptr to
10673 // avoid an unnecessary data privatization
10674 if (!Info.HasMapper)
10675 RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10676 else
10677 RTArgs.MappersArray =
10678 Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);
10679}
10680
10682 InsertPointTy CodeGenIP,
10683 MapInfosTy &CombinedInfo,
10684 TargetDataInfo &Info) {
10686 CombinedInfo.NonContigInfo;
10687
10688 // Build an array of struct descriptor_dim and then assign it to
10689 // offload_args.
10690 //
10691 // struct descriptor_dim {
10692 // uint64_t offset;
10693 // uint64_t count;
10694 // uint64_t stride
10695 // };
10696 Type *Int64Ty = Builder.getInt64Ty();
10698 M.getContext(), ArrayRef<Type *>({Int64Ty, Int64Ty, Int64Ty}),
10699 "struct.descriptor_dim");
10700
10701 enum { OffsetFD = 0, CountFD, StrideFD };
10702 // We need two index variable here since the size of "Dims" is the same as
10703 // the size of Components, however, the size of offset, count, and stride is
10704 // equal to the size of base declaration that is non-contiguous.
10705 for (unsigned I = 0, L = 0, E = NonContigInfo.Dims.size(); I < E; ++I) {
10706 // Skip emitting ir if dimension size is 1 since it cannot be
10707 // non-contiguous.
10708 if (NonContigInfo.Dims[I] == 1)
10709 continue;
10710 Builder.restoreIP(AllocaIP);
10711 ArrayType *ArrayTy = ArrayType::get(DimTy, NonContigInfo.Dims[I]);
10712 AllocaInst *DimsAddr =
10713 Builder.CreateAlloca(ArrayTy, /* ArraySize = */ nullptr, "dims");
10714 Info.RTArgs.NonContiguousDescriptors.push_back({I, DimsAddr});
10715 Builder.restoreIP(CodeGenIP);
10716 for (unsigned II = 0, EE = NonContigInfo.Dims[I]; II < EE; ++II) {
10717 unsigned RevIdx = EE - II - 1;
10718 Value *DimsLVal = Builder.CreateInBoundsGEP(
10719 ArrayTy, DimsAddr, {Builder.getInt64(0), Builder.getInt64(II)});
10720 // Offset
10721 Value *OffsetLVal = Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);
10722 Builder.CreateAlignedStore(
10723 NonContigInfo.Offsets[L][RevIdx], OffsetLVal,
10724 M.getDataLayout().getPrefTypeAlign(OffsetLVal->getType()));
10725 // Count
10726 Value *CountLVal = Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);
10727 Builder.CreateAlignedStore(
10728 NonContigInfo.Counts[L][RevIdx], CountLVal,
10729 M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));
10730 // Stride
10731 Value *StrideLVal = Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);
10732 Builder.CreateAlignedStore(
10733 NonContigInfo.Strides[L][RevIdx], StrideLVal,
10734 M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));
10735 }
10736 // args[I] = &dims
10737 Builder.restoreIP(CodeGenIP);
10738 Value *DAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
10739 DimsAddr, Builder.getPtrTy());
10740 Value *P = Builder.CreateConstInBoundsGEP2_32(
10741 ArrayType::get(Builder.getPtrTy(), Info.NumberOfPtrs),
10742 Info.RTArgs.PointersArray, 0, I);
10743 Builder.CreateAlignedStore(
10744 DAddr, P, M.getDataLayout().getPrefTypeAlign(Builder.getPtrTy()));
10745 ++L;
10746 }
10747}
10748
10749void OpenMPIRBuilder::emitUDMapperArrayInitOrDel(
10750 Function *MapperFn, Value *MapperHandle, Value *Base, Value *Begin,
10751 Value *Size, Value *MapType, Value *MapName, TypeSize ElementSize,
10752 BasicBlock *ExitBB, bool IsInit) {
10753 StringRef Prefix = IsInit ? ".init" : ".del";
10754
10755 // Evaluate if this is an array section.
10757 M.getContext(), createPlatformSpecificName({"omp.array", Prefix}));
10758 Value *IsArray =
10759 Builder.CreateICmpSGT(Size, Builder.getInt64(1), "omp.arrayinit.isarray");
10760 Value *DeleteBit = Builder.CreateAnd(
10761 MapType,
10762 Builder.getInt64(
10763 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10764 OpenMPOffloadMappingFlags::OMP_MAP_DELETE)));
10765 Value *DeleteCond;
10766 Value *Cond;
10767 if (IsInit) {
10768 // base != begin?
10769 Value *BaseIsBegin = Builder.CreateICmpNE(Base, Begin);
10770 Cond = Builder.CreateOr(IsArray, BaseIsBegin);
10771 DeleteCond = Builder.CreateIsNull(
10772 DeleteBit,
10773 createPlatformSpecificName({"omp.array", Prefix, ".delete"}));
10774 } else {
10775 Cond = IsArray;
10776 DeleteCond = Builder.CreateIsNotNull(
10777 DeleteBit,
10778 createPlatformSpecificName({"omp.array", Prefix, ".delete"}));
10779 }
10780 Cond = Builder.CreateAnd(Cond, DeleteCond);
10781 Builder.CreateCondBr(Cond, BodyBB, ExitBB);
10782
10783 emitBlock(BodyBB, MapperFn);
10784 // Get the array size by multiplying element size and element number (i.e., \p
10785 // Size).
10786 Value *ArraySize = Builder.CreateNUWMul(Size, Builder.getInt64(ElementSize));
10787 // Remove OMP_MAP_TO and OMP_MAP_FROM from the map type, so that it achieves
10788 // memory allocation/deletion purpose only.
10789 Value *MapTypeArg = Builder.CreateAnd(
10790 MapType,
10791 Builder.getInt64(
10792 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10793 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10794 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10795 MapTypeArg = Builder.CreateOr(
10796 MapTypeArg,
10797 Builder.getInt64(
10798 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10799 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT)));
10800
10801 // Call the runtime API __tgt_push_mapper_component to fill up the runtime
10802 // data structure.
10803 Value *OffloadingArgs[] = {MapperHandle, Base, Begin,
10804 ArraySize, MapTypeArg, MapName};
10806 getOrCreateRuntimeFunction(M, OMPRTL___tgt_push_mapper_component),
10807 OffloadingArgs);
10808}
10809
10812 llvm::Value *BeginArg)>
10813 GenMapInfoCB,
10814 Type *ElemTy, StringRef FuncName, CustomMapperCallbackTy CustomMapperCB,
10815 bool PreserveMemberOfFlags, bool PropagatePresentToPointeeStorage,
10816 bool PropagatePresentToNonPointeeStorage) {
10817 SmallVector<Type *> Params;
10818 Params.emplace_back(Builder.getPtrTy());
10819 Params.emplace_back(Builder.getPtrTy());
10820 Params.emplace_back(Builder.getPtrTy());
10821 Params.emplace_back(Builder.getInt64Ty());
10822 Params.emplace_back(Builder.getInt64Ty());
10823 Params.emplace_back(Builder.getPtrTy());
10824
10825 auto *FnTy =
10826 FunctionType::get(Builder.getVoidTy(), Params, /* IsVarArg */ false);
10827
10828 Function *MapperFn =
10830 MapperFn->addFnAttr(Attribute::NoInline);
10831 MapperFn->addFnAttr(Attribute::NoUnwind);
10832 MapperFn->addParamAttr(0, Attribute::NoUndef);
10833 MapperFn->addParamAttr(1, Attribute::NoUndef);
10834 MapperFn->addParamAttr(2, Attribute::NoUndef);
10835 MapperFn->addParamAttr(3, Attribute::NoUndef);
10836 MapperFn->addParamAttr(4, Attribute::NoUndef);
10837 MapperFn->addParamAttr(5, Attribute::NoUndef);
10838
10839 // Start the mapper function code generation.
10840 BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", MapperFn);
10842 Builder.SetInsertPoint(EntryBB);
10843 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
10844
10845 Value *MapperHandle = MapperFn->getArg(0);
10846 Value *BaseIn = MapperFn->getArg(1);
10847 Value *BeginIn = MapperFn->getArg(2);
10848 Value *Size = MapperFn->getArg(3);
10849 Value *MapType = MapperFn->getArg(4);
10850 Value *MapName = MapperFn->getArg(5);
10851
10852 // Compute the starting and end addresses of array elements.
10853 // Prepare common arguments for array initiation and deletion.
10854 // Convert the size in bytes into the number of array elements.
10855 TypeSize ElementSize = M.getDataLayout().getTypeStoreSize(ElemTy);
10856 Size = Builder.CreateExactUDiv(Size, Builder.getInt64(ElementSize));
10857 Value *PtrBegin = BeginIn;
10858 Value *PtrEnd = Builder.CreateGEP(ElemTy, PtrBegin, Size);
10859
10860 // Emit array initiation if this is an array section and \p MapType indicates
10861 // that memory allocation is required.
10862 BasicBlock *HeadBB = BasicBlock::Create(M.getContext(), "omp.arraymap.head");
10863 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn, Size,
10864 MapType, MapName, ElementSize, HeadBB,
10865 /*IsInit=*/true);
10866
10867 // Emit a for loop to iterate through SizeArg of elements and map all of them.
10868
10869 // Emit the loop header block.
10870 emitBlock(HeadBB, MapperFn);
10871 BasicBlock *BodyBB = BasicBlock::Create(M.getContext(), "omp.arraymap.body");
10872 BasicBlock *DoneBB = BasicBlock::Create(M.getContext(), "omp.done");
10873 // Evaluate whether the initial condition is satisfied.
10874 Value *IsEmpty =
10875 Builder.CreateICmpEQ(PtrBegin, PtrEnd, "omp.arraymap.isempty");
10876 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
10877
10878 // Emit the loop body block.
10879 emitBlock(BodyBB, MapperFn);
10880 BasicBlock *LastBB = BodyBB;
10881 PHINode *PtrPHI =
10882 Builder.CreatePHI(PtrBegin->getType(), 2, "omp.arraymap.ptrcurrent");
10883 PtrPHI->addIncoming(PtrBegin, HeadBB);
10884
10885 // Get map clause information. Fill up the arrays with all mapped variables.
10886 MapInfosOrErrorTy Info = GenMapInfoCB(Builder.saveIP(), PtrPHI, BeginIn);
10887 if (!Info)
10888 return Info.takeError();
10889
10890 // Number of components already in the mapper handle, shifted into the
10891 // MEMBER_OF field; assigned below, once a conditional leading parent (if
10892 // any) has been pushed, and read by pushComponent through the reference
10893 // capture.
10894 Value *ShiftedPreviousSize = nullptr;
10895
10896 // Emits a single mapper sub-component: computes the MEMBER_OF-adjusted map
10897 // type, applies map-type-modifier propagation, and pushes it either via a
10898 // child mapper function or __tgt_push_mapper_component. Returns the last
10899 // basic block emitted, so callers can update the outer per-array-element
10900 // loop's PHI incoming block.
10901 //
10902 // Add MEMBER_OF (ShiftedPreviousSize) to group this sub-map with the
10903 // current array element (N = __tgt_mapper_num_components() at loop body
10904 // start).
10905 //
10906 // Example 1:
10907 // struct S { int x; int *p; };
10908 //
10909 // mapper: #pragma omp declare mapper(id: S s) map(s.x, s.p[0:10])
10910 // use: S arr[2]; ... map(arr)
10911 // entries per element:
10912 //
10913 // &arr[i], &arr[i].x, sizeof(int), MEMBER_OF(N)|TO|FROM
10914 // &arr[i].p[0], &arr[i].p[0], 10*sizeof(int), TO|FROM (*)
10915 // &arr[i].p, &arr[i].p[0], sizeof(int*), ATTACH (**)
10916 //
10917 // Example 2:
10918 // struct S1 { int x; int y; };
10919 // struct S2 { int z; S1 *s1p; };
10920 //
10921 // mapper: #pragma omp declare mapper(S2 s2) map(s2.z, s2.s1p->x,
10922 // s2.s1p->y)
10923 // use: S2 arr[2]; ... map(arr)
10924 // entries per element:
10925 //
10926 // &arr[i], &arr[i].z, sizeof(int), MEMBER_OF(N)|TO|FROM
10927 // &arr[i].s1p[0], &arr[i].s1p->x, sizeof(s1p->x..y), ALLOC (*)
10928 // &arr[i].s1p[0], &arr[i].s1p->x, 4, MEMBER_OF(N+2)|TO|FROM (*)(***)
10929 // &arr[i].s1p[0], &arr[i].s1p->y, 4, MEMBER_OF(N+2)|TO|FROM (*)(***)
10930 // &arr[i].s1p, &arr[i].s1p->x, sizeof(ptr), ATTACH (**)
10931 //
10932 // x/y carry inner MEMBER_OF(2)
10933 // which is shifted by N to become MEMBER_OF(N+2).
10934 //
10935 // HasAttachPtr is set on all of the s1p entries except the ATTACH one:
10936 // the combined ALLOC entry for the s1p->x..y block, and the individual
10937 // x/y entries that are MEMBER_OF that block, all describe storage
10938 // reached through the attach ptr arr[i].s1p.
10939 //
10940 // Entries of the following kinds do NOT receive a new outer MEMBER_OF
10941 // linking them to the parent struct:
10942 //
10943 // * (*) Entries with HasAttachPtr: they represent pointee data that
10944 // occupies a different storage block than the struct being mapped, so
10945 // they are not a member of it. They may still be MEMBER_OF an entry
10946 // within that pointee block, in which case those pre-existing bits are
10947 // shifted -- see (***).
10948 // * (**) ATTACH entries: they are not a member of anything — they just
10949 // link a ptr to its ptee.
10950 // * All entries when PreserveMemberOfFlags is set (the Flang/MLIR path):
10951 // its pre-shaped entries already carry their final MEMBER_OF bits.
10952 // TODO: set HasAttachPtr from Flang for entries whose storage is the
10953 // pointee's (e.g. s%p(0:10)) and drop PreserveMemberOfFlags in favor of
10954 // it.
10955 //
10956 // (***) If such an entry already has its own MEMBER_OF bits (e.g. the
10957 // s1p->x/y entries above), those bits are still shifted by N.
10958 auto pushComponent = [&](Value *CurBaseArg, Value *CurBeginArg,
10959 Value *CurSizeArg, Value *CurNameArg,
10960 uint64_t RawType, bool HasAttachPtrFlag,
10961 Function *ChildMapperFn) -> BasicBlock * {
10962 Value *OriMapType = Builder.getInt64(RawType);
10963 constexpr uint64_t MemberOfMask =
10964 static_cast<uint64_t>(OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF);
10965 constexpr uint64_t AttachBit =
10966 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10967 OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
10968 constexpr uint64_t PtrAndObjBit =
10969 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10970 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ);
10971
10972 Value *MemberMapType;
10973 if (PreserveMemberOfFlags || (RawType & AttachBit) || HasAttachPtrFlag) {
10974 if (RawType & MemberOfMask)
10975 MemberMapType = Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10976 else
10977 MemberMapType = OriMapType;
10978 } else {
10979 MemberMapType = Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10980 }
10981
10982 // Combine the map type inherited from user-defined mapper with that
10983 // specified in the program. According to the OMP_MAP_TO and OMP_MAP_FROM
10984 // bits of the \a MapType, which is the input argument of the mapper
10985 // function, the following code will set the OMP_MAP_TO and OMP_MAP_FROM
10986 // bits of MemberMapType.
10987 // [OpenMP 5.0], 1.2.6. map-type decay.
10988 // | alloc | to | from | tofrom | release | delete
10989 // ----------------------------------------------------------
10990 // alloc | alloc | alloc | alloc | alloc | release | delete
10991 // to | alloc | to | alloc | to | release | delete
10992 // from | alloc | alloc | from | from | release | delete
10993 // tofrom | alloc | to | from | tofrom | release | delete
10994 Value *LeftToFrom = Builder.CreateAnd(
10995 MapType,
10996 Builder.getInt64(
10997 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10998 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10999 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11000 BasicBlock *AllocBB = BasicBlock::Create(M.getContext(), "omp.type.alloc");
11001 BasicBlock *AllocElseBB =
11002 BasicBlock::Create(M.getContext(), "omp.type.alloc.else");
11003 BasicBlock *ToBB = BasicBlock::Create(M.getContext(), "omp.type.to");
11004 BasicBlock *ToElseBB =
11005 BasicBlock::Create(M.getContext(), "omp.type.to.else");
11006 BasicBlock *FromBB = BasicBlock::Create(M.getContext(), "omp.type.from");
11007 BasicBlock *EndBB = BasicBlock::Create(M.getContext(), "omp.type.end");
11008 Value *IsAlloc = Builder.CreateIsNull(LeftToFrom);
11009 Builder.CreateCondBr(IsAlloc, AllocBB, AllocElseBB);
11010 // In case of alloc, clear OMP_MAP_TO and OMP_MAP_FROM.
11011 emitBlock(AllocBB, MapperFn);
11012 Value *AllocMapType = Builder.CreateAnd(
11013 MemberMapType,
11014 Builder.getInt64(
11015 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11016 OpenMPOffloadMappingFlags::OMP_MAP_TO |
11017 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11018 Builder.CreateBr(EndBB);
11019 emitBlock(AllocElseBB, MapperFn);
11020 Value *IsTo = Builder.CreateICmpEQ(
11021 LeftToFrom,
11022 Builder.getInt64(
11023 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11024 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11025 Builder.CreateCondBr(IsTo, ToBB, ToElseBB);
11026 // In case of to, clear OMP_MAP_FROM.
11027 emitBlock(ToBB, MapperFn);
11028 Value *ToMapType = Builder.CreateAnd(
11029 MemberMapType,
11030 Builder.getInt64(
11031 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11032 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11033 Builder.CreateBr(EndBB);
11034 emitBlock(ToElseBB, MapperFn);
11035 Value *IsFrom = Builder.CreateICmpEQ(
11036 LeftToFrom,
11037 Builder.getInt64(
11038 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11039 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11040 Builder.CreateCondBr(IsFrom, FromBB, EndBB);
11041 // In case of from, clear OMP_MAP_TO.
11042 emitBlock(FromBB, MapperFn);
11043 Value *FromMapType = Builder.CreateAnd(
11044 MemberMapType,
11045 Builder.getInt64(
11046 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11047 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11048 // In case of tofrom, do nothing.
11049 emitBlock(EndBB, MapperFn);
11050 PHINode *CurMapType =
11051 Builder.CreatePHI(Builder.getInt64Ty(), 4, "omp.maptype");
11052 CurMapType->addIncoming(AllocMapType, AllocBB);
11053 CurMapType->addIncoming(ToMapType, ToBB);
11054 CurMapType->addIncoming(FromMapType, FromBB);
11055 CurMapType->addIncoming(MemberMapType, ToElseBB);
11056
11057 // Propagate map-type-modifying bits from the outer map clause to each map
11058 // inserted by the mapper.
11059 //
11060 // OpenMP 6.0:281:34: The effect of the mapper modifier is to remove the
11061 // list item from the map clause and to apply the clauses specified in the
11062 // declared mapper to the construct on which the map clause appears...
11063 // If any modifier with the map-type-modifying property appears in the map
11064 // clause then the effect is as if that modifier appears in each map clause
11065 // specified in the declared mapper.
11066 //
11067 // Map-type-modifying bits: ALWAYS, DELETE, CLOSE, PRESENT.
11068 //
11069 // ALWAYS/DELETE/CLOSE are propagated to every (non-ATTACH) entry.
11070 //
11071 // PRESENT propagation is controlled independently for entries describing
11072 // pointee storage (HasAttachPtr) and entries describing non-pointee
11073 // storage. This lets frontends select current Clang behavior (pointee only)
11074 // or OpenMP 6.x behavior for mapper propagation (all eligible storage).
11075 // PRESENT is not propagated to ATTACH or PTR_AND_OBJ entries.
11076 //
11077 // Pointee storage is gated on \p PropagatePresentToPointeeStorage (set by
11078 // caller only for OpenMP >= 6.0). Before 6.0 the present modifier is
11079 // treated as not applying to the pointee: the spec committee confirmed the
11080 // divergence between the present "motion" modifier (to/from) and the
11081 // present map-type modifier (map) was unintentional, to be fixed as an
11082 // OpenMP 6.0 erratum, so for 5.2 present is ignored for the pointee for
11083 // both map and to/from.
11084 //
11085 // Non-pointee storage is gated on \p PropagatePresentToNonPointeeStorage:
11086 // PRESENT is ten propagated to the struct's own members (e.g. the s.x,
11087 // s.y of map(present, mapper(id): s)) so that an absent member triggers
11088 // the present-check.
11089 //
11090 // Present cannot be mapped to members with PTR_AND_OBJ, a single combined
11091 // entry allocates the whole struct (including the pointer's storage),
11092 // so propagating PRESENT to it would wrongly require the pointer's
11093 // pointee to be present.
11094 uint64_t ModifierBits =
11095 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11096 OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS |
11097 OpenMPOffloadMappingFlags::OMP_MAP_DELETE |
11098 OpenMPOffloadMappingFlags::OMP_MAP_CLOSE);
11099 bool IsPresentEligibleStorage = !(RawType & (AttachBit | PtrAndObjBit));
11100 bool PropagatePresent =
11101 IsPresentEligibleStorage &&
11102 (HasAttachPtrFlag ? PropagatePresentToPointeeStorage
11103 : PropagatePresentToNonPointeeStorage);
11104 if (PropagatePresent)
11105 ModifierBits |=
11106 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11107 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11108 Value *ImportedModifierBits =
11109 Builder.CreateAnd(MapType, Builder.getInt64(ModifierBits));
11110 Value *CurMapTypeWithModifiers = Builder.CreateOr(
11111 CurMapType, ImportedModifierBits, "omp.maptype.with.modifiers");
11112
11113 // ATTACH entries must not receive map-type-modifying bits: ATTACH|ALWAYS is
11114 // reserved for the attach(always) map-type modifier, and other modifier
11115 // bits (DELETE, CLOSE) have no meaning for an ATTACH entry.
11116 Value *FinalMapType =
11117 (RawType & AttachBit) ? CurMapType : CurMapTypeWithModifiers;
11118
11119 Value *OffloadingArgs[] = {MapperHandle, CurBaseArg, CurBeginArg,
11120 CurSizeArg, FinalMapType, CurNameArg};
11121 if (ChildMapperFn) {
11122 // Call the corresponding mapper function.
11123 createRuntimeFunctionCall(ChildMapperFn, OffloadingArgs)
11124 ->setDoesNotThrow();
11125 } else {
11126 // Call the runtime API __tgt_push_mapper_component to fill up the runtime
11127 // data structure.
11129 getOrCreateRuntimeFunction(M, OMPRTL___tgt_push_mapper_component),
11130 OffloadingArgs);
11131 }
11132 return EndBB;
11133 };
11134
11135 // A leading parent synthesized for the dynamic segments is pushed only when
11136 // some segment will contribute components. Its own map type carries no
11137 // MEMBER_OF bits, so it does not read ShiftedPreviousSize.
11138 unsigned FirstStaticIdx = 0;
11139 if (Info->LeadingParentCond) {
11140 assert(PreserveMemberOfFlags &&
11141 "conditional leading parent requires pre-shaped MEMBER_OF flags");
11142 assert(!Info->BasePointers.empty() && "no leading parent component");
11143 BasicBlock *PushBB =
11144 BasicBlock::Create(M.getContext(), "omp.iterparent.push");
11145 BasicBlock *ContBB =
11146 BasicBlock::Create(M.getContext(), "omp.iterparent.cont");
11147 Builder.CreateCondBr(Info->LeadingParentCond, PushBB, ContBB);
11148 emitBlock(PushBB, MapperFn);
11149 Value *CurNameArg = Info->Names.size()
11150 ? Info->Names[0]
11151 : Constant::getNullValue(Builder.getPtrTy());
11152 pushComponent(
11153 Info->BasePointers[0], Info->Pointers[0], Info->Sizes[0], CurNameArg,
11154 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11155 Info->Types[0]),
11156 Info->HasAttachPtr[0], /*ChildMapperFn=*/nullptr);
11157 Builder.CreateBr(ContBB);
11158 emitBlock(ContBB, MapperFn);
11159 LastBB = ContBB;
11160 FirstStaticIdx = 1;
11161 }
11162
11163 // Call the runtime API __tgt_mapper_num_components to get the number of
11164 // pre-existing components. The compile-time MEMBER_OF indices count the
11165 // leading parent as component 0 whether or not it was pushed; reading the
11166 // count after that push and subtracting one yields the right base in both
11167 // cases (N if pushed, N - 1 if skipped, N being the count at body start).
11168 Value *OffloadingArgs[] = {MapperHandle};
11169 Value *PreviousSize = createRuntimeFunctionCall(
11170 getOrCreateRuntimeFunction(M, OMPRTL___tgt_mapper_num_components),
11171 OffloadingArgs);
11172 if (Info->LeadingParentCond)
11173 PreviousSize = Builder.CreateSub(PreviousSize, Builder.getInt64(1));
11174 ShiftedPreviousSize =
11175 Builder.CreateShl(PreviousSize, Builder.getInt64(getFlagMemberOffset()));
11176
11177 // Fill up the runtime mapper handle for all statically-known components.
11178 for (unsigned I = FirstStaticIdx; I < Info->BasePointers.size(); ++I) {
11179 Value *CurNameArg = Info->Names.size()
11180 ? Info->Names[I]
11181 : Constant::getNullValue(Builder.getPtrTy());
11182 Expected<Function *> ChildMapperFn = CustomMapperCB(I);
11183 if (!ChildMapperFn)
11184 return ChildMapperFn.takeError();
11185 LastBB = pushComponent(
11186 Info->BasePointers[I], Info->Pointers[I], Info->Sizes[I], CurNameArg,
11187 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11188 Info->Types[I]),
11189 Info->HasAttachPtr[I], *ChildMapperFn);
11190 }
11191
11192 // Fill up the runtime mapper handle for components whose count is only
11193 // known at runtime (produced by an `iterator` modifier on the mapper's own
11194 // map clause): push each one individually, from inside a generated loop,
11195 // via the same __tgt_push_mapper_component call used above.
11196 for (MapInfosTy::DynamicSegment &Seg : Info->DynamicSegments) {
11198 auto BodyGen = [&](InsertPointTy BodyIP, Value *LinearIV) -> Error {
11199 Builder.restoreIP(BodyIP);
11201 Seg.GenEntry(Builder, LinearIV);
11202 if (!EntryOrErr)
11203 return EntryOrErr.takeError();
11204 SmallVector<Value *, 3> &Entry = *EntryOrErr;
11205 pushComponent(
11206 Entry[0], Entry[1], Entry[2],
11207 Constant::getNullValue(Builder.getPtrTy()),
11208 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11209 Seg.Type),
11210 Seg.HasAttachPtr, Seg.ChildMapperFn);
11211 return Error::success();
11212 };
11213 InsertPointOrErrorTy AfterIP =
11214 createIteratorLoop(Loc, Seg.Count, BodyGen, "mapper.iterator");
11215 if (!AfterIP)
11216 return AfterIP.takeError();
11217 Builder.restoreIP(*AfterIP);
11218 LastBB = Builder.GetInsertBlock();
11219 }
11220
11221 // Update the pointer to point to the next element that needs to be mapped,
11222 // and check whether we have mapped all elements.
11223 Value *PtrNext = Builder.CreateConstGEP1_32(ElemTy, PtrPHI, /*Idx0=*/1,
11224 "omp.arraymap.next");
11225 PtrPHI->addIncoming(PtrNext, LastBB);
11226 Value *IsDone = Builder.CreateICmpEQ(PtrNext, PtrEnd, "omp.arraymap.isdone");
11227 BasicBlock *ExitBB = BasicBlock::Create(M.getContext(), "omp.arraymap.exit");
11228 Builder.CreateCondBr(IsDone, ExitBB, BodyBB);
11229
11230 emitBlock(ExitBB, MapperFn);
11231 // Emit array deletion if this is an array section and \p MapType indicates
11232 // that deletion is required.
11233 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn, Size,
11234 MapType, MapName, ElementSize, DoneBB,
11235 /*IsInit=*/false);
11236
11237 // Emit the function exit block.
11238 emitBlock(DoneBB, MapperFn, /*IsFinished=*/true);
11239
11240 Builder.CreateRetVoid();
11241 return MapperFn;
11242}
11243
11245 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
11246 TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB,
11247 bool IsNonContiguous,
11248 function_ref<void(unsigned int, Value *)> DeviceAddrCB) {
11249
11250 // Reset the array information.
11251 Info.clearArrayInfo();
11252 Info.NumberOfPtrs = CombinedInfo.BasePointers.size();
11253
11254 if (Info.NumberOfPtrs == 0)
11255 return Error::success();
11256
11257 Builder.restoreIP(AllocaIP);
11258 // Detect if we have any capture size requiring runtime evaluation of the
11259 // size so that a constant array could be eventually used.
11260 ArrayType *PointerArrayType =
11261 ArrayType::get(Builder.getPtrTy(), Info.NumberOfPtrs);
11262
11263 Info.RTArgs.BasePointersArray = Builder.CreateAlloca(
11264 PointerArrayType, /* ArraySize = */ nullptr, ".offload_baseptrs");
11265
11266 Info.RTArgs.PointersArray = Builder.CreateAlloca(
11267 PointerArrayType, /* ArraySize = */ nullptr, ".offload_ptrs");
11268 AllocaInst *MappersArray = Builder.CreateAlloca(
11269 PointerArrayType, /* ArraySize = */ nullptr, ".offload_mappers");
11270 Info.RTArgs.MappersArray = MappersArray;
11271
11272 // If we don't have any VLA types or other types that require runtime
11273 // evaluation, we can use a constant array for the map sizes, otherwise we
11274 // need to fill up the arrays as we do for the pointers.
11275 Type *Int64Ty = Builder.getInt64Ty();
11276 SmallVector<Constant *> ConstSizes(CombinedInfo.Sizes.size(),
11277 ConstantInt::get(Int64Ty, 0));
11278 SmallBitVector RuntimeSizes(CombinedInfo.Sizes.size());
11279 for (unsigned I = 0, E = CombinedInfo.Sizes.size(); I < E; ++I) {
11280 bool IsNonContigEntry =
11281 IsNonContiguous &&
11282 (static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11283 CombinedInfo.Types[I] &
11284 OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG) != 0);
11285 // For NON_CONTIG entries, ArgSizes stores the dimension count (number of
11286 // descriptor_dim records), not the byte size.
11287 if (IsNonContigEntry) {
11288 assert(I < CombinedInfo.NonContigInfo.Dims.size() &&
11289 "Index must be in-bounds for NON_CONTIG Dims array");
11290 const uint64_t DimCount = CombinedInfo.NonContigInfo.Dims[I];
11291 assert(DimCount > 0 && "NON_CONTIG DimCount must be > 0");
11292 ConstSizes[I] = ConstantInt::get(Int64Ty, DimCount);
11293 continue;
11294 }
11295 if (auto *CI = dyn_cast<Constant>(CombinedInfo.Sizes[I])) {
11296 if (!isa<ConstantExpr>(CI) && !isa<GlobalValue>(CI)) {
11297 ConstSizes[I] = CI;
11298 continue;
11299 }
11300 }
11301 RuntimeSizes.set(I);
11302 }
11303
11304 if (RuntimeSizes.all()) {
11305 ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);
11306 Info.RTArgs.SizesArray = Builder.CreateAlloca(
11307 SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");
11308 restoreIPandDebugLoc(Builder, CodeGenIP);
11309 } else {
11310 auto *SizesArrayInit = ConstantArray::get(
11311 ArrayType::get(Int64Ty, ConstSizes.size()), ConstSizes);
11312 std::string Name = createPlatformSpecificName({"offload_sizes"});
11313 auto *SizesArrayGbl =
11314 new GlobalVariable(M, SizesArrayInit->getType(), /*isConstant=*/true,
11315 GlobalValue::PrivateLinkage, SizesArrayInit, Name);
11316 SizesArrayGbl->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
11317
11318 if (!RuntimeSizes.any()) {
11319 Info.RTArgs.SizesArray = SizesArrayGbl;
11320 } else {
11321 unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);
11322 Align OffloadSizeAlign = M.getDataLayout().getABIIntegerTypeAlignment(64);
11323 ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);
11324 AllocaInst *Buffer = Builder.CreateAlloca(
11325 SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");
11326 Buffer->setAlignment(OffloadSizeAlign);
11327 restoreIPandDebugLoc(Builder, CodeGenIP);
11328 Builder.CreateMemCpy(
11329 Buffer, M.getDataLayout().getPrefTypeAlign(Buffer->getType()),
11330 SizesArrayGbl, OffloadSizeAlign,
11331 Builder.getIntN(
11332 IndexSize,
11333 Buffer->getAllocationSize(M.getDataLayout())->getFixedValue()));
11334
11335 Info.RTArgs.SizesArray = Buffer;
11336 }
11337 restoreIPandDebugLoc(Builder, CodeGenIP);
11338 }
11339
11340 // The map types are always constant so we don't need to generate code to
11341 // fill arrays. Instead, we create an array constant.
11343 for (auto mapFlag : CombinedInfo.Types)
11344 Mapping.push_back(
11345 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11346 mapFlag));
11347 std::string MaptypesName = createPlatformSpecificName({"offload_maptypes"});
11348 auto *MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);
11349 Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
11350
11351 // The information types are only built if provided.
11352 if (!CombinedInfo.Names.empty()) {
11353 auto *MapNamesArrayGbl = createOffloadMapnames(
11354 CombinedInfo.Names, createPlatformSpecificName({"offload_mapnames"}));
11355 Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
11356 Info.EmitDebug = true;
11357 } else {
11358 Info.RTArgs.MapNamesArray =
11360 Info.EmitDebug = false;
11361 }
11362
11363 // If there's a present map type modifier, it must not be applied to the end
11364 // of a region, so generate a separate map type array in that case.
11365 if (Info.separateBeginEndCalls()) {
11366 bool EndMapTypesDiffer = false;
11367 for (uint64_t &Type : Mapping) {
11368 if (Type & static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11369 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT)) {
11370 Type &= ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11371 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11372 EndMapTypesDiffer = true;
11373 }
11374 }
11375 if (EndMapTypesDiffer) {
11376 MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);
11377 Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
11378 }
11379 }
11380
11381 PointerType *PtrTy = Builder.getPtrTy();
11382 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
11383 Value *BPVal = CombinedInfo.BasePointers[I];
11384 Value *BP = Builder.CreateConstInBoundsGEP2_32(
11385 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.BasePointersArray,
11386 0, I);
11387 Builder.CreateAlignedStore(BPVal, BP,
11388 M.getDataLayout().getPrefTypeAlign(PtrTy));
11389
11390 if (Info.requiresDevicePointerInfo()) {
11391 if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Pointer) {
11392 CodeGenIP = Builder.saveIP();
11393 Builder.restoreIP(AllocaIP);
11394 Info.DevicePtrInfoMap[BPVal] = {BP, Builder.CreateAlloca(PtrTy)};
11395 restoreIPandDebugLoc(Builder, CodeGenIP);
11396 if (DeviceAddrCB)
11397 DeviceAddrCB(I, Info.DevicePtrInfoMap[BPVal].second);
11398 } else if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Address) {
11399 Info.DevicePtrInfoMap[BPVal] = {BP, BP};
11400 if (DeviceAddrCB)
11401 DeviceAddrCB(I, BP);
11402 }
11403 }
11404
11405 Value *PVal = CombinedInfo.Pointers[I];
11406 Value *P = Builder.CreateConstInBoundsGEP2_32(
11407 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray, 0,
11408 I);
11409 // TODO: Check alignment correct.
11410 Builder.CreateAlignedStore(PVal, P,
11411 M.getDataLayout().getPrefTypeAlign(PtrTy));
11412
11413 if (RuntimeSizes.test(I)) {
11414 Value *S = Builder.CreateConstInBoundsGEP2_32(
11415 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
11416 /*Idx0=*/0,
11417 /*Idx1=*/I);
11418 Builder.CreateAlignedStore(Builder.CreateIntCast(CombinedInfo.Sizes[I],
11419 Int64Ty,
11420 /*isSigned=*/true),
11421 S, M.getDataLayout().getPrefTypeAlign(PtrTy));
11422 }
11423 // Fill up the mapper array.
11424 unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);
11425 Value *MFunc = ConstantPointerNull::get(PtrTy);
11426
11427 auto CustomMFunc = CustomMapperCB(I);
11428 if (!CustomMFunc)
11429 return CustomMFunc.takeError();
11430 if (*CustomMFunc)
11431 MFunc = Builder.CreatePointerCast(*CustomMFunc, PtrTy);
11432
11433 Value *MAddr = Builder.CreateInBoundsGEP(
11434 PointerArrayType, MappersArray,
11435 {Builder.getIntN(IndexSize, 0), Builder.getIntN(IndexSize, I)});
11436 Builder.CreateAlignedStore(
11437 MFunc, MAddr, M.getDataLayout().getPrefTypeAlign(MAddr->getType()));
11438 }
11439
11440 if (!IsNonContiguous || CombinedInfo.NonContigInfo.Offsets.empty() ||
11441 Info.NumberOfPtrs == 0)
11442 return Error::success();
11443 emitNonContiguousDescriptor(AllocaIP, CodeGenIP, CombinedInfo, Info);
11444 return Error::success();
11445}
11446
11448 BasicBlock *CurBB = Builder.GetInsertBlock();
11449
11450 if (!CurBB || CurBB->hasTerminator()) {
11451 // If there is no insert point or the previous block is already
11452 // terminated, don't touch it.
11453 } else {
11454 // Otherwise, create a fall-through branch.
11455 Builder.CreateBr(Target);
11456 }
11457
11458 Builder.ClearInsertionPoint();
11459}
11460
11462 bool IsFinished) {
11463 BasicBlock *CurBB = Builder.GetInsertBlock();
11464
11465 // Fall out of the current block (if necessary).
11466 emitBranch(BB);
11467
11468 if (IsFinished && BB->use_empty()) {
11469 BB->eraseFromParent();
11470 return;
11471 }
11472
11473 // Place the block after the current block, if possible, or else at
11474 // the end of the function.
11475 if (CurBB && CurBB->getParent())
11476 CurFn->insert(std::next(CurBB->getIterator()), BB);
11477 else
11478 CurFn->insert(CurFn->end(), BB);
11479 Builder.SetInsertPoint(BB);
11480}
11481
11483 BodyGenCallbackTy ElseGen,
11484 InsertPointTy AllocaIP,
11485 ArrayRef<BasicBlock *> DeallocBlocks) {
11486 // If the condition constant folds and can be elided, try to avoid emitting
11487 // the condition and the dead arm of the if/else.
11488 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
11489 auto CondConstant = CI->getSExtValue();
11490 if (CondConstant)
11491 return ThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
11492
11493 return ElseGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
11494 }
11495
11496 Function *CurFn = Builder.GetInsertBlock()->getParent();
11497
11498 // Otherwise, the condition did not fold, or we couldn't elide it. Just
11499 // emit the conditional branch.
11500 BasicBlock *ThenBlock = BasicBlock::Create(M.getContext(), "omp_if.then");
11501 BasicBlock *ElseBlock = BasicBlock::Create(M.getContext(), "omp_if.else");
11502 BasicBlock *ContBlock = BasicBlock::Create(M.getContext(), "omp_if.end");
11503 Builder.CreateCondBr(Cond, ThenBlock, ElseBlock);
11504 // Emit the 'then' code.
11505 emitBlock(ThenBlock, CurFn);
11506 if (Error Err = ThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks)) {
11507 // Let the function own the blocks not emitted yet so they are freed.
11508 ElseBlock->insertInto(CurFn);
11509 ContBlock->insertInto(CurFn);
11510 return Err;
11511 }
11512 emitBranch(ContBlock);
11513 // Emit the 'else' code if present.
11514 // There is no need to emit line number for unconditional branch.
11515 emitBlock(ElseBlock, CurFn);
11516 if (Error Err = ElseGen(AllocaIP, Builder.saveIP(), DeallocBlocks)) {
11517 ContBlock->insertInto(CurFn);
11518 return Err;
11519 }
11520 // There is no need to emit line number for unconditional branch.
11521 emitBranch(ContBlock);
11522 // Emit the continuation block for code after the if.
11523 emitBlock(ContBlock, CurFn, /*IsFinished=*/true);
11524 return Error::success();
11525}
11526
11530 AtomicOrdering AO, InsertPointTy AllocaIP) {
11531 if (!updateToLocation(Loc))
11532 return Loc.IP;
11533
11534 assert(X.Var->getType()->isPointerTy() &&
11535 "OMP Atomic expects a pointer to target memory");
11536 Type *XElemTy = X.ElemTy;
11537 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11538 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11539 "OMP atomic read expected a scalar type");
11540
11541 Value *XRead = nullptr;
11542
11543 if (XElemTy->isIntegerTy()) {
11544 LoadInst *XLD =
11545 Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
11546 XLD->setAtomic(AO);
11547 XRead = cast<Value>(XLD);
11548 } else if (XElemTy->isStructTy()) {
11549 // FIXME: Add checks to ensure __atomic_load is emitted iff the
11550 // target does not support `atomicrmw` of the size of the struct
11551 LoadInst *OldVal = Builder.CreateLoad(XElemTy, X.Var, "omp.atomic.read");
11552 OldVal->setAtomic(AO);
11553 const DataLayout &DL = OldVal->getDataLayout();
11554 unsigned LoadSize = DL.getTypeStoreSize(XElemTy);
11555 OpenMPIRBuilder::AtomicInfo atomicInfo(
11556 &Builder, XElemTy, LoadSize * 8, LoadSize * 8, OldVal->getAlign(),
11557 OldVal->getAlign(), true /* UseLibcall */, AllocaIP, X.Var);
11558 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11559 XRead = AtomicLoadRes.first;
11560 OldVal->eraseFromParent();
11561 } else {
11562 // We need to perform atomic op as integer
11563 IntegerType *IntCastTy =
11564 IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
11565 LoadInst *XLoad =
11566 Builder.CreateLoad(IntCastTy, X.Var, X.IsVolatile, "omp.atomic.load");
11567 XLoad->setAtomic(AO);
11568 if (XElemTy->isFloatingPointTy()) {
11569 XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
11570 } else {
11571 XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
11572 }
11573 }
11574 Builder.CreateStore(XRead, V.Var, V.IsVolatile);
11575 return Builder.saveIP();
11576}
11577
11580 AtomicOpValue &X, Value *Expr,
11581 AtomicOrdering AO, InsertPointTy AllocaIP) {
11582 if (!updateToLocation(Loc))
11583 return Loc.IP;
11584
11585 assert(X.Var->getType()->isPointerTy() &&
11586 "OMP Atomic expects a pointer to target memory");
11587 Type *XElemTy = X.ElemTy;
11588 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11589 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11590 "OMP atomic write expected a scalar type");
11591
11592 if (XElemTy->isIntegerTy()) {
11593 StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
11594 XSt->setAtomic(AO);
11595 } else if (XElemTy->isStructTy()) {
11596 LoadInst *OldVal = Builder.CreateLoad(XElemTy, X.Var, "omp.atomic.read");
11597 const DataLayout &DL = OldVal->getDataLayout();
11598 unsigned LoadSize = DL.getTypeStoreSize(XElemTy);
11599 OpenMPIRBuilder::AtomicInfo atomicInfo(
11600 &Builder, XElemTy, LoadSize * 8, LoadSize * 8, OldVal->getAlign(),
11601 OldVal->getAlign(), true /* UseLibcall */, AllocaIP, X.Var);
11602 atomicInfo.EmitAtomicStoreLibcall(AO, Expr);
11603 OldVal->eraseFromParent();
11604 } else {
11605 // We need to bitcast and perform atomic op as integers
11606 IntegerType *IntCastTy =
11607 IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
11608 Value *ExprCast =
11609 Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
11610 StoreInst *XSt = Builder.CreateStore(ExprCast, X.Var, X.IsVolatile);
11611 XSt->setAtomic(AO);
11612 }
11613
11614 return Builder.saveIP();
11615}
11616
11619 Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
11620 AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr,
11621 bool IsIgnoreDenormalMode, bool IsFineGrainedMemory, bool IsRemoteMemory) {
11622 assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
11623 if (!updateToLocation(Loc))
11624 return Loc.IP;
11625
11626 LLVM_DEBUG({
11627 Type *XTy = X.Var->getType();
11628 assert(XTy->isPointerTy() &&
11629 "OMP Atomic expects a pointer to target memory");
11630 Type *XElemTy = X.ElemTy;
11631 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11632 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11633 "OMP atomic update expected a scalar or struct type");
11634 });
11635
11636 Expected<std::pair<Value *, Value *>> AtomicResult = emitAtomicUpdate(
11637 AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp, X.IsVolatile,
11638 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11639 if (!AtomicResult)
11640 return AtomicResult.takeError();
11641 return Builder.saveIP();
11642}
11643
11644// FIXME: Duplicating AtomicExpand
11645Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
11646 AtomicRMWInst::BinOp RMWOp) {
11647 switch (RMWOp) {
11648 case AtomicRMWInst::Add:
11649 return Builder.CreateAdd(Src1, Src2);
11650 case AtomicRMWInst::Sub:
11651 return Builder.CreateSub(Src1, Src2);
11652 case AtomicRMWInst::And:
11653 return Builder.CreateAnd(Src1, Src2);
11655 return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
11656 case AtomicRMWInst::Or:
11657 return Builder.CreateOr(Src1, Src2);
11658 case AtomicRMWInst::Xor:
11659 return Builder.CreateXor(Src1, Src2);
11660 case AtomicRMWInst::Max:
11661 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, Src1, Src2);
11662 case AtomicRMWInst::Min:
11663 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, Src1, Src2);
11665 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, Src1, Src2);
11667 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, Src1, Src2);
11669 return Builder.CreateFAdd(Src1, Src2);
11671 return Builder.CreateFSub(Src1, Src2);
11673 return Builder.CreateMaxNum(Src1, Src2);
11675 return Builder.CreateMinNum(Src1, Src2);
11677 return Builder.CreateMaximum(Src1, Src2);
11679 return Builder.CreateMinimum(Src1, Src2);
11688 llvm_unreachable("Unsupported atomic update operation");
11689 }
11690 llvm_unreachable("Unsupported atomic update operation");
11691}
11692
11694 // Loads cannot use Release or AcquireRelease ordering. This load is
11695 // just the initial value for the cmpxchg loop; the cmpxchg itself
11696 // retains the original ordering.
11697 AtomicOrdering LoadAO = AO;
11698
11699 if (AO == AtomicOrdering::Release) {
11701 } else if (AO == AtomicOrdering::AcquireRelease) {
11702 LoadAO = AtomicOrdering::Acquire;
11703 }
11704
11705 return LoadAO;
11706}
11707
11708Expected<std::pair<Value *, Value *>> OpenMPIRBuilder::emitAtomicUpdate(
11709 InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
11711 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr,
11712 bool IsIgnoreDenormalMode, bool IsFineGrainedMemory, bool IsRemoteMemory) {
11713 // TODO: handle the case where XElemTy is not byte-sized or not a power of 2.
11714 bool emitRMWOp = false;
11715 switch (RMWOp) {
11716 case AtomicRMWInst::Add:
11717 case AtomicRMWInst::And:
11719 case AtomicRMWInst::Or:
11720 case AtomicRMWInst::Xor:
11722 case AtomicRMWInst::Max:
11723 case AtomicRMWInst::Min:
11731 emitRMWOp = XElemTy;
11732 break;
11733 case AtomicRMWInst::Sub:
11735 emitRMWOp = (IsXBinopExpr && XElemTy);
11736 break;
11737 default:
11738 emitRMWOp = false;
11739 }
11740 emitRMWOp &=
11741 (XElemTy->isIntegerTy() || XElemTy->isFloatTy() || XElemTy->isDoubleTy());
11742
11743 std::pair<Value *, Value *> Res;
11744 if (emitRMWOp) {
11745 AtomicRMWInst *RMWInst =
11746 Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
11747 if (IsIgnoreDenormalMode)
11748 RMWInst->setMetadata(llvm::LLVMContext::MD_atomic_ignore_denormal_mode,
11749 llvm::MDNode::get(Builder.getContext(), {}));
11750 if (T.isAMDGPU()) {
11751 if (!IsFineGrainedMemory)
11752 RMWInst->setMetadata("amdgpu.no.fine.grained.memory",
11753 llvm::MDNode::get(Builder.getContext(), {}));
11754 if (!IsRemoteMemory)
11755 RMWInst->setMetadata("amdgpu.no.remote.memory",
11756 llvm::MDNode::get(Builder.getContext(), {}));
11757 }
11758 Res.first = RMWInst;
11759 // not needed except in case of postfix captures. Generate anyway for
11760 // consistency with the else part. Will be removed with any DCE pass.
11761 // AtomicRMWInst::Xchg does not have a coressponding instruction.
11762 if (RMWOp == AtomicRMWInst::Xchg)
11763 Res.second = Res.first;
11764 else
11765 Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
11766 } else if (XElemTy->isStructTy()) {
11767 LoadInst *OldVal =
11768 Builder.CreateLoad(XElemTy, X, X->getName() + ".atomic.load");
11770 OldVal->setAtomic(LoadAO);
11771 const DataLayout &LoadDL = OldVal->getDataLayout();
11772 unsigned LoadSize = LoadDL.getTypeStoreSize(XElemTy);
11773
11774 OpenMPIRBuilder::AtomicInfo atomicInfo(
11775 &Builder, XElemTy, LoadSize * 8, LoadSize * 8, OldVal->getAlign(),
11776 OldVal->getAlign(), true /* UseLibcall */, AllocaIP, X);
11777 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11778 BasicBlock *CurBB = Builder.GetInsertBlock();
11779 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
11780 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
11781 BasicBlock *ExitBB =
11782 CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
11783 BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
11784 X->getName() + ".atomic.cont");
11785 ContBB->getTerminator()->eraseFromParent();
11786 Builder.restoreIP(AllocaIP);
11787 AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
11788 NewAtomicAddr->setName(X->getName() + "x.new.val");
11789 Builder.SetInsertPoint(ContBB);
11790 llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
11791 PHI->addIncoming(AtomicLoadRes.first, CurBB);
11792 Value *OldExprVal = PHI;
11793 Expected<Value *> CBResult = UpdateOp(OldExprVal, Builder);
11794 if (!CBResult)
11795 return CBResult.takeError();
11796 Value *Upd = *CBResult;
11797 Builder.CreateStore(Upd, NewAtomicAddr);
11800 auto Result = atomicInfo.EmitAtomicCompareExchangeLibcall(
11801 AtomicLoadRes.second, NewAtomicAddr, AO, Failure);
11802 LoadInst *PHILoad = Builder.CreateLoad(XElemTy, Result.first);
11803 PHI->addIncoming(PHILoad, Builder.GetInsertBlock());
11804 Builder.CreateCondBr(Result.second, ExitBB, ContBB);
11805 OldVal->eraseFromParent();
11806 Res.first = OldExprVal;
11807 Res.second = Upd;
11808
11809 if (UnreachableInst *ExitTI =
11811 CurBBTI->eraseFromParent();
11812 Builder.SetInsertPoint(ExitBB);
11813 } else {
11814 Builder.SetInsertPoint(ExitTI);
11815 }
11816 } else {
11817 IntegerType *IntCastTy =
11818 IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
11819 LoadInst *OldVal =
11820 Builder.CreateLoad(IntCastTy, X, X->getName() + ".atomic.load");
11822 OldVal->setAtomic(LoadAO);
11823 // CurBB
11824 // | /---\
11825 // ContBB |
11826 // | \---/
11827 // ExitBB
11828 BasicBlock *CurBB = Builder.GetInsertBlock();
11829 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
11830 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
11831 BasicBlock *ExitBB =
11832 CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
11833 BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
11834 X->getName() + ".atomic.cont");
11835 ContBB->getTerminator()->eraseFromParent();
11836 Builder.restoreIP(AllocaIP);
11837 AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
11838 NewAtomicAddr->setName(X->getName() + "x.new.val");
11839 Builder.SetInsertPoint(ContBB);
11840 llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
11841 PHI->addIncoming(OldVal, CurBB);
11842 bool IsIntTy = XElemTy->isIntegerTy();
11843 Value *OldExprVal = PHI;
11844 if (!IsIntTy) {
11845 if (XElemTy->isFloatingPointTy()) {
11846 OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
11847 X->getName() + ".atomic.fltCast");
11848 } else {
11849 OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
11850 X->getName() + ".atomic.ptrCast");
11851 }
11852 }
11853
11854 Expected<Value *> CBResult = UpdateOp(OldExprVal, Builder);
11855 if (!CBResult)
11856 return CBResult.takeError();
11857 Value *Upd = *CBResult;
11858 Builder.CreateStore(Upd, NewAtomicAddr);
11859 LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicAddr);
11862 AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
11863 X, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
11864 Result->setVolatile(VolatileX);
11865 Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
11866 Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
11867 PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
11868 Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
11869
11870 Res.first = OldExprVal;
11871 Res.second = Upd;
11872
11873 // set Insertion point in exit block
11874 if (UnreachableInst *ExitTI =
11876 CurBBTI->eraseFromParent();
11877 Builder.SetInsertPoint(ExitBB);
11878 } else {
11879 Builder.SetInsertPoint(ExitTI);
11880 }
11881 }
11882
11883 return Res;
11884}
11885
11888 AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
11889 AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
11890 bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr,
11891 bool IsIgnoreDenormalMode, bool IsFineGrainedMemory, bool IsRemoteMemory) {
11892 if (!updateToLocation(Loc))
11893 return Loc.IP;
11894
11895 LLVM_DEBUG({
11896 Type *XTy = X.Var->getType();
11897 assert(XTy->isPointerTy() &&
11898 "OMP Atomic expects a pointer to target memory");
11899 Type *XElemTy = X.ElemTy;
11900 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11901 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11902 "OMP atomic capture expected a scalar or struct type");
11903 });
11904
11905 // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
11906 // 'x' is simply atomically rewritten with 'expr'.
11907 AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
11908 Expected<std::pair<Value *, Value *>> AtomicResult = emitAtomicUpdate(
11909 AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp, X.IsVolatile,
11910 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11911 if (!AtomicResult)
11912 return AtomicResult.takeError();
11913 Value *CapturedVal =
11914 (IsPostfixUpdate ? AtomicResult->first : AtomicResult->second);
11915 Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
11916
11917 return Builder.saveIP();
11918}
11919
11923 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
11924 bool IsFailOnly, bool IsWeak) {
11925
11927 return createAtomicCompare(Loc, X, V, R, E, D, AO, Op, IsXBinopExpr,
11928 IsPostfixUpdate, IsFailOnly, Failure, IsWeak);
11929}
11930
11934 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
11935 bool IsFailOnly, AtomicOrdering Failure, bool IsWeak) {
11936
11937 if (!updateToLocation(Loc))
11938 return Loc.IP;
11939
11940 assert(X.Var->getType()->isPointerTy() &&
11941 "OMP atomic expects a pointer to target memory");
11942 // compare capture
11943 if (V.Var) {
11944 assert(V.Var->getType()->isPointerTy() && "v.var must be of pointer type");
11945 assert(V.ElemTy == X.ElemTy && "x and v must be of same type");
11946 }
11947
11948 bool IsInteger = E->getType()->isIntegerTy();
11949
11950 if (Op == OMPAtomicCompareOp::EQ) {
11951 // OldValue and SuccessOrFail are set below and used in the shared V.Var /
11952 // R.Var handling.
11953 Value *OldValue = nullptr;
11954 Value *SuccessOrFail = nullptr;
11955
11956 if (!IsInteger && HandleFPNegZero) {
11957 // IEEE 754 special cases for cmpxchg (which is bitwise):
11958 // 1. -0.0 == +0.0 but they have different bit patterns.
11959 // 2. NaN != NaN but identical NaN bit patterns would match.
11960 //
11961 // CurBB:
11962 // %e_int = bitcast E to intN
11963 // %d_int = bitcast D to intN
11964 // %x_curr = load atomic intN, X
11965 // %x_fp = bitcast %x_curr to FP
11966 // %e_is_nan = fcmp uno E, E
11967 // %x_is_nan = fcmp uno %x_fp, %x_fp
11968 // %either_nan = or %e_is_nan, %x_is_nan
11969 // br %either_nan, NaNBB, NotNaNBB
11970 // NaNBB: ; NaN == anything is always false
11971 // br ExitBB
11972 // NotNaNBB:
11973 // %x_is_zero = fcmp oeq %x_fp, 0.0
11974 // %e_is_zero = fcmp oeq E, 0.0
11975 // %both_zero = and %x_is_zero, %e_is_zero
11976 // br %both_zero, ZeroBB, NormalBB
11977 // ZeroBB: ; both ±0.0 → x = d
11978 // cmpxchg X, %x_curr, %d_int
11979 // br ExitBB
11980 // NormalBB: ; original path
11981 // cmpxchg X, %e_int, %d_int
11982 // br ExitBB
11983 // ExitBB:
11984 // phi merge
11985 IntegerType *IntCastTy =
11986 IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());
11987 Value *EBCast = Builder.CreateBitCast(E, IntCastTy);
11988 Value *DBCast = Builder.CreateBitCast(D, IntCastTy);
11989
11990 // Load X atomically.
11991 LoadInst *XCurr = Builder.CreateLoad(IntCastTy, X.Var,
11992 X.Var->getName() + ".atomic.load");
11994 Value *XFP = Builder.CreateBitCast(XCurr, X.ElemTy);
11995
11996 // IEEE 754: NaN != NaN, but cmpxchg would succeed if E and X have
11997 // the same NaN bit pattern. Skip cmpxchg when either is NaN.
11998 Value *EIsNaN = Builder.CreateFCmpUNO(E, E, "atomic.e.isnan");
11999 Value *XIsNaN = Builder.CreateFCmpUNO(XFP, XFP, "atomic.x.isnan");
12000 Value *EitherNaN = Builder.CreateOr(EIsNaN, XIsNaN, "atomic.either.nan");
12001
12002 BasicBlock *CurBB = Builder.GetInsertBlock();
12003 Function *F = CurBB->getParent();
12004 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
12005 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
12006 BasicBlock *ExitBB =
12007 CurBB->splitBasicBlock(CurBBTI, X.Var->getName() + ".atomic.exit");
12009 M.getContext(), X.Var->getName() + ".atomic.nan", F, ExitBB);
12010 BasicBlock *NotNaNBB = BasicBlock::Create(
12011 M.getContext(), X.Var->getName() + ".atomic.notnan", F, ExitBB);
12013 M.getContext(), X.Var->getName() + ".atomic.zero", F, ExitBB);
12014 BasicBlock *NormalBB = BasicBlock::Create(
12015 M.getContext(), X.Var->getName() + ".atomic.normal", F, ExitBB);
12016
12017 // If either E or X is NaN → NaNBB (always fails), else check for ±0.0.
12018 CurBB->getTerminator()->eraseFromParent();
12019 Builder.SetInsertPoint(CurBB);
12020 Builder.CreateCondBr(EitherNaN, NaNBB, NotNaNBB);
12021
12022 // NaNBB: NaN == anything is always false; skip cmpxchg.
12023 Builder.SetInsertPoint(NaNBB);
12024 Builder.CreateBr(ExitBB);
12025
12026 // NotNaNBB: check both X and E for ±0.0.
12027 Builder.SetInsertPoint(NotNaNBB);
12028 Value *XIsZero =
12029 Builder.CreateFCmpOEQ(XFP, ConstantFP::getZero(X.ElemTy),
12030 X.Var->getName() + ".atomic.xiszero");
12031 Value *EIsZero = Builder.CreateFCmpOEQ(E, ConstantFP::getZero(X.ElemTy),
12032 "atomic.e.iszero");
12033 Value *BothZero = Builder.CreateAnd(XIsZero, EIsZero, "atomic.both.zero");
12034 Builder.CreateCondBr(BothZero, ZeroBB, NormalBB);
12035
12036 // ZeroBB: cmpxchg with X's loaded bit-pattern.
12037 Builder.SetInsertPoint(ZeroBB);
12038 AtomicCmpXchgInst *ResZero = Builder.CreateAtomicCmpXchg(
12039 X.Var, XCurr, DBCast, MaybeAlign(), AO, Failure);
12040 ResZero->setWeak(IsWeak);
12041 Value *OldZero = Builder.CreateExtractValue(ResZero, /*Idxs=*/0);
12042 Value *OkZero = Builder.CreateExtractValue(ResZero, /*Idxs=*/1);
12043 Builder.CreateBr(ExitBB);
12044
12045 // NormalBB: original bitwise cmpxchg.
12046 Builder.SetInsertPoint(NormalBB);
12047 AtomicCmpXchgInst *ResNormal = Builder.CreateAtomicCmpXchg(
12048 X.Var, EBCast, DBCast, MaybeAlign(), AO, Failure);
12049 ResNormal->setWeak(IsWeak);
12050 Value *OldNormal = Builder.CreateExtractValue(ResNormal, /*Idxs=*/0);
12051 Value *OkNormal = Builder.CreateExtractValue(ResNormal, /*Idxs=*/1);
12052 Builder.CreateBr(ExitBB);
12053
12054 // ExitBB: merge results from NaN, Zero, and Normal paths.
12055 Builder.SetInsertPoint(ExitBB->begin());
12056 PHINode *OldIntPHI =
12057 Builder.CreatePHI(IntCastTy, 3, X.Var->getName() + ".atomic.old");
12058 OldIntPHI->addIncoming(XCurr, NaNBB);
12059 OldIntPHI->addIncoming(OldZero, ZeroBB);
12060 OldIntPHI->addIncoming(OldNormal, NormalBB);
12061 PHINode *SuccessPHI = Builder.CreatePHI(Builder.getInt1Ty(), 3,
12062 X.Var->getName() + ".atomic.ok");
12063 SuccessPHI->addIncoming(Builder.getFalse(), NaNBB);
12064 SuccessPHI->addIncoming(OkZero, ZeroBB);
12065 SuccessPHI->addIncoming(OkNormal, NormalBB);
12066
12067 if (isa<UnreachableInst>(ExitBB->getTerminator())) {
12068 CurBBTI->eraseFromParent();
12069 Builder.SetInsertPoint(ExitBB);
12070 } else {
12071 Builder.SetInsertPoint(&*ExitBB->getFirstNonPHIIt());
12072 }
12073
12074 OldValue = Builder.CreateBitCast(OldIntPHI, X.ElemTy,
12075 X.Var->getName() + ".atomic.old.fp");
12076 SuccessOrFail = SuccessPHI;
12077 } else {
12078 AtomicCmpXchgInst *Result = nullptr;
12079 if (!IsInteger) {
12080 IntegerType *IntCastTy =
12081 IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());
12082 Value *EBCast = Builder.CreateBitCast(E, IntCastTy);
12083 Value *DBCast = Builder.CreateBitCast(D, IntCastTy);
12084 Result = Builder.CreateAtomicCmpXchg(X.Var, EBCast, DBCast,
12085 MaybeAlign(), AO, Failure);
12086 } else {
12087 Result =
12088 Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
12089 }
12090 Result->setWeak(IsWeak);
12091
12092 if (V.Var) {
12093 OldValue = Builder.CreateExtractValue(Result, /*Idxs=*/0);
12094 if (!IsInteger)
12095 OldValue = Builder.CreateBitCast(OldValue, X.ElemTy);
12096 assert(OldValue->getType() == V.ElemTy &&
12097 "OldValue and V must be of same type");
12098 if (IsPostfixUpdate) {
12099 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12100 } else {
12101 SuccessOrFail = Builder.CreateExtractValue(Result, /*Idxs=*/1);
12102 if (IsFailOnly) {
12103 BasicBlock *CurBB = Builder.GetInsertBlock();
12104 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
12105 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
12106 BasicBlock *ExitBB = CurBB->splitBasicBlock(
12107 CurBBTI, X.Var->getName() + ".atomic.exit");
12108 BasicBlock *ContBB = CurBB->splitBasicBlock(
12109 CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
12110 ContBB->getTerminator()->eraseFromParent();
12111 CurBB->getTerminator()->eraseFromParent();
12112
12113 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12114
12115 Builder.SetInsertPoint(ContBB);
12116 Builder.CreateStore(OldValue, V.Var);
12117 Builder.CreateBr(ExitBB);
12118
12119 if (UnreachableInst *ExitTI =
12121 CurBBTI->eraseFromParent();
12122 Builder.SetInsertPoint(ExitBB);
12123 } else {
12124 Builder.SetInsertPoint(ExitTI);
12125 }
12126 } else {
12127 Value *CapturedValue =
12128 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12129 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12130 }
12131 }
12132 }
12133 // The comparison result has to be stored.
12134 if (R.Var) {
12135 assert(R.Var->getType()->isPointerTy() &&
12136 "r.var must be of pointer type");
12137 assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
12138
12139 Value *SuccessFailureVal =
12140 Builder.CreateExtractValue(Result, /*Idxs=*/1);
12141 Value *ResultCast =
12142 R.IsSigned ? Builder.CreateSExt(SuccessFailureVal, R.ElemTy)
12143 : Builder.CreateZExt(SuccessFailureVal, R.ElemTy);
12144 Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
12145 }
12146 }
12147
12148 // For the HandleFPNegZero path, handle V.Var and R.Var using the
12149 // pre-computed OldValue and SuccessOrFail.
12150 if (HandleFPNegZero && !IsInteger) {
12151 if (V.Var) {
12152 assert(OldValue->getType() == V.ElemTy &&
12153 "OldValue and V must be of same type");
12154 if (IsPostfixUpdate) {
12155 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12156 } else {
12157 if (IsFailOnly) {
12158 BasicBlock *CurBB = Builder.GetInsertBlock();
12159 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
12160 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
12161 BasicBlock *ExitBB = CurBB->splitBasicBlock(
12162 CurBBTI, X.Var->getName() + ".atomic.exit");
12163 BasicBlock *ContBB = CurBB->splitBasicBlock(
12164 CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
12165 ContBB->getTerminator()->eraseFromParent();
12166 CurBB->getTerminator()->eraseFromParent();
12167
12168 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12169
12170 Builder.SetInsertPoint(ContBB);
12171 Builder.CreateStore(OldValue, V.Var);
12172 Builder.CreateBr(ExitBB);
12173
12174 if (UnreachableInst *ExitTI =
12176 CurBBTI->eraseFromParent();
12177 Builder.SetInsertPoint(ExitBB);
12178 } else {
12179 Builder.SetInsertPoint(ExitTI);
12180 }
12181 } else {
12182 Value *CapturedValue =
12183 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12184 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12185 }
12186 }
12187 }
12188 // The comparison result has to be stored.
12189 if (R.Var) {
12190 assert(R.Var->getType()->isPointerTy() &&
12191 "r.var must be of pointer type");
12192 assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
12193
12194 Value *ResultCast = R.IsSigned
12195 ? Builder.CreateSExt(SuccessOrFail, R.ElemTy)
12196 : Builder.CreateZExt(SuccessOrFail, R.ElemTy);
12197 Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
12198 }
12199 }
12200 } else {
12201 assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
12202 "Op should be either max or min at this point");
12203 assert(!IsFailOnly && "IsFailOnly is only valid when the comparison is ==");
12204
12205 // Reverse the ordop as the OpenMP forms are different from LLVM forms.
12206 // Let's take max as example.
12207 // OpenMP form:
12208 // x = x > expr ? expr : x;
12209 // LLVM form:
12210 // *ptr = *ptr > val ? *ptr : val;
12211 // We need to transform to LLVM form.
12212 // x = x <= expr ? x : expr;
12214 if (IsXBinopExpr) {
12215 if (IsInteger) {
12216 if (X.IsSigned)
12217 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
12219 else
12220 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
12222 } else {
12223 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMin
12225 }
12226 } else {
12227 if (IsInteger) {
12228 if (X.IsSigned)
12229 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
12231 else
12232 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
12234 } else {
12235 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMax
12237 }
12238 }
12239
12240 AtomicRMWInst *OldValue =
12241 Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
12242 if (V.Var) {
12243 Value *CapturedValue = nullptr;
12244 if (IsPostfixUpdate) {
12245 CapturedValue = OldValue;
12246 } else {
12247 CmpInst::Predicate Pred;
12248 switch (NewOp) {
12249 case AtomicRMWInst::Max:
12250 Pred = CmpInst::ICMP_SGT;
12251 break;
12253 Pred = CmpInst::ICMP_UGT;
12254 break;
12256 Pred = CmpInst::FCMP_OGT;
12257 break;
12258 case AtomicRMWInst::Min:
12259 Pred = CmpInst::ICMP_SLT;
12260 break;
12262 Pred = CmpInst::ICMP_ULT;
12263 break;
12265 Pred = CmpInst::FCMP_OLT;
12266 break;
12267 default:
12268 llvm_unreachable("unexpected comparison op");
12269 }
12270 Value *NonAtomicCmp = Builder.CreateCmp(Pred, OldValue, E);
12271 CapturedValue = Builder.CreateSelect(NonAtomicCmp, E, OldValue);
12272 }
12273 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12274 }
12275 }
12276
12277 return Builder.saveIP();
12278}
12279
12282 BodyGenCallbackTy BodyGenCB, Value *NumTeamsLower,
12283 Value *NumTeamsUpper, Value *ThreadLimit,
12284 Value *IfExpr) {
12285 if (!updateToLocation(Loc))
12286 return InsertPointTy();
12287
12288 uint32_t SrcLocStrSize;
12289 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
12290 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
12291 Function *CurrentFunction = Builder.GetInsertBlock()->getParent();
12292
12293 // Outer allocation basicblock is the entry block of the current function.
12294 BasicBlock &OuterAllocaBB = CurrentFunction->getEntryBlock();
12295 if (&OuterAllocaBB == Builder.GetInsertBlock()) {
12296 BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "teams.entry");
12297 Builder.SetInsertPoint(BodyBB->begin());
12298 }
12299
12300 // The current basic block is split into four basic blocks. After outlining,
12301 // they will be mapped as follows:
12302 // ```
12303 // def current_fn() {
12304 // current_basic_block:
12305 // br label %teams.exit
12306 // teams.exit:
12307 // ; instructions after teams
12308 // }
12309 //
12310 // def outlined_fn() {
12311 // teams.alloca:
12312 // br label %teams.body
12313 // teams.body:
12314 // ; instructions within teams body
12315 // }
12316 // ```
12317 BasicBlock *ExitBB = splitBB(Builder, /*CreateBranch=*/true, "teams.exit");
12318 BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "teams.body");
12319 BasicBlock *AllocaBB =
12320 splitBB(Builder, /*CreateBranch=*/true, "teams.alloca");
12321
12322 bool SubClausesPresent =
12323 (NumTeamsLower || NumTeamsUpper || ThreadLimit || IfExpr);
12324 // Push num_teams
12325 if (!Config.isTargetDevice() && SubClausesPresent) {
12326 assert((NumTeamsLower == nullptr || NumTeamsUpper != nullptr) &&
12327 "if lowerbound is non-null, then upperbound must also be non-null "
12328 "for bounds on num_teams");
12329
12330 if (NumTeamsUpper == nullptr)
12331 NumTeamsUpper = Builder.getInt32(0);
12332
12333 if (NumTeamsLower == nullptr)
12334 NumTeamsLower = NumTeamsUpper;
12335
12336 if (IfExpr) {
12337 assert(IfExpr->getType()->isIntegerTy() &&
12338 "argument to if clause must be an integer value");
12339
12340 // upper = ifexpr ? upper : 1
12341 if (IfExpr->getType() != Int1)
12342 IfExpr = Builder.CreateICmpNE(IfExpr,
12343 ConstantInt::get(IfExpr->getType(), 0));
12344 NumTeamsUpper = Builder.CreateSelect(
12345 IfExpr, NumTeamsUpper, Builder.getInt32(1), "numTeamsUpper");
12346
12347 // lower = ifexpr ? lower : 1
12348 NumTeamsLower = Builder.CreateSelect(
12349 IfExpr, NumTeamsLower, Builder.getInt32(1), "numTeamsLower");
12350 }
12351
12352 if (ThreadLimit == nullptr)
12353 ThreadLimit = Builder.getInt32(0);
12354
12355 // The __kmpc_push_num_teams_51 function expects int32 as the arguments. So,
12356 // truncate or sign extend the passed values to match the int32 parameters.
12357 Value *NumTeamsLowerInt32 =
12358 Builder.CreateSExtOrTrunc(NumTeamsLower, Builder.getInt32Ty());
12359 Value *NumTeamsUpperInt32 =
12360 Builder.CreateSExtOrTrunc(NumTeamsUpper, Builder.getInt32Ty());
12361 Value *ThreadLimitInt32 =
12362 Builder.CreateSExtOrTrunc(ThreadLimit, Builder.getInt32Ty());
12363
12364 Value *ThreadNum = getOrCreateThreadID(Ident);
12365
12367 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_teams_51),
12368 {Ident, ThreadNum, NumTeamsLowerInt32, NumTeamsUpperInt32,
12369 ThreadLimitInt32});
12370 }
12371 // Generate the body of teams.
12372 InsertPointTy AllocaIP(AllocaBB->begin());
12373 InsertPointTy CodeGenIP(BodyBB->begin());
12374 if (Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12375 return Err;
12376
12377 auto OI = std::make_unique<OutlineInfo>();
12378 OI->EntryBB = AllocaBB;
12379 OI->ExitBB = ExitBB;
12380 OI->OuterAllocBB = &OuterAllocaBB;
12381
12382 // Insert fake values for global tid and bound tid.
12384 InsertPointTy OuterAllocaIP(OuterAllocaBB.begin());
12385 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
12386 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "gid", true));
12387 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
12388 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "tid", true));
12389
12390 auto HostPostOutlineCB = [this, Ident,
12391 ToBeDeleted](Function &OutlinedFn) mutable {
12392 // The stale call instruction will be replaced with a new call instruction
12393 // for runtime call with the outlined function.
12394
12395 assert(OutlinedFn.hasOneUse() &&
12396 "there must be a single user for the outlined function");
12397 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
12398 ToBeDeleted.push_back(StaleCI);
12399
12400 assert((OutlinedFn.arg_size() == 2 || OutlinedFn.arg_size() == 3) &&
12401 "Outlined function must have two or three arguments only");
12402
12403 bool HasShared = OutlinedFn.arg_size() == 3;
12404
12405 OutlinedFn.getArg(0)->setName("global.tid.ptr");
12406 OutlinedFn.getArg(1)->setName("bound.tid.ptr");
12407 if (HasShared)
12408 OutlinedFn.getArg(2)->setName("data");
12409
12410 // Call to the runtime function for teams in the current function.
12411 assert(StaleCI && "Error while outlining - no CallInst user found for the "
12412 "outlined function.");
12413 Builder.SetInsertPoint(StaleCI);
12414 SmallVector<Value *> Args = {
12415 Ident, Builder.getInt32(StaleCI->arg_size() - 2), &OutlinedFn};
12416 if (HasShared)
12417 Args.push_back(StaleCI->getArgOperand(2));
12420 omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),
12421 Args);
12422
12423 Builder.ClearInsertionPoint();
12424 for (Instruction *I : llvm::reverse(ToBeDeleted))
12425 I->eraseFromParent();
12426 };
12427
12428 if (!Config.isTargetDevice())
12429 OI->PostOutlineCB = HostPostOutlineCB;
12430
12431 addOutlineInfo(std::move(OI));
12432
12433 Builder.SetInsertPoint(ExitBB);
12434
12435 return Builder.saveIP();
12436}
12437
12439 const LocationDescription &Loc, InsertPointTy OuterAllocIP,
12440 ArrayRef<BasicBlock *> OuterDeallocBlocks, BodyGenCallbackTy BodyGenCB) {
12441 if (!updateToLocation(Loc))
12442 return InsertPointTy();
12443
12444 BasicBlock *OuterAllocaBB = OuterAllocIP.getNodeParent();
12445
12446 if (OuterAllocaBB == Builder.GetInsertBlock()) {
12447 BasicBlock *BodyBB =
12448 splitBB(Builder, /*CreateBranch=*/true, "distribute.entry");
12449 Builder.SetInsertPoint(BodyBB->begin());
12450 }
12451 BasicBlock *ExitBB =
12452 splitBB(Builder, /*CreateBranch=*/true, "distribute.exit");
12453 BasicBlock *BodyBB =
12454 splitBB(Builder, /*CreateBranch=*/true, "distribute.body");
12455 BasicBlock *AllocaBB =
12456 splitBB(Builder, /*CreateBranch=*/true, "distribute.alloca");
12457
12458 // Generate the body of distribute clause
12459 InsertPointTy AllocaIP(AllocaBB->begin());
12460 InsertPointTy CodeGenIP(BodyBB->begin());
12461 if (Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12462 return Err;
12463
12464 // When using target we use different runtime functions which require a
12465 // callback.
12466 if (Config.isTargetDevice()) {
12467 auto OI = std::make_unique<OutlineInfo>();
12468 OI->OuterAllocBB = OuterAllocIP.getNodeParent();
12469 OI->EntryBB = AllocaBB;
12470 OI->ExitBB = ExitBB;
12471 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.size());
12472 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.end());
12473
12474 addOutlineInfo(std::move(OI));
12475 }
12476 Builder.SetInsertPoint(ExitBB);
12477
12478 return Builder.saveIP();
12479}
12480
12483 std::string VarName) {
12484 llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
12486 Names.size()),
12487 Names);
12488 auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
12489 M, MapNamesArrayInit->getType(),
12490 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
12491 VarName);
12492 return MapNamesArrayGlobal;
12493}
12494
12495// Create all simple and struct types exposed by the runtime and remember
12496// the llvm::PointerTypes of them for easy access later.
12497void OpenMPIRBuilder::initializeTypes(Module &M) {
12498 LLVMContext &Ctx = M.getContext();
12499 StructType *T;
12500 unsigned DefaultTargetAS = Config.getDefaultTargetAS();
12501 unsigned ProgramAS = M.getDataLayout().getProgramAddressSpace();
12502#define OMP_TYPE(VarName, InitValue) VarName = InitValue;
12503#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
12504 VarName##Ty = ArrayType::get(ElemTy, ArraySize); \
12505 VarName##PtrTy = PointerType::get(Ctx, DefaultTargetAS);
12506#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
12507 VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg); \
12508 VarName##Ptr = PointerType::get(Ctx, ProgramAS);
12509#define OMP_STRUCT_TYPE(VarName, StructName, Packed, ...) \
12510 T = StructType::getTypeByName(Ctx, StructName); \
12511 if (!T) \
12512 T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed); \
12513 VarName = T; \
12514 VarName##Ptr = PointerType::get(Ctx, DefaultTargetAS);
12515#include "llvm/Frontend/OpenMP/OMPKinds.def"
12516}
12517
12520 SmallVectorImpl<BasicBlock *> &BlockVector) {
12522 BlockSet.insert(EntryBB);
12523 BlockSet.insert(ExitBB);
12524
12525 Worklist.push_back(EntryBB);
12526 while (!Worklist.empty()) {
12527 BasicBlock *BB = Worklist.pop_back_val();
12528 BlockVector.push_back(BB);
12529 for (BasicBlock *SuccBB : successors(BB))
12530 if (BlockSet.insert(SuccBB).second)
12531 Worklist.push_back(SuccBB);
12532 }
12533}
12534
12535std::unique_ptr<CodeExtractor>
12537 bool ArgsInZeroAddressSpace,
12538 Twine Suffix) {
12539 return std::make_unique<CodeExtractor>(
12540 Blocks, /* DominatorTree */ nullptr,
12541 /* AggregateArgs */ true,
12542 /* BlockFrequencyInfo */ nullptr,
12543 /* BranchProbabilityInfo */ nullptr,
12544 /* AssumptionCache */ nullptr,
12545 /* AllowVarArgs */ true,
12546 /* AllowAlloca */ true,
12547 /* AllocationBlock*/ OuterAllocBB,
12548 /* DeallocationBlocks */ ArrayRef<BasicBlock *>(),
12549 /* Suffix */ Suffix.str(), ArgsInZeroAddressSpace);
12550}
12551
12552std::unique_ptr<CodeExtractor> DeviceSharedMemOutlineInfo::createCodeExtractor(
12553 ArrayRef<BasicBlock *> Blocks, bool ArgsInZeroAddressSpace, Twine Suffix) {
12554 return std::make_unique<DeviceSharedMemCodeExtractor>(
12555 OMPBuilder, Blocks, /* DominatorTree */ nullptr,
12556 /* AggregateArgs */ true,
12557 /* BlockFrequencyInfo */ nullptr,
12558 /* BranchProbabilityInfo */ nullptr,
12559 /* AssumptionCache */ nullptr,
12560 /* AllowVarArgs */ true,
12561 /* AllowAlloca */ true,
12562 /* AllocationBlock*/ OuterAllocBB,
12563 /* DeallocationBlocks */ OuterDeallocBBs.empty()
12565 : OuterDeallocBBs,
12566 /* Suffix */ Suffix.str(), ArgsInZeroAddressSpace);
12567}
12568
12570 uint64_t Size, int32_t Flags,
12572 StringRef Name) {
12573 if (!Config.isGPU()) {
12576 Name.empty() ? Addr->getName() : Name, Size, Flags, /*Data=*/0);
12577 return;
12578 }
12579 // TODO: Add support for global variables on the device after declare target
12580 // support.
12581 Function *Fn = dyn_cast<Function>(Addr);
12582 if (!Fn)
12583 return;
12584
12585 // Add a function attribute for the kernel.
12586 Fn->addFnAttr("kernel");
12587 if (T.isAMDGCN())
12588 Fn->addFnAttr("uniform-work-group-size");
12589 Fn->addFnAttr(Attribute::MustProgress);
12590}
12591
12592// We only generate metadata for function that contain target regions.
12595
12596 // If there are no entries, we don't need to do anything.
12597 if (OffloadInfoManager.empty())
12598 return;
12599
12600 LLVMContext &C = M.getContext();
12603 16>
12604 OrderedEntries(OffloadInfoManager.size());
12605
12606 // Auxiliary methods to create metadata values and strings.
12607 auto &&GetMDInt = [this](unsigned V) {
12608 return ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), V));
12609 };
12610
12611 auto &&GetMDString = [&C](StringRef V) { return MDString::get(C, V); };
12612
12613 // Create the offloading info metadata node.
12614 NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
12615 auto &&TargetRegionMetadataEmitter =
12616 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
12617 const TargetRegionEntryInfo &EntryInfo,
12619 // Generate metadata for target regions. Each entry of this metadata
12620 // contains:
12621 // - Entry 0 -> Kind of this type of metadata (0).
12622 // - Entry 1 -> Device ID of the file where the entry was identified.
12623 // - Entry 2 -> File ID of the file where the entry was identified.
12624 // - Entry 3 -> Mangled name of the function where the entry was
12625 // identified.
12626 // - Entry 4 -> Line in the file where the entry was identified.
12627 // - Entry 5 -> Count of regions at this DeviceID/FilesID/Line.
12628 // - Entry 6 -> Order the entry was created.
12629 // The first element of the metadata node is the kind.
12630 Metadata *Ops[] = {
12631 GetMDInt(E.getKind()), GetMDInt(EntryInfo.DeviceID),
12632 GetMDInt(EntryInfo.FileID), GetMDString(EntryInfo.ParentName),
12633 GetMDInt(EntryInfo.Line), GetMDInt(EntryInfo.Count),
12634 GetMDInt(E.getOrder())};
12635
12636 // Save this entry in the right position of the ordered entries array.
12637 OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);
12638
12639 // Add metadata to the named metadata node.
12640 MD->addOperand(MDNode::get(C, Ops));
12641 };
12642
12643 OffloadInfoManager.actOnTargetRegionEntriesInfo(TargetRegionMetadataEmitter);
12644
12645 // Create function that emits metadata for each device global variable entry;
12646 auto &&DeviceGlobalVarMetadataEmitter =
12647 [&C, &OrderedEntries, &GetMDInt, &GetMDString, MD](
12648 StringRef MangledName,
12650 // Generate metadata for global variables. Each entry of this metadata
12651 // contains:
12652 // - Entry 0 -> Kind of this type of metadata (1).
12653 // - Entry 1 -> Mangled name of the variable.
12654 // - Entry 2 -> Declare target kind.
12655 // - Entry 3 -> Order the entry was created.
12656 // The first element of the metadata node is the kind.
12657 Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),
12658 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
12659
12660 // Save this entry in the right position of the ordered entries array.
12661 TargetRegionEntryInfo varInfo(MangledName, 0, 0, 0);
12662 OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);
12663
12664 // Add metadata to the named metadata node.
12665 MD->addOperand(MDNode::get(C, Ops));
12666 };
12667
12668 OffloadInfoManager.actOnDeviceGlobalVarEntriesInfo(
12669 DeviceGlobalVarMetadataEmitter);
12670
12671 for (const auto &E : OrderedEntries) {
12672 assert(E.first && "All ordered entries must exist!");
12673 if (const auto *CE =
12675 E.first)) {
12676 if (!CE->getID() || !CE->getAddress()) {
12677 // Do not blame the entry if the parent funtion is not emitted.
12678 TargetRegionEntryInfo EntryInfo = E.second;
12679 StringRef FnName = EntryInfo.ParentName;
12680 if (!M.getNamedValue(FnName))
12681 continue;
12682 ErrorFn(EMIT_MD_TARGET_REGION_ERROR, EntryInfo);
12683 continue;
12684 }
12685 createOffloadEntry(CE->getID(), CE->getAddress(),
12686 /*Size=*/0, CE->getFlags(),
12688 } else if (const auto *CE = dyn_cast<
12690 E.first)) {
12693 CE->getFlags());
12694 switch (Flags) {
12697 if (Config.isTargetDevice() && Config.hasRequiresUnifiedSharedMemory())
12698 continue;
12699 if (!CE->getAddress()) {
12700 ErrorFn(EMIT_MD_DECLARE_TARGET_ERROR, E.second);
12701 continue;
12702 }
12703 // The vaiable has no definition - no need to add the entry.
12704 if (CE->getVarSize() == 0)
12705 continue;
12706 break;
12708 assert(((Config.isTargetDevice() && !CE->getAddress()) ||
12709 (!Config.isTargetDevice() && CE->getAddress())) &&
12710 "Declaret target link address is set.");
12711 if (Config.isTargetDevice())
12712 continue;
12713 if (!CE->getAddress()) {
12715 continue;
12716 }
12717 break;
12720 if (!CE->getAddress()) {
12721 ErrorFn(EMIT_MD_GLOBAL_VAR_INDIRECT_ERROR, E.second);
12722 continue;
12723 }
12724 break;
12725 default:
12726 break;
12727 }
12728
12729 // Hidden or internal symbols on the device are not externally visible.
12730 // We should not attempt to register them by creating an offloading
12731 // entry. Indirect variables are handled separately on the device.
12732 if (auto *GV = dyn_cast<GlobalValue>(CE->getAddress()))
12733 if ((GV->hasLocalLinkage() || GV->hasHiddenVisibility()) &&
12734 (Flags !=
12736 Flags != OffloadEntriesInfoManager::
12737 OMPTargetGlobalVarEntryIndirectVTable))
12738 continue;
12739
12740 // Indirect globals need to use a special name that doesn't match the name
12741 // of the associated host global.
12743 Flags ==
12745 createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),
12746 Flags, CE->getLinkage(), CE->getVarName());
12747 else
12748 createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),
12749 Flags, CE->getLinkage());
12750
12751 } else {
12752 llvm_unreachable("Unsupported entry kind.");
12753 }
12754 }
12755
12756 // Emit requires directive globals to a special entry so the runtime can
12757 // register them when the device image is loaded.
12758 // TODO: This reduces the offloading entries to a 32-bit integer. Offloading
12759 // entries should be redesigned to better suit this use-case.
12760 if (Config.hasRequiresFlags() && !Config.isTargetDevice())
12764 ".requires", /*Size=*/0,
12766 Config.getRequiresFlags());
12767}
12768
12771 unsigned FileID, unsigned Line, unsigned Count) {
12772 raw_svector_ostream OS(Name);
12773 OS << KernelNamePrefix << llvm::format("%x", DeviceID)
12774 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
12775 if (Count)
12776 OS << "_" << Count;
12777}
12778
12780 SmallVectorImpl<char> &Name, const TargetRegionEntryInfo &EntryInfo) {
12781 unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);
12783 Name, EntryInfo.ParentName, EntryInfo.DeviceID, EntryInfo.FileID,
12784 EntryInfo.Line, NewCount);
12785}
12786
12789 vfs::FileSystem &VFS,
12790 StringRef ParentName) {
12791 sys::fs::UniqueID ID(0xdeadf17e, 0);
12792 auto FileIDInfo = CallBack();
12793 uint64_t FileID = 0;
12794 if (ErrorOr<vfs::Status> Status = VFS.status(std::get<0>(FileIDInfo))) {
12795 ID = Status->getUniqueID();
12796 FileID = Status->getUniqueID().getFile();
12797 } else {
12798 // If the inode ID could not be determined, create a hash value
12799 // the current file name and use that as an ID.
12800 FileID = hash_value(std::get<0>(FileIDInfo));
12801 }
12802
12803 return TargetRegionEntryInfo(ParentName, ID.getDevice(), FileID,
12804 std::get<1>(FileIDInfo));
12805}
12806
12808 unsigned Offset = 0;
12809 for (uint64_t Remain =
12810 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12812 !(Remain & 1); Remain = Remain >> 1)
12813 Offset++;
12814 return Offset;
12815}
12816
12819 // Rotate by getFlagMemberOffset() bits.
12820 return static_cast<omp::OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
12821 << getFlagMemberOffset());
12822}
12823
12826 omp::OpenMPOffloadMappingFlags MemberOfFlag) {
12827 // If the entry is PTR_AND_OBJ but has not been marked with the special
12828 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
12829 // marked as MEMBER_OF.
12830 if (static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12832 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12835 return;
12836
12837 // Entries with ATTACH are not members-of anything. They are handled
12838 // separately by the runtime after other maps have been handled.
12839 if (static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12841 return;
12842
12843 // Reset the placeholder value to prepare the flag for the assignment of the
12844 // proper MEMBER_OF value.
12845 Flags &= ~omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
12846 Flags |= MemberOfFlag;
12847}
12848
12852 bool IsDeclaration, bool IsExternallyVisible,
12853 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
12854 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
12855 std::vector<Triple> TargetTriple, Type *LlvmPtrTy,
12856 std::function<Constant *()> GlobalInitializer,
12857 std::function<GlobalValue::LinkageTypes()> VariableLinkage) {
12858 // TODO: convert this to utilise the IRBuilder Config rather than
12859 // a passed down argument.
12860 if (OpenMPSIMD)
12861 return nullptr;
12862
12865 CaptureClause ==
12867 Config.hasRequiresUnifiedSharedMemory())) {
12868 SmallString<64> PtrName;
12869 {
12870 raw_svector_ostream OS(PtrName);
12871 OS << MangledName;
12872 if (!IsExternallyVisible)
12873 OS << format("_%x", EntryInfo.FileID);
12874 OS << "_decl_tgt_ref_ptr";
12875 }
12876
12877 Value *Ptr = M.getNamedValue(PtrName);
12878
12879 if (!Ptr) {
12880 GlobalValue *GlobalValue = M.getNamedValue(MangledName);
12881 Ptr = getOrCreateInternalVariable(LlvmPtrTy, PtrName);
12882
12883 auto *GV = cast<GlobalVariable>(Ptr);
12884 GV->setLinkage(GlobalValue::WeakAnyLinkage);
12885
12886 if (!Config.isTargetDevice()) {
12887 if (GlobalInitializer)
12888 GV->setInitializer(GlobalInitializer());
12889 else
12890 GV->setInitializer(GlobalValue);
12891 }
12892
12894 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12895 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12896 GlobalInitializer, VariableLinkage, LlvmPtrTy, cast<Constant>(Ptr));
12897 }
12898
12899 return cast<Constant>(Ptr);
12900 }
12901
12902 return nullptr;
12903}
12904
12908 bool IsDeclaration, bool IsExternallyVisible,
12909 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
12910 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
12911 std::vector<Triple> TargetTriple,
12912 std::function<Constant *()> GlobalInitializer,
12913 std::function<GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy,
12914 Constant *Addr) {
12916 (TargetTriple.empty() && !Config.isTargetDevice()))
12917 return;
12918
12920 StringRef VarName;
12921 int64_t VarSize;
12923
12925 CaptureClause ==
12927 !Config.hasRequiresUnifiedSharedMemory()) {
12929 VarName = MangledName;
12930 GlobalValue *LlvmVal = M.getNamedValue(VarName);
12931
12932 if (!IsDeclaration)
12933 VarSize = divideCeil(
12934 M.getDataLayout().getTypeSizeInBits(LlvmVal->getValueType()), 8);
12935 else
12936 VarSize = 0;
12937 Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->getLinkage();
12938
12939 // This is a workaround carried over from Clang which prevents undesired
12940 // optimisation of internal variables.
12941 if (Config.isTargetDevice() &&
12942 (!IsExternallyVisible || Linkage == GlobalValue::LinkOnceODRLinkage)) {
12943 // Do not create a "ref-variable" if the original is not also available
12944 // on the host.
12945 if (!OffloadInfoManager.hasDeviceGlobalVarEntryInfo(VarName))
12946 return;
12947
12948 std::string RefName = createPlatformSpecificName({VarName, "ref"});
12949
12950 if (!M.getNamedValue(RefName)) {
12951 Constant *AddrRef =
12952 getOrCreateInternalVariable(Addr->getType(), RefName);
12953 auto *GvAddrRef = cast<GlobalVariable>(AddrRef);
12954 GvAddrRef->setConstant(true);
12955 GvAddrRef->setLinkage(GlobalValue::InternalLinkage);
12956 GvAddrRef->setInitializer(Addr);
12957 GeneratedRefs.push_back(GvAddrRef);
12958 }
12959 }
12960 } else {
12963 else
12965
12966 if (Config.isTargetDevice()) {
12967 VarName = (Addr) ? Addr->getName() : "";
12968 Addr = nullptr;
12969 } else {
12971 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12972 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12973 LlvmPtrTy, GlobalInitializer, VariableLinkage);
12974 VarName = (Addr) ? Addr->getName() : "";
12975 }
12976 VarSize = M.getDataLayout().getPointerSize();
12978 }
12979
12980 OffloadInfoManager.registerDeviceGlobalVarEntryInfo(VarName, Addr, VarSize,
12981 Flags, Linkage);
12982}
12983
12984/// Loads all the offload entries information from the host IR
12985/// metadata.
12987 // If we are in target mode, load the metadata from the host IR. This code has
12988 // to match the metadata creation in createOffloadEntriesAndInfoMetadata().
12989
12990 NamedMDNode *MD = M.getNamedMetadata(ompOffloadInfoName);
12991 if (!MD)
12992 return;
12993
12994 for (MDNode *MN : MD->operands()) {
12995 auto &&GetMDInt = [MN](unsigned Idx) {
12996 auto *V = cast<ConstantAsMetadata>(MN->getOperand(Idx));
12997 return cast<ConstantInt>(V->getValue())->getZExtValue();
12998 };
12999
13000 auto &&GetMDString = [MN](unsigned Idx) {
13001 auto *V = cast<MDString>(MN->getOperand(Idx));
13002 return V->getString();
13003 };
13004
13005 switch (GetMDInt(0)) {
13006 default:
13007 llvm_unreachable("Unexpected metadata!");
13008 break;
13009 case OffloadEntriesInfoManager::OffloadEntryInfo::
13010 OffloadingEntryInfoTargetRegion: {
13011 TargetRegionEntryInfo EntryInfo(/*ParentName=*/GetMDString(3),
13012 /*DeviceID=*/GetMDInt(1),
13013 /*FileID=*/GetMDInt(2),
13014 /*Line=*/GetMDInt(4),
13015 /*Count=*/GetMDInt(5));
13016 OffloadInfoManager.initializeTargetRegionEntryInfo(EntryInfo,
13017 /*Order=*/GetMDInt(6));
13018 break;
13019 }
13020 case OffloadEntriesInfoManager::OffloadEntryInfo::
13021 OffloadingEntryInfoDeviceGlobalVar:
13022 OffloadInfoManager.initializeDeviceGlobalVarEntryInfo(
13023 /*MangledName=*/GetMDString(1),
13025 /*Flags=*/GetMDInt(2)),
13026 /*Order=*/GetMDInt(3));
13027 break;
13028 }
13029 }
13030}
13031
13033 StringRef HostFilePath) {
13034 if (HostFilePath.empty())
13035 return;
13036
13037 auto Buf = VFS.getBufferForFile(HostFilePath);
13038 if (std::error_code Err = Buf.getError()) {
13039 report_fatal_error(("error opening host file from host file path inside of "
13040 "OpenMPIRBuilder: " +
13041 Err.message())
13042 .c_str());
13043 }
13044
13045 LLVMContext Ctx;
13047 Ctx, parseBitcodeFile(Buf.get()->getMemBufferRef(), Ctx));
13048 if (std::error_code Err = M.getError()) {
13050 ("error parsing host file inside of OpenMPIRBuilder: " + Err.message())
13051 .c_str());
13052 }
13053
13054 loadOffloadInfoMetadata(*M.get());
13055}
13056
13059 llvm::StringRef Name) {
13060 Builder.restoreIP(Loc.IP);
13061
13062 BasicBlock *CurBB = Builder.GetInsertBlock();
13063 assert(CurBB &&
13064 "expected a valid insertion block for creating an iterator loop");
13065 Function *F = CurBB->getParent();
13066
13067 InsertPointTy SplitIP = Builder.saveIP();
13068 if (SplitIP == CurBB->end())
13069 if (Instruction *Terminator = CurBB->getTerminatorOrNull())
13070 SplitIP = Terminator->getIterator();
13071
13072 BasicBlock *ContBB =
13073 splitBB(SplitIP, /*CreateBranch=*/false,
13074 Builder.getCurrentDebugLocation(), "omp.it.cont");
13075
13076 CanonicalLoopInfo *CLI =
13077 createLoopSkeleton(Builder.getCurrentDebugLocation(), TripCount, F,
13078 /*PreInsertBefore=*/ContBB,
13079 /*PostInsertBefore=*/ContBB, Name);
13080
13081 // Enter loop from original block.
13082 redirectTo(CurBB, CLI->getPreheader(), Builder.getCurrentDebugLocation());
13083
13084 // Remove the unconditional branch inserted by createLoopSkeleton in the body
13085 if (Instruction *T = CLI->getBody()->getTerminatorOrNull())
13086 T->eraseFromParent();
13087
13088 InsertPointTy BodyIP = CLI->getBodyIP();
13089 // Blocks that exist before BodyGen, other than the body and latch, are
13090 // outside the loop body.
13091 SmallPtrSet<BasicBlock *, 32> ExistingBlocks;
13092 for (BasicBlock &Block : *F)
13093 ExistingBlocks.insert(&Block);
13094 if (llvm::Error Err = BodyGen(BodyIP, CLI->getIndVar()))
13095 return Err;
13096
13097 // The body may span several blocks. Branch its single unterminated block to
13098 // the latch; otherwise some block must already branch there.
13099 BasicBlock *Latch = CLI->getLatch();
13100 BasicBlock *OpenBB = nullptr;
13101 bool ReachesLatch = false;
13102 SmallVector<BasicBlock *> Worklist{CLI->getBody()};
13103 SmallPtrSet<BasicBlock *, 8> Visited{CLI->getBody()};
13104 while (!Worklist.empty()) {
13105 BasicBlock *BB = Worklist.pop_back_val();
13106 if (!BB->hasTerminator()) {
13107 if (OpenBB)
13109 "iterator bodygen must leave at most one unterminated block",
13111 OpenBB = BB;
13112 continue;
13113 }
13114 for (BasicBlock *Succ : successors(BB)) {
13115 if (Succ == Latch) {
13116 ReachesLatch = true;
13117 continue;
13118 }
13119 if (Succ != CLI->getBody() && ExistingBlocks.contains(Succ))
13121 "iterator bodygen must not branch out of the loop body",
13123 if (Visited.insert(Succ).second)
13124 Worklist.push_back(Succ);
13125 }
13126 }
13127
13128 if (OpenBB) {
13129 Builder.SetInsertPoint(OpenBB);
13130 Builder.CreateBr(Latch);
13131 } else if (!ReachesLatch) {
13132 return make_error<StringError>("iterator bodygen must reach the loop latch",
13134 }
13135
13136 // Link After -> ContBB
13137 Builder.SetInsertPoint(CLI->getAfter()->begin());
13138 if (!CLI->getAfter()->hasTerminator())
13139 Builder.CreateBr(ContBB);
13140
13141 return ContBB->begin();
13142}
13143
13144/// Mangle the parameter part of the vector function name according to
13145/// their OpenMP classification. The mangling function is defined in
13146/// section 4.5 of the AAVFABI(2021Q1).
13147static std::string mangleVectorParameters(
13149 SmallString<256> Buffer;
13150 llvm::raw_svector_ostream Out(Buffer);
13151 for (const auto &ParamAttr : ParamAttrs) {
13152 switch (ParamAttr.Kind) {
13154 Out << 'l';
13155 break;
13157 Out << 'R';
13158 break;
13160 Out << 'U';
13161 break;
13163 Out << 'L';
13164 break;
13166 Out << 'u';
13167 break;
13169 Out << 'v';
13170 break;
13171 }
13172 if (ParamAttr.HasVarStride)
13173 Out << "s" << ParamAttr.StrideOrArg;
13174 else if (ParamAttr.Kind ==
13176 ParamAttr.Kind ==
13178 ParamAttr.Kind ==
13180 ParamAttr.Kind ==
13182 // Don't print the step value if it is not present or if it is
13183 // equal to 1.
13184 if (ParamAttr.StrideOrArg < 0)
13185 Out << 'n' << -ParamAttr.StrideOrArg;
13186 else if (ParamAttr.StrideOrArg != 1)
13187 Out << ParamAttr.StrideOrArg;
13188 }
13189
13190 if (!!ParamAttr.Alignment)
13191 Out << 'a' << ParamAttr.Alignment;
13192 }
13193
13194 return std::string(Out.str());
13195}
13196
13198 llvm::Function *Fn, unsigned NumElts, const llvm::APSInt &VLENVal,
13200 struct ISADataTy {
13201 char ISA;
13202 unsigned VecRegSize;
13203 };
13204 ISADataTy ISAData[] = {
13205 {'b', 128}, // SSE
13206 {'c', 256}, // AVX
13207 {'d', 256}, // AVX2
13208 {'e', 512}, // AVX512
13209 };
13211 switch (Branch) {
13213 Masked.push_back('N');
13214 Masked.push_back('M');
13215 break;
13217 Masked.push_back('N');
13218 break;
13220 Masked.push_back('M');
13221 break;
13222 }
13223 for (char Mask : Masked) {
13224 for (const ISADataTy &Data : ISAData) {
13226 llvm::raw_svector_ostream Out(Buffer);
13227 Out << "_ZGV" << Data.ISA << Mask;
13228 if (!VLENVal) {
13229 assert(NumElts && "Non-zero simdlen/cdtsize expected");
13230 Out << llvm::APSInt::getUnsigned(Data.VecRegSize / NumElts);
13231 } else {
13232 Out << VLENVal;
13233 }
13234 Out << mangleVectorParameters(ParamAttrs);
13235 Out << '_' << Fn->getName();
13236 Fn->addFnAttr(Out.str());
13237 }
13238 }
13239}
13240
13241// Function used to add the attribute. The parameter `VLEN` is templated to
13242// allow the use of `x` when targeting scalable functions for SVE.
13243template <typename T>
13244static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix,
13245 char ISA, StringRef ParSeq,
13246 StringRef MangledName, bool OutputBecomesInput,
13247 llvm::Function *Fn) {
13248 SmallString<256> Buffer;
13249 llvm::raw_svector_ostream Out(Buffer);
13250 Out << Prefix << ISA << LMask << VLEN;
13251 if (OutputBecomesInput)
13252 Out << 'v';
13253 Out << ParSeq << '_' << MangledName;
13254 Fn->addFnAttr(Out.str());
13255}
13256
13257// Helper function to generate the Advanced SIMD names depending on the value
13258// of the NDS when simdlen is not present.
13259static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask,
13260 StringRef Prefix, char ISA,
13261 StringRef ParSeq, StringRef MangledName,
13262 bool OutputBecomesInput,
13263 llvm::Function *Fn) {
13264 switch (NDS) {
13265 case 8:
13266 addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
13267 OutputBecomesInput, Fn);
13268 addAArch64VectorName(16, Mask, Prefix, ISA, ParSeq, MangledName,
13269 OutputBecomesInput, Fn);
13270 break;
13271 case 16:
13272 addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
13273 OutputBecomesInput, Fn);
13274 addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
13275 OutputBecomesInput, Fn);
13276 break;
13277 case 32:
13278 addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
13279 OutputBecomesInput, Fn);
13280 addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
13281 OutputBecomesInput, Fn);
13282 break;
13283 case 64:
13284 case 128:
13285 addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
13286 OutputBecomesInput, Fn);
13287 break;
13288 default:
13289 llvm_unreachable("Scalar type is too wide.");
13290 }
13291}
13292
13293/// Emit vector function attributes for AArch64, as defined in the AAVFABI.
13295 llvm::Function *Fn, unsigned UserVLEN,
13297 char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput) {
13298 assert((ISA == 'n' || ISA == 's') && "Expected ISA either 's' or 'n'.");
13299
13300 // Sort out parameter sequence.
13301 const std::string ParSeq = mangleVectorParameters(ParamAttrs);
13302 StringRef Prefix = "_ZGV";
13303 StringRef MangledName = Fn->getName();
13304
13305 // Generate simdlen from user input (if any).
13306 if (UserVLEN) {
13307 if (ISA == 's') {
13308 // SVE generates only a masked function.
13309 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
13310 OutputBecomesInput, Fn);
13311 return;
13312 }
13313
13314 switch (Branch) {
13316 addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
13317 OutputBecomesInput, Fn);
13318 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
13319 OutputBecomesInput, Fn);
13320 break;
13322 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
13323 OutputBecomesInput, Fn);
13324 break;
13326 addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
13327 OutputBecomesInput, Fn);
13328 break;
13329 }
13330 return;
13331 }
13332
13333 if (ISA == 's') {
13334 // SVE, section 3.4.1, item 1.
13335 addAArch64VectorName("x", "M", Prefix, ISA, ParSeq, MangledName,
13336 OutputBecomesInput, Fn);
13337 return;
13338 }
13339
13340 switch (Branch) {
13342 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "N", Prefix, ISA, ParSeq,
13343 MangledName, OutputBecomesInput, Fn);
13344 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "M", Prefix, ISA, ParSeq,
13345 MangledName, OutputBecomesInput, Fn);
13346 break;
13348 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "M", Prefix, ISA, ParSeq,
13349 MangledName, OutputBecomesInput, Fn);
13350 break;
13352 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "N", Prefix, ISA, ParSeq,
13353 MangledName, OutputBecomesInput, Fn);
13354 break;
13355 }
13356}
13357
13358//===----------------------------------------------------------------------===//
13359// OffloadEntriesInfoManager
13360//===----------------------------------------------------------------------===//
13361
13363 return OffloadEntriesTargetRegion.empty() &&
13364 OffloadEntriesDeviceGlobalVar.empty();
13365}
13366
13367unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(
13368 const TargetRegionEntryInfo &EntryInfo) const {
13369 auto It = OffloadEntriesTargetRegionCount.find(
13370 getTargetRegionEntryCountKey(EntryInfo));
13371 if (It == OffloadEntriesTargetRegionCount.end())
13372 return 0;
13373 return It->second;
13374}
13375
13376void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(
13377 const TargetRegionEntryInfo &EntryInfo) {
13378 OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =
13379 EntryInfo.Count + 1;
13380}
13381
13382/// Initialize target region entry.
13384 const TargetRegionEntryInfo &EntryInfo, unsigned Order) {
13385 OffloadEntriesTargetRegion[EntryInfo] =
13386 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
13388 ++OffloadingEntriesNum;
13389}
13390
13392 TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID,
13394 assert(EntryInfo.Count == 0 && "expected default EntryInfo");
13395
13396 // Update the EntryInfo with the next available count for this location.
13397 EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);
13398
13399 // If we are emitting code for a target, the entry is already initialized,
13400 // only has to be registered.
13401 if (OMPBuilder->Config.isTargetDevice()) {
13402 // This could happen if the device compilation is invoked standalone.
13403 if (!hasTargetRegionEntryInfo(EntryInfo)) {
13404 return;
13405 }
13406 auto &Entry = OffloadEntriesTargetRegion[EntryInfo];
13407 Entry.setAddress(Addr);
13408 Entry.setID(ID);
13409 Entry.setFlags(Flags);
13410 } else {
13412 hasTargetRegionEntryInfo(EntryInfo, /*IgnoreAddressId*/ true))
13413 return;
13414 assert(!hasTargetRegionEntryInfo(EntryInfo) &&
13415 "Target region entry already registered!");
13416 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
13417 OffloadEntriesTargetRegion[EntryInfo] = Entry;
13418 ++OffloadingEntriesNum;
13419 }
13420 incrementTargetRegionEntryInfoCount(EntryInfo);
13421}
13422
13424 TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId) const {
13425
13426 // Update the EntryInfo with the next available count for this location.
13427 EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);
13428
13429 auto It = OffloadEntriesTargetRegion.find(EntryInfo);
13430 if (It == OffloadEntriesTargetRegion.end()) {
13431 return false;
13432 }
13433 // Fail if this entry is already registered.
13434 if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))
13435 return false;
13436 return true;
13437}
13438
13440 const OffloadTargetRegionEntryInfoActTy &Action) {
13441 // Scan all target region entries and perform the provided action.
13442 for (const auto &It : OffloadEntriesTargetRegion) {
13443 Action(It.first, It.second);
13444 }
13445}
13446
13448 StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order) {
13449 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
13450 ++OffloadingEntriesNum;
13451}
13452
13454 StringRef VarName, Constant *Addr, int64_t VarSize,
13456 if (OMPBuilder->Config.isTargetDevice()) {
13457 // This could happen if the device compilation is invoked standalone.
13458 if (!hasDeviceGlobalVarEntryInfo(VarName))
13459 return;
13460 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13461 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
13462 if (Entry.getVarSize() == 0) {
13463 Entry.setVarSize(VarSize);
13464 Entry.setLinkage(Linkage);
13465 }
13466 return;
13467 }
13468 Entry.setVarSize(VarSize);
13469 Entry.setLinkage(Linkage);
13470 Entry.setAddress(Addr);
13471 } else {
13472 if (hasDeviceGlobalVarEntryInfo(VarName)) {
13473 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13474 assert(Entry.isValid() && Entry.getFlags() == Flags &&
13475 "Entry not initialized!");
13476 if (Entry.getVarSize() == 0) {
13477 Entry.setVarSize(VarSize);
13478 Entry.setLinkage(Linkage);
13479 }
13480 return;
13481 }
13483 Flags ==
13485 OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,
13486 Addr, VarSize, Flags, Linkage,
13487 VarName.str());
13488 else
13489 OffloadEntriesDeviceGlobalVar.try_emplace(
13490 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage, "");
13491 ++OffloadingEntriesNum;
13492 }
13493}
13494
13497 // Scan all target region entries and perform the provided action.
13498 for (const auto &E : OffloadEntriesDeviceGlobalVar)
13499 Action(E.getKey(), E.getValue());
13500}
13501
13502//===----------------------------------------------------------------------===//
13503// CanonicalLoopInfo
13504//===----------------------------------------------------------------------===//
13505
13506void CanonicalLoopInfo::reportUnsupportedVirtualCollapse() const {
13507 assert(isValid() && "Requires a valid canonical loop");
13508 assert(VirtualCollapse && "Requires Virtual collapse state");
13510 "virtual collapse must be the final structural loop transformation");
13511}
13512
13513void CanonicalLoopInfo::collectControlBlocks(
13515 if (VirtualCollapse)
13516 reportUnsupportedVirtualCollapse();
13517 // We only count those BBs as control block for which we do not need to
13518 // reverse the CFG, i.e. not the loop body which can contain arbitrary control
13519 // flow. For consistency, this also means we do not add the Body block, which
13520 // is just the entry to the body code.
13521 BBs.reserve(BBs.size() + 6);
13522 BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
13523}
13524
13525BasicBlock *CanonicalLoopInfo::getVirtualCollapseInit() const {
13526 return VirtualCollapse ? VirtualCollapse->Count->getParent() : nullptr;
13527}
13528
13530 assert(isValid() && "Requires a valid canonical loop");
13531 if (VirtualCollapse)
13532 return getVirtualCollapseInit()->getSinglePredecessor();
13533
13534 for (BasicBlock *Pred : predecessors(Header)) {
13535 if (Pred != Latch)
13536 return Pred;
13537 }
13538 llvm_unreachable("Missing preheader");
13539}
13540
13541void CanonicalLoopInfo::setTripCount(Value *TripCount) {
13542 assert(isValid() && "Requires a valid canonical loop");
13543
13544 Instruction *CmpI = &getCond()->front();
13545 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
13546 CmpI->setOperand(1, TripCount);
13547
13548#ifndef NDEBUG
13549 assertOK();
13550#endif
13551}
13552
13553void CanonicalLoopInfo::mapIndVar(
13554 llvm::function_ref<Value *(Instruction *)> Updater) {
13555 assert(isValid() && "Requires a valid canonical loop");
13556
13557 Instruction *OldIV = getIndVar();
13558
13559 // Record all uses excluding those introduced by the updater. Uses by the
13560 // CanonicalLoopInfo itself to keep track of the number of iterations are
13561 // excluded.
13562 SmallVector<Use *> ReplacableUses;
13563 for (Use &U : OldIV->uses()) {
13564 auto *User = dyn_cast<Instruction>(U.getUser());
13565 if (!User)
13566 continue;
13567 if (User->getParent() == getCond())
13568 continue;
13569 if (User->getParent() == getLatch())
13570 continue;
13571 ReplacableUses.push_back(&U);
13572 }
13573
13574 // Run the updater that may introduce new uses
13575 Value *NewIV = Updater(OldIV);
13576
13577 // Replace the old uses with the value returned by the updater.
13578 for (Use *U : ReplacableUses)
13579 U->set(NewIV);
13580
13581#ifndef NDEBUG
13582 assertOK();
13583#endif
13584}
13585
13587#ifndef NDEBUG
13588 // No constraints if this object currently does not describe a loop.
13589 if (!isValid())
13590 return;
13591
13592 bool IsVirtual = VirtualCollapse.has_value();
13593 BasicBlock *Preheader = getPreheader();
13594 BasicBlock *Init = getVirtualCollapseInit();
13595 BasicBlock *IndVarEntry = Preheader;
13596 if (IsVirtual) {
13597 auto *Guard = cast<CondBrInst>(Init->getTerminator());
13598 IndVarEntry = Guard->getSuccessor(0);
13599 assert(IndVarEntry->getSinglePredecessor() == Init);
13600 assert(IndVarEntry->getSingleSuccessor() == Header);
13601 assert(Guard->getSuccessor(1) == Exit);
13602 assert(VirtualCollapse->Begin->getParent() == Init);
13603 for (BinaryOperator *Copy :
13604 {VirtualCollapse->Begin, VirtualCollapse->Count}) {
13605 auto *Zero = dyn_cast<ConstantInt>(Copy->getOperand(1));
13606 assert(Copy->getOpcode() == Instruction::Add && Zero && Zero->isZero() &&
13607 "Virtual range copies must add zero");
13608 }
13609 auto *NonEmpty = cast<ICmpInst>(Guard->getCondition());
13610 assert(NonEmpty->getPredicate() == ICmpInst::ICMP_NE &&
13611 NonEmpty->getOperand(0) == VirtualCollapse->Count &&
13612 cast<ConstantInt>(NonEmpty->getOperand(1))->isZero() &&
13613 "Collapsed guard must skip empty ranges with zero count");
13614 }
13615
13616 // Validate the retained physical loop without exposing a logical body or IV.
13617 BasicBlock *Body =
13618 IsVirtual ? cast<CondBrInst>(Cond->getTerminator())->getSuccessor(0)
13619 : getBody();
13620 BasicBlock *After = getAfter();
13621
13622 // Verify standard control-flow we use for OpenMP loops.
13623 assert(Preheader);
13624 assert(isa<UncondBrInst>(Preheader->getTerminator()) &&
13625 "Preheader must terminate with unconditional branch");
13626 if (IsVirtual)
13627 assert(Preheader->getSingleSuccessor() == Init &&
13628 "Preheader must jump to collapsed initialization");
13629 else
13630 assert(Preheader->getSingleSuccessor() == Header &&
13631 "Preheader must jump to header");
13632
13633 assert(Header);
13634 assert(isa<UncondBrInst>(Header->getTerminator()) &&
13635 "Header must terminate with unconditional branch");
13636 assert(Header->getSingleSuccessor() == Cond &&
13637 "Header must jump to exiting block");
13638
13639 assert(Cond);
13640 assert(Cond->getSinglePredecessor() == Header &&
13641 "Exiting block only reachable from header");
13642
13643 assert(isa<CondBrInst>(Cond->getTerminator()) &&
13644 "Exiting block must terminate with conditional branch");
13645 assert(cast<CondBrInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
13646 "Exiting block's first successor jump to the body");
13647 assert(cast<CondBrInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
13648 "Exiting block's second successor must exit the loop");
13649
13650 assert(Body);
13651 assert(Body->getSinglePredecessor() == Cond &&
13652 "Body only reachable from exiting block");
13653 assert(!isa<PHINode>(Body->front()));
13654
13655 assert(Latch);
13656 assert(isa<UncondBrInst>(Latch->getTerminator()) &&
13657 "Latch must terminate with unconditional branch");
13658 assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
13659 // TODO: To support simple redirecting of the end of the body code that has
13660 // multiple; introduce another auxiliary basic block like preheader and after.
13661 assert(Latch->getSinglePredecessor() != nullptr);
13662 assert(!isa<PHINode>(Latch->front()));
13663
13664 assert(Exit);
13665 assert(isa<UncondBrInst>(Exit->getTerminator()) &&
13666 "Exit block must terminate with unconditional branch");
13667 assert(Exit->getSingleSuccessor() == After &&
13668 "Exit block must jump to after block");
13669
13670 assert(After);
13671 assert(After->getSinglePredecessor() == Exit &&
13672 "After block only reachable from exit block");
13673 assert(After->empty() || !isa<PHINode>(After->front()));
13674
13675 Instruction *IndVar = IsVirtual ? &Header->front() : getIndVar();
13676 assert(IndVar && "Canonical induction variable not found?");
13677 assert(isa<IntegerType>(IndVar->getType()) &&
13678 "Induction variable must be an integer");
13679 assert(cast<PHINode>(IndVar)->getParent() == Header &&
13680 "Induction variable must be a PHI in the loop header");
13681 assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == IndVarEntry);
13682 if (!IsVirtual)
13683 assert(cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))
13684 ->isZero());
13685 assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
13686
13687 auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
13688 assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
13689 assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
13690 assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
13691 assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
13692 ->isOne());
13693
13694 Value *TripCount =
13695 IsVirtual ? cast<CmpInst>(&Cond->front())->getOperand(1) : getTripCount();
13696 assert(TripCount && "Loop trip count not found?");
13697 assert(IndVar->getType() == TripCount->getType() &&
13698 "Trip count and induction variable must have the same type");
13699
13700 auto *CmpI = cast<CmpInst>(&Cond->front());
13701 assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
13702 "Exit condition must be a signed less-than comparison");
13703 assert(CmpI->getOperand(0) == IndVar &&
13704 "Exit condition must compare the induction variable");
13705 assert(CmpI->getOperand(1) == TripCount &&
13706 "Exit condition must compare with the trip count");
13707#endif
13708}
13709
13711 Header = nullptr;
13712 Cond = nullptr;
13713 Latch = nullptr;
13714 Exit = nullptr;
13715 VirtualCollapse.reset();
13716}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
@ ParamAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Hexagon Common GEP
Hexagon Hardware Loops
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define OMP_KERNEL_ARG_VERSION
Provides definitions for Target specific Grid Values.
static Value * removeASCastIfPresent(Value *V)
static void createTargetLoopWorkshareCall(OpenMPIRBuilder *OMPBuilder, WorksharingLoopType LoopType, BasicBlock *InsertBlock, Value *Ident, Value *LoopBodyArg, Value *TripCount, Function &LoopBodyFn, bool NoLoop)
Value * createFakeIntVal(IRBuilderBase &Builder, OpenMPIRBuilder::InsertPointTy OuterAllocaIP, llvm::SmallVectorImpl< Instruction * > &ToBeDeleted, OpenMPIRBuilder::InsertPointTy InnerAllocaIP, const Twine &Name="", bool AsPtr=true, bool Is64Bit=false)
static Function * createTargetParallelWrapper(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn)
Create wrapper function used to gather the outlined function's argument structure from a shared buffe...
static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL)
Make Source branch to Target.
static FunctionCallee getKmpcDistForStaticInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
static void applyParallelAccessesMetadata(CanonicalLoopInfo *CLI, LLVMContext &Ctx, Loop *Loop, LoopInfo &LoopInfo, SmallVector< Metadata * > &LoopMDList)
static void checkRuntimeCallDebugLocs(Module &M)
Assert that every direct call to an OpenMP runtime function in M has a debug location if its function...
static Expected< Function * > createOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, StringRef FuncName, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB, DebugLoc OutlinedFnLoc)
static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix, char ISA, StringRef ParSeq, StringRef MangledName, bool OutputBecomesInput, llvm::Function *Fn)
static FunctionCallee getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
Returns an LLVM function to call for finalizing the dynamic loop using depending on type.
static void FixupDebugInfoForOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Function *Func, DenseMap< Value *, std::tuple< Value *, unsigned > > &ValueReplacementMap)
static OMPScheduleType getOpenMPOrderingScheduleType(OMPScheduleType BaseScheduleType, bool HasOrderedClause)
Adds ordering modifier flags to schedule type.
static OMPScheduleType getOpenMPMonotonicityScheduleType(OMPScheduleType ScheduleType, bool HasSimdModifier, bool HasMonotonic, bool HasNonmonotonic, bool HasOrderedClause)
Adds monotonicity modifier flags to schedule type.
static std::string mangleVectorParameters(ArrayRef< llvm::OpenMPIRBuilder::DeclareSimdAttrTy > ParamAttrs)
Mangle the parameter part of the vector function name according to their OpenMP classification.
static bool isGenericKernel(Function &Fn)
static void workshareLoopTargetCallback(OpenMPIRBuilder *OMPIRBuilder, CanonicalLoopInfo *CLI, Value *Ident, Function &OutlinedFn, const SmallVector< Instruction *, 4 > &ToBeDeleted, WorksharingLoopType LoopType, bool NoLoop)
static bool isValidWorkshareLoopScheduleType(OMPScheduleType SchedType)
static bool isAtomicableReductionSet(ArrayRef< OpenMPIRBuilder::ReductionInfo > ReductionInfos)
static llvm::CallInst * emitNoUnwindRuntimeCall(IRBuilder<> &Builder, llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const llvm::Twine &Name)
static bool isRuntimeFunctionName(StringRef Name)
Return true if Name names an OpenMP runtime function.
static Error populateReductionFunction(Function *ReductionFunc, ArrayRef< OpenMPIRBuilder::ReductionInfo > ReductionInfos, IRBuilder<> &Builder, ArrayRef< bool > IsByRef, bool IsGPU)
static Function * getFreshReductionFunc(Module &M)
static void raiseUserConstantDataAllocasToEntryBlock(IRBuilderBase &Builder, Function *Function)
static FunctionCallee getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
Returns an LLVM function to call for updating the next loop using OpenMP dynamic scheduling depending...
static bool isConflictIP(IRBuilder<>::InsertPoint IP1, IRBuilder<>::InsertPoint IP2)
Return whether IP1 and IP2 are ambiguous, i.e.
static void checkReductionInfos(ArrayRef< OpenMPIRBuilder::ReductionInfo > ReductionInfos, bool IsGPU)
static Type * getOffloadingArrayType(Value *V)
static OMPScheduleType getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks, bool HasSimdModifier, bool HasDistScheduleChunks)
Determine which scheduling algorithm to use, determined from schedule clause arguments.
static OMPScheduleType computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks, bool HasSimdModifier, bool HasMonotonicModifier, bool HasNonmonotonicModifier, bool HasOrderedClause, bool HasDistScheduleChunks)
Determine the schedule type using schedule and ordering clause arguments.
static FunctionCallee getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
Returns an LLVM function to call for initializing loop bounds using OpenMP dynamic scheduling dependi...
static std::optional< omp::OMPTgtExecModeFlags > getTargetKernelExecMode(Function &Kernel)
Given a function, if it represents the entry point of a target kernel, this returns the execution mod...
static cl::opt< bool > UseDefaultMaxThreads("openmp-ir-builder-use-default-max-threads", cl::Hidden, cl::desc("Use a default max threads if none is provided."), cl::init(true))
static Error emitTargetOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, bool IsOffloadEntry, TargetRegionEntryInfo &EntryInfo, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, Function *&OutlinedFn, Constant *&OutlinedFnID, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB, DebugLoc OutlinedFnLoc)
static Value * emitTaskDependencies(OpenMPIRBuilder &OMPBuilder, const SmallVectorImpl< OpenMPIRBuilder::DependData > &Dependencies)
static void updateNVPTXAttr(Function &Kernel, StringRef Name, int32_t Value, bool Min)
static OpenMPIRBuilder::InsertPointTy getInsertPointAfterInstr(Instruction *I)
static void redirectAllPredecessorsTo(BasicBlock *OldTarget, BasicBlock *NewTarget, DebugLoc DL)
Redirect all edges that branch to OldTarget to NewTarget.
static void hoistNonEntryAllocasToEntryBlock(llvm::BasicBlock &Block)
static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
static void addAccessGroupMetadata(BasicBlock *Block, MDNode *AccessGroup, LoopInfo &LI)
Attach llvm.access.group metadata to the memref instructions of Block.
static void addBasicBlockMetadata(BasicBlock *BB, ArrayRef< Metadata * > Properties)
Attach metadata Properties to the basic block described by BB.
static void restoreIPandDebugLoc(llvm::IRBuilderBase &Builder, llvm::IRBuilderBase::InsertPoint IP)
This is a wrapper over IRBuilderBase::restoreIP that also restores a current debug location when the ...
static cl::opt< bool > OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden, cl::desc("Use optimistic attributes describing " "'as-if' properties of runtime calls."), cl::init(false))
static bool hasGridValue(const Triple &T)
static StructType * createTaskWithPrivatesTy(OpenMPIRBuilder &OMPIRBuilder, ArrayRef< Value * > OffloadingArraysToPrivatize, ArrayRef< Type * > DescriptorTypes)
static FunctionCallee getKmpcForStaticLoopForType(Type *Ty, OpenMPIRBuilder *OMPBuilder, WorksharingLoopType LoopType)
static const omp::GV & getGridValue(const Triple &T, Function *Kernel)
static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask, StringRef Prefix, char ISA, StringRef ParSeq, StringRef MangledName, bool OutputBecomesInput, llvm::Function *Fn)
static Error emitTargetCall(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Value *RTLocOverride, OpenMPIRBuilder::InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, OpenMPIRBuilder::TargetDataInfo &Info, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, const OpenMPIRBuilder::TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond, Function *OutlinedFn, Constant *OutlinedFnID, SmallVectorImpl< Value * > &Args, OpenMPIRBuilder::GenMapInfoCallbackTy GenMapInfoCB, OpenMPIRBuilder::CustomMapperCallbackTy CustomMapperCB, const OpenMPIRBuilder::DependenciesInfo &Dependencies, bool HasNoWait, Value *DynCGroupMem, OMPDynGroupprivateFallbackType DynCGroupMemFallback)
static LoadInst * loadSharedDataFromTaskDescriptor(IRBuilderBase &Builder, Value *TaskWithPrivates)
Given a task descriptor, TaskWithPrivates, return the pointer to the block of pointers containing sha...
static Function * emitTargetTaskProxyFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, CallInst *StaleCI, StructType *PrivatesTy, StructType *TaskWithPrivatesTy, const size_t NumOffloadingArrays, const int SharedArgsOperandNo)
Create an entry point for a target task with the following.
static void addLoopMetadata(CanonicalLoopInfo *Loop, ArrayRef< Metadata * > Properties)
Attach loop metadata Properties to the loop described by Loop.
static AtomicOrdering TransformReleaseAcquireRelease(AtomicOrdering AO)
static void removeUnusedBlocksFromParent(ArrayRef< BasicBlock * > BBs)
static void targetParallelCallback(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn, BasicBlock *OuterAllocaBB, Value *Ident, Value *IfCondition, Value *NumThreads, Instruction *PrivTID, AllocaInst *PrivTIDAddr, Value *ThreadID, const SmallVector< Instruction *, 4 > &ToBeDeleted)
static void hostParallelCallback(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn, Value *Ident, Value *IfCondition, Instruction *PrivTID, AllocaInst *PrivTIDAddr, const SmallVector< Instruction *, 4 > &ToBeDeleted)
#define P(N)
FunctionAnalysisManager FAM
Function * Fun
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file implements the SmallBitVector class.
This file defines the SmallSet class.
This file defines less commonly used SmallVector utilities.
This file contains some functions that are useful when dealing with strings.
StringSet - A set-like wrapper for the StringMap.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
The Input class is used to parse a yaml document into in-memory structs and vectors.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getUnsigned(uint64_t X)
Definition APSInt.h:349
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
void setWeak(bool IsWeak)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
LLVM_ABI std::pair< LoadInst *, AllocaInst * > EmitAtomicLoadLibcall(AtomicOrdering AO)
Definition Atomic.cpp:109
LLVM_ABI void EmitAtomicStoreLibcall(AtomicOrdering AO, Value *Source)
Definition Atomic.cpp:150
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
LLVM_ABI AttributeSet addAttributes(LLVMContext &C, AttributeSet AS) const
Add attributes to the attribute set.
LLVM_ABI AttributeSet addAttribute(LLVMContext &C, Attribute::AttrKind Kind) const
Add an argument attribute.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator end()
Definition BasicBlock.h:452
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
reverse_iterator rbegin()
Definition BasicBlock.h:455
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:231
bool empty() const
Definition BasicBlock.h:461
const Instruction & back() const
Definition BasicBlock.h:464
LLVM_ABI BasicBlock * splitBasicBlockBefore(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction and insert the new basic blo...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:462
InstListType::reverse_iterator reverse_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
const Instruction * getTerminatorOrNull() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:247
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI void insertInto(Function *Parent, BasicBlock *InsertBefore=nullptr)
Insert unlinked basic block into a function.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
reverse_iterator rend()
Definition BasicBlock.h:457
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:366
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:637
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
void setDoesNotThrow()
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
Class to represented the control flow structure of an OpenMP canonical loop.
Value * getTripCount() const
Returns the llvm::Value containing the number of loop iterations.
BasicBlock * getHeader() const
The header is the entry for each iteration.
LLVM_ABI void assertOK() const
Consistency self-check.
Type * getIndVarType() const
Return the type of the induction variable (and the trip count).
BasicBlock * getBody() const
The body block is the single entry for a loop iteration and not controlled by CanonicalLoopInfo.
bool isValid() const
Returns whether this object currently represents the IR of a loop.
void setLastIter(Value *IterVar)
Sets the last iteration variable for this loop.
OpenMPIRBuilder::InsertPointTy getAfterIP() const
Return the insertion point for user code after the loop.
OpenMPIRBuilder::InsertPointTy getBodyIP() const
Return the insertion point for user code in the body.
BasicBlock * getAfter() const
The after block is intended for clean-up code such as lifetime end markers.
Function * getFunction() const
LLVM_ABI void invalidate()
Invalidate this loop.
BasicBlock * getLatch() const
Reaching the latch indicates the end of the loop body code.
OpenMPIRBuilder::InsertPointTy getPreheaderIP() const
Return the insertion point for user code before the loop.
BasicBlock * getCond() const
The condition block computes whether there is another loop iteration.
BasicBlock * getExit() const
Reaching the exit indicates no more iterations are being executed.
LLVM_ABI BasicBlock * getPreheader() const
The preheader ensures that there is only a single edge entering the loop.
Instruction * getIndVar() const
Returns the instruction representing the current logical induction variable.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
A cache for the CodeExtractor analysis.
Utility class for extracting code into a new function.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
DILocalScope * getScope() const
Get the local scope for this variable.
DINodeArray getAnnotations() const
DIFile * getFile() const
Subprogram description. Uses SubclassData1.
Base class for types.
uint32_t getAlignInBits() const
DIFile * getFile() const
DIType * getType() const
unsigned getLine() const
StringRef getName() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:581
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Represents either an error or a value T.
Definition ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:641
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const BasicBlock & getEntryBlock() const
Definition Function.h:803
Argument * arg_iterator
Definition Function.h:73
bool empty() const
Definition Function.h:853
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition Function.cpp:447
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
DISubprogram * getSubprogram() const
Get the attached subprogram.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
const Function & getFunction() const
Definition Function.h:167
iterator begin()
Definition Function.h:847
arg_iterator arg_begin()
Definition Function.h:862
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:669
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Definition Function.h:749
size_t arg_size() const
Definition Function.h:895
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
iterator end()
Definition Function.h:849
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
Argument * getArg(unsigned i) const
Definition Function.h:880
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LinkageTypes getLinkage() const
void setLinkage(LinkageTypes LT)
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
InsertPoint saveIP() const
Returns the current insert point.
Definition IRBuilder.h:257
BasicBlock::iterator InsertPoint
InsertPoint - A saved insertion point.
Definition IRBuilder.h:254
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
Definition IRBuilder.h:267
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
user_iterator user_end()
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class represents a loop nest and can be used to query its properties.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI MDNode * createCallbackEncoding(unsigned CalleeArgNo, ArrayRef< int > Arguments, bool VarArgsArePassed)
Return metadata describing a callback (see llvm::AbstractCallSite).
Metadata node.
Definition Metadata.h:1087
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1596
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
size_type size() const
Definition MapVector.h:59
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:325
A tuple of MDNodes.
Definition Metadata.h:1806
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
LLVM_ABI void addOperand(MDNode *M)
Class that manages information about offload code regions and data.
function_ref< void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)> OffloadDeviceGlobalVarEntryInfoActTy
Applies action Action on all registered entries.
OMPTargetDeviceClauseKind
Kind of device clause for declare target variables and functions NOTE: Currently not used as a part o...
@ OMPTargetDeviceClauseAny
The target is marked for all devices.
LLVM_ABI void registerDeviceGlobalVarEntryInfo(StringRef VarName, Constant *Addr, int64_t VarSize, OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage)
Register device global variable entry.
LLVM_ABI void initializeDeviceGlobalVarEntryInfo(StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order)
Initialize device global variable entry.
LLVM_ABI void actOnDeviceGlobalVarEntriesInfo(const OffloadDeviceGlobalVarEntryInfoActTy &Action)
OMPTargetRegionEntryKind
Kind of the target registry entry.
@ OMPTargetRegionEntryTargetRegion
Mark the entry as target region.
LLVM_ABI void getTargetRegionEntryFnName(SmallVectorImpl< char > &Name, const TargetRegionEntryInfo &EntryInfo)
LLVM_ABI bool hasTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId=false) const
Return true if a target region entry with the provided information exists.
LLVM_ABI void registerTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID, OMPTargetRegionEntryKind Flags)
Register target region entry.
LLVM_ABI void actOnTargetRegionEntriesInfo(const OffloadTargetRegionEntryInfoActTy &Action)
LLVM_ABI void initializeTargetRegionEntryInfo(const TargetRegionEntryInfo &EntryInfo, unsigned Order)
Initialize target region entry.
OMPTargetGlobalVarEntryKind
Kind of the global variable entry..
@ OMPTargetGlobalVarEntryEnter
Mark the entry as a declare target enter.
@ OMPTargetGlobalRegisterRequires
Mark the entry as a register requires global.
@ OMPTargetGlobalVarEntryIndirect
Mark the entry as a declare target indirect global.
@ OMPTargetGlobalVarEntryLink
Mark the entry as a to declare target link.
@ OMPTargetGlobalVarEntryTo
Mark the entry as a to declare target.
@ OMPTargetGlobalVarEntryIndirectVTable
Mark the entry as a declare target indirect vtable.
function_ref< void(const TargetRegionEntryInfo &EntryInfo, const OffloadEntryInfoTargetRegion &)> OffloadTargetRegionEntryInfoActTy
brief Applies action Action on all registered entries.
bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const
Checks if the variable with the given name has been registered already.
LLVM_ABI bool empty() const
Return true if a there are no entries defined.
std::optional< bool > IsTargetDevice
Flag to define whether to generate code for the role of the OpenMP host (if set to false) or device (...
std::optional< bool > IsGPU
Flag for specifying if the compilation is done for an accelerator.
LLVM_ABI int64_t getRequiresFlags() const
Returns requires directive clauses as flags compatible with those expected by libomptarget.
std::optional< bool > OpenMPOffloadMandatory
Flag for specifying if offloading is mandatory.
LLVM_ABI void setHasRequiresReverseOffload(bool Value)
LLVM_ABI bool hasRequiresUnifiedSharedMemory() const
LLVM_ABI void setHasRequiresUnifiedSharedMemory(bool Value)
unsigned getDefaultTargetAS() const
LLVM_ABI bool hasRequiresDynamicAllocators() const
LLVM_ABI void setHasRequiresUnifiedAddress(bool Value)
LLVM_ABI void setHasRequiresDynamicAllocators(bool Value)
LLVM_ABI bool hasRequiresReverseOffload() const
LLVM_ABI bool hasRequiresUnifiedAddress() const
Struct that keeps the information that should be kept throughout a 'target data' region.
An interface to create LLVM-IR for OpenMP directives.
LLVM_ABI InsertPointOrErrorTy createOrderedThreadsSimd(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsThreads)
Generator for 'omp ordered [threads | simd]'.
LLVM_ABI void emitAArch64DeclareSimdFunction(llvm::Function *Fn, unsigned VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch, char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput)
Emit AArch64 vector-function ABI attributes for a declare simd function.
LLVM_ABI Constant * getOrCreateIdent(Constant *SrcLocStr, uint32_t SrcLocStrSize, omp::IdentFlag Flags=omp::IdentFlag(0), unsigned Reserve2Flags=0)
Return an ident_t* encoding the source location SrcLocStr and Flags.
LLVM_ABI void emitFlush(const LocationDescription &Loc, AtomicOrdering AO=AtomicOrdering::SequentiallyConsistent, AtomicScope Scope=AtomicScope::Device)
Generate a flush: a fence on a GPU, and a runtime call otherwise.
LLVM_ABI void registerDeclareTargetGlobalReplacement(GlobalValue *Original, GlobalValue *Replacement)
Register a module-scope replacement of a declare target global variable.
LLVM_ABI FunctionCallee getOrCreateRuntimeFunction(Module &M, omp::RuntimeFunction FnID)
Return the function declaration for the runtime function with FnID.
LLVM_ABI InsertPointOrErrorTy createCancel(const LocationDescription &Loc, Value *IfCondition, omp::Directive CanceledDirective)
Generator for 'omp cancel'.
std::function< Expected< Function * >(StringRef FunctionName)> FunctionGenCallback
Functions used to generate a function with the given name.
LLVM_ABI CallInst * createOMPAllocShared(const LocationDescription &Loc, Value *Size, const Twine &Name=Twine(""))
Create a runtime call for kmpc_alloc_shared.
ReductionGenCBKind
Enum class for the RedctionGen CallBack type to be used.
LLVM_ABI CanonicalLoopInfo * collapseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, InsertPointTy ComputeIP)
Collapse a loop nest using Config.CollapseMapping.
LLVM_ABI void createTaskyield(const LocationDescription &Loc)
Generator for 'omp taskyield'.
std::function< Error(InsertPointTy CodeGenIP)> FinalizeCallbackTy
Callback type for variable finalization (think destructors).
LLVM_ABI void emitBranch(BasicBlock *Target)
LLVM_ABI Error emitCancelationCheckImpl(Value *CancelFlag, omp::Directive CanceledDirective)
Generate control flow and cleanup for cancellation.
static LLVM_ABI void writeThreadBoundsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc)
Generate a taskwait runtime call.
LLVM_ABI Constant * registerTargetRegionFunction(TargetRegionEntryInfo &EntryInfo, Function *OutlinedFunction, StringRef EntryFnName, StringRef EntryFnIDName)
Registers the given function and sets up the attribtues of the function Returns the FunctionID.
LLVM_ABI GlobalVariable * emitKernelExecutionMode(StringRef KernelName, omp::OMPTgtExecModeFlags Mode)
Emit the kernel execution mode.
LLVM_ABI void initialize()
Initialize the internal state, this will put structures types and potentially other helpers into the ...
LLVM_ABI InsertPointTy createAtomicCompare(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO, omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly, bool IsWeak=false)
LLVM_ABI InsertPointTy createAtomicWrite(const LocationDescription &Loc, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic write for : X = Expr — Only Scalar data types.
LLVM_ABI void loadOffloadInfoMetadata(Module &M)
Loads all the offload entries information from the host IR metadata.
function_ref< MapInfosTy &(InsertPointTy CodeGenIP)> GenMapInfoCallbackTy
Callback type for creating the map infos for the kernel parameters.
LLVM_ABI Error emitOffloadingArrays(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Emit the arrays used to pass the captures and map information to the offloading runtime library.
LLVM_ABI void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully unroll a loop.
function_ref< Error(InsertPointTy CodeGenIP, Value *IndVar)> LoopBodyGenCallbackTy
Callback type for loop body code generation.
LLVM_ABI InsertPointOrErrorTy emitScanReduction(const LocationDescription &Loc, ArrayRef< llvm::OpenMPIRBuilder::ReductionInfo > ReductionInfos, ScanInfo *ScanRedInfo)
This function performs the scan reduction of the values updated in the input phase.
LLVM_ABI InsertPointOrErrorTy createScope(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsNowait)
Generator for 'omp scope'.
static LLVM_ABI std::pair< int32_t, int32_t > readThreadBoundsForKernel(const Triple &T, Function &Kernel)
}
OpenMPIRBuilderConfig Config
The OpenMPIRBuilder Configuration.
LLVM_ABI CallInst * createOMPInteropDestroy(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_destroy.
LLVM_ABI void emitUsed(StringRef Name, ArrayRef< llvm::WeakTrackingVH > List)
Emit the llvm.used metadata.
LLVM_ABI InsertPointOrErrorTy createSingle(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsNowait, ArrayRef< llvm::Value * > CPVars={}, ArrayRef< llvm::Function * > CPFuncs={})
Generator for 'omp single'.
LLVM_ABI InsertPointOrErrorTy createTarget(const LocationDescription &Loc, bool IsOffloadEntry, OpenMPIRBuilder::InsertPointTy AllocaIP, OpenMPIRBuilder::InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks, TargetDataInfo &Info, TargetRegionEntryInfo &EntryInfo, const TargetKernelDefaultAttrs &DefaultAttrs, const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond, SmallVectorImpl< Value * > &Inputs, GenMapInfoCallbackTy GenMapInfoCB, TargetBodyGenCallbackTy BodyGenCB, TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB, CustomMapperCallbackTy CustomMapperCB, const DependenciesInfo &Dependencies={}, bool HasNowait=false, Value *DynCGroupMem=nullptr, omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback=omp::OMPDynGroupprivateFallbackType::Abort, DebugLoc OutlinedFnLoc={}, Value *RTLocOverride=nullptr)
Generator for 'omp target'.
LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, Value *NumTeamsLower=nullptr, Value *NumTeamsUpper=nullptr, Value *ThreadLimit=nullptr, Value *IfExpr=nullptr)
Generator for #omp teams
std::forward_list< CanonicalLoopInfo > LoopInfos
Collection of owned canonical loop objects that eventually need to be free'd.
LLVM_ABI llvm::StructType * getKmpTaskAffinityInfoTy()
Return the LLVM struct type matching runtime kmp_task_affinity_info_t.
LLVM_ABI Constant * emitKernelEnvironment(const LocationDescription &Loc, const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
The omp target interface.
LLVM_ABI std::string createPlatformSpecificName(ArrayRef< StringRef > Parts) const
Get the create a name using the platform specific separators.
LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_next_* runtime function for the specified size IVSize and sign IVSigned.
static LLVM_ABI void getKernelArgsVector(TargetKernelArgs &KernelArgs, IRBuilderBase &Builder, SmallVector< Value * > &ArgsVector)
Create the kernel args vector used by emitTargetKernel.
LLVM_ABI void createFlush(const LocationDescription &Loc, AtomicOrdering AO=AtomicOrdering::SequentiallyConsistent, AtomicScope Scope=AtomicScope::Device)
Generator for 'omp flush'.
LLVM_ABI void unrollLoopHeuristic(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully or partially unroll a loop.
LLVM_ABI omp::OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position)
Get OMP_MAP_MEMBER_OF flag with extra bits reserved based on the position given.
LLVM_ABI void addAttributes(omp::RuntimeFunction FnID, Function &Fn)
Add attributes known for FnID to Fn.
LLVM_ABI Expected< Function * > emitUserDefinedMapper(function_ref< MapInfosOrErrorTy(InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)> PrivAndGenMapInfoCB, llvm::Type *ElemTy, StringRef FuncName, CustomMapperCallbackTy CustomMapperCB, bool PreserveMemberOfFlags=false, bool PropagatePresentToPointeeStorage=false, bool PropagatePresentToNonPointeeStorage=false)
Emit the user-defined mapper function.
Module & M
The underlying LLVM-IR module.
StringMap< Constant * > SrcLocStrMap
Map to remember source location strings.
LLVM_ABI void createMapperAllocas(const LocationDescription &Loc, InsertPointTy AllocaIP, unsigned NumOperands, struct MapperAllocas &MapperAllocas)
Create the allocas instruction used in call to mapper functions.
SmallVector< DeclareTargetGlobalReplacement, 8 > DeclareTargetGlobalReplacements
Collection of declare target globals to rewrite uses of during device module finalizaiton.
LLVM_ABI Constant * getOrCreateSrcLocStr(StringRef LocStr, uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the source location LocStr.
LLVM_ABI Error emitTargetRegionFunction(TargetRegionEntryInfo &EntryInfo, FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry, Function *&OutlinedFn, Constant *&OutlinedFnID)
Create a unique name for the entry function using the source location information of the current targ...
LLVM_ABI InsertPointOrErrorTy createIteratorLoop(LocationDescription Loc, llvm::Value *TripCount, IteratorBodyGenTy BodyGen, llvm::StringRef Name="iterator")
Create a canonical iterator loop at the current insertion point.
LLVM_ABI Expected< SmallVector< llvm::CanonicalLoopInfo * > > createCanonicalScanLoops(const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB, Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop, InsertPointTy ComputeIP, const Twine &Name, ScanInfo *ScanRedInfo)
Generator for the control flow structure of an OpenMP canonical loops if the parent directive has an ...
LLVM_ABI FunctionCallee createDispatchFiniFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_fini_* runtime function for the specified size IVSize and sign IVSigned.
function_ref< InsertPointOrErrorTy( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks)> TargetBodyGenCallbackTy
LLVM_ABI void unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop, int32_t Factor, CanonicalLoopInfo **UnrolledCLI)
Partially unroll a loop.
function_ref< Error(Value *DeviceID, Value *RTLoc, IRBuilderBase::InsertPoint TargetTaskAllocaIP)> TargetTaskBodyCallbackTy
Callback type for generating the bodies of device directives that require outer target tasks (e....
Expected< MapInfosTy & > MapInfosOrErrorTy
bool HandleFPNegZero
Emit atomic compare for constructs: — Only scalar data types cond-expr-stmt: x = x ordop expr ?
LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc)
Generate a taskyield runtime call.
LLVM_ABI void emitMapperCall(const LocationDescription &Loc, Function *MapperFunc, Value *SrcLocInfo, Value *MaptypesArg, Value *MapnamesArg, struct MapperAllocas &MapperAllocas, int64_t DeviceID, unsigned NumOperands)
Create the call for the target mapper function.
LLVM_ABI InsertPointOrErrorTy createDistribute(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB)
Generator for #omp distribute
function_ref< Expected< Function * >(unsigned int)> CustomMapperCallbackTy
LLVM_ABI InsertPointTy createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP, unsigned NumLoops, ArrayRef< llvm::Value * > StoreValues, const Twine &Name, bool IsDependSource)
Generator for 'omp ordered depend (source | sink)'.
LLVM_ABI InsertPointTy createCopyinClauseBlocks(InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr, llvm::IntegerType *IntPtrTy, bool BranchtoEnd=true)
Generate conditional branch and relevant BasicBlocks through which private threads copy the 'copyin' ...
function_ref< InsertPointOrErrorTy( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original, Value &Inner, Value *&ReplVal)> PrivatizeCallbackTy
Callback type for variable privatization (think copy & default constructor).
LLVM_ABI bool isFinalized()
Check whether the finalize function has already run.
SmallVector< FinalizationInfo, 8 > FinalizationStack
The finalization stack made up of finalize callbacks currently in-flight, wrapped into FinalizationIn...
LLVM_ABI std::vector< CanonicalLoopInfo * > tileLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, ArrayRef< Value * > TileSizes)
Tile a loop nest.
LLVM_ABI CallInst * createOMPInteropInit(const LocationDescription &Loc, Value *InteropVar, omp::OMPInteropType InteropType, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_init.
LLVM_ABI Error emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen, BodyGenCallbackTy ElseGen, InsertPointTy AllocaIP={}, ArrayRef< BasicBlock * > DeallocBlocks={})
Emits code for OpenMP 'if' clause using specified BodyGenCallbackTy Here is the logic: if (Cond) { Th...
LLVM_ABI void finalize(Function *Fn=nullptr)
Finalize the underlying module, e.g., by outlining regions.
LLVM_ABI Function * getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID)
void addOutlineInfo(std::unique_ptr< OutlineInfo > &&OI)
Add a new region that will be outlined later.
LLVM_ABI InsertPointTy createTargetInit(const LocationDescription &Loc, const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
Create a runtime call for kmpc_target_init.
LLVM_ABI InsertPointOrErrorTy createReductions(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< ReductionInfo > ReductionInfos, ArrayRef< bool > IsByRef, bool IsNoWait=false, bool IsTeamsReduction=false)
Generator for 'omp reduction'.
const Triple T
The target triple of the underlying module.
DenseMap< std::pair< Constant *, uint64_t >, Constant * > IdentMap
Map to remember existing ident_t*.
LLVM_ABI CallInst * createOMPFree(const LocationDescription &Loc, Value *Addr, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_free.
LLVM_ABI InsertPointOrErrorTy createReductionsGPU(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< ReductionInfo > ReductionInfos, ArrayRef< bool > IsByRef, bool IsNoWait=false, bool IsTeamsReduction=false, bool IsSPMD=false, ReductionGenCBKind ReductionGenCBKind=ReductionGenCBKind::MLIR, std::optional< omp::GV > GridValue={}, Value *SrcLocInfo=nullptr)
Design of OpenMP reductions on the GPU.
LLVM_ABI FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned, bool IsGPUDistribute)
Returns __kmpc_for_static_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI CallInst * createOMPAlloc(const LocationDescription &Loc, Value *Size, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_alloc.
LLVM_ABI void emitNonContiguousDescriptor(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info)
Emit an array of struct descriptors to be assigned to the offload args.
LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB)
Generator for 'omp section'.
LLVM_ABI InsertPointOrErrorTy createTaskgroup(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB)
Generator for the taskgroup construct.
LLVM_ABI InsertPointOrErrorTy createParallel(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable)
Generator for 'omp parallel'.
function_ref< InsertPointOrErrorTy(InsertPointTy)> EmitFallbackCallbackTy
Callback function type for functions emitting the host fallback code that is executed when the kernel...
static LLVM_ABI TargetRegionEntryInfo getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack, vfs::FileSystem &VFS, StringRef ParentName="")
Creates a unique info for a target entry when provided a filename and line number from.
LLVM_ABI void emitTaskDependency(IRBuilderBase &Builder, Value *Entry, const DependData &Dep)
Store one kmp_depend_info entry at the given Entry pointer.
LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn, bool IsFinished=false)
LLVM_ABI Value * getOrCreateThreadID(Value *Ident)
Return the current thread ID.
LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB)
Generator for 'omp master'.
LLVM_ABI InsertPointOrErrorTy createTargetData(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks, Value *DeviceID, Value *IfCond, TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB, omp::RuntimeFunction *MapperFunc=nullptr, function_ref< InsertPointOrErrorTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)> BodyGenCB=nullptr, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr, Value *SrcLocInfo=nullptr)
Generator for 'omp target data'.
LLVM_ABI InsertPointOrErrorTy emitKernelLaunch(const LocationDescription &Loc, Value *OutlinedFnID, EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args, Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP)
Generate a target region entry call and host fallback call.
StringMap< GlobalVariable *, BumpPtrAllocator > InternalVars
An ordered map of auto-generated variables to their unique names.
LLVM_ABI InsertPointOrErrorTy createCancellationPoint(const LocationDescription &Loc, omp::Directive CanceledDirective)
Generator for 'omp cancellation point'.
LLVM_ABI CallInst * createOMPAlignedAlloc(const LocationDescription &Loc, Value *Align, Value *Size, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_align_alloc.
LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< llvm::Value * > ScanVars, ArrayRef< llvm::Type * > ScanVarsType, bool IsInclusive, ScanInfo *ScanRedInfo)
This directive split and directs the control flow to input phase blocks or scan phase blocks based on...
LLVM_ABI CallInst * createOMPFreeShared(const LocationDescription &Loc, Value *Addr, Value *Size, const Twine &Name=Twine(""))
Create a runtime call for kmpc_free_shared.
LLVM_ABI CallInst * createOMPInteropUse(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_use.
IRBuilder<>::InsertPoint InsertPointTy
Type used throughout for insertion points.
LLVM_ABI GlobalVariable * getOrCreateInternalVariable(Type *Ty, const StringRef &Name, std::optional< unsigned > AddressSpace={})
Gets (if variable with the given name already exist) or creates internal global variable with the spe...
LLVM_ABI GlobalVariable * createOffloadMapnames(SmallVectorImpl< llvm::Constant * > &Names, std::string VarName)
Create the global variable holding the offload names information.
LLVM_ABI InsertPointOrErrorTy createTask(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB, bool Tied=true, Value *Final=nullptr, Value *IfCondition=nullptr, const DependenciesInfo &Dependencies={}, const AffinityData &Affinities={}, bool Mergeable=false, Value *EventHandle=nullptr, Value *Priority=nullptr, bool FreeAgent=false)
Generator for #omp taskloop
std::forward_list< ScanInfo > ScanInfos
Collection of owned ScanInfo objects that eventually need to be free'd.
static LLVM_ABI void writeTeamsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
LLVM_ABI Value * calculateCanonicalLoopTripCount(const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop, const Twine &Name="loop")
Calculate the trip count of a canonical loop.
LLVM_ABI InsertPointOrErrorTy createBarrier(const LocationDescription &Loc, omp::Directive Kind, bool ForceSimpleCall=false, bool CheckCancelFlag=true)
Emitter methods for OpenMP directives.
LLVM_ABI void setCorrectMemberOfFlag(omp::OpenMPOffloadMappingFlags &Flags, omp::OpenMPOffloadMappingFlags MemberOfFlag)
Given an initial flag set, this function modifies it to contain the passed in MemberOfFlag generated ...
LLVM_ABI Error emitOffloadingArraysAndArgs(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info, TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, bool ForEndCall=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Allocates memory for and populates the arrays required for offloading (offload_{baseptrs|ptrs|mappers...
LLVM_ABI Constant * getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the default source location.
LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst)
Generator for 'omp critical'.
LLVM_ABI void createError(const LocationDescription &Loc, bool IsFatal, Value *Message)
Generate a call to the runtime to emit the diagnostic of an OpenMP error directive with at(execution)...
LLVM_ABI void createOffloadEntry(Constant *ID, Constant *Addr, uint64_t Size, int32_t Flags, GlobalValue::LinkageTypes, StringRef Name="")
Creates offloading entry for the provided entry ID ID, address Addr, size Size, and flags Flags.
static LLVM_ABI unsigned getOpenMPDefaultSimdAlign(const Triple &TargetTriple, const StringMap< bool > &Features)
Get the default alignment value for given target.
LLVM_ABI unsigned getFlagMemberOffset()
Get the offset of the OMP_MAP_MEMBER_OF field.
LLVM_ABI InsertPointOrErrorTy createAtomicCapture(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, AtomicOpValue &V, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: — Only Scalar data types V = X; X = X BinOp Expr ,...
LLVM_ABI CanonicalLoopInfo * createLoopSkeleton(DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore, BasicBlock *PostInsertBefore, const Twine &Name={}, bool IsCollapsed=false)
Create the control flow structure of a canonical OpenMP loop.
LLVM_ABI void createOffloadEntriesAndInfoMetadata(EmitMetadataErrorReportFunctionTy &ErrorReportFunction)
LLVM_ABI void applySimd(CanonicalLoopInfo *Loop, MapVector< Value *, Value * > AlignedVars, Value *IfCond, omp::OrderKind Order, ConstantInt *Simdlen, ConstantInt *Safelen)
Add metadata to simd-ize a loop.
SmallVector< std::unique_ptr< OutlineInfo >, 16 > OutlineInfos
Collection of regions that need to be outlined during finalization.
LLVM_ABI InsertPointOrErrorTy createAtomicUpdate(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X For complex Operations: X = ...
std::function< std::tuple< std::string, uint64_t >()> FileIdentifierInfoCallbackTy
bool isLastFinalizationInfoCancellable(omp::Directive DK)
Return true if the last entry in the finalization stack is of kind DK and cancellable.
LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return, Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads, Value *HostPtr, ArrayRef< Value * > KernelArgs)
Generate a target region entry call.
LLVM_ABI GlobalVariable * createOffloadMaptypes(SmallVectorImpl< uint64_t > &Mappings, std::string VarName)
Create the global variable holding the offload mappings information.
LLVM_ABI CallInst * createCachedThreadPrivate(const LocationDescription &Loc, llvm::Value *Pointer, llvm::ConstantInt *Size, const llvm::Twine &Name=Twine(""))
Create a runtime call for kmpc_threadprivate_cached.
IRBuilder Builder
The LLVM-IR Builder used to create IR.
LLVM_ABI GlobalValue * createGlobalFlag(unsigned Value, StringRef Name)
Create a hidden global flag Name in the module with initial value Value.
LLVM_ABI void emitOffloadingArraysArgument(IRBuilderBase &Builder, OpenMPIRBuilder::TargetDataRTArgs &RTArgs, OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall=false)
Emit the arguments to be passed to the runtime library based on the arrays of base pointers,...
LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, Value *Filter)
Generator for 'omp masked'.
LLVM_ABI Expected< CanonicalLoopInfo * > createCanonicalLoop(const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB, Value *TripCount, const Twine &Name="loop")
Generator for the control flow structure of an OpenMP canonical loop.
function_ref< Expected< InsertPointTy >( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value *DestPtr, Value *SrcPtr)> TaskDupCallbackTy
Callback type for task duplication function code generation.
LLVM_ABI Value * getSizeInBytes(Value *BasePtr)
Computes the size of type in bytes.
llvm::function_ref< llvm::Error( InsertPointTy BodyIP, llvm::Value *LinearIV)> IteratorBodyGenTy
LLVM_ABI FunctionCallee createDispatchDeinitFunction()
Returns __kmpc_dispatch_deinit runtime function.
LLVM_ABI void registerTargetGlobalVariable(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy, Constant *Addr)
Registers a target variable for device or host.
LLVM_ABI void createTargetDeinit(const LocationDescription &Loc, int32_t TeamsReductionDataSize=0)
Create a runtime call for kmpc_target_deinit.
BodyGenTy
Type of BodyGen to use for region codegen.
LLVM_ABI CanonicalLoopInfo * fuseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops)
Fuse a sequence of loops.
LLVM_ABI void emitX86DeclareSimdFunction(llvm::Function *Fn, unsigned NumElements, const llvm::APSInt &VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch)
Emit x86 vector-function ABI attributes for a declare simd function.
SmallVector< llvm::Function *, 16 > ConstantAllocaRaiseCandidates
A collection of candidate target functions that's constant allocas will attempt to be raised on a cal...
OffloadEntriesInfoManager OffloadInfoManager
Info manager to keep track of target regions.
static LLVM_ABI std::pair< int32_t, int32_t > readTeamBoundsForKernel(const Triple &T, Function &Kernel)
Read/write a bounds on teams for Kernel.
const std::string ompOffloadInfoName
OMP Offload Info Metadata name string.
LLVM_ABI InsertPointOrErrorTy applyWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP, bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind=llvm::omp::OMP_SCHEDULE_Default, Value *ChunkSize=nullptr, bool HasSimdModifier=false, bool HasMonotonicModifier=false, bool HasNonmonotonicModifier=false, bool HasOrderedClause=false, omp::WorksharingLoopType LoopType=omp::WorksharingLoopType::ForStaticLoop, bool NoLoop=false, bool HasDistSchedule=false, Value *DistScheduleChunkSize=nullptr, bool NeedsLastIter=false)
Modifies the canonical loop to be a workshare loop.
Expected< InsertPointTy > InsertPointOrErrorTy
Type used to represent an insertion point or an error value.
LLVM_ABI InsertPointTy createCopyPrivate(const LocationDescription &Loc, llvm::Value *BufSize, llvm::Value *CpyBuf, llvm::Value *CpyFn, llvm::Value *DidIt)
Generator for __kmpc_copyprivate.
LLVM_ABI InsertPointOrErrorTy createSections(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< StorableBodyGenCallbackTy > SectionCBs, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait)
Generator for 'omp sections'.
std::function< void(EmitMetadataErrorKind, TargetRegionEntryInfo)> EmitMetadataErrorReportFunctionTy
Callback function type.
function_ref< InsertPointOrErrorTy( Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< InsertPointTy > DeallocIPs)> TargetGenArgAccessorsCallbackTy
LLVM_ABI Expected< ScanInfo * > scanInfoInitialize()
Creates a ScanInfo object, allocates and returns the pointer.
LLVM_ABI InsertPointOrErrorTy emitTargetTask(TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP, const DependenciesInfo &Dependencies, const TargetDataRTArgs &RTArgs, bool HasNoWait)
Generate a target-task for the target construct.
LLVM_ABI InsertPointTy createAtomicRead(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic Read for : V = X — Only Scalar data types.
LLVM_ABI CallInst * createRuntimeFunctionCall(FunctionCallee Callee, ArrayRef< Value * > Args, const Twine &Name="")
function_ref< Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks)> BodyGenCallbackTy
Callback type for body (=inner region) code generation.
bool updateToLocation(const LocationDescription &Loc)
Update the internal location to Loc.
LLVM_ABI Constant * getAddrOfDeclareTargetVar(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, Type *LlvmPtrTy, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage)
Retrieve (or create if non-existent) the address of a declare target variable, used in conjunction wi...
LLVM_ABI void createTaskwait(const LocationDescription &Loc, DependenciesInfo Dependencies={}, bool IsNowait=false)
Generator for 'omp taskwait'.
origPtr *with the address space normalization required by the runtime entry point *The NULL descriptor makes the runtime walk the enclosing taskgroups to *find the matching task_reduction registration for the item The lookups *are emitted at p Loc
EmitMetadataErrorKind
The kind of errors that can occur when emitting the offload entries and metadata.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Pseudo-analysis pass that exposes the PassInstrumentation to pass managers.
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
ScanInfo holds the information to assist in lowering of Scan reduction.
llvm::SmallDenseMap< llvm::Value *, llvm::Value * > * ScanBuffPtrs
Maps the private reduction variable to the pointer of the temporary buffer.
llvm::BasicBlock * OMPScanLoopExit
Exit block of loop body.
llvm::Value * IV
Keeps track of value of iteration variable for input/scan loop to be used for Scan directive lowering...
llvm::BasicBlock * OMPAfterScanBlock
Dominates the body of the loop before scan directive.
llvm::BasicBlock * OMPScanInit
Block before loop body where scan initializations are done.
llvm::BasicBlock * OMPBeforeScanBlock
Dominates the body of the loop before scan directive.
llvm::BasicBlock * OMPScanFinish
Block after loop body where scan finalizations are done.
llvm::Value * Span
Stores the span of canonical loop being lowered to be used for temporary buffer allocation or Finaliz...
bool OMPFirstScanLoop
If true, it indicates Input phase is lowered; else it indicates ScanPhase is lowered.
llvm::BasicBlock * OMPScanDispatch
Controls the flow to before or after scan blocks.
A vector that has set insertion semantics.
Definition SetVector.h:57
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
Definition SetVector.h:236
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool test(unsigned Idx) const
Returns true if bit Idx is set.
bool all() const
Returns true if all bits are set.
bool any() const
Returns true if any bit is set.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition StringMap.h:250
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t count(char C) const
Return the number of occurrences of C in the string.
Definition StringRef.h:463
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition StringRef.h:634
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:27
bool contains(StringRef key) const
Check if the set contains the given key.
Definition StringSet.h:62
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
Type * getElementType(unsigned N) const
Multiway switch.
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isPPC() const
Tests whether the target is PowerPC (32- or 64-bit LE or BE).
Definition Triple.h:1146
bool isX86() const
Tests whether the target is x86 (32- or 64-bit).
Definition Triple.h:1203
bool isWasm() const
Tests whether the target is wasm (32- and 64-bit).
Definition Triple.h:1217
bool isSystemZ() const
Tests whether the target is SystemZ.
Definition Triple.h:1200
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI Type * getStructElementType(unsigned N) const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
User * user_back()
Definition Value.h:414
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
Definition Value.cpp:180
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:556
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A raw_ostream that writes to an SmallVector or SmallString.
The virtual file system interface.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false, bool IsText=true)
This is a convenience method that opens a file, gets its content and then closes the file.
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr StringLiteral MaxNTID("nvvm.maxntid")
constexpr StringLiteral MaxClusterRank("nvvm.maxclusterrank")
initializer< Ty > init(const Ty &Val)
@ Init
Initialization function, sets up the coroutine frame.
Definition CodeView.h:644
@ User
could "use" a pointer
LLVM_ABI GlobalVariable * emitOffloadingEntry(Module &M, object::OffloadKind Kind, Constant *Addr, StringRef Name, uint64_t Size, uint32_t Flags, uint64_t Data, Constant *AuxAddr=nullptr)
Definition Utility.cpp:103
OpenMPOffloadMappingFlags
Values for bit flags used to specify the mapping type for offloading.
@ OMP_MAP_PTR_AND_OBJ
The element being mapped is a pointer-pointee pair; both the pointer and the pointee should be mapped...
@ OMP_MAP_MEMBER_OF
The 16 MSBs of the flags indicate whether the entry is member of some struct/class.
IdentFlag
IDs for all omp runtime library ident_t flag encodings (see their defintion in openmp/runtime/src/kmp...
RuntimeFunction
IDs for all omp runtime library (RTL) functions.
constexpr const GV & getAMDGPUGridValues()
constexpr unsigned DefaultPartialUnrollFactor
Unroll factor for a partial unroll without an explicit factor, when the unrolled loop must be materia...
static constexpr GV SPIRVGridValues
For generic SPIR-V GPUs.
OMPDynGroupprivateFallbackType
The fallback types for the dyn_groupprivate clause.
static constexpr GV NVPTXGridValues
For Nvidia GPUs.
@ OMP_TGT_EXEC_MODE_SPMD_NO_LOOP
Function * Kernel
Summary of a kernel (=entry point for target offloading).
Definition OpenMPOpt.h:21
WorksharingLoopType
A type of worksharing loop construct.
OMPAtomicCompareOp
Atomic compare operations. Currently OpenMP only supports ==, >, and <.
EnumSet< Property > Properties
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI BasicBlock * splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch, llvm::Twine Suffix=".split")
Like splitBB, but reuses the current block's name for the new name.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
AtomicScope
Target-neutral memory synchronization scopes.
Definition AtomicScope.h:23
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:388
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE()
LLVM_ABI BasicBlock * splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch, DebugLoc DL, llvm::Twine Name={})
Split a BasicBlock at an InsertPoint, even if the block is degenerate (missing the terminator).
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
std::string utostr(uint64_t X, bool isNeg=false)
void * PointerTy
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap, AssumptionCache *AC=nullptr)
Remaps instructions in Blocks using the mapping in VMap.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
AtomicOrderingCABI toCABI(AtomicOrdering AO)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Mul
Product of integers.
@ Add
Sum of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New, bool CreateBranch, DebugLoc DL)
Move the instruction after an InsertPoint to the beginning of another BasicBlock.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
std::optional< StringRef > getAtomicScopeIRString(const Triple &T, AtomicScope S, bool IsSingleAddressSpace=false)
Returns the LLVM IR syncscope string that T uses to spell S.
Definition AtomicScope.h:34
auto predecessors(const MachineBasicBlock *BB)
auto filter_to_vector(ContainerTy &&C, PredicateFn &&Pred)
Filter a range to a SmallVector with the element types deduced.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
@ Continue
Definition DWP.h:26
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
Physical handles captured before the source descriptors are invalidated.
SmallVector< PHINode *, 4 > IndVars
SmallVector< BasicBlock *, 4 > Preheaders
SmallVector< BasicBlock *, 4 > Latches
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
A struct to pack the relevant information for an OpenMP affinity clause.
a struct to pack relevant information while generating atomic Ops
A struct to pack the relevant information for an OpenMP depend clause.
omp::RTLDependenceKindTy DepKind
A struct to pack static and dynamic dependency information for a task.
LLVM_ABI Error mergeFiniBB(IRBuilderBase &Builder, BasicBlock *ExistingFiniBB)
For cases where there is an unavoidable existing finalization block (e.g.
LLVM_ABI Expected< BasicBlock * > getFiniBB(IRBuilderBase &Builder)
The basic block to which control should be transferred to implement the FiniCB.
Description of a LLVM-IR insertion point (IP) and a debug/source location (filename,...
Represents a group of mapper sub-components produced by an iterator modifier on a declare mapper's ma...
omp::OpenMPOffloadMappingFlags Type
Map type/HasAttachPtr, constant across the segment.
Value * Count
Runtime (i64) trip count for this segment.
Function * ChildMapperFn
User-defined mapper to invoke for this segment's component, if the underlying map clause carries one ...
std::function< Expected< SmallVector< Value *, 3 > >(IRBuilderBase &, Value *)> GenEntry
Emits the code computing one iteration's (BasePointer, Pointer, Size) triple, given the loop's linear...
This structure contains combined information generated for mappable clauses, including base pointers,...
MapDeviceInfoArrayTy DevicePointers
StructNonContiguousInfo NonContigInfo
Helper that contains information about regions we need to outline during finalization.
void collectBlocks(SmallPtrSetImpl< BasicBlock * > &BlockSet, SmallVectorImpl< BasicBlock * > &BlockVector)
Collect all blocks in between EntryBB and ExitBB in both the given vector and set.
virtual std::unique_ptr< CodeExtractor > createCodeExtractor(ArrayRef< BasicBlock * > Blocks, bool ArgsInZeroAddressSpace, Twine Suffix=Twine(""))
Create a CodeExtractor instance based on the information stored in this structure,...
Information about an OpenMP reduction.
EvalKind EvaluationKind
Reduction evaluation kind - scalar, complex or aggregate.
ReductionGenAtomicCBTy AtomicReductionGen
Callback for generating the atomic reduction body, may be null.
ReductionGenCBTy ReductionGen
Callback for generating the reduction body.
Value * Variable
Reduction variable of pointer type.
Value * PrivateVariable
Thread-private partial reduction variable.
ReductionGenClangCBTy ReductionGenClang
Clang callback for generating the reduction body.
Type * ElementType
Reduction element type, must match pointee type of variable.
ReductionGenDataPtrPtrCBTy DataPtrPtrGen
Container for the arguments used to pass data to the runtime library.
Value * SizesArray
The array of sizes passed to the runtime library.
Value * PointersArray
The array of section pointers passed to the runtime library.
Value * MappersArray
The array of user-defined mappers passed to the runtime library.
Value * MapTypesArrayEnd
The array of map types passed to the runtime library for the end of the region, or nullptr if there a...
Value * BasePointersArray
The array of base pointer passed to the runtime library.
Value * MapTypesArray
The array of map types passed to the runtime library for the beginning of the region or for the entir...
SmallVector< NonContiguousDescriptor, 2 > NonContiguousDescriptors
Descriptors referenced by PointersArray need their own task-private copies when the runtime call is d...
Value * MapNamesArray
The array of original declaration names of mapped pointers sent to the runtime library for debugging.
Data structure that contains the needed information to construct the kernel args vector.
bool StrictBlocks
True if the kernel strictly requires the number of blocks and threads above to run.
ArrayRef< Value * > NumThreads
The number of threads.
TargetDataRTArgs RTArgs
Arguments passed to the runtime library.
Value * NumIterations
The number of iterations.
Value * DynCGroupMem
The size of the dynamic shared memory.
unsigned NumTargetItems
Number of arguments passed to the runtime library.
bool HasNoWait
True if the kernel has 'no wait' clause.
ArrayRef< Value * > NumTeams
The number of teams.
omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback
The fallback mechanism for the shared memory.
Container to pass the default attributes with which a kernel must be launched, used to set kernel att...
Container to pass LLVM IR runtime values or constants related to the number of teams and threads with...
Value * DeviceID
Device ID value used in the kernel launch.
Value * LoopTripCount
Total number of iterations of the SPMD or Generic-SPMD kernel or null if it is a generic kernel.
SmallVector< Value * > MaxThreads
'parallel' construct 'num_threads' clause value, if present and it is an SPMD kernel.
Data structure to contain the information needed to uniquely identify a target entry.
static LLVM_ABI void getTargetRegionEntryFnName(SmallVectorImpl< char > &Name, StringRef ParentName, unsigned DeviceID, unsigned FileID, unsigned Line, unsigned Count)
static constexpr const char * KernelNamePrefix
The prefix used for kernel names.
Defines various target-specific GPU grid values that must be consistent between host RTL (plugin),...