61#define DEBUG_TYPE "openmp-ir-builder"
68 cl::desc(
"Use optimistic attributes describing "
69 "'as-if' properties of runtime calls."),
73 "openmp-ir-builder-use-default-max-threads",
cl::Hidden,
84 if (!IP1.isValid() || !IP2.isValid())
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:
142 SchedType & OMPScheduleType::MonotonicityMask;
143 if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
157 Builder.restoreIP(IP);
161 if (Builder.GetInsertPoint() != BB->
end())
171 unsigned Line = FSP->getScopeLine() ? FSP->getScopeLine() : FSP->getLine();
172 Builder.SetCurrentDebugLocation(
178 return T.isAMDGPU() ||
T.isNVPTX() ||
T.isSPIRV();
184 Kernel->getFnAttribute(
"target-features").getValueAsString();
185 if (Features.
count(
"+wavefrontsize64"))
200 bool HasSimdModifier,
bool HasDistScheduleChunks) {
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;
227 bool HasOrderedClause) {
228 assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
229 OMPScheduleType::None &&
230 "Must not have ordering nor monotonicity flags already set");
233 ? OMPScheduleType::ModifierOrdered
234 : OMPScheduleType::ModifierUnordered;
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;
245 return OrderingScheduleType;
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");
260 return ScheduleType | OMPScheduleType::ModifierMonotonic;
261 }
else if (HasNonmonotonic) {
262 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
272 if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
273 (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
279 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
287 bool HasSimdModifier,
bool HasMonotonicModifier,
288 bool HasNonmonotonicModifier,
bool HasOrderedClause,
289 bool HasDistScheduleChunks) {
291 ClauseKind, HasChunks, HasSimdModifier, HasDistScheduleChunks);
295 OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
296 HasNonmonotonicModifier, HasOrderedClause);
304static std::optional<omp::OMPTgtExecModeFlags>
309 if (
Call->getCalledFunction()->getName() ==
"__kmpc_target_init") {
310 TargetInitCall =
Call;
335 std::optional<omp::OMPTgtExecModeFlags> ExecMode =
347 if (
Instruction *Term = Source->getTerminatorOrNull()) {
356 NewBr->setDebugLoc(
DL);
361 assert(New->getFirstInsertionPt() == New->begin() &&
362 "Target BB must not have PHI nodes");
378 New->splice(New->begin(), Old, IP, Old->
end());
382 NewBr->setDebugLoc(
DL);
394 Builder.SetInsertPoint(Old);
398 Builder.SetCurrentDebugLocation(
DebugLoc);
408 New->replaceSuccessorsPhiUsesWith(Old, New);
420 Builder.SetInsertPoint(Old);
423 Builder.SetCurrentDebugLocation(
DebugLoc);
435 Builder.SetInsertPoint(Old);
438 Builder.SetCurrentDebugLocation(
DebugLoc);
455 const Twine &Name =
"",
bool AsPtr =
true,
456 bool Is64Bit =
false) {
457 Builder.restoreIP(OuterAllocaIP);
461 Builder.CreateAlloca(IntTy,
nullptr, Name +
".addr");
465 FakeVal = FakeValAddr;
470 FakeValAddr, Builder.getPtrTy(), Name +
".ascast"));
474 FakeVal = Builder.CreateLoad(IntTy, FakeValAddr, Name +
".val");
479 Builder.restoreIP(InnerAllocaIP);
482 UseFakeVal = Builder.CreateLoad(IntTy, FakeVal, Name +
".use");
485 FakeVal, Is64Bit ? Builder.getInt64(10) : Builder.getInt32(10)));
498enum OpenMPOffloadingRequiresDirFlags {
500 OMP_REQ_UNDEFINED = 0x000,
502 OMP_REQ_NONE = 0x001,
504 OMP_REQ_REVERSE_OFFLOAD = 0x002,
506 OMP_REQ_UNIFIED_ADDRESS = 0x004,
508 OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
510 OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
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,
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) {}
530 virtual ~OMPCodeExtractor() =
default;
533 OpenMPIRBuilder &OMPBuilder;
536class DeviceSharedMemCodeExtractor :
public OMPCodeExtractor {
538 using OMPCodeExtractor::OMPCodeExtractor;
539 virtual ~DeviceSharedMemCodeExtractor() =
default;
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);
549 virtual Instruction *deallocateVar(IRBuilder<>::InsertPoint DeallocIP,
551 Type *VarType)
override {
552 return OMPBuilder.createOMPFreeShared({DeallocIP,
DL}, Var, VarType);
559 OpenMPIRBuilder &OMPBuilder;
561 DeviceSharedMemOutlineInfo(OpenMPIRBuilder &OMPBuilder)
562 : OMPBuilder(OMPBuilder) {}
563 virtual ~DeviceSharedMemOutlineInfo() =
default;
565 virtual std::unique_ptr<CodeExtractor>
567 bool ArgsInZeroAddressSpace,
568 Twine Suffix = Twine(
""))
override;
574 : RequiresFlags(OMP_REQ_UNDEFINED) {}
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;
594 return RequiresFlags & OMP_REQ_REVERSE_OFFLOAD;
598 return RequiresFlags & OMP_REQ_UNIFIED_ADDRESS;
602 return RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY;
606 return RequiresFlags & OMP_REQ_DYNAMIC_ALLOCATORS;
611 :
static_cast<int64_t
>(OMP_REQ_NONE);
616 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
618 RequiresFlags &= ~OMP_REQ_REVERSE_OFFLOAD;
623 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
625 RequiresFlags &= ~OMP_REQ_UNIFIED_ADDRESS;
630 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
632 RequiresFlags &= ~OMP_REQ_UNIFIED_SHARED_MEMORY;
637 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
639 RequiresFlags &= ~OMP_REQ_DYNAMIC_ALLOCATORS;
652 constexpr size_t MaxDim = 3;
657 Value *DynCGroupMemFallbackFlag =
659 DynCGroupMemFallbackFlag =
Builder.CreateShl(DynCGroupMemFallbackFlag, 2);
664 StrictBlocksFlag =
Builder.CreateShl(StrictBlocksFlag, 6);
665 StrictThreadsFlag =
Builder.CreateShl(StrictThreadsFlag, 7);
667 Value *Flags =
Builder.CreateOr(HasNoWaitFlag, DynCGroupMemFallbackFlag);
668 Flags =
Builder.CreateOr(Flags, StrictBlocksFlag);
669 Flags =
Builder.CreateOr(Flags, StrictThreadsFlag);
675 Value *NumThreads3D =
706 auto FnAttrs = Attrs.getFnAttrs();
707 auto RetAttrs = Attrs.getRetAttrs();
709 for (
size_t ArgNo = 0; ArgNo < Fn.
arg_size(); ++ArgNo)
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.");
721 if (
auto AK = TargetLibraryInfo::getExtAttrForI32Param(
T, HasSignExt))
724 TargetLibraryInfo::getExtAttrForI32Return(
T, HasSignExt))
731#define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
732#include "llvm/Frontend/OpenMP/OMPKinds.def"
736#define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \
738 FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet); \
739 addAttrSet(RetAttrs, RetAttrSet, 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)); \
744#include "llvm/Frontend/OpenMP/OMPKinds.def"
757#define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \
759 FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__}, \
763#include "llvm/Frontend/OpenMP/OMPKinds.def"
766 return M.getOrInsertFunction(Name, FnTy, [&](
Function &Fn) {
769 if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
778 LLVMContext::MD_callback,
780 2, {-1, -1},
true)}));
795 Builder.SetInsertPoint(FiniBB);
807 FiniBB = OtherFiniBB;
809 Builder.SetInsertPoint(FiniBB->getFirstNonPHIIt());
817 auto EndIt = FiniBB->end();
818 if (FiniBB->size() >= 1)
819 if (
auto Prev = std::prev(EndIt); Prev->isTerminator())
824 FiniBB->replaceAllUsesWith(OtherFiniBB);
825 FiniBB->eraseFromParent();
826 FiniBB = OtherFiniBB;
833 assert(Fn &&
"Failed to create OpenMP runtime function pointer");
856 for (
auto Inst =
Block->getReverseIterator()->begin();
857 Inst !=
Block->getReverseIterator()->end();) {
886 Block.getParent()->getEntryBlock().getTerminator()->getIterator();
903#define OMP_RTL(Enum, Str, ...) Str,
904#include "llvm/Frontend/OpenMP/OMPKinds.def"
913 if (!
F.getSubprogram())
917 if (!CB || CB->getDebugLoc())
919 Function *Callee = CB->getCalledFunction();
921 errs() <<
"OpenMP runtime call to '" << Callee->getName()
922 <<
"' in function '" <<
F.getName()
923 <<
"' has no debug location\n";
939 DeferredOutlines.
push_back(std::move(OI));
943 ParallelRegionBlockSet.
clear();
945 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
955 bool ArgsInZeroAddressSpace =
Config.isTargetDevice();
956 std::unique_ptr<CodeExtractor> Extractor =
957 OI->createCodeExtractor(Blocks, ArgsInZeroAddressSpace,
".omp_par");
961 <<
" Exit: " << OI->ExitBB->getName() <<
"\n");
962 assert(Extractor->isEligible() &&
963 "Expected OpenMP outlining to be possible!");
965 for (
auto *V : OI->ExcludeArgsFromAggregate)
966 Extractor->excludeArgFromAggregate(V);
969 Extractor->extractCodeRegion(CEAC, OI->Inputs, OI->Outputs);
973 if (TargetCpuAttr.isStringAttribute())
976 auto TargetFeaturesAttr = OuterFn->
getFnAttribute(
"target-features");
977 if (TargetFeaturesAttr.isStringAttribute())
978 OutlinedFn->
addFnAttr(TargetFeaturesAttr);
981 LLVM_DEBUG(
dbgs() <<
" Outlined function: " << *OutlinedFn <<
"\n");
983 "OpenMP outlined functions should not return a value!");
988 M.getFunctionList().insertAfter(OuterFn->
getIterator(), OutlinedFn);
995 assert(OI->EntryBB->getUniquePredecessor() == &ArtificialEntry);
1002 "Expected instructions to add in the outlined region entry");
1009 if (
I.isTerminator()) {
1011 if (
Instruction *TI = OI->EntryBB->getTerminatorOrNull())
1012 TI->adoptDbgRecords(&ArtificialEntry,
I.getIterator(),
false);
1016 I.moveBeforePreserving(*OI->EntryBB,
1017 OI->EntryBB->getFirstInsertionPt());
1020 OI->EntryBB->moveBefore(&ArtificialEntry);
1027 if (OI->PostOutlineCB)
1028 OI->PostOutlineCB(*OutlinedFn);
1030 if (OI->FixUpNonEntryAllocas)
1060 errs() <<
"Error of kind: " << Kind
1061 <<
" when emitting offload entries and metadata during "
1062 "OMPIRBuilder finalization \n";
1071 if (
Config.isTargetDevice())
1072 applyDeclareTargetGlobalReplacements();
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);
1094 assert(Original && Replacement &&
1095 "Null values provided to registerDeclareTargetGlobalReplacement");
1099void OpenMPIRBuilder::applyDeclareTargetGlobalReplacements() {
1105 "A null value was inserted into DeclareTargetGlobalReplacements");
1109 if (!OldGV || !NewGV)
1143 for (
unsigned I = 0, E =
PHI->getNumIncomingValues();
I < E; ++
I) {
1144 if (
PHI->getIncomingValue(
I) != OldGV)
1149 Builder.SetCurrentDebugLocation(
PHI->getDebugLoc());
1151 PHI->setIncomingValue(
I, EdgeLoad);
1157 Builder.SetCurrentDebugLocation(Insn->getDebugLoc());
1173 "Non-default address space declare target global");
1175 unsigned DestAS = ASC->getType()->getPointerAddressSpace();
1176 if (DestAS == 0 && NewGVAS != OldGVAS) {
1177 ASC->replaceAllUsesWith(
Load);
1178 ASC->eraseFromParent();
1183 Insn->replaceUsesOfWith(OldGV,
Load);
1199 ConstantInt::get(I32Ty,
Value), Name);
1212 for (
unsigned I = 0, E =
List.size();
I != E; ++
I)
1216 if (UsedArray.
empty())
1223 GV->setSection(
"llvm.metadata");
1229 auto *Int8Ty =
Builder.getInt8Ty();
1232 ConstantInt::get(Int8Ty, Mode),
Twine(KernelName,
"_exec_mode"));
1240 unsigned Reserve2Flags) {
1242 LocFlags |= OMP_IDENT_FLAG_KMPC;
1249 ConstantInt::get(Int32,
uint32_t(LocFlags)),
1250 ConstantInt::get(Int32, Reserve2Flags),
1251 ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
1253 size_t SrcLocStrArgIdx = 4;
1254 if (OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx)
1258 SrcLocStr, OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx));
1265 if (
GV.getValueType() == OpenMPIRBuilder::Ident &&
GV.hasInitializer())
1266 if (
GV.getInitializer() == Initializer)
1271 M, OpenMPIRBuilder::Ident,
1274 M.getDataLayout().getDefaultGlobalsAddressSpace());
1286 SrcLocStrSize = LocStr.
size();
1295 if (
GV.isConstant() &&
GV.hasInitializer() &&
1296 GV.getInitializer() == Initializer)
1299 SrcLocStr =
Builder.CreateGlobalString(
1300 LocStr,
"",
M.getDataLayout().getDefaultGlobalsAddressSpace(),
1308 unsigned Line,
unsigned Column,
1314 Buffer.
append(FunctionName);
1316 Buffer.
append(std::to_string(Line));
1318 Buffer.
append(std::to_string(Column));
1326 StringRef UnknownLoc =
";unknown;unknown;0;0;;";
1337 !DIL->getFilename().empty() ? DIL->getFilename() :
M.getName();
1342 DIL->getColumn(), SrcLocStrSize);
1348 Loc.IP.getNodeParent()->getParent());
1354 "omp_global_thread_num");
1362 "expected one result pointer type per in_reduction item");
1365 if (OrigPtrs.
empty())
1366 return Builder.saveIP();
1385 for (
unsigned Idx = 0; Idx < OrigPtrs.
size(); ++Idx) {
1388 Value *OrigPtr = OrigPtrs[Idx];
1390 OrigPtrTy && OrigPtrTy->getAddressSpace() != 0)
1391 OrigPtr = Builder.CreateAddrSpaceCast(OrigPtr, PtrTy);
1394 GetThData, {Gtid, NullDesc, OrigPtr},
"omp.inred.priv");
1399 ResPtrTy && ResPtrTy->getAddressSpace() != 0)
1400 Priv = Builder.CreateAddrSpaceCast(
Priv, ResultPtrTys[Idx]);
1402 MapPrivateCB(Idx,
Priv);
1409 bool ForceSimpleCall,
bool CheckCancelFlag) {
1419 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
1422 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
1425 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
1428 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
1431 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
1444 bool UseCancelBarrier =
1449 ? OMPRTL___kmpc_cancel_barrier
1450 : OMPRTL___kmpc_barrier),
1453 if (UseCancelBarrier && CheckCancelFlag)
1463 omp::Directive CanceledDirective) {
1468 auto *UI =
Builder.CreateUnreachable();
1476 Builder.SetInsertPoint(ElseTI);
1477 auto ElseIP =
Builder.saveIP();
1485 Builder.SetInsertPoint(ThenTI);
1487 Value *CancelKind =
nullptr;
1488 switch (CanceledDirective) {
1489#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1490 case DirectiveEnum: \
1491 CancelKind = Builder.getInt32(Value); \
1493#include "llvm/Frontend/OpenMP/OMPKinds.def"
1510 Builder.SetInsertPoint(UI->getParent());
1511 UI->eraseFromParent();
1518 omp::Directive CanceledDirective) {
1523 auto *UI =
Builder.CreateUnreachable();
1526 Value *CancelKind =
nullptr;
1527 switch (CanceledDirective) {
1528#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1529 case DirectiveEnum: \
1530 CancelKind = Builder.getInt32(Value); \
1532#include "llvm/Frontend/OpenMP/OMPKinds.def"
1549 Builder.SetInsertPoint(UI->getParent());
1550 UI->eraseFromParent();
1563 auto *KernelArgsPtr =
1564 Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs,
nullptr,
"kernel_args");
1569 Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr,
I);
1572 M.getDataLayout().getPrefTypeAlign(KernelArgs[
I]->getType()));
1576 NumThreads, HostPtr, KernelArgsPtr};
1603 assert(OutlinedFnID &&
"Invalid outlined function ID!");
1607 Value *Return =
nullptr;
1627 Builder, AllocaIP, Return, RTLoc, DeviceID, Args.NumTeams.front(),
1628 Args.NumThreads.front(), OutlinedFnID, ArgsVector));
1635 Builder.CreateCondBr(
Failed, OffloadFailedBlock, OffloadContBlock);
1637 auto CurFn =
Builder.GetInsertBlock()->getParent();
1644 emitBlock(OffloadContBlock, CurFn,
true);
1649 Value *CancelFlag, omp::Directive CanceledDirective) {
1651 "Unexpected cancellation!");
1671 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
1680 Builder.SetInsertPoint(CancellationBlock);
1681 Builder.CreateBr(*FiniBBOrErr);
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;
1704 {Builder.getInt16Ty(), Builder.getInt32Ty()},
1708 OutlinedFn.
getName() +
".wrapper", OMPIRBuilder->
M);
1710 WrapperFn->addParamAttr(0, Attribute::NoUndef);
1711 WrapperFn->addParamAttr(0, Attribute::ZExt);
1712 WrapperFn->addParamAttr(1, Attribute::NoUndef);
1716 Builder.SetInsertPoint(EntryBB);
1719 Value *AddrAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1721 AddrAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1722 AddrAlloca, Builder.getPtrTy(0),
1723 AddrAlloca->
getName() +
".ascast");
1725 Value *ZeroAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1727 ZeroAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1728 ZeroAlloca, Builder.getPtrTy(0),
1729 ZeroAlloca->
getName() +
".ascast");
1731 Value *ArgsAlloca =
nullptr;
1733 ArgsAlloca = Builder.CreateAlloca(Builder.getPtrTy(),
1734 nullptr,
"global_args");
1735 ArgsAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1736 ArgsAlloca, Builder.getPtrTy(0),
1737 ArgsAlloca->
getName() +
".ascast");
1741 Builder.CreateStore(WrapperFn->getArg(1), AddrAlloca);
1742 Builder.CreateStore(Builder.getInt32(0), ZeroAlloca);
1746 llvm::omp::RuntimeFunction::OMPRTL___kmpc_get_shared_variables),
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);
1762 Builder.CreateCall(&OutlinedFn, Args);
1763 Builder.CreateRetVoid();
1778 "Expected at least tid and bounded tid as arguments");
1779 unsigned NumCapturedVars = OutlinedFn.
arg_size() - 2;
1787 OutlinedFn.
addFnAttr(Attribute::NoUnwind);
1790 assert(CI &&
"Expected call instruction to outlined function");
1791 CI->
getParent()->setName(
"omp_parallel");
1793 Builder.SetInsertPoint(CI);
1794 Type *PtrTy = OMPIRBuilder->VoidPtr;
1797 OpenMPIRBuilder ::InsertPointTy CurrentIP = Builder.saveIP();
1801 Value *Args = ArgsAlloca;
1805 Args = Builder.CreatePointerCast(ArgsAlloca, PtrTy);
1806 Builder.restoreIP(CurrentIP);
1809 for (
unsigned Idx = 0; Idx < NumCapturedVars; Idx++) {
1811 Value *StoreAddress = Builder.CreateConstInBoundsGEP2_64(
1813 Builder.CreateStore(
V, StoreAddress);
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);
1831 Value *Parallel60CallArgs[] = {
1836 Builder.getInt32(-1),
1840 Builder.getInt64(NumCapturedVars),
1841 Builder.getInt32(0)};
1849 << *Builder.GetInsertBlock()->getParent() <<
"\n");
1852 Builder.SetInsertPoint(PrivTID);
1854 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1861 I->eraseFromParent();
1884 if (!
F->hasMetadata(LLVMContext::MD_callback)) {
1892 F->addMetadata(LLVMContext::MD_callback,
1901 OutlinedFn.
addFnAttr(Attribute::NoUnwind);
1904 "Expected at least tid and bounded tid as arguments");
1905 unsigned NumCapturedVars = OutlinedFn.
arg_size() - 2;
1928 if (NumCapturedVars) {
1929 assert(NumCapturedVars == 1 &&
"Expected an aggregate capture argument");
1932 ->getAllocatedType()
1934 "Expected a stack-allocated capture structure");
1940 CI->
getParent()->setName(
"omp_parallel");
1941 Builder.SetInsertPoint(CI);
1944 Value *ForkCallArgs[] = {Ident, Builder.getInt32(NumCapturedVars),
1948 RealArgs.
append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1950 Value *
Cond = Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32);
1957 auto PtrTy = OMPIRBuilder->VoidPtr;
1958 if (IfCondition && NumCapturedVars == 0) {
1966 << *Builder.GetInsertBlock()->getParent() <<
"\n");
1969 Builder.SetInsertPoint(PrivTID);
1971 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1978 I->eraseFromParent();
1986 Value *NumThreads, omp::ProcBindKind ProcBind,
bool IsCancellable) {
1995 const bool NeedThreadID = NumThreads ||
Config.isTargetDevice() ||
1996 (ProcBind != OMP_PROC_BIND_default);
2003 bool ArgsInZeroAddressSpace =
Config.isTargetDevice();
2007 if (NumThreads && !
Config.isTargetDevice()) {
2010 Builder.CreateIntCast(NumThreads, Int32,
false)};
2015 if (ProcBind != OMP_PROC_BIND_default) {
2019 ConstantInt::get(Int32,
unsigned(ProcBind),
true)};
2029 BasicBlock *OuterAllocaBlock = OuterAllocIP.getNodeParent();
2041 Builder.CreateAlloca(Int32,
nullptr,
"zero.addr");
2044 if (ArgsInZeroAddressSpace &&
M.getDataLayout().getAllocaAddrSpace() != 0) {
2047 TIDAddrAlloca, PointerType ::get(
M.getContext(), 0),
"tid.addr.ascast");
2051 PointerType ::get(
M.getContext(), 0),
2052 "zero.addr.ascast");
2065 UI->setDebugLoc(
Loc.DL);
2077 if (IP == IP.getNodeParent()->end()) {
2081 IP =
I->getIterator();
2083 assert(IP.getNodeParent()->getTerminator()->getNumSuccessors() == 1 &&
2084 IP.getNodeParent()->getTerminator()->getSuccessor(0) == PRegExitBB &&
2085 "Unexpected insertion point for finalization call!");
2097 Builder.CreateAlloca(Int32,
nullptr,
"tid.addr.local");
2103 Builder.CreateLoad(Int32, ZeroAddr,
"zero.addr.use");
2121 LLVM_DEBUG(
dbgs() <<
"Before body codegen: " << *OuterFn <<
"\n");
2124 assert(BodyGenCB &&
"Expected body generation callback!");
2126 if (
Error Err = BodyGenCB(InnerAllocaIP, CodeGenIP, PRegExitBB))
2129 LLVM_DEBUG(
dbgs() <<
"After body codegen: " << *OuterFn <<
"\n");
2133 bool UsesDeviceSharedMemory =
2135 std::unique_ptr<OutlineInfo> OI =
2136 UsesDeviceSharedMemory
2137 ? std::make_unique<DeviceSharedMemOutlineInfo>(*
this)
2138 : std::make_unique<OutlineInfo>();
2140 if (
Config.isTargetDevice()) {
2142 OI->PostOutlineCB = [=, ToBeDeletedVec =
2143 std::move(ToBeDeleted)](
Function &OutlinedFn) {
2145 IfCondition, NumThreads, PrivTID, PrivTIDAddr,
2146 ThreadID, ToBeDeletedVec);
2150 OI->PostOutlineCB = [=, ToBeDeletedVec =
2151 std::move(ToBeDeleted)](
Function &OutlinedFn) {
2153 PrivTID, PrivTIDAddr, ToBeDeletedVec);
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());
2166 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
2178 ".omp_par", ArgsInZeroAddressSpace);
2183 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
2185 Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands,
2190 return GV->getValueType() == OpenMPIRBuilder::Ident;
2195 LLVM_DEBUG(
dbgs() <<
"Before privatization: " << *OuterFn <<
"\n");
2201 if (&V == TIDAddr || &V == ZeroAddr) {
2202 OI->ExcludeArgsFromAggregate.push_back(&V);
2207 for (
Use &U : V.uses())
2209 if (ParallelRegionBlockSet.
count(UserI->getParent()))
2219 if (!V.getType()->isPointerTy()) {
2223 Builder.restoreIP(OuterAllocIP);
2225 if (UsesDeviceSharedMemory) {
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");
2235 Builder.getCurrentDebugLocation()},
2239 Ptr =
Builder.CreateAlloca(V.getType(),
nullptr,
2240 V.getName() +
".reloaded");
2249 Builder.restoreIP(InnerAllocaIP);
2250 Inner =
Builder.CreateLoad(V.getType(), Ptr);
2253 Value *ReplacementValue =
nullptr;
2256 ReplacementValue = PrivTID;
2259 PrivCB(InnerAllocaIP,
Builder.saveIP(), V, *Inner, ReplacementValue);
2264 InnerAllocaIP.getNodeParent()->getTerminator()->getIterator();
2266 assert(ReplacementValue &&
2267 "Expected copy/create callback to set replacement value!");
2268 if (ReplacementValue == &V)
2273 UPtr->set(ReplacementValue);
2296 for (
Value *Output : Outputs)
2300 "OpenMP outlining should not produce live-out values!");
2302 LLVM_DEBUG(
dbgs() <<
"After privatization: " << *OuterFn <<
"\n");
2304 for (
auto *BB : Blocks)
2305 dbgs() <<
" PBR: " << BB->getName() <<
"\n";
2313 assert(FiniInfo.DK == OMPD_parallel &&
2314 "Unexpected finalization stack state!");
2325 Builder.CreateBr(*FiniBBOrErr);
2328 Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
2335 UI->eraseFromParent();
2348 if (
Config.IsGPU.value_or(
M.getTargetTriple().isGPU())) {
2351 Builder.CreateFence(AO,
M.getContext().getOrInsertSyncScopeID(ScopeName));
2369 Builder.getInt32(
static_cast<unsigned>(Scope))};
2392 Value *Severity = ConstantInt::get(Int32, IsFatal ? 2 : 1);
2394 Value *Args[] = {Ident, Severity, MessageArg};
2423 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
2425 Builder.CreateStore(DepValPtr, Addr);
2428 DependInfo, Entry,
static_cast<unsigned int>(RTLDependInfoFields::Len));
2430 ConstantInt::get(SizeTy,
2435 DependInfo, Entry,
static_cast<unsigned int>(RTLDependInfoFields::Flags));
2437 static_cast<unsigned int>(Dep.
DepKind)),
2450 if (Dependencies.
empty())
2470 Type *DependInfo = OMPBuilder.DependInfo;
2472 Value *DepArray =
nullptr;
2478 Builder.SetInsertPoint(
2479 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator());
2480 DepArray = Builder.CreateAlloca(DepArrayTy,
nullptr,
".dep.arr.addr");
2483 for (
const auto &[DepIdx, Dep] :
enumerate(Dependencies)) {
2485 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2510 Value *DepArray =
nullptr;
2511 Type *DepArrayTy =
nullptr;
2512 Value *NumDeps =
nullptr;
2515 NumDeps = Dependencies.
NumDeps;
2516 }
else if (!Dependencies.
Deps.empty()) {
2518 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
2522 Builder.GetInsertBlock()->getParent()->getEntryBlock();
2524 DepArray =
Builder.CreateAlloca(DepArrayTy,
nullptr,
".dep.arr.addr");
2527 for (
const auto &[DepIdx, Dep] :
enumerate(Dependencies.
Deps)) {
2529 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2543 ConstantInt::get(
Builder.getInt32Ty(), 0),
2545 ConstantInt::get(
Builder.getInt32Ty(), IsNowait)};
2548 omp::RuntimeFunction::OMPRTL___kmpc_omp_taskwait_deps_51),
2558 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2570 auto *VoidPtrTy =
PointerType::get(Builder.getContext(), ProgramAddressSpace);
2573 Builder.getVoidTy(), {VoidPtrTy, VoidPtrTy, Builder.getInt32Ty()},
2577 "omp_taskloop_dup", M);
2580 Value *LastprivateFlagArg = DupFunction->
getArg(2);
2581 DestTaskArg->
setName(
"dest_task");
2582 SrcTaskArg->
setName(
"src_task");
2583 LastprivateFlagArg->
setName(
"lastprivate_flag");
2586 Builder.SetInsertPoint(
2589 auto GetTaskContextPtrFromArg = [&](
Value *Arg) ->
Value * {
2590 Type *TaskWithPrivatesTy =
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)});
2600 Value *DestTaskContextPtr = GetTaskContextPtrFromArg(DestTaskArg);
2601 Value *SrcTaskContextPtr = GetTaskContextPtrFromArg(SrcTaskArg);
2603 DestTaskContextPtr->
setName(
"destPtr");
2604 SrcTaskContextPtr->
setName(
"srcPtr");
2608 Expected<IRBuilderBase::InsertPoint> AfterIPOrError =
2609 DupCB(AllocaIP, CodeGenIP, DestTaskContextPtr, SrcTaskContextPtr);
2610 if (!AfterIPOrError)
2612 Builder.restoreIP(*AfterIPOrError);
2622 llvm::function_ref<llvm::Expected<llvm::CanonicalLoopInfo *>()> LoopInfo,
2624 Value *GrainSize,
bool NoGroup,
int Sched,
Value *Final,
bool Mergeable,
2626 Value *TaskContextStructPtrVal,
bool FreeAgent) {
2631 uint32_t SrcLocStrSize;
2645 if (
Error Err = BodyGenCB(TaskloopAllocaIP, TaskloopBodyIP, TaskloopExitBB))
2648 llvm::Expected<llvm::CanonicalLoopInfo *> result = LoopInfo();
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());
2664 SmallVector<Instruction *> ToBeDeleted;
2667 Builder, AllocaIP, ToBeDeleted, TaskloopAllocaIP,
"global.tid",
false));
2669 TaskloopAllocaIP,
"lb",
false,
true);
2671 TaskloopAllocaIP,
"ub",
false,
true);
2673 TaskloopAllocaIP,
"step",
false,
true);
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 "
2689 unsigned ProgramAddressSpace =
M.getDataLayout().getProgramAddressSpace();
2693 {FakeLB->getType(), FakeUB->getType(), FakeStep->getType(), PointerTy});
2694 Expected<Value *> TaskDupFnOrErr = createTaskDuplicationFunction(
2697 if (!TaskDupFnOrErr) {
2700 Value *TaskDupFn = *TaskDupFnOrErr;
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,
2707 FreeAgent](
Function &OutlinedFn)
mutable {
2709 assert(OutlinedFn.hasOneUse() &&
2710 "there must be a single user for the outlined function");
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");
2724 Builder.SetInsertPoint(StaleCI);
2762 divideCeil(
M.getDataLayout().getTypeSizeInBits(Task), 8));
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 =
2772 "Unable to determine size of arguments for extracted function");
2773 Value *SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
2779 TaskAllocFn, {Ident, ThreadID,
Flags,
2780 TaskSize, SharedsSize,
2785 Value *TaskShareds =
Builder.CreateLoad(VoidPtr, TaskData);
2791 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(0)});
2794 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(1)});
2797 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(2)});
2803 IfCond ?
Builder.CreateIntCast(IfCond,
Builder.getInt32Ty(),
true)
2809 Value *GrainSizeVal =
2810 GrainSize ?
Builder.CreateIntCast(GrainSize,
Builder.getInt64Ty(),
true)
2812 Value *TaskDup = TaskDupFn;
2814 Value *
Args[] = {Ident, ThreadID, TaskData, IfCondVal, Lb, Ub,
2815 Loadstep, NoGroupVal, SchedVal, GrainSizeVal, TaskDup};
2832 Builder.SetInsertPoint(TaskloopAllocaBB->begin());
2834 LoadInst *SharedsOutlined =
2835 Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
2836 OutlinedFn.getArg(1)->replaceUsesWithIf(
2838 [SharedsOutlined](Use &U) {
return U.getUser() != SharedsOutlined; });
2841 Type *IVTy =
IV->getType();
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) {
2857 switch (CI->getZExtValue()) {
2869 }
else if (
I.getOpcode() == Instruction::Load) {
2871 if (
Load.getPointerOperand() == TaskLB) {
2872 assert(TaskLB !=
nullptr &&
"Expected value for TaskLB");
2874 }
else if (
Load.getPointerOperand() == TaskUB) {
2875 assert(TaskUB !=
nullptr &&
"Expected value for TaskUB");
2877 }
else if (
Load.getPointerOperand() == TaskStep) {
2878 assert(TaskStep !=
nullptr &&
"Expected value for TaskStep");
2884 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2886 assert(LoadTaskLB !=
nullptr &&
"Expected value for LoadTaskLB");
2887 assert(LoadTaskUB !=
nullptr &&
"Expected value for LoadTaskUB");
2888 assert(LoadTaskStep !=
nullptr &&
"Expected value for LoadTaskStep");
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);
2895 CLI->setTripCount(CastedTripCount);
2897 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
2899 if (NumOfCollapseLoops > 1) {
2905 Builder.CreateSub(CastedTaskLB, ConstantInt::get(IVTy, 1)));
2908 for (
auto IVUse = CLI->getIndVar()->uses().begin();
2909 IVUse != CLI->getIndVar()->uses().end(); IVUse++) {
2910 User *IVUser = IVUse->getUser();
2912 if (
Op->getOpcode() == Instruction::URem ||
2913 Op->getOpcode() == Instruction::UDiv) {
2918 for (User *User : UsersToReplace) {
2919 User->replaceUsesOfWith(CLI->getIndVar(), IVPlusTaskLB);
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()) {
2940 if (
Mul->getOpcode() == Instruction::Mul) {
2941 for (User *MulUser :
Mul->users()) {
2943 if (
Add->getOpcode() == Instruction::Add) {
2944 Add->setOperand(1, CastedTaskLB);
2953 FakeLB->replaceAllUsesWith(CastedLBVal);
2954 FakeUB->replaceAllUsesWith(CastedUBVal);
2955 FakeStep->replaceAllUsesWith(CastedStepVal);
2957 I->eraseFromParent();
2968 M.getContext(),
M.getDataLayout().getPointerSizeInBits());
2978 bool Mergeable,
Value *EventHandle,
Value *Priority,
bool FreeAgent) {
3009 if (
Error Err = BodyGenCB(TaskAllocaIP, TaskBodyIP, TaskExitBB))
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());
3022 Builder, AllocaIP, ToBeDeleted, TaskAllocaIP,
"global.tid",
false));
3024 OI->PostOutlineCB = [
this, Ident, Tied, Final, IfCondition, Dependencies,
3025 Affinities, Mergeable, Priority, EventHandle, FreeAgent,
3027 ToBeDeleted](
Function &OutlinedFn)
mutable {
3029 assert(OutlinedFn.hasOneUse() &&
3030 "there must be a single user for the outlined function");
3035 bool HasShareds = StaleCI->
arg_size() > 1;
3036 Builder.SetInsertPoint(StaleCI);
3063 bool UseMergedIf0Path = ConstIfCondition && ConstIfCondition->isZero();
3067 Flags =
Builder.CreateOr(FinalFlag, Flags);
3070 if (Mergeable || UseMergedIf0Path)
3084 divideCeil(
M.getDataLayout().getTypeSizeInBits(Task), 8));
3093 assert(ArgStructAlloca &&
3094 "Unable to find the alloca instruction corresponding to arguments "
3095 "for extracted function");
3096 std::optional<TypeSize> ArgAllocSize =
3099 "Unable to determine size of arguments for extracted function");
3100 SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
3106 TaskAllocFn, {Ident, ThreadID, Flags,
3107 TaskSize, SharedsSize,
3110 if (Affinities.
Count && Affinities.
Info) {
3112 OMPRTL___kmpc_omp_reg_task_with_affinity);
3123 OMPRTL___kmpc_task_allow_completion_event);
3127 Builder.CreatePointerBitCastOrAddrSpaceCast(EventHandle,
3129 EventVal =
Builder.CreatePtrToInt(EventVal,
Builder.getInt64Ty());
3130 Builder.CreateStore(EventVal, EventHandleAddr);
3136 Value *TaskShareds =
Builder.CreateLoad(VoidPtr, TaskData);
3158 VoidPtr, VoidPtr,
Builder.getInt32Ty(), VoidPtr, VoidPtr);
3160 TaskStructType, TaskGEP, {
Zero, ConstantInt::get(Int32Ty, 4)});
3163 Value *CmplrData =
Builder.CreateInBoundsGEP(CmplrStructType,
3165 Builder.CreateStore(Priority, CmplrData);
3168 Value *DepArray =
nullptr;
3169 Value *NumDeps =
nullptr;
3172 NumDeps = Dependencies.
NumDeps;
3173 }
else if (!Dependencies.
Deps.empty()) {
3175 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
3195 if (IfCondition && !UseMergedIf0Path) {
3200 Builder.GetInsertPoint()->getParent()->getTerminator();
3201 Instruction *ThenTI = IfTerminator, *ElseTI =
nullptr;
3202 Builder.SetInsertPoint(IfTerminator);
3205 Builder.SetInsertPoint(ElseTI);
3212 {Ident, ThreadID, NumDeps, DepArray,
3213 ConstantInt::get(
Builder.getInt32Ty(), 0),
3228 Builder.SetInsertPoint(ThenTI);
3236 {Ident, ThreadID, TaskData, NumDeps, DepArray,
3237 ConstantInt::get(
Builder.getInt32Ty(), 0),
3250 LoadInst *Shareds =
Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
3251 OutlinedFn.getArg(1)->replaceUsesWithIf(
3252 Shareds, [Shareds](
Use &U) {
return U.getUser() != Shareds; });
3258 Builder.ClearInsertionPoint();
3260 I->eraseFromParent();
3286 if (
Error Err = BodyGenCB(AllocaIP,
Builder.saveIP(), DeallocBlocks))
3289 Builder.SetInsertPoint(TaskgroupExitBB);
3332 unsigned CaseNumber = 0;
3333 for (
auto SectionCB : SectionCBs) {
3335 M.getContext(),
"omp_section_loop.body.case", CurFn,
Continue);
3337 Builder.SetInsertPoint(CaseBB);
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");
3359 applyStaticWorkshareLoop(
Loc.DL, *
LoopInfo, AllocaIP,
3360 WorksharingLoopType::ForStaticLoop, !IsNowait);
3366 assert(LoopFini &&
"Bad structure of static workshare loop finalization");
3370 assert(FiniInfo.DK == OMPD_sections &&
3371 "Unexpected finalization stack state!");
3372 if (
Error Err = FiniInfo.mergeFiniBB(
Builder, LoopFini))
3386 if (IP != IP.getNodeParent()->end())
3397 auto *CaseBB =
Loc.IP.getNodeParent();
3398 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
3399 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
3401 IP =
I->getIterator();
3405 Directive OMPD = Directive::OMPD_sections;
3408 return EmitOMPInlinedRegion(OMPD,
nullptr,
nullptr, BodyGenCB, FiniCBWrapper,
3419Value *OpenMPIRBuilder::getGPUThreadID() {
3422 OMPRTL___kmpc_get_hardware_thread_id_in_block),
3426Value *OpenMPIRBuilder::getGPUWarpSize() {
3431Value *OpenMPIRBuilder::getNVPTXWarpID() {
3432 unsigned LaneIDBits =
Log2_32(
Config.getGridValue().GV_Warp_Size);
3433 return Builder.CreateAShr(getGPUThreadID(), LaneIDBits,
"nvptx_warp_id");
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 = ~0
u >> (32u - LaneIDBits);
3440 return Builder.CreateAnd(getGPUThreadID(),
Builder.getInt32(LaneIDMask),
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)
3453 if (FromSize == ToSize)
3454 return Builder.CreateBitCast(From, ToType);
3456 return Builder.CreateIntCast(From, ToType,
true);
3462 Value *ValCastItem =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3463 CastItem,
Builder.getPtrTy(0));
3464 Builder.CreateStore(From, ValCastItem);
3465 return Builder.CreateLoad(ToType, CastItem);
3472 uint64_t Size =
M.getDataLayout().getTypeStoreSize(ElementType);
3473 assert(
Size <= 8 &&
"Unsupported bitwidth in shuffle instruction");
3477 Value *ElemCast = castValueToType(AllocaIP, Element, CastTy);
3479 Builder.CreateIntCast(getGPUWarpSize(),
Builder.getInt16Ty(),
true);
3481 Size <= 4 ? RuntimeFunction::OMPRTL___kmpc_shuffle_int32
3482 : RuntimeFunction::OMPRTL___kmpc_shuffle_int64);
3483 Value *WarpSizeCast =
3485 Value *ShuffleCall =
3490 return castValueToType(AllocaIP, ShuffleCall, ElementType);
3497 uint64_t Size =
M.getDataLayout().getTypeStoreSize(ElemType);
3509 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3510 Value *ElemPtr = DstAddr;
3511 Value *Ptr = SrcAddr;
3512 for (
unsigned IntSize = 8; IntSize >= 1; IntSize /= 2) {
3516 Ptr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3519 Builder.CreateGEP(ElemType, SrcAddr, {ConstantInt::get(IndexTy, 1)});
3520 ElemPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3524 if ((
Size / IntSize) > 1) {
3525 Value *PtrEnd =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3526 SrcAddrGEP,
Builder.getPtrTy());
3543 Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr,
Builder.getPtrTy()));
3545 Builder.CreateICmpSGT(PtrDiff,
Builder.getInt64(IntSize - 1)), ThenBB,
3548 Value *Res = createRuntimeShuffleFunction(
3551 IntType, Ptr,
M.getDataLayout().getPrefTypeAlign(ElemType)),
3553 Builder.CreateAlignedStore(Res, ElemPtr,
3554 M.getDataLayout().getPrefTypeAlign(ElemType));
3556 Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3557 Value *LocalElemPtr =
3558 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
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)});
3571 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3577Error OpenMPIRBuilder::emitReductionListCopy(
3582 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3583 Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
3587 for (
auto En :
enumerate(ReductionInfos)) {
3589 Value *SrcElementAddr =
nullptr;
3590 AllocaInst *DestAlloca =
nullptr;
3591 Value *DestElementAddr =
nullptr;
3592 Value *DestElementPtrAddr =
nullptr;
3594 bool ShuffleInElement =
false;
3597 bool UpdateDestListPtr =
false;
3601 ReductionArrayTy, SrcBase,
3602 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3603 SrcElementAddr =
Builder.CreateLoad(
Builder.getPtrTy(), SrcElementPtrAddr);
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()]);
3616 Type *DestAllocaType =
3617 IsByRefElem ? RI.ByRefAllocatedType : RI.ElementType;
3618 DestAlloca =
Builder.CreateAlloca(DestAllocaType,
nullptr,
3619 ".omp.reduction.element");
3621 M.getDataLayout().getPrefTypeAlign(DestAllocaType));
3622 DestElementAddr = DestAlloca;
3625 DestElementAddr->
getName() +
".ascast");
3627 ShuffleInElement =
true;
3628 UpdateDestListPtr =
true;
3640 if (ShuffleInElement) {
3641 Type *ShuffleType = RI.ElementType;
3642 Value *ShuffleSrcAddr = SrcElementAddr;
3643 Value *ShuffleDestAddr = DestElementAddr;
3644 AllocaInst *LocalStorage =
nullptr;
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");
3654 ShuffleType = RI.ByRefElementType;
3656 if (RI.DataPtrPtrGen) {
3659 Builder.saveIP(), ShuffleSrcAddr, ShuffleSrcAddr);
3662 return GenResult.takeError();
3671 LocalStorage =
Builder.CreateAlloca(ShuffleType);
3673 ShuffleDestAddr = LocalStorage;
3678 ShuffleDestAddr = DestElementAddr;
3682 shuffleAndStore(AllocaIP, ShuffleSrcAddr, ShuffleDestAddr, ShuffleType,
3683 RemoteLaneOffset, ReductionArrayTy, IsByRefElem);
3685 if (IsByRefElem && RI.DataPtrPtrGen) {
3687 Value *DestDescriptorAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3688 DestAlloca,
Builder.getPtrTy(),
".ascast");
3691 DestDescriptorAddr, LocalStorage, SrcElementAddr,
3692 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
3695 return GenResult.takeError();
3698 switch (RI.EvaluationKind) {
3700 Value *Elem =
Builder.CreateLoad(RI.ElementType, SrcElementAddr);
3702 Builder.CreateStore(Elem, DestElementAddr);
3706 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
3707 RI.ElementType, SrcElementAddr, 0, 0,
".realp");
3709 RI.ElementType->getStructElementType(0), SrcRealPtr,
".real");
3711 RI.ElementType, SrcElementAddr, 0, 1,
".imagp");
3713 RI.ElementType->getStructElementType(1), SrcImgPtr,
".imag");
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);
3725 M.getDataLayout().getTypeStoreSize(RI.ElementType));
3727 DestElementAddr,
M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3728 SrcElementAddr,
M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3740 if (UpdateDestListPtr) {
3741 Value *CastDestAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3742 DestElementAddr,
Builder.getPtrTy(),
3743 DestElementAddr->
getName() +
".ascast");
3744 Builder.CreateStore(CastDestAddr, DestElementPtrAddr);
3751Expected<Function *> OpenMPIRBuilder::emitInterWarpCopyFunction(
3754 IRBuilder<>::InsertPointGuard IPG(
Builder);
3755 LLVMContext &Ctx =
M.getContext();
3757 Builder.getVoidTy(), {Builder.getPtrTy(), Builder.getInt32Ty()},
3761 "_omp_reduction_inter_warp_copy_func", &
M);
3767 Builder.SetInsertPoint(EntryBB);
3785 StringRef TransferMediumName =
3786 "__openmp_nvptx_data_transfer_temporary_storage";
3787 GlobalVariable *TransferMedium =
M.getGlobalVariable(TransferMediumName);
3788 unsigned WarpSize =
Config.getGridValue().GV_Warp_Size;
3790 if (!TransferMedium) {
3791 TransferMedium =
new GlobalVariable(
3799 Value *GPUThreadID = getGPUThreadID();
3801 Value *LaneID = getNVPTXLaneID();
3803 Value *WarpID = getNVPTXWarpID();
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);
3828 for (
auto En :
enumerate(ReductionInfos)) {
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) {
3840 unsigned NumIters = RealTySize / TySize;
3843 Value *Cnt =
nullptr;
3844 Value *CntAddr =
nullptr;
3851 Builder.CreateAlloca(
Builder.getInt32Ty(),
nullptr,
".cnt.addr");
3853 CntAddr =
Builder.CreateAddrSpaceCast(CntAddr,
Builder.getPtrTy(),
3854 CntAddr->
getName() +
".ascast");
3866 Cnt, ConstantInt::get(
Builder.getInt32Ty(), NumIters));
3867 Builder.CreateCondBr(Cmp, BodyBB, ExitBB);
3874 omp::Directive::OMPD_unknown,
3878 return BarrierIP1.takeError();
3884 Value *IsWarpMaster =
Builder.CreateIsNull(LaneID,
"warp_master");
3885 Builder.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3889 auto *RedListArrayTy =
3892 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3894 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3895 {ConstantInt::get(IndexTy, 0),
3896 ConstantInt::get(IndexTy, En.index())});
3900 if (IsByRefElem && RI.DataPtrPtrGen) {
3902 RI.DataPtrPtrGen(
Builder.saveIP(), ElemPtr, ElemPtr);
3905 return GenRes.takeError();
3916 ArrayTy, TransferMedium, {
Builder.getInt64(0), WarpID});
3921 Builder.CreateStore(Elem, MediumPtr,
3933 omp::Directive::OMPD_unknown,
3937 return BarrierIP2.takeError();
3944 Value *NumWarpsVal =
3947 Value *IsActiveThread =
3948 Builder.CreateICmpULT(GPUThreadID, NumWarpsVal,
"is_active_thread");
3949 Builder.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3956 ArrayTy, TransferMedium, {
Builder.getInt64(0), GPUThreadID});
3958 Value *TargetElemPtrPtr =
3959 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3960 {ConstantInt::get(IndexTy, 0),
3961 ConstantInt::get(IndexTy, En.index())});
3962 Value *TargetElemPtrVal =
3964 Value *TargetElemPtr = TargetElemPtrVal;
3966 if (IsByRefElem && RI.DataPtrPtrGen) {
3968 RI.DataPtrPtrGen(
Builder.saveIP(), TargetElemPtr, TargetElemPtr);
3971 return GenRes.takeError();
3973 TargetElemPtr =
Builder.CreateLoad(
Builder.getPtrTy(), TargetElemPtr);
3981 Value *SrcMediumValue =
3982 Builder.CreateLoad(CType, SrcMediumPtrVal,
true);
3983 Builder.CreateStore(SrcMediumValue, TargetElemPtr);
3993 Cnt, ConstantInt::get(
Builder.getInt32Ty(), 1));
3994 Builder.CreateStore(Cnt, CntAddr,
false);
3996 auto *CurFn =
Builder.GetInsertBlock()->getParent();
4000 RealTySize %= TySize;
4009Expected<Function *> OpenMPIRBuilder::emitShuffleAndReduceFunction(
4012 LLVMContext &Ctx =
M.getContext();
4013 IRBuilder<>::InsertPointGuard IPG(
Builder);
4014 FunctionType *FuncTy =
4016 {Builder.getPtrTy(), Builder.getInt16Ty(),
4017 Builder.getInt16Ty(), Builder.getInt16Ty()},
4021 "_omp_reduction_shuffle_and_reduce_func", &
M);
4032 Builder.SetInsertPoint(EntryBB);
4044 Type *ReduceListArgType = ReduceListArg->
getType();
4048 ReduceListArgType,
nullptr, ReduceListArg->
getName() +
".addr");
4049 Value *LaneIdAlloca =
Builder.CreateAlloca(LaneIDArgType,
nullptr,
4050 LaneIDArg->
getName() +
".addr");
4052 LaneIDArgType,
nullptr, RemoteLaneOffsetArg->
getName() +
".addr");
4053 Value *AlgoVerAlloca =
Builder.CreateAlloca(LaneIDArgType,
nullptr,
4054 AlgoVerArg->
getName() +
".addr");
4061 RedListArrayTy,
nullptr,
".omp.reduction.remote_reduce_list");
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");
4077 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
4078 Builder.CreateStore(LaneIDArg, LaneIdAddrCast);
4079 Builder.CreateStore(RemoteLaneOffsetArg, RemoteLaneOffsetAddrCast);
4080 Builder.CreateStore(AlgoVerArg, AlgoVerAddrCast);
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);
4093 Error EmitRedLsCpRes = emitReductionListCopy(
4095 ReduceList, RemoteListAddrCast, IsByRef,
4096 {RemoteLaneOffset,
nullptr,
nullptr});
4099 return EmitRedLsCpRes;
4124 Value *LaneComp =
Builder.CreateICmpULT(LaneId, RemoteLaneOffset);
4129 Value *Algo2AndLaneIdComp =
Builder.CreateAnd(Algo2, LaneIdComp);
4130 Value *RemoteOffsetComp =
4132 Value *CondAlgo2 =
Builder.CreateAnd(Algo2AndLaneIdComp, RemoteOffsetComp);
4133 Value *CA0OrCA1 =
Builder.CreateOr(CondAlgo0, CondAlgo1);
4134 Value *CondReduce =
Builder.CreateOr(CA0OrCA1, CondAlgo2);
4140 Builder.CreateCondBr(CondReduce, ThenBB, ElseBB);
4142 Value *LocalReduceListPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4143 ReduceList,
Builder.getPtrTy());
4144 Value *RemoteReduceListPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4145 RemoteListAddrCast,
Builder.getPtrTy());
4147 ->addFnAttr(Attribute::NoUnwind);
4158 Value *LaneIdGtOffset =
Builder.CreateICmpUGE(LaneId, RemoteLaneOffset);
4159 Value *CondCopy =
Builder.CreateAnd(Algo1, LaneIdGtOffset);
4164 Builder.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
4168 EmitRedLsCpRes = emitReductionListCopy(
4170 RemoteListAddrCast, ReduceList, IsByRef);
4173 return EmitRedLsCpRes;
4188OpenMPIRBuilder::generateReductionDescriptor(
4190 Type *DescriptorType,
4196 Value *DescriptorSize =
4197 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(DescriptorType));
4199 DescriptorAddr,
M.getDataLayout().getPrefTypeAlign(DescriptorType),
4200 SrcDescriptorAddr,
M.getDataLayout().getPrefTypeAlign(DescriptorType),
4204 Value *DataPtrField;
4206 DataPtrPtrGen(
Builder.saveIP(), DescriptorAddr, DataPtrField);
4209 return GenResult.takeError();
4212 DataPtr,
Builder.getPtrTy(),
".ascast"),
4218Expected<Value *> OpenMPIRBuilder::createReductionDescriptorCopy(
4220 Value *SrcDescriptorAddr,
Type *DescriptorPtrTy,
const Twine &Name) {
4224 AllocaInst *DescriptorAlloca =
4225 Builder.CreateAlloca(RI.ByRefAllocatedType,
nullptr, Name);
4227 M.getDataLayout().getPrefTypeAlign(RI.ByRefAllocatedType));
4228 Value *DescriptorAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4229 DescriptorAlloca, DescriptorPtrTy,
4230 DescriptorAlloca->
getName() +
".ascast");
4235 generateReductionDescriptor(DescriptorAddr, DataPtr, SrcDescriptorAddr,
4236 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
4238 return GenResult.takeError();
4240 return DescriptorAddr;
4243Expected<Function *> OpenMPIRBuilder::emitListToGlobalCopyFunction(
4246 IRBuilder<>::InsertPointGuard IPG(
Builder);
4247 LLVMContext &Ctx =
M.getContext();
4250 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4254 "_omp_reduction_list_to_global_copy_func", &
M);
4261 Builder.SetInsertPoint(EntryBlock);
4272 BufferArg->
getName() +
".addr");
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");
4286 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4287 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4288 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4290 Value *LocalReduceList =
4292 Value *BufferArgVal =
4296 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4297 for (
auto En :
enumerate(ReductionInfos)) {
4299 auto *RedListArrayTy =
4303 RedListArrayTy, LocalReduceList,
4304 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4310 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferArgVal, Idxs);
4312 ReductionsBufferTy, BufferVD, 0, En.index());
4314 switch (RI.EvaluationKind) {
4316 Value *TargetElement;
4318 if (IsByRef.
empty() || !IsByRef[En.index()]) {
4319 TargetElement =
Builder.CreateLoad(RI.ElementType, ElemPtr);
4321 if (RI.DataPtrPtrGen) {
4323 RI.DataPtrPtrGen(
Builder.saveIP(), ElemPtr, ElemPtr);
4326 return GenResult.takeError();
4330 TargetElement =
Builder.CreateLoad(RI.ByRefElementType, ElemPtr);
4333 Builder.CreateStore(TargetElement, GlobVal);
4337 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4338 RI.ElementType, ElemPtr, 0, 0,
".realp");
4340 RI.ElementType->getStructElementType(0), SrcRealPtr,
".real");
4342 RI.ElementType, ElemPtr, 0, 1,
".imagp");
4344 RI.ElementType->getStructElementType(1), SrcImgPtr,
".imag");
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);
4356 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(RI.ElementType));
4358 GlobVal,
M.getDataLayout().getPrefTypeAlign(RI.ElementType), ElemPtr,
4359 M.getDataLayout().getPrefTypeAlign(RI.ElementType), SizeVal,
false);
4369Expected<Function *> OpenMPIRBuilder::emitListToGlobalReduceFunction(
4372 IRBuilder<>::InsertPointGuard IPG(
Builder);
4373 LLVMContext &Ctx =
M.getContext();
4376 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4380 "_omp_reduction_list_to_global_reduce_func", &
M);
4387 Builder.SetInsertPoint(EntryBlock);
4398 BufferArg->
getName() +
".addr");
4402 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4403 auto *RedListArrayTy =
4408 Value *LocalReduceList =
4409 Builder.CreateAlloca(RedListArrayTy,
nullptr,
".omp.reduction.red_list");
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");
4425 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4426 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4427 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4432 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4433 for (
auto En :
enumerate(ReductionInfos)) {
4436 Value *TargetElementPtrPtr =
Builder.CreateInBoundsGEP(
4437 RedListArrayTy, LocalReduceListAddrCast,
4438 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4440 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4442 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4443 ReductionsBufferTy, BufferVD, 0, En.index());
4445 if (!IsByRef.
empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4449 Value *SrcElementPtrPtr =
4450 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
4451 {ConstantInt::get(IndexTy, 0),
4452 ConstantInt::get(IndexTy, En.index())});
4453 Value *SrcDescriptorAddr =
4457 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4458 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr,
Builder.getPtrTy());
4462 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4464 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4472 ->addFnAttr(Attribute::NoUnwind);
4477Expected<Function *> OpenMPIRBuilder::emitGlobalToListCopyFunction(
4480 IRBuilder<>::InsertPointGuard IPG(
Builder);
4481 LLVMContext &Ctx =
M.getContext();
4484 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4488 "_omp_reduction_global_to_list_copy_func", &
M);
4495 Builder.SetInsertPoint(EntryBlock);
4506 BufferArg->
getName() +
".addr");
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);
4523 Value *LocalReduceList =
4528 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4529 for (
auto En :
enumerate(ReductionInfos)) {
4530 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
4531 auto *RedListArrayTy =
4535 RedListArrayTy, LocalReduceList,
4536 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4541 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4542 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4543 ReductionsBufferTy, BufferVD, 0, En.index());
4549 if (!IsByRef.
empty() && IsByRef[En.index()]) {
4556 return GenResult.takeError();
4562 Value *TargetElement =
Builder.CreateLoad(ElemType, GlobValPtr);
4563 Builder.CreateStore(TargetElement, ElemPtr);
4567 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4576 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4578 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
4580 Builder.CreateStore(SrcReal, DestRealPtr);
4581 Builder.CreateStore(SrcImg, DestImgPtr);
4588 ElemPtr,
M.getDataLayout().getPrefTypeAlign(RI.
ElementType),
4589 GlobValPtr,
M.getDataLayout().getPrefTypeAlign(RI.
ElementType),
4600Expected<Function *> OpenMPIRBuilder::emitGlobalToListReduceFunction(
4603 IRBuilder<>::InsertPointGuard IPG(
Builder);
4604 LLVMContext &Ctx =
M.getContext();
4607 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4611 "_omp_reduction_global_to_list_reduce_func", &
M);
4618 Builder.SetInsertPoint(EntryBlock);
4629 BufferArg->
getName() +
".addr");
4633 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4639 Value *LocalReduceList =
4640 Builder.CreateAlloca(RedListArrayTy,
nullptr,
".omp.reduction.red_list");
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");
4656 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4657 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4658 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4663 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4664 for (
auto En :
enumerate(ReductionInfos)) {
4667 Value *TargetElementPtrPtr =
Builder.CreateInBoundsGEP(
4668 RedListArrayTy, ReductionList,
4669 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4672 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4673 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4674 ReductionsBufferTy, BufferVD, 0, En.index());
4676 if (!IsByRef.
empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4678 Value *ReduceListVal =
4680 Value *SrcElementPtrPtr =
4681 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceListVal,
4682 {ConstantInt::get(IndexTy, 0),
4683 ConstantInt::get(IndexTy, En.index())});
4684 Value *SrcDescriptorAddr =
4688 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4689 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr,
Builder.getPtrTy());
4693 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4695 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4703 ->addFnAttr(Attribute::NoUnwind);
4708std::string OpenMPIRBuilder::getReductionFuncName(StringRef Name)
const {
4709 std::string Suffix =
4711 return (Name + Suffix).str();
4714Expected<Function *> OpenMPIRBuilder::createReductionFunction(
4717 AttributeList FuncAttrs) {
4718 IRBuilder<>::InsertPointGuard IPG(
Builder);
4720 {Builder.getPtrTy(), Builder.getPtrTy()},
4722 std::string
Name = getReductionFuncName(ReducerName);
4731 Builder.SetInsertPoint(EntryBB);
4736 Value *LHSArrayPtr =
nullptr;
4737 Value *RHSArrayPtr =
nullptr;
4744 Builder.CreateAlloca(Arg0Type,
nullptr, Arg0->
getName() +
".addr");
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);
4758 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4760 for (
auto En :
enumerate(ReductionInfos)) {
4763 RedArrayTy, RHSArrayPtr,
4764 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4766 Value *RHSPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4767 RHSI8Ptr, RI.PrivateVariable->getType(),
4768 RHSI8Ptr->
getName() +
".ascast");
4771 RedArrayTy, LHSArrayPtr,
4772 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4774 Value *LHSPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4775 LHSI8Ptr, RI.Variable->getType(), LHSI8Ptr->
getName() +
".ascast");
4784 if (!IsByRef.
empty() && !IsByRef[En.index()]) {
4785 LHS =
Builder.CreateLoad(RI.ElementType, LHSPtr);
4786 RHS =
Builder.CreateLoad(RI.ElementType, RHSPtr);
4793 return AfterIP.takeError();
4794 if (!
Builder.GetInsertBlock())
4795 return ReductionFunc;
4799 if (!IsByRef.
empty() && !IsByRef[En.index()])
4800 Builder.CreateStore(Reduced, LHSPtr);
4805 for (
auto En :
enumerate(ReductionInfos)) {
4806 unsigned Index = En.index();
4808 Value *LHSFixupPtr, *RHSFixupPtr;
4809 Builder.restoreIP(RI.ReductionGenClang(
4810 Builder.saveIP(), Index, &LHSFixupPtr, &RHSFixupPtr, ReductionFunc));
4815 LHSPtrs[Index], [ReductionFunc](
const Use &U) {
4820 RHSPtrs[Index], [ReductionFunc](
const Use &U) {
4834 return ReductionFunc;
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");
4848 RI.Variable->getType() == RI.PrivateVariable->getType() &&
4849 "expected variables and their private equivalents to have the same "
4852 assert(RI.Variable->getType()->isPointerTy() &&
4853 "expected variables to be pointers");
4870 ArrayRef<bool> IsByRef,
bool IsNoWait,
bool IsTeamsReduction,
bool IsSPMD,
4872 Value *SrcLocInfo) {
4887 if (ReductionInfos.
size() == 0)
4901 AttrBuilder AttrBldr(Ctx);
4903 AttrBldr.addAttribute(Attr);
4904 AttrBldr.removeAttribute(Attribute::OptimizeNone);
4905 FuncAttrs = FuncAttrs.addFnAttributes(Ctx, AttrBldr);
4908 Builder.GetInsertBlock()->getParent()->getName(), ReductionInfos, IsByRef,
4910 if (!ReductionResult)
4912 Function *ReductionFunc = *ReductionResult;
4915 if (GridValue.has_value())
4916 Config.setGridValue(GridValue.value());
4931 Builder.getPtrTy(
M.getDataLayout().getProgramAddressSpace());
4933 Value *ReductionList;
4937 Value *ReductionListAlloca =
4938 Builder.CreateAlloca(RedArrayTy,
nullptr,
".omp.reduction.red_list");
4939 ReductionList =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4940 ReductionListAlloca, PtrTy, ReductionListAlloca->
getName() +
".ascast");
4943 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4944 for (
auto En :
enumerate(ReductionInfos)) {
4947 RedArrayTy, ReductionList,
4948 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4951 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
4956 Builder.CreatePointerBitCastOrAddrSpaceCast(PrivateVar, PtrTy);
4957 Builder.CreateStore(CastElem, ElemPtr);
4960 ReductionInfos, ReductionFunc, FuncAttrs, IsByRef);
4966 emitInterWarpCopyFunction(
Loc, ReductionInfos, FuncAttrs, IsByRef);
4971 Value *RL =
Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList, PtrTy);
4980 unsigned MaxDataSize = 0;
4982 for (
auto En :
enumerate(ReductionInfos)) {
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)
4994 Value *ReductionDataSize =
4995 Builder.getInt64(MaxDataSize * ReductionInfos.
size());
4999 Function *CopyScratchToListFunc =
nullptr;
5001 Value *ScratchForCopyBack =
nullptr;
5004 Value *RLForCopyBack = RL;
5006 bool IsAtomicReduction =
5009 if (!IsTeamsReduction) {
5010 Value *SarFuncCast =
5011 Builder.CreatePointerBitCastOrAddrSpaceCast(*SarFunc, FuncPtrTy);
5013 Builder.CreatePointerBitCastOrAddrSpaceCast(WcFunc, FuncPtrTy);
5014 Value *Args[] = {SrcLocInfo, ReductionDataSize, RL, SarFuncCast,
5017 RuntimeFunction::OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2);
5019 }
else if (IsAtomicReduction) {
5023 RuntimeFunction::OMPRTL___kmpc_is_team_main_thread);
5027 Ctx, ReductionTypeArgs,
"struct._globalized_locals_ty");
5030 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5035 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5040 ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs, IsByRef);
5061 Value *RuntimeRL = RL;
5064 Value *PerThreadScratch;
5070 Value *PerThreadScratchAlloca =
5071 Builder.CreateAlloca(ReductionsBufferTy,
nullptr,
5072 ".omp.reduction.scratch");
5073 PerThreadScratch =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5074 PerThreadScratchAlloca, PtrTy,
5075 PerThreadScratchAlloca->
getName() +
".ascast");
5078 Value *PerThreadRedListAlloca =
5079 Builder.CreateAlloca(RedArrayTy,
nullptr,
5080 ".omp.reduction.per_thread_red_list");
5081 RuntimeRL =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5082 PerThreadRedListAlloca, PtrTy,
5083 PerThreadRedListAlloca->
getName() +
".ascast");
5088 for (
auto En :
enumerate(ReductionInfos)) {
5090 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
5093 ReductionsBufferTy, PerThreadScratch, 0, En.index());
5094 Value *Slot =
Builder.CreateConstInBoundsGEP2_32(RedArrayTy, RuntimeRL,
5097 Value *RuntimeListEntry = FieldPtr;
5099 Value *SrcDescriptor =
5102 AllocaIP, RI, FieldPtr, SrcDescriptor, PtrTy);
5105 RuntimeListEntry = *Descriptor;
5107 Builder.CreateStore(RuntimeListEntry, Slot);
5113 Type *CopyArg0Ty = (*LtGCFunc)->getFunctionType()->getParamType(0);
5114 Type *CopyArg2Ty = (*LtGCFunc)->getFunctionType()->getParamType(2);
5115 ScratchForCopyBack =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5116 PerThreadScratch, CopyArg0Ty);
5118 Builder.CreatePointerBitCastOrAddrSpaceCast(RL, CopyArg2Ty);
5126 *LtGCFunc, {ScratchForCopyBack,
Builder.getInt32(0), RLForCopyBack});
5127 CopyScratchToListFunc = *GtLCFunc;
5130 Value *Args3[] = {SrcLocInfo, RuntimeRL, *SarFunc, WcFunc,
5131 *LtGCFunc, *GtLCFunc, *GtLRFunc};
5134 RuntimeFunction::OMPRTL___kmpc_gpu_xteam_reduce_nowait);
5154 if (ScratchForCopyBack) {
5157 CopyScratchToListFunc,
5158 {ScratchForCopyBack,
Builder.getInt32(0), RLForCopyBack});
5162 for (
auto En :
enumerate(ReductionInfos)) {
5168 if (IsAtomicReduction) {
5184 Value *LHSPtr, *RHSPtr;
5186 &LHSPtr, &RHSPtr, CurFunc));
5192 RedValue =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5194 if (RHSPtr->
getType() != RHS->getType())
5196 Builder.CreatePointerBitCastOrAddrSpaceCast(RHS, RHSPtr->
getType());
5207 if (IsByRef.
empty() || !IsByRef[En.index()]) {
5209 "red.value." +
Twine(En.index()));
5220 if (!IsByRef.
empty() && !IsByRef[En.index()])
5225 if (ContinuationBlock) {
5226 Builder.CreateBr(ContinuationBlock);
5227 Builder.SetInsertPoint(ContinuationBlock);
5229 Config.setEmitLLVMUsed();
5240 ".omp.reduction.func", &M);
5251 Builder.SetInsertPoint(ReductionFuncBlock);
5253 Value *LHSArrayPtr =
nullptr;
5254 Value *RHSArrayPtr =
nullptr;
5265 Builder.CreateAlloca(Arg0Type,
nullptr, Arg0->
getName() +
".addr");
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);
5277 LHSArrayPtr = ReductionFunc->
getArg(0);
5278 RHSArrayPtr = ReductionFunc->
getArg(1);
5281 unsigned NumReductions = ReductionInfos.
size();
5284 for (
auto En :
enumerate(ReductionInfos)) {
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(
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(
5304 Builder.restoreIP(*AfterIP);
5306 if (!Builder.GetInsertBlock())
5310 if (!IsByRef[En.index()])
5311 Builder.CreateStore(Reduced, LHSPtr);
5313 Builder.CreateRetVoid();
5320 bool IsNoWait,
bool IsTeamsReduction) {
5324 IsByRef, IsNoWait, IsTeamsReduction);
5331 if (ReductionInfos.
size() == 0)
5341 unsigned NumReductions = ReductionInfos.
size();
5343 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getTerminator());
5344 Value *RedArray =
Builder.CreateAlloca(RedArrayTy,
nullptr,
"red.array");
5351 for (
auto En :
enumerate(ReductionInfos)) {
5352 unsigned Index = En.index();
5354 Value *RedArrayElemPtr =
Builder.CreateConstInBoundsGEP2_64(
5355 RedArrayTy, RedArray, 0, Index,
"red.array.elem." +
Twine(Index));
5362 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
5372 ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
5377 unsigned RedArrayByteSize =
DL.getTypeStoreSize(RedArrayTy);
5378 Constant *RedArraySize = ConstantInt::get(IndexTy, RedArrayByteSize);
5380 Value *Lock = getOMPCriticalRegionLock(
".reduction");
5382 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
5383 : RuntimeFunction::OMPRTL___kmpc_reduce);
5386 {Ident, ThreadId, NumVariables, RedArraySize,
5387 RedArray, ReductionFunc, Lock},
5398 Builder.CreateSwitch(ReduceCall, ContinuationBlock, 2);
5399 Switch->addCase(
Builder.getInt32(1), NonAtomicRedBlock);
5400 Switch->addCase(
Builder.getInt32(2), AtomicRedBlock);
5405 Builder.SetInsertPoint(NonAtomicRedBlock);
5406 for (
auto En :
enumerate(ReductionInfos)) {
5412 if (!IsByRef[En.index()]) {
5414 "red.value." +
Twine(En.index()));
5416 Value *PrivateRedValue =
5418 "red.private.value." +
Twine(En.index()));
5426 if (!
Builder.GetInsertBlock())
5429 if (!IsByRef[En.index()])
5433 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
5434 : RuntimeFunction::OMPRTL___kmpc_end_reduce);
5436 Builder.CreateBr(ContinuationBlock);
5441 Builder.SetInsertPoint(AtomicRedBlock);
5442 if (CanGenerateAtomic &&
llvm::none_of(IsByRef, [](
bool P) {
return P; })) {
5449 if (!
Builder.GetInsertBlock())
5452 Builder.CreateBr(ContinuationBlock);
5465 if (!
Builder.GetInsertBlock())
5468 Builder.SetInsertPoint(ContinuationBlock);
5479 Directive OMPD = Directive::OMPD_master;
5484 Value *Args[] = {Ident, ThreadId};
5492 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5504 Directive OMPD = Directive::OMPD_masked;
5510 Value *ArgsEnd[] = {Ident, ThreadId};
5518 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5528 Call->setDoesNotThrow();
5543 bool IsInclusive,
ScanInfo *ScanRedInfo) {
5545 llvm::Error Err = emitScanBasedDirectiveDeclsIR(AllocaIP, ScanVars,
5546 ScanVarsType, ScanRedInfo);
5557 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5560 Type *DestTy = ScanVarsType[i];
5561 Value *Val =
Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5564 Builder.CreateStore(Src, Val);
5569 Builder.GetInsertBlock()->getParent());
5572 IV = ScanRedInfo->
IV;
5575 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5578 Type *DestTy = ScanVarsType[i];
5580 Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5582 Builder.CreateStore(Src, ScanVars[i]);
5596 Builder.GetInsertBlock()->getParent());
5601Error OpenMPIRBuilder::emitScanBasedDirectiveDeclsIR(
5605 Builder.restoreIP(AllocaIP);
5607 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5609 Builder.CreateAlloca(Builder.getPtrTy(),
nullptr,
"vla");
5616 Builder.restoreIP(CodeGenIP);
5618 Builder.CreateAdd(ScanRedInfo->
Span, Builder.getInt32(1));
5619 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5621 Value *Allocsize = Builder.CreateTypeSize(
5622 IntPtrTy, M.getDataLayout().getTypeAllocSize(ScanVarsType[i]));
5624 Builder.CreateMalloc(
IntPtrTy, Allocsize, AllocSpan,
nullptr,
"arr");
5625 Builder.CreateStore(Buff, (*(ScanRedInfo->
ScanBuffPtrs))[ScanVars[i]]);
5652Error OpenMPIRBuilder::emitScanBasedDirectiveFinalsIR(
5658 Value *PrivateVar = RedInfo.PrivateVariable;
5659 Value *OrigVar = RedInfo.Variable;
5663 Type *SrcTy = RedInfo.ElementType;
5668 Builder.CreateStore(Src, OrigVar);
5729 llvm::ConstantInt::get(ScanRedInfo->
Span->
getType(), 1));
5730 Builder.SetInsertPoint(InputBB);
5733 Builder.SetInsertPoint(LoopBB);
5749 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5751 Builder.SetInsertPoint(InnerLoopBB);
5755 Value *ReductionVal = RedInfo.PrivateVariable;
5758 Type *DestTy = RedInfo.ElementType;
5761 Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5764 Builder.CreateInBoundsGEP(DestTy, Buff, OffsetIval,
"arrayOffset");
5769 RedInfo.ReductionGen(
Builder.saveIP(), LHS, RHS, Result);
5772 Builder.CreateStore(Result, LHSPtr);
5775 IVal, llvm::ConstantInt::get(
Builder.getInt32Ty(), 1));
5777 CmpI =
Builder.CreateICmpUGE(NextIVal, Pow2K);
5778 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5781 Counter, llvm::ConstantInt::get(Counter->
getType(), 1));
5787 Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
5808 Error Err = emitScanBasedDirectiveFinalsIR(ReductionInfos, ScanRedInfo);
5815Error OpenMPIRBuilder::emitScanBasedDirectiveIR(
5827 Error Err = InputLoopGen();
5838 Error Err = ScanLoopGen(Builder);
5845void OpenMPIRBuilder::createScanBBs(ScanInfo *ScanRedInfo) {
5882 Builder.SetInsertPoint(Preheader);
5885 Builder.SetInsertPoint(Header);
5886 PHINode *IndVarPHI =
Builder.CreatePHI(IndVarTy, 2,
"omp_" + Name +
".iv");
5887 IndVarPHI->
addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
5892 Builder.CreateICmpULT(IndVarPHI, TripCount,
"omp_" + Name +
".cmp");
5893 Builder.CreateCondBr(Cmp, Body, Exit);
5898 Builder.SetInsertPoint(Latch);
5908 bool HasNSW =
Config.hasNoSignedWrap();
5911 unsigned BitWidth = CI->getType()->getIntegerBitWidth();
5913 if (CI->getValue().ugt(SignedMax))
5915 }
else if (IsCollapsed) {
5920 Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
5921 "omp_" + Name +
".next",
true, HasNSW);
5932 CL->Header = Header;
5951 NextBB, NextBB, Name);
5983 Value *Start,
Value *Stop,
Value *Step,
bool IsSigned,
bool InclusiveStop,
5992 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
5993 ScanRedInfo->
Span = TripCount;
5999 ScanRedInfo->
IV =
IV;
6000 createScanBBs(ScanRedInfo);
6003 assert(Terminator->getNumSuccessors() == 1);
6004 BasicBlock *ContinueBlock = Terminator->getSuccessor(0);
6007 Builder.GetInsertBlock()->getParent());
6010 Builder.GetInsertBlock()->getParent());
6011 Builder.CreateBr(ContinueBlock);
6017 const auto &&InputLoopGen = [&]() ->
Error {
6020 InclusiveStop, ComputeIP, Name,
true, ScanRedInfo);
6024 Builder.restoreIP((*LoopInfo)->getAfterIP());
6030 InclusiveStop, ComputeIP, Name,
true, ScanRedInfo);
6034 Builder.restoreIP((*LoopInfo)->getAfterIP());
6038 Error Err = emitScanBasedDirectiveIR(InputLoopGen, ScanLoopGen, ScanRedInfo);
6046 bool IsSigned,
bool InclusiveStop,
const Twine &Name) {
6056 assert(IndVarTy == Stop->
getType() &&
"Stop type mismatch");
6057 assert(IndVarTy == Step->
getType() &&
"Step type mismatch");
6077 Incr =
Builder.CreateSelect(IsNeg,
Builder.CreateNeg(Step), Step);
6080 Span =
Builder.CreateSub(UB, LB,
"",
false,
true);
6084 Span =
Builder.CreateSub(Stop, Start,
"",
true);
6089 Value *CountIfLooping;
6090 if (InclusiveStop) {
6091 CountIfLooping =
Builder.CreateAdd(
Builder.CreateUDiv(Span, Incr), One);
6097 CountIfLooping =
Builder.CreateSelect(OneCmp, One, CountIfTwo);
6100 return Builder.CreateSelect(ZeroCmp,
Zero, CountIfLooping,
6101 "omp_" + Name +
".tripcount");
6106 Value *Start,
Value *Stop,
Value *Step,
bool IsSigned,
bool InclusiveStop,
6113 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
6118 Config.hasNoSignedWrap());
6119 Value *IndVar =
Builder.CreateAdd(Span, Start,
"",
false,
6120 Config.hasNoSignedWrap());
6122 ScanRedInfo->
IV = IndVar;
6123 return BodyGenCB(
Builder.saveIP(), IndVar);
6129 Builder.getCurrentDebugLocation());
6140 unsigned Bitwidth = Ty->getIntegerBitWidth();
6143 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_4u);
6146 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_8u);
6156 unsigned Bitwidth = Ty->getIntegerBitWidth();
6159 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
6162 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
6170 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6172 "Require dedicated allocate IP");
6178 uint32_t SrcLocStrSize;
6182 case WorksharingLoopType::ForStaticLoop:
6183 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6185 case WorksharingLoopType::DistributeStaticLoop:
6186 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6188 case WorksharingLoopType::DistributeForStaticLoop:
6189 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6196 FunctionCallee StaticInit =
6197 LoopType == WorksharingLoopType::DistributeForStaticLoop
6200 FunctionCallee StaticFini =
6204 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
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");
6219 Constant *One = ConstantInt::get(IVTy, 1);
6222 Builder.CreateStore(UpperBound, PUpperBound);
6223 Builder.CreateStore(One, PStride);
6229 (LoopType == WorksharingLoopType::DistributeStaticLoop)
6230 ? OMPScheduleType::OrderedDistribute
6233 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6237 auto BuildInitCall = [LoopType, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6238 PUpperBound, IVTy, PStride, One,
Zero, StaticInit,
6241 PLowerBound, PUpperBound});
6242 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6243 Value *PDistUpperBound =
6244 Builder.CreateAlloca(IVTy,
nullptr,
"p.distupperbound");
6245 Args.push_back(PDistUpperBound);
6250 BuildInitCall(SchedulingType,
Builder);
6251 if (HasDistSchedule &&
6252 LoopType != WorksharingLoopType::DistributeStaticLoop) {
6253 Constant *DistScheduleSchedType = ConstantInt::get(
6258 BuildInitCall(DistScheduleSchedType,
Builder);
6261 Value *InclusiveUpperBound =
Builder.CreateLoad(IVTy, PUpperBound);
6263 Value *TripCount =
Builder.CreateAdd(TripCountMinusOne, One);
6264 if (CLI->VirtualCollapse) {
6265 bindCollapsedRange(CLI,
LowerBound, TripCount);
6270 CLI->setTripCount(TripCount);
6277 if (!CLI->VirtualCollapse)
6278 CLI->mapIndVar([&](Instruction *OldIV) ->
Value * {
6282 Config.hasNoSignedWrap());
6293 omp::Directive::OMPD_for,
false,
6296 return BarrierIP.takeError();
6327 Reachable.insert(
Block);
6341OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
6345 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6346 assert((ChunkSize || DistScheduleChunkSize) &&
"Chunk size is required");
6351 Type *IVTy =
IV->getType();
6353 "Max supported tripcount bitwidth is 64 bits");
6355 :
Type::getInt64Ty(Ctx);
6358 Constant *One = ConstantInt::get(InternalIVTy, 1);
6363 SmallVector<Instruction *> UIs;
6364 for (BasicBlock &BB : *
F)
6365 if (!BB.hasTerminator())
6366 UIs.
push_back(
new UnreachableInst(
F->getContext(), &BB));
6371 LoopInfo &&LI = LIA.
run(*
F,
FAM);
6372 for (Instruction *
I : UIs)
6373 I->eraseFromParent();
6376 if (ChunkSize || DistScheduleChunkSize)
6381 FunctionCallee StaticInit =
6383 FunctionCallee StaticFini =
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");
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");
6411 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6413 ConstantInt::get(I32Type,
static_cast<int>(DistScheduleSchedType));
6415 Value *OrigUpperBound =
Builder.CreateSub(CastedTripCount, One);
6418 Builder.CreateSelect(IsTripCountZero,
Zero, OrigUpperBound);
6419 Builder.CreateStore(UpperBound, PUpperBound);
6420 Builder.CreateStore(One, PStride);
6424 uint32_t SrcLocStrSize;
6427 if (DistScheduleSchedType != OMPScheduleType::None) {
6428 Flag |= OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6433 auto BuildInitCall = [StaticInit, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6434 PUpperBound, PStride, One,
6435 this](
Value *SchedulingType,
Value *ChunkSize,
6438 StaticInit, {SrcLoc, ThreadNum,
6439 SchedulingType, PLastIter,
6440 PLowerBound, PUpperBound,
6444 BuildInitCall(SchedulingType, CastedChunkSize,
Builder);
6445 if (DistScheduleSchedType != OMPScheduleType::None &&
6446 SchedType != OMPScheduleType::OrderedDistributeChunked &&
6447 SchedType != OMPScheduleType::OrderedDistribute) {
6451 BuildInitCall(DistSchedulingType, CastedDistScheduleChunkSize,
Builder);
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);
6461 Builder.CreateSub(FirstChunkEnd, FirstChunkStart,
"omp_chunk.range");
6462 Value *NextChunkStride =
6463 Builder.CreateLoad(InternalIVTy, PStride,
"omp_dispatch.stride");
6467 Value *DispatchCounter;
6475 DispatchCounter = Counter;
6478 FirstChunkStart, CastedTripCount, NextChunkStride,
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);
6507 IsLastChunk, CountUntilOrigTripCount, ChunkRange,
"omp_chunk.tripcount");
6508 Value *BackcastedChunkTC =
6509 Builder.CreateTrunc(ChunkTripCount, IVTy,
"omp_chunk.tripcount.trunc");
6510 CLI->setTripCount(BackcastedChunkTC);
6515 Value *BackcastedDispatchCounter =
6516 Builder.CreateTrunc(DispatchCounter, IVTy,
"omp_dispatch.iv.trunc");
6517 CLI->mapIndVar([&](Instruction *) ->
Value * {
6519 return Builder.CreateAdd(
IV, BackcastedDispatchCounter);
6532 return AfterIP.takeError();
6547static FunctionCallee
6550 unsigned Bitwidth = Ty->getIntegerBitWidth();
6553 case WorksharingLoopType::ForStaticLoop:
6556 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_4u);
6559 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_8u);
6561 case WorksharingLoopType::DistributeStaticLoop:
6564 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_4u);
6567 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_8u);
6569 case WorksharingLoopType::DistributeForStaticLoop:
6572 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_4u);
6575 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_8u);
6578 if (Bitwidth != 32 && Bitwidth != 64) {
6590 Function &LoopBodyFn,
bool NoLoop) {
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()));
6609 M, omp::RuntimeFunction::OMPRTL_omp_get_num_threads);
6610 Builder.restoreIP(std::prev(InsertBlock->
end()));
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));
6620 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6644 Builder.restoreIP(Preheader->
end());
6647 Builder.CreateBr(CLI->
getExit());
6655 CleanUpInfo.
collectBlocks(RegionBlockSet, BlocksToBeRemoved);
6663 "Expected unique undroppable user of outlined function");
6665 assert(OutlinedFnCallInstruction &&
"Expected outlined function call");
6667 "Expected outlined function call to be located in loop preheader");
6669 if (OutlinedFnCallInstruction->
arg_size() > 1)
6676 LoopBodyArg, TripCount, OutlinedFn, NoLoop);
6678 for (
auto &ToBeDeletedItem : ToBeDeleted)
6679 ToBeDeletedItem->eraseFromParent();
6686 bool NeedsLastIter) {
6687 uint32_t SrcLocStrSize;
6691 if (NeedsLastIter) {
6694 AllocaInst *PLastIter =
6695 Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6699 Builder.CreateStore(ConstantInt::get(I32Type, 0), PLastIter);
6704 Builder.CreateSub(TripCount, ConstantInt::get(TripCount->
getType(), 1));
6707 Builder.CreateStore(
Builder.CreateZExt(IsLast, I32Type), PLastIter);
6712 case WorksharingLoopType::ForStaticLoop:
6713 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6715 case WorksharingLoopType::DistributeStaticLoop:
6716 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6718 case WorksharingLoopType::DistributeForStaticLoop:
6719 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6724 auto OI = std::make_unique<OutlineInfo>();
6729 SmallVector<Instruction *, 4> ToBeDeleted;
6731 OI->OuterAllocBB = AllocaIP.getNodeParent();
6754 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
6756 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
6758 CodeExtractorAnalysisCache CEAC(*OuterFn);
6759 CodeExtractor Extractor(Blocks,
6773 SetVector<Value *> SinkingCands, HoistingCands;
6777 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
6784 for (
auto Use :
Users) {
6786 if (ParallelRegionBlockSet.
count(Inst->getParent())) {
6787 Inst->replaceUsesOfWith(CLI->
getIndVar(), NewLoopCntLoad);
6793 OI->ExcludeArgsFromAggregate.push_back(NewLoopCntLoad);
6800 OI->PostOutlineCB = [=, ToBeDeletedVec =
6801 std::move(ToBeDeleted)](
Function &OutlinedFn) {
6818 return BarrierIP.takeError();
6825 bool NeedsBarrier, omp::ScheduleKind SchedKind,
Value *ChunkSize,
6826 bool HasSimdModifier,
bool HasMonotonicModifier,
6827 bool HasNonmonotonicModifier,
bool HasOrderedClause,
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);
6842 SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
6843 HasNonmonotonicModifier, HasOrderedClause, DistScheduleChunkSize);
6845 bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
6846 OMPScheduleType::ModifierOrdered;
6848 if (HasDistSchedule) {
6849 DistScheduleSchedType = DistScheduleChunkSize
6850 ? OMPScheduleType::OrderedDistributeChunked
6851 : OMPScheduleType::OrderedDistribute;
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);
6862 if (DistScheduleChunkSize)
6863 return applyStaticChunkedWorkshareLoop(
6864 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6865 DistScheduleChunkSize, DistScheduleSchedType);
6866 return applyStaticWorkshareLoop(
DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6869 case OMPScheduleType::BaseStaticChunked:
6870 case OMPScheduleType::BaseDistributeChunked:
6871 if (IsOrdered && !HasDistSchedule)
6872 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6873 NeedsBarrier, ChunkSize);
6875 return applyStaticChunkedWorkshareLoop(
6876 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6877 DistScheduleChunkSize, DistScheduleSchedType);
6879 case OMPScheduleType::BaseRuntime:
6880 case OMPScheduleType::BaseAuto:
6881 case OMPScheduleType::BaseGreedy:
6882 case OMPScheduleType::BaseBalanced:
6883 case OMPScheduleType::BaseSteal:
6884 case OMPScheduleType::BaseRuntimeSimd:
6886 "schedule type does not support user-defined chunk sizes");
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);
6908 unsigned Bitwidth = Ty->getIntegerBitWidth();
6911 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
6914 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
6922static FunctionCallee
6924 unsigned Bitwidth = Ty->getIntegerBitWidth();
6927 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
6930 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
6937static FunctionCallee
6939 unsigned Bitwidth = Ty->getIntegerBitWidth();
6942 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
6945 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
6950OpenMPIRBuilder::applyDynamicWorkshareLoop(
DebugLoc DL, CanonicalLoopInfo *CLI,
6953 bool NeedsBarrier,
Value *Chunk) {
6954 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6956 "Require dedicated allocate IP");
6958 "Require valid schedule type");
6960 bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
6961 OMPScheduleType::ModifierOrdered;
6966 uint32_t SrcLocStrSize;
6973 Type *IVTy =
IV->getType();
6978 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
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");
6992 Constant *One = ConstantInt::get(IVTy, 1);
6993 Builder.CreateStore(One, PLowerBound);
6995 Builder.CreateStore(UpperBound, PUpperBound);
6996 Builder.CreateStore(One, PStride);
7014 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
7026 Builder.SetInsertPoint(OuterCond->getFirstInsertionPt());
7029 {SrcLoc, ThreadNum, PLastIter, PLowerBound, PUpperBound, PStride});
7030 Constant *Zero32 = ConstantInt::get(I32Type, 0);
7033 Builder.CreateSub(
Builder.CreateLoad(IVTy, PLowerBound), One,
"lb");
7034 Builder.CreateCondBr(MoreWork, Header, Exit);
7040 PI->setIncomingBlock(0, OuterCond);
7046 Br->setSuccessor(OuterCond);
7051 Builder.SetInsertPoint(
Cond->getFirstInsertionPt());
7052 UpperBound =
Builder.CreateLoad(IVTy, PUpperBound,
"ub");
7055 CI->setOperand(1, UpperBound);
7059 assert(BI->getSuccessor(1) == Exit);
7060 BI->setSuccessor(1, OuterCond);
7074 omp::Directive::OMPD_for,
false,
7077 return BarrierIP.takeError();
7140 "Virtual collapse requires unobserved canonical loop controls");
7149 if (
Loops.front()->getBody()->getUniqueSuccessor() !=
7151 Loops.back()->getAfter()->getSingleSuccessor() != Plan.
Latches.front())
7158 const VirtualRowPlan &Plan,
7162 DebugLoc DL = Builder.getCurrentDebugLocation();
7168 Builder.SetInsertPoint(Entry);
7170 Builder.CreateURem(Begin, TripCounts.
back(),
"omp_collapsed.begin.1");
7172 Builder.CreateUDiv(Begin, TripCounts.
back(),
"omp_collapsed.begin.0");
7175 Value *InitialRemaining =
7176 Builder.CreateAdd(
Count, InnerBegin,
"omp_collapsed.row.remaining");
7177 Builder.CreateBr(OuterHeader);
7180 Builder.SetCurrentDebugLocation(
DL);
7182 Builder.CreatePHI(IVType, 2,
"omp_collapsed.row.remaining.0");
7187 if (!InnerCount || !InnerCount->isOne()) {
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);
7197 BasicBlock *InnerHeader = Plan.IndVars.back()->getParent();
7201 Builder.SetInsertPoint(InnerEntry);
7203 Builder.CreateBr(InnerHeader);
7204 InnerBr->setSuccessor(InnerEntry);
7205 Plan.IndVars.back()->setIncomingBlock(0, InnerEntry);
7207 Builder.SetInsertPoint(Plan.Preheaders.back()->getTerminator());
7210 "omp_collapsed.row.is_final");
7212 IsFinalRow, Remaining, TripCounts.
back(),
"omp_collapsed.row.stop");
7213 Plan.InnerCmp->setOperand(1, InnerStop);
7221 "omp_collapsed.row.remaining.next",
7229 Builder.SetInsertPoint(Guard);
7236 for (
auto [
IV, TripCount] :
zip(Plan.IndVars, TripCounts))
7240 Plan.IndVars.front()->setIncomingValue(0, OuterBegin);
7241 Plan.IndVars.front()->setIncomingBlock(0, Entry);
7244CanonicalLoopInfo *OpenMPIRBuilder::createVirtualCollapsedLoop(
7247 Value *CollapsedTripCount) {
7255 BasicBlock *Preheader = Plan.Preheaders.front();
7270 "omp_collapsed.range.begin");
7272 Builder.Insert(BinaryOperator::CreateAdd(CollapsedTripCount,
Zero),
7273 "omp_collapsed.range.count");
7276 Result->VirtualCollapse =
7277 CanonicalLoopInfo::VirtualCollapseInfo{Begin,
Count};
7281 createVirtualRowExecutor(Result, Plan, TripCounts, Begin,
Count, Entry);
7291void OpenMPIRBuilder::bindCollapsedRange(CanonicalLoopInfo *
Loop,
Value *Begin,
7294 Loop->VirtualCollapse->Begin->setOperand(0, Begin);
7295 Loop->VirtualCollapse->Count->setOperand(0,
Count);
7301 assert(
Loops.size() >= 1 &&
"At least one loop required");
7302 size_t NumLoops =
Loops.size();
7306 return Loops.front();
7308 if (
Config.CollapseMapping == CollapseIVMapping::Virtual) {
7309 if (
Loops.size() != 2)
7313 if (
Loop->VirtualCollapse)
7314 Loop->reportUnsupportedVirtualCollapse();
7319 if (ComputeIP.isValid())
7328 for (
Value *&TripCount : TripCounts) {
7331 auto [It, Inserted] = Counts.
try_emplace(TripCount, TripCount);
7333 It->second =
Builder.CreateFreeze(TripCount,
"omp_collapsed.tripcount");
7334 TripCount = It->second;
7336 Value *CollapsedTripCount =
7338 return createVirtualCollapsedLoop(
DL,
Loops, Plan, TripCounts,
7339 CollapsedTripCount);
7352 Loop->collectControlBlocks(OldControlBBs);
7356 if (ComputeIP.isValid())
7363 Value *CollapsedTripCount =
nullptr;
7366 "All loops to collapse must be valid canonical loops");
7367 Value *OrigTripCount = L->getTripCount();
7368 if (!CollapsedTripCount) {
7369 CollapsedTripCount = OrigTripCount;
7374 CollapsedTripCount =
7375 Builder.CreateNUWMul(CollapsedTripCount, OrigTripCount);
7381 OrigPreheader->
getNextNode(), OrigAfter,
"collapsed",
7388 Builder.restoreIP(Result->getBodyIP());
7390 Value *Leftover = Result->getIndVar();
7392 NewIndVars.
resize(NumLoops);
7393 for (
int i = NumLoops - 1; i >= 1; --i) {
7394 Value *OrigTripCount =
Loops[i]->getTripCount();
7396 Value *NewIndVar =
Builder.CreateURem(Leftover, OrigTripCount);
7397 NewIndVars[i] = NewIndVar;
7399 Leftover =
Builder.CreateUDiv(Leftover, OrigTripCount);
7402 NewIndVars[0] = Leftover;
7411 BasicBlock *ContinueBlock = Result->getBody();
7413 auto ContinueWith = [&ContinueBlock, &ContinuePred,
DL](
BasicBlock *Dest,
7420 ContinueBlock =
nullptr;
7421 ContinuePred = NextSrc;
7428 for (
size_t i = 0; i < NumLoops - 1; ++i)
7429 ContinueWith(
Loops[i]->getBody(),
Loops[i + 1]->getHeader());
7435 for (
size_t i = NumLoops - 1; i > 0; --i)
7436 ContinueWith(
Loops[i]->getAfter(),
Loops[i - 1]->getLatch());
7439 ContinueWith(Result->getLatch(),
nullptr);
7446 for (
size_t i = 0; i < NumLoops; ++i)
7447 Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
7461std::vector<CanonicalLoopInfo *>
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");
7479 Loop->collectControlBlocks(OldControlBBs);
7487 assert(L->isValid() &&
"All input loops must be valid canonical loops");
7488 OrigTripCounts.
push_back(L->getTripCount());
7499 for (
int i = 0; i < NumLoops - 1; ++i) {
7512 for (
int i = 0; i < NumLoops; ++i) {
7513 Value *TileSize = TileSizes[i];
7514 Value *OrigTripCount = OrigTripCounts[i];
7517 Value *FloorCompleteTripCount =
Builder.CreateUDiv(OrigTripCount, TileSize);
7518 Value *FloorTripRem =
Builder.CreateURem(OrigTripCount, TileSize);
7527 Value *FloorTripOverflow =
7528 Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
7530 FloorTripOverflow =
Builder.CreateZExt(FloorTripOverflow, IVType);
7531 Value *FloorTripCount =
7532 Builder.CreateAdd(FloorCompleteTripCount, FloorTripOverflow,
7533 "omp_floor" +
Twine(i) +
".tripcount",
true);
7536 FloorCompleteCount.
push_back(FloorCompleteTripCount);
7542 std::vector<CanonicalLoopInfo *> Result;
7543 Result.reserve(NumLoops * 2);
7556 auto EmbeddNewLoop =
7557 [
this,
DL,
F, InnerEnter, &Enter, &
Continue, &OutroInsertBefore](
7560 DL, TripCount,
F, InnerEnter, OutroInsertBefore, Name);
7565 Enter = EmbeddedLoop->
getBody();
7567 OutroInsertBefore = EmbeddedLoop->
getLatch();
7568 return EmbeddedLoop;
7572 const Twine &NameBase) {
7575 EmbeddNewLoop(
P.value(), NameBase +
Twine(
P.index()));
7576 Result.push_back(EmbeddedLoop);
7580 EmbeddNewLoops(FloorCount,
"floor");
7586 for (
int i = 0; i < NumLoops; ++i) {
7588 Value *TileSize = TileSizes[i];
7590 Value *FloorIsEpilogue =
7592 Value *TileTripCount =
7593 Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
7599 EmbeddNewLoops(TileCounts,
"tile");
7604 for (std::pair<BasicBlock *, BasicBlock *>
P : InbetweenCode) {
7613 BodyEnter =
nullptr;
7614 BodyEntered = ExitBB;
7626 Builder.restoreIP(Result.back()->getBodyIP());
7627 for (
int i = 0; i < NumLoops; ++i) {
7630 Value *OrigIndVar = OrigIndVars[i];
7681 assert(
Loop->isValid() &&
"Expecting a valid CanonicalLoopInfo");
7685 assert(Latch &&
"A valid CanonicalLoopInfo must have a unique latch");
7693 if (
I.mayReadOrWriteMemory()) {
7697 I.setMetadata(LLVMContext::MD_access_group,
AccessGroup);
7711 Loop->collectControlBlocks(oldControlBBs);
7716 assert(L->isValid() &&
"All input loops must be valid canonical loops");
7717 origTripCounts.
push_back(L->getTripCount());
7726 Builder.SetInsertPoint(TCBlock);
7727 Value *fusedTripCount =
nullptr;
7729 assert(L->isValid() &&
"All loops to fuse must be valid canonical loops");
7730 Value *origTripCount = L->getTripCount();
7731 if (!fusedTripCount) {
7732 fusedTripCount = origTripCount;
7735 Value *condTP =
Builder.CreateICmpSGT(fusedTripCount, origTripCount);
7736 fusedTripCount =
Builder.CreateSelect(condTP, fusedTripCount, origTripCount,
7750 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7751 Loops[i]->getPreheader()->moveBefore(TCBlock);
7752 Loops[i]->getAfter()->moveBefore(TCBlock);
7756 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7768 for (
size_t i = 0; i <
Loops.size(); ++i) {
7770 F->getContext(),
"omp.fused.inner.cond",
F,
Loops[i]->getBody());
7771 Builder.SetInsertPoint(condBlock);
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]);
7797 "omp.fused.pre_latch");
7814 assert(
Loop->isValid() &&
"Expecting a valid CanonicalLoopInfo");
7815 if (
Loop->VirtualCollapse)
7838 const Twine &NamePrefix) {
7867 C, NamePrefix +
".if.then",
Cond->getParent(),
Cond->getNextNode());
7869 C, NamePrefix +
".if.else",
Cond->getParent(), CanonicalLoop->
getExit());
7872 Builder.SetInsertPoint(SplitBeforeIt);
7874 Builder.CreateCondBr(IfCond, ThenBlock, ElseBlock);
7877 spliceBB(IP, ThenBlock,
false, Builder.getCurrentDebugLocation());
7880 Builder.SetInsertPoint(ElseBlock);
7886 ExistingBlocks.
reserve(L->getNumBlocks() + 1);
7888 ExistingBlocks.
append(L->block_begin(), L->block_end());
7894 assert(LoopCond && LoopHeader &&
"Invalid loop structure");
7896 if (
Block == L->getLoopPreheader() ||
Block == L->getLoopLatch() ||
7903 if (
Block == ThenBlock)
7904 NewBB->
setName(NamePrefix +
".if.else");
7907 VMap[
Block] = NewBB;
7915 L->getLoopLatch()->splitBasicBlockBefore(
L->getLoopLatch()->begin(),
7916 NamePrefix +
".pre_latch");
7920 L->addBasicBlockToLoop(ThenBlock, LI);
7926 if (TargetTriple.
isX86()) {
7927 if (Features.
lookup(
"avx512f"))
7929 else if (Features.
lookup(
"avx"))
7933 if (TargetTriple.
isPPC())
7935 if (TargetTriple.
isWasm())
7944 Value *IfCond, OrderKind Order,
7946 if (CanonicalLoop->VirtualCollapse)
7947 CanonicalLoop->reportUnsupportedVirtualCollapse();
7956 if (!BB.hasTerminator())
7972 I->eraseFromParent();
7975 if (AlignedVars.
size()) {
7977 for (
auto &AlignedItem : AlignedVars) {
7978 Value *AlignedPtr = AlignedItem.first;
7982 Builder.CreateAlignmentAssumption(
F->getDataLayout(), AlignedPtr,
7990 createIfVersion(CanonicalLoop, IfCond, VMap, LIA, LI, L,
"simd");
8003 Reachable.insert(
Block);
8013 if ((Safelen ==
nullptr) || (Order == OrderKind::OMP_ORDER_concurrent))
8029 if (Simdlen || Safelen) {
8033 ConstantInt *VectorizeWidth = Simdlen ==
nullptr ? Safelen : Simdlen;
8045 assert(Factor >= 0 &&
"Unroll factor must not be negative");
8061 Ctx, {
MDString::get(Ctx,
"llvm.loop.unroll.count"), FactorConst}));
8064 addUnrollMetadata(
Loop, LoopMetadata);
8069 if (
Loop->VirtualCollapse)
8070 Loop->reportUnsupportedVirtualCollapse();
8076 *UnrolledCLI =
Loop;
8081 "unrolling only makes sense with a factor of 2 or larger");
8083 Type *IndVarTy =
Loop->getIndVarType();
8090 std::vector<CanonicalLoopInfo *>
LoopNest =
8105 Ctx, {
MDString::get(Ctx,
"llvm.loop.unroll.count"), FactorConst})});
8108 (*UnrolledCLI)->assertOK();
8126 Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
8145 if (!CPVars.
empty()) {
8150 Directive OMPD = Directive::OMPD_single;
8155 Value *Args[] = {Ident, ThreadId};
8164 if (
Error Err = FiniCB(IP))
8185 EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCBWrapper,
8192 for (
size_t I = 0, E = CPVars.
size();
I < E; ++
I)
8195 ConstantInt::get(Int64, 0), CPVars[
I],
8198 }
else if (!IsNowait) {
8201 omp::Directive::OMPD_unknown,
false,
8219 Directive::OMPD_scope,
nullptr,
nullptr,
8220 BodyGenCB, FiniCB,
false,
true,
8228 omp::Directive::OMPD_unknown,
8244 Directive OMPD = Directive::OMPD_critical;
8249 Value *LockVar = getOMPCriticalRegionLock(CriticalName);
8250 Value *Args[] = {Ident, ThreadId, LockVar};
8267 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8275 const Twine &Name,
bool IsDependSource) {
8278 [](
Value *SV) {
return SV->getType()->isIntegerTy(64); }) &&
8279 "OpenMP runtime requires depend vec with i64 type");
8292 for (
unsigned I = 0;
I < NumLoops; ++
I) {
8306 Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
8324 Directive OMPD = Directive::OMPD_ordered_blockassoc;
8333 Value *Args[] = {Ident, ThreadId};
8343 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8350 bool HasFinalize,
bool IsCancellable) {
8357 BasicBlock *EntryBB = Builder.GetInsertBlock();
8361 SplitPos->
setDebugLoc(Builder.getCurrentDebugLocation());
8368 emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
8380 "Unexpected control flow graph state!!");
8382 emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
8384 return AfterIP.takeError();
8389 "Unexpected Insertion point location!");
8392 auto InsertBB = merged ? ExitPredBB : ExitBB;
8395 Builder.SetInsertPoint(InsertBB);
8401 Directive OMPD,
Value *EntryCall, BasicBlock *ExitBB,
bool Conditional) {
8403 if (!Conditional || !EntryCall)
8409 auto *UI =
new UnreachableInst(
Builder.getContext(), ThenBB);
8419 Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
8423 UI->eraseFromParent();
8431 omp::Directive OMPD,
InsertPointTy FinIP, Instruction *ExitCall,
8439 "Unexpected finalization stack state!");
8442 assert(Fi.DK == OMPD &&
"Unexpected Directive for Finalization call!");
8446 return std::move(Err);
8493 "copyin.not.master.end");
8500 Builder.SetInsertPoint(OMP_Entry);
8503 Value *cmp =
Builder.CreateICmpNE(MasterPtr, PrivatePtr);
8504 Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
8506 Builder.SetInsertPoint(CopyBegin);
8524 Value *Args[] = {ThreadId,
Size, Allocator};
8561 Value *Args[] = {ThreadId, Addr, Allocator};
8568 const Twine &Name) {
8576 M.getContext(),
M.getDataLayout().getPrefTypeAlign(Int64)));
8582 const Twine &Name) {
8584 Loc,
Builder.getInt64(
M.getDataLayout().getTypeAllocSize(VarType)), Name);
8589 const Twine &Name) {
8600 const Twine &Name) {
8602 Loc, Addr,
Builder.getInt64(
M.getDataLayout().getTypeAllocSize(VarType)),
8609 Value *DependenceAddress,
bool HaveNowaitClause) {
8619 else if (
Device->getType() != Int32)
8622 if (NumDependences ==
nullptr) {
8623 NumDependences = ConstantInt::get(Int32, 0);
8627 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8629 Ident, ThreadId, InteropVar, InteropTypeVal,
8630 Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
8639 Value *NumDependences,
Value *DependenceAddress,
bool HaveNowaitClause) {
8649 else if (
Device->getType() != Int32)
8651 if (NumDependences ==
nullptr) {
8652 NumDependences = ConstantInt::get(Int32, 0);
8656 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8658 Ident, ThreadId, InteropVar,
Device,
8659 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8668 Value *NumDependences,
8669 Value *DependenceAddress,
8670 bool HaveNowaitClause) {
8679 else if (
Device->getType() != Int32)
8681 if (NumDependences ==
nullptr) {
8682 NumDependences = ConstantInt::get(Int32, 0);
8686 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8688 Ident, ThreadId, InteropVar,
Device,
8689 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8719 assert(!Attrs.MaxThreads.empty() && !Attrs.MaxTeams.empty() &&
8720 "expected num_threads and num_teams to be specified");
8740 const std::string DebugPrefix =
"_debug__";
8741 if (KernelName.
ends_with(DebugPrefix)) {
8742 KernelName = KernelName.
drop_back(DebugPrefix.length());
8743 Kernel =
M.getFunction(KernelName);
8749 if (Attrs.MinTeams.front() > 1 || Attrs.MaxTeams.front() > 0)
8751 Attrs.MaxTeams.front());
8754 int32_t MaxThreadsVal = Attrs.MaxThreads.front();
8764 Attrs.MinThreads.front());
8769 if (MaxThreadsVal > 0 &&
8772 MaxThreadsVal = int32_t(
8773 std::min<int64_t>(int64_t(MaxThreadsVal) + 64,
8776 if (MaxThreadsVal > 0)
8791 Twine DynamicEnvironmentName = KernelName +
"_dynamic_environment";
8792 Constant *DynamicEnvironmentInitializer =
8796 DynamicEnvironmentInitializer, DynamicEnvironmentName,
8798 DL.getDefaultGlobalsAddressSpace());
8802 DynamicEnvironmentGV->
getType() == DynamicEnvironmentPtr
8803 ? DynamicEnvironmentGV
8805 DynamicEnvironmentPtr);
8808 ConfigurationEnvironment, {
8809 UseGenericStateMachineVal,
8810 MayUseNestedParallelismVal,
8819 KernelEnvironment, {
8820 ConfigurationEnvironmentInitializer,
8824 std::string KernelEnvironmentName =
8825 (KernelName +
"_kernel_environment").str();
8828 KernelEnvironmentInitializer, KernelEnvironmentName,
8830 DL.getDefaultGlobalsAddressSpace());
8833 return KernelEnvironmentGV->
getType() == KernelEnvironmentPtr
8834 ? KernelEnvironmentGV
8836 KernelEnvironmentPtr);
8843 if (!KernelEnvironment)
8851 omp::RuntimeFunction::OMPRTL___kmpc_target_init);
8853 Value *KernelLaunchEnvironment =
8856 KernelLaunchEnvironment =
8857 KernelLaunchEnvironment->
getType() == KernelLaunchEnvParamTy
8858 ? KernelLaunchEnvironment
8859 :
Builder.CreateAddrSpaceCast(KernelLaunchEnvironment,
8860 KernelLaunchEnvParamTy);
8862 Fn, {KernelEnvironment, KernelLaunchEnvironment});
8874 auto *UI =
Builder.CreateUnreachable();
8880 Builder.SetInsertPoint(WorkerExitBB);
8884 Builder.SetInsertPoint(CheckBBTI);
8885 Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
8887 CheckBBTI->eraseFromParent();
8888 UI->eraseFromParent();
8896 int32_t TeamsReductionDataSize) {
8901 omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
8905 if (!TeamsReductionDataSize)
8911 const std::string DebugPrefix =
"_debug__";
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();
8919 KernelEnvironmentInitializer,
8920 ConstantInt::get(Int32, TeamsReductionDataSize), {0, 7});
8921 KernelEnvironmentGV->setInitializer(NewInitializer);
8926 if (
Kernel.hasFnAttribute(Name)) {
8927 int32_t OldLimit =
Kernel.getFnAttributeAsParsedInteger(Name);
8933std::pair<int32_t, int32_t>
8935 int32_t ThreadLimit =
8936 Kernel.getFnAttributeAsParsedInteger(
"omp_target_thread_limit");
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(
',');
8945 return {0, ThreadLimit};
8946 UB = ThreadLimit ? std::min(ThreadLimit, UB) : UB;
8954 return {0, ThreadLimit ? std::min(ThreadLimit, UB) : UB};
8956 return {0, ThreadLimit};
8962 Kernel.addFnAttr(
"omp_target_thread_limit", std::to_string(UB));
8965 Kernel.addFnAttr(
"amdgpu-flat-work-group-size",
8973std::pair<int32_t, int32_t>
8976 return {0,
Kernel.getFnAttributeAsParsedInteger(
"omp_target_num_teams")};
8980 int32_t LB, int32_t UB) {
8988 Kernel.addFnAttr(
"omp_target_num_teams", std::to_string(LB));
8991void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
9000 else if (
T.isNVPTX())
9002 else if (
T.isSPIRV())
9008 StringRef EntryFnIDName) {
9009 if (
Config.isTargetDevice()) {
9010 assert(OutlinedFn &&
"The outlined function must exist if embedded");
9014 return new GlobalVariable(
9019Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(
Function *OutlinedFn,
9020 StringRef EntryFnName) {
9024 assert(!
M.getGlobalVariable(EntryFnName,
true) &&
9025 "Named kernel already exists?");
9026 return new GlobalVariable(
9039 if (
Config.isTargetDevice() || !
Config.openMPOffloadMandatory()) {
9043 OutlinedFn = *CBResult;
9045 OutlinedFn =
nullptr;
9051 if (!IsOffloadEntry)
9054 std::string EntryFnIDName =
9056 ? std::string(EntryFnName)
9060 EntryFnName, EntryFnIDName);
9068 setOutlinedTargetRegionFunctionAttributes(OutlinedFn);
9069 auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
9070 auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
9072 EntryInfo, EntryAddr, OutlinedFnID,
9074 return OutlinedFnID;
9092 bool IsStandAlone = !BodyGenCB;
9099 MapInfo = &GenMapInfoCB(
Builder.saveIP());
9101 AllocaIP,
Builder.saveIP(), *MapInfo, Info, CustomMapperCB,
9102 true, DeviceAddrCB))
9109 Value *PointerNum =
Builder.getInt32(Info.NumberOfPtrs);
9119 SrcLocInfo, DeviceID,
9126 assert(MapperFunc &&
"MapperFunc missing for standalone target data");
9130 if (Info.HasNoWait) {
9140 if (Info.HasNoWait) {
9144 emitBlock(OffloadContBlock, CurFn,
true);
9150 bool RequiresOuterTargetTask = Info.HasNoWait;
9151 if (!RequiresOuterTargetTask)
9152 cantFail(TaskBodyCB(
nullptr,
nullptr,
9156 {}, RTArgs, Info.HasNoWait));
9159 omp::OMPRTL___tgt_target_data_begin_mapper);
9163 for (
auto DeviceMap : Info.DevicePtrInfoMap) {
9167 Builder.CreateStore(LI, DeviceMap.second.second);
9204 Value *PointerNum =
Builder.getInt32(Info.NumberOfPtrs);
9213 Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,
9236 return emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);
9237 return BeginThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9252 return emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);
9253 return EndThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9256 return emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);
9257 return BeginThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9268 bool IsGPUDistribute) {
9269 assert((IVSize == 32 || IVSize == 64) &&
9270 "IV size is not compatible with the omp runtime");
9272 if (IsGPUDistribute)
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);
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);
9289 assert((IVSize == 32 || IVSize == 64) &&
9290 "IV size is not compatible with the omp runtime");
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);
9302 assert((IVSize == 32 || IVSize == 64) &&
9303 "IV size is not compatible with the omp runtime");
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);
9315 assert((IVSize == 32 || IVSize == 64) &&
9316 "IV size is not compatible with the omp runtime");
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);
9332 DenseMap<
Value *, std::tuple<Value *, unsigned>> &ValueReplacementMap) {
9340 auto GetUpdatedDIVariable = [&](
DILocalVariable *OldVar,
unsigned arg) {
9344 if (NewVar && (arg == NewVar->
getArg()))
9354 auto UpdateDebugRecord = [&](
auto *DR) {
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;
9365 DR->setVariable(GetUpdatedDIVariable(OldVar, ArgNo));
9370 if (DVR->getNumVariableLocationOps() != 1u) {
9371 DVR->setKillLocation();
9374 Value *
Loc = DVR->getVariableLocationOp(0u);
9381 RequiredBB = &DVR->getFunction()->getEntryBlock();
9383 if (RequiredBB && RequiredBB != CurBB) {
9395 UpdateDebugRecord(&DVR);
9396 MoveDebugRecordToCorrectBlock(&DVR);
9399 for (
auto *DVR : DVRsToDelete)
9400 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);
9404 Module *M = Func->getParent();
9407 DB.createQualifiedType(dwarf::DW_TAG_pointer_type,
nullptr);
9408 unsigned ArgNo = Func->arg_size();
9410 NewSP,
"dyn_ptr", ArgNo, NewSP->
getFile(), 0, VoidPtrTy,
9411 false, DINode::DIFlags::FlagArtificial);
9413 Argument *LastArg = Func->getArg(Func->arg_size() - 1);
9414 DB.insertDeclare(LastArg, Var, DB.createExpression(),
Loc,
9436 for (
auto &Arg : Inputs)
9437 ParameterTypes.
push_back(Arg->getType()->isPointerTy()
9441 for (
auto &Arg : Inputs)
9442 ParameterTypes.
push_back(Arg->getType());
9450 auto BB = Builder.GetInsertBlock();
9451 auto M = BB->getModule();
9462 if (TargetCpuAttr.isStringAttribute())
9463 Func->addFnAttr(TargetCpuAttr);
9465 auto TargetFeaturesAttr = ParentFn->
getFnAttribute(
"target-features");
9466 if (TargetFeaturesAttr.isStringAttribute())
9467 Func->addFnAttr(TargetFeaturesAttr);
9472 OMPBuilder.
emitUsed(
"llvm.compiler.used", {ExecMode});
9482 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9486 Builder.SetInsertPoint(EntryBB);
9497 BasicBlock *UserCodeEntryBB = Builder.GetInsertBlock();
9506 splitBB(Builder,
true,
"outlined.body");
9508 CBFunc(Builder.saveIP(), OutlinedBodyBB->
begin(), ExitBB);
9511 Builder.SetInsertPoint(ExitBB);
9519 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9526 Builder.CreateRetVoid();
9530 auto AllocaIP = Builder.saveIP();
9535 const auto &ArgRange =
make_range(Func->arg_begin(), Func->arg_end() - 1);
9567 if (Instr->getFunction() == Func)
9568 Instr->replaceUsesOfWith(
Input, InputCopy);
9574 for (
auto InArg :
zip(Inputs, ArgRange)) {
9576 Argument &Arg = std::get<1>(InArg);
9577 Value *InputCopy =
nullptr;
9580 Arg,
Input, InputCopy, AllocaIP, Builder.saveIP(), ExitBB->
begin());
9583 Builder.restoreIP(*AfterIP);
9584 ValueReplacementMap[
Input] = std::make_tuple(InputCopy, Arg.
getArgNo());
9604 DeferredReplacement.push_back(std::make_pair(
Input, InputCopy));
9611 ReplaceValue(
Input, InputCopy, Func);
9615 for (
auto Deferred : DeferredReplacement)
9616 ReplaceValue(std::get<0>(Deferred), std::get<1>(Deferred), Func);
9619 ValueReplacementMap);
9626 Value *TaskWithPrivates) {
9644 const size_t NumOffloadingArrays,
const int SharedArgsOperandNo) {
9649 assert((!NumOffloadingArrays || PrivatesTy) &&
9650 "PrivatesTy cannot be nullptr when there are offloadingArrays"
9680 Type *TaskPtrTy = OMPBuilder.TaskPtr;
9681 [[maybe_unused]]
Type *TaskTy = OMPBuilder.Task;
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");
9693 bool HasShareds = SharedArgsOperandNo > 0;
9694 bool HasOffloadingArrays = NumOffloadingArrays > 0;
9698 Builder.SetInsertPoint(EntryBB);
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");
9711 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskWithPrivates, 1);
9712 for (
unsigned int i = 0; i < NumOffloadingArrays; ++i)
9714 Builder.CreateStructGEP(PrivatesTy, Privates, i));
9718 auto *ArgStructAlloca =
9720 assert(ArgStructAlloca &&
9721 "Unable to find the alloca instruction corresponding to arguments "
9722 "for extracted function");
9724 std::optional<TypeSize> ArgAllocSize =
9726 assert(ArgStructType && ArgAllocSize &&
9727 "Unable to determine size of arguments for extracted function");
9728 uint64_t StructSize = ArgAllocSize->getFixedValue();
9731 Builder.CreateAlloca(ArgStructType,
nullptr,
"structArg");
9733 Value *SharedsSize = Builder.getInt64(StructSize);
9738 Builder.CreateMemCpy(
9739 NewArgStructAlloca, NewArgStructAlloca->
getAlign(), LoadShared,
9741 KernelLaunchArgs.
push_back(NewArgStructAlloca);
9744 Builder.CreateRetVoid();
9750 return GEP->getSourceElementType();
9752 return Alloca->getAllocatedType();
9776 if (OffloadingArraysToPrivatize.
empty() && DescriptorTypes.
empty())
9777 return OMPIRBuilder.Task;
9780 for (
Value *
V : OffloadingArraysToPrivatize) {
9781 assert(
V->getType()->isPointerTy() &&
9782 "Expected pointer to array to privatize. Got a non-pointer value "
9785 assert(ArrayTy &&
"ArrayType cannot be nullptr");
9792 "struct.task_with_privates");
9807 EntryFnName, Inputs, CBFunc,
9808 ArgAccessorFuncCB, OutlinedFnLoc);
9812 EntryInfo, GenerateOutlinedFunction, IsOffloadEntry, OutlinedFn,
9951 auto OI = std::make_unique<OutlineInfo>();
9952 OI->EntryBB = TargetTaskAllocaBB;
9953 OI->OuterAllocBB = AllocaIP.getNodeParent();
9958 Builder, AllocaIP, ToBeDeleted, TargetTaskAllocaIP,
"global.tid",
false));
9961 Builder.restoreIP(TargetTaskBodyIP);
9962 if (
Error Err = TaskBodyCB(DeviceID, RTLoc, TargetTaskAllocaIP))
9980 bool NeedsTargetTask = HasNoWait && DeviceID;
9981 if (NeedsTargetTask) {
9987 OffloadingArraysToPrivatize.
push_back(V);
9988 OI->ExcludeArgsFromAggregate.push_back(V);
9993 if (!NeedsTargetTask)
9994 NonContiguousDescriptors.clear();
9995 OI->PostOutlineCB = [
this, ToBeDeleted, Dependencies, NeedsTargetTask,
9996 DeviceID, OffloadingArraysToPrivatize,
9997 NonContiguousDescriptors,
10001 "there must be a single user for the outlined function");
10015 const unsigned int NumStaleCIArgs = StaleCI->
arg_size();
10016 bool HasShareds = NumStaleCIArgs > OffloadingArraysToPrivatize.
size() + 1;
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;
10026 for (
const auto &Descriptor : NonContiguousDescriptors)
10027 DescriptorTypes.
push_back(Descriptor.Storage->getAllocatedType());
10029 *
this, OffloadingArraysToPrivatize, DescriptorTypes);
10032 if (!OffloadingArraysToPrivatize.
empty())
10037 *
this,
Builder, StaleCI, PrivatesTy, TaskWithPrivatesTy,
10038 OffloadingArraysToPrivatize.
size(), SharedArgOperandNo);
10040 LLVM_DEBUG(
dbgs() <<
"Proxy task entry function created: " << *ProxyFn
10043 Builder.SetInsertPoint(StaleCI);
10060 OMPRTL___kmpc_omp_target_task_alloc);
10072 M.getDataLayout().getTypeStoreSize(TaskWithPrivatesTy));
10079 auto *ArgStructAlloca =
10081 assert(ArgStructAlloca &&
10082 "Unable to find the alloca instruction corresponding to arguments "
10083 "for extracted function");
10084 std::optional<TypeSize> ArgAllocSize =
10087 "Unable to determine size of arguments for extracted function");
10088 SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
10107 TaskSize, SharedsSize,
10110 if (NeedsTargetTask) {
10111 assert(DeviceID &&
"Expected non-empty device ID.");
10124 if (!OffloadingArraysToPrivatize.
empty()) {
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];
10136 "ElementType should match ArrayType");
10139 Value *Dst =
Builder.CreateStructGEP(PrivatesTy, Privates, i);
10142 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(ElementType)));
10143 if (PtrToPrivatize == PointersArray)
10144 PrivatePointersArray = Dst;
10149 assert(PrivatePointersArray &&
"missing task-private pointer array");
10151 PrivatesTy, Privates, OffloadingArraysToPrivatize.
size() +
I);
10153 Dst,
Alignment, Descriptor.Storage, Descriptor.Storage->getAlign(),
10154 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(
10155 Descriptor.Storage->getAllocatedType())));
10158 Descriptor.MapIndex);
10163 Value *DepArray =
nullptr;
10164 Value *NumDeps =
nullptr;
10167 NumDeps = Dependencies.
NumDeps;
10168 }
else if (!Dependencies.
Deps.empty()) {
10170 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
10181 if (!NeedsTargetTask) {
10190 ConstantInt::get(
Builder.getInt32Ty(), 0),
10203 }
else if (DepArray) {
10211 {Ident, ThreadID, TaskData, NumDeps, DepArray,
10212 ConstantInt::get(
Builder.getInt32Ty(), 0),
10220 Builder.ClearInsertionPoint();
10223 I->eraseFromParent();
10228 << *(
Builder.GetInsertBlock()) <<
"\n");
10230 << *(
Builder.getModule()) <<
"\n");
10241 CustomMapperCB, IsNonContiguous, DeviceAddrCB))
10264 Builder.restoreIP(IP);
10270 return Builder.saveIP();
10273 bool HasDependencies = !Dependencies.
empty();
10274 bool RequiresOuterTargetTask = HasNoWait || HasDependencies;
10291 if (OutlinedFnID && DeviceID)
10293 EmitTargetCallFallbackCB, KArgs,
10294 DeviceID, RTLoc, TargetTaskAllocaIP);
10302 return EmitTargetCallFallbackCB(OMPBuilder.
Builder.
saveIP());
10309 auto &&EmitTargetCallElse =
10316 if (RequiresOuterTargetTask) {
10323 Dependencies, EmptyRTArgs, HasNoWait);
10325 return EmitTargetCallFallbackCB(Builder.saveIP());
10328 Builder.restoreIP(AfterIP);
10332 auto &&EmitTargetCallThen =
10336 Info.HasNoWait = HasNoWait;
10341 AllocaIP, Builder.saveIP(), Info, RTArgs, MapInfo, CustomMapperCB,
10347 for (
auto [DefaultVal, RuntimeVal] :
10349 NumTeamsC.
push_back(RuntimeVal ? RuntimeVal
10350 : Builder.getInt32(DefaultVal));
10354 auto InitMaxThreadsClause = [&Builder](
Value *
Clause) {
10356 Clause = Builder.CreateIntCast(
Clause, Builder.getInt32Ty(),
10360 auto CombineMaxThreadsClauses = [&Builder](
Value *
Clause,
Value *&Result) {
10363 Result ? Builder.CreateSelect(Builder.CreateICmpULT(Result,
Clause),
10371 Value *MaxThreadsClause =
10373 ? InitMaxThreadsClause(RuntimeAttrs.
MaxThreads.front())
10376 for (
auto [TeamsVal, TargetVal] :
zip_equal(
10378 Value *TeamsThreadLimitClause = InitMaxThreadsClause(TeamsVal);
10379 Value *NumThreads = InitMaxThreadsClause(TargetVal);
10381 CombineMaxThreadsClauses(TeamsThreadLimitClause, NumThreads);
10382 CombineMaxThreadsClauses(MaxThreadsClause, NumThreads);
10384 NumThreadsC.
push_back(NumThreads ? NumThreads : Builder.getInt32(0));
10387 unsigned NumTargetItems = Info.NumberOfPtrs;
10388 Value *RTLoc = RTLocOverride;
10399 Builder.getInt64Ty(),
10401 : Builder.getInt64(0);
10405 DynCGroupMem = Builder.getInt32(0);
10408 NumTargetItems, RTArgs, TripCount, NumTeamsC, NumThreadsC, DynCGroupMem,
10409 HasNoWait,
false,
false,
10410 DynCGroupMemFallback);
10417 if (RequiresOuterTargetTask)
10419 RTLoc, AllocaIP, Dependencies,
10420 KArgs.
RTArgs, Info.HasNoWait);
10423 Builder, OutlinedFnID, EmitTargetCallFallbackCB, KArgs,
10424 RuntimeAttrs.
DeviceID, RTLoc, AllocaIP);
10427 Builder.restoreIP(AfterIP);
10435 return EmitTargetCallElse(AllocaIP, Builder.saveIP(), DeallocBlocks);
10439 return EmitTargetCallThen(AllocaIP, Builder.saveIP(), DeallocBlocks);
10441 return OMPBuilder.
emitIfClause(IfCond, EmitTargetCallThen, EmitTargetCallElse,
10455 bool HasNowait,
Value *DynCGroupMem,
10457 Value *RTLocOverride) {
10462 Builder.restoreIP(CodeGenIP);
10470 *
this,
Builder, IsOffloadEntry, EntryInfo, DefaultAttrs, OutlinedFn,
10471 OutlinedFnID, Inputs, CBFunc, ArgAccessorFuncCB, OutlinedFnLoc))
10477 if (!
Config.isTargetDevice()) {
10479 *
this,
Builder, RTLocOverride, AllocaIP, DeallocBlocks, Info,
10480 DefaultAttrs, RuntimeAttrs, IfCond, OutlinedFn, OutlinedFnID,
10481 Inputs, GenMapInfoCB, CustomMapperCB, Dependencies, HasNowait,
10482 DynCGroupMem, DynCGroupMemFallback))
10498 return OS.
str().str();
10503 return OpenMPIRBuilder::getNameWithSeparators(Parts,
Config.firstSeparator(),
10509 auto &Elem = *
InternalVars.try_emplace(Name,
nullptr).first;
10511 assert(Elem.second->getValueType() == Ty &&
10512 "OMP internal variable has different type than requested");
10525 :
M.getTargetTriple().isAMDGPU()
10527 :
DL.getDefaultGlobalsAddressSpace();
10528 auto Linkage = this->
M.getTargetTriple().isWasm()
10536 const llvm::Align PtrAlign =
DL.getPointerABIAlignment(AddressSpaceVal);
10537 GV->setAlignment(std::max(TypeAlign, PtrAlign));
10541 return Elem.second;
10544Value *OpenMPIRBuilder::getOMPCriticalRegionLock(
StringRef CriticalName) {
10545 std::string Prefix =
Twine(
"gomp_critical_user_", CriticalName).
str();
10546 std::string Name = getNameWithSeparators({Prefix,
"var"},
".",
".");
10557 return SizePtrToInt;
10562 std::string VarName) {
10570 return MaptypesArrayGlobal;
10575 unsigned NumOperands,
10584 ArrI8PtrTy,
nullptr,
".offload_baseptrs");
10588 ArrI64Ty,
nullptr,
".offload_sizes");
10599 int64_t DeviceID,
unsigned NumOperands) {
10605 Value *ArgsBaseGEP =
10607 {Builder.getInt32(0), Builder.getInt32(0)});
10610 {Builder.getInt32(0), Builder.getInt32(0)});
10611 Value *ArgSizesGEP =
10613 {Builder.getInt32(0), Builder.getInt32(0)});
10617 Builder.getInt32(NumOperands),
10618 ArgsBaseGEP, ArgsGEP, ArgSizesGEP,
10619 MaptypesArg, MapnamesArg, NullPtr});
10626 assert((!ForEndCall || Info.separateBeginEndCalls()) &&
10627 "expected region end call to runtime only when end call is separate");
10629 auto VoidPtrTy = UnqualPtrTy;
10630 auto VoidPtrPtrTy = UnqualPtrTy;
10632 auto Int64PtrTy = UnqualPtrTy;
10635 if (!Info.NumberOfPtrs) {
10647 Info.RTArgs.BasePointersArray,
10650 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
10654 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
10658 ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd
10659 : Info.RTArgs.MapTypesArray,
10665 if (!Info.EmitDebug)
10669 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,
10674 if (!Info.HasMapper)
10678 Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);
10699 "struct.descriptor_dim");
10701 enum { OffsetFD = 0, CountFD, StrideFD };
10705 for (
unsigned I = 0, L = 0, E = NonContigInfo.
Dims.
size();
I < E; ++
I) {
10708 if (NonContigInfo.
Dims[
I] == 1)
10713 Builder.CreateAlloca(ArrayTy,
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;
10721 Value *OffsetLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);
10723 NonContigInfo.
Offsets[L][RevIdx], OffsetLVal,
10724 M.getDataLayout().getPrefTypeAlign(OffsetLVal->
getType()));
10726 Value *CountLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);
10728 NonContigInfo.
Counts[L][RevIdx], CountLVal,
10729 M.getDataLayout().getPrefTypeAlign(CountLVal->
getType()));
10731 Value *StrideLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);
10733 NonContigInfo.
Strides[L][RevIdx], StrideLVal,
10734 M.getDataLayout().getPrefTypeAlign(CountLVal->
getType()));
10737 Builder.restoreIP(CodeGenIP);
10738 Value *DAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
10739 DimsAddr,
Builder.getPtrTy());
10742 Info.RTArgs.PointersArray, 0,
I);
10744 DAddr,
P,
M.getDataLayout().getPrefTypeAlign(
Builder.getPtrTy()));
10749void OpenMPIRBuilder::emitUDMapperArrayInitOrDel(
10753 StringRef Prefix = IsInit ?
".init" :
".del";
10759 Builder.CreateICmpSGT(
Size, Builder.getInt64(1),
"omp.arrayinit.isarray");
10760 Value *DeleteBit = Builder.CreateAnd(
10763 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10764 OpenMPOffloadMappingFlags::OMP_MAP_DELETE)));
10769 Value *BaseIsBegin = Builder.CreateICmpNE(
Base, Begin);
10770 Cond = Builder.CreateOr(IsArray, BaseIsBegin);
10771 DeleteCond = Builder.CreateIsNull(
10776 DeleteCond =
Builder.CreateIsNotNull(
10792 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10793 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10794 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10795 MapTypeArg =
Builder.CreateOr(
10798 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10799 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT)));
10803 Value *OffloadingArgs[] = {MapperHandle,
Base, Begin,
10804 ArraySize, MapTypeArg, MapName};
10815 bool PreserveMemberOfFlags,
bool PropagatePresentToPointeeStorage,
10816 bool PropagatePresentToNonPointeeStorage) {
10830 MapperFn->
addFnAttr(Attribute::NoInline);
10831 MapperFn->
addFnAttr(Attribute::NoUnwind);
10842 Builder.SetInsertPoint(EntryBB);
10857 Value *PtrBegin = BeginIn;
10863 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn,
Size,
10864 MapType, MapName, ElementSize, HeadBB,
10875 Builder.CreateICmpEQ(PtrBegin, PtrEnd,
"omp.arraymap.isempty");
10876 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
10882 Builder.CreatePHI(PtrBegin->
getType(), 2,
"omp.arraymap.ptrcurrent");
10883 PtrPHI->addIncoming(PtrBegin, HeadBB);
10888 return Info.takeError();
10894 Value *ShiftedPreviousSize =
nullptr;
10958 auto pushComponent = [&](
Value *CurBaseArg,
Value *CurBeginArg,
10960 uint64_t RawType,
bool HasAttachPtrFlag,
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);
10972 Value *MemberMapType;
10973 if (PreserveMemberOfFlags || (RawType & AttachBit) || HasAttachPtrFlag) {
10974 if (RawType & MemberOfMask)
10975 MemberMapType =
Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10977 MemberMapType = OriMapType;
10979 MemberMapType =
Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10997 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10998 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10999 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11009 Builder.CreateCondBr(IsAlloc, AllocBB, AllocElseBB);
11015 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11016 OpenMPOffloadMappingFlags::OMP_MAP_TO |
11017 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11023 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11024 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11025 Builder.CreateCondBr(IsTo, ToBB, ToElseBB);
11031 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11032 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11038 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11039 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11040 Builder.CreateCondBr(IsFrom, FromBB, EndBB);
11046 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11047 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11055 CurMapType->
addIncoming(MemberMapType, ToElseBB);
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)
11106 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11107 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11108 Value *ImportedModifierBits =
11111 CurMapType, ImportedModifierBits,
"omp.maptype.with.modifiers");
11116 Value *FinalMapType =
11117 (RawType & AttachBit) ? CurMapType : CurMapTypeWithModifiers;
11119 Value *OffloadingArgs[] = {MapperHandle, CurBaseArg, CurBeginArg,
11120 CurSizeArg, FinalMapType, CurNameArg};
11121 if (ChildMapperFn) {
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");
11147 Builder.CreateCondBr(Info->LeadingParentCond, PushBB, ContBB);
11149 Value *CurNameArg = Info->Names.size()
11153 Info->BasePointers[0], Info->Pointers[0], Info->Sizes[0], CurNameArg,
11154 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11156 Info->HasAttachPtr[0],
nullptr);
11160 FirstStaticIdx = 1;
11168 Value *OffloadingArgs[] = {MapperHandle};
11172 if (Info->LeadingParentCond)
11173 PreviousSize =
Builder.CreateSub(PreviousSize,
Builder.getInt64(1));
11174 ShiftedPreviousSize =
11178 for (
unsigned I = FirstStaticIdx;
I < Info->BasePointers.size(); ++
I) {
11179 Value *CurNameArg = Info->Names.size()
11183 if (!ChildMapperFn)
11185 LastBB = pushComponent(
11186 Info->BasePointers[
I], Info->Pointers[
I], Info->Sizes[
I], CurNameArg,
11187 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11189 Info->HasAttachPtr[
I], *ChildMapperFn);
11206 Entry[0], Entry[1], Entry[2],
11208 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11218 LastBB =
Builder.GetInsertBlock();
11224 "omp.arraymap.next");
11225 PtrPHI->addIncoming(PtrNext, LastBB);
11226 Value *IsDone =
Builder.CreateICmpEQ(PtrNext, PtrEnd,
"omp.arraymap.isdone");
11228 Builder.CreateCondBr(IsDone, ExitBB, BodyBB);
11233 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn,
Size,
11234 MapType, MapName, ElementSize, DoneBB,
11247 bool IsNonContiguous,
11251 Info.clearArrayInfo();
11254 if (Info.NumberOfPtrs == 0)
11263 Info.RTArgs.BasePointersArray =
Builder.CreateAlloca(
11264 PointerArrayType,
nullptr,
".offload_baseptrs");
11266 Info.RTArgs.PointersArray =
Builder.CreateAlloca(
11267 PointerArrayType,
nullptr,
".offload_ptrs");
11269 PointerArrayType,
nullptr,
".offload_mappers");
11270 Info.RTArgs.MappersArray = MappersArray;
11277 ConstantInt::get(Int64Ty, 0));
11279 for (
unsigned I = 0, E = CombinedInfo.
Sizes.
size();
I < E; ++
I) {
11280 bool IsNonContigEntry =
11282 (
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11284 OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG) != 0);
11287 if (IsNonContigEntry) {
11289 "Index must be in-bounds for NON_CONTIG Dims array");
11291 assert(DimCount > 0 &&
"NON_CONTIG DimCount must be > 0");
11292 ConstSizes[
I] = ConstantInt::get(Int64Ty, DimCount);
11297 ConstSizes[
I] = CI;
11301 RuntimeSizes.
set(
I);
11304 if (RuntimeSizes.
all()) {
11306 Info.RTArgs.SizesArray =
Builder.CreateAlloca(
11307 SizeArrayType,
nullptr,
".offload_sizes");
11313 auto *SizesArrayGbl =
11318 if (!RuntimeSizes.
any()) {
11319 Info.RTArgs.SizesArray = SizesArrayGbl;
11321 unsigned IndexSize =
M.getDataLayout().getIndexSizeInBits(0);
11322 Align OffloadSizeAlign =
M.getDataLayout().getABIIntegerTypeAlignment(64);
11325 SizeArrayType,
nullptr,
".offload_sizes");
11329 Buffer,
M.getDataLayout().getPrefTypeAlign(Buffer->
getType()),
11330 SizesArrayGbl, OffloadSizeAlign,
11335 Info.RTArgs.SizesArray = Buffer;
11343 for (
auto mapFlag : CombinedInfo.
Types)
11345 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11349 Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
11355 Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
11356 Info.EmitDebug =
true;
11358 Info.RTArgs.MapNamesArray =
11360 Info.EmitDebug =
false;
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;
11375 if (EndMapTypesDiffer) {
11377 Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
11382 for (
unsigned I = 0;
I < Info.NumberOfPtrs; ++
I) {
11385 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.BasePointersArray,
11387 Builder.CreateAlignedStore(BPVal, BP,
11388 M.getDataLayout().getPrefTypeAlign(PtrTy));
11390 if (Info.requiresDevicePointerInfo()) {
11392 CodeGenIP =
Builder.saveIP();
11394 Info.DevicePtrInfoMap[BPVal] = {BP,
Builder.CreateAlloca(PtrTy)};
11397 DeviceAddrCB(
I, Info.DevicePtrInfoMap[BPVal].second);
11399 Info.DevicePtrInfoMap[BPVal] = {BP, BP};
11401 DeviceAddrCB(
I, BP);
11407 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray, 0,
11410 Builder.CreateAlignedStore(PVal,
P,
11411 M.getDataLayout().getPrefTypeAlign(PtrTy));
11413 if (RuntimeSizes.
test(
I)) {
11415 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
11421 S,
M.getDataLayout().getPrefTypeAlign(PtrTy));
11424 unsigned IndexSize =
M.getDataLayout().getIndexSizeInBits(0);
11427 auto CustomMFunc = CustomMapperCB(
I);
11429 return CustomMFunc.takeError();
11431 MFunc =
Builder.CreatePointerCast(*CustomMFunc, PtrTy);
11434 PointerArrayType, MappersArray,
11437 MFunc, MAddr,
M.getDataLayout().getPrefTypeAlign(MAddr->
getType()));
11441 Info.NumberOfPtrs == 0)
11458 Builder.ClearInsertionPoint();
11489 auto CondConstant = CI->getSExtValue();
11491 return ThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
11493 return ElseGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
11503 Builder.CreateCondBr(
Cond, ThenBlock, ElseBlock);
11506 if (
Error Err = ThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks)) {
11516 if (
Error Err = ElseGen(AllocaIP,
Builder.saveIP(), DeallocBlocks)) {
11534 assert(
X.Var->getType()->isPointerTy() &&
11535 "OMP Atomic expects a pointer to target memory");
11536 Type *XElemTy =
X.ElemTy;
11539 "OMP atomic read expected a scalar type");
11541 Value *XRead =
nullptr;
11545 Builder.CreateLoad(XElemTy,
X.Var,
X.IsVolatile,
"omp.atomic.read");
11554 unsigned LoadSize =
DL.getTypeStoreSize(XElemTy);
11557 OldVal->
getAlign(),
true , AllocaIP,
X.Var);
11559 XRead = AtomicLoadRes.first;
11566 Builder.CreateLoad(IntCastTy,
X.Var,
X.IsVolatile,
"omp.atomic.load");
11569 XRead =
Builder.CreateBitCast(XLoad, XElemTy,
"atomic.flt.cast");
11571 XRead =
Builder.CreateIntToPtr(XLoad, XElemTy,
"atomic.ptr.cast");
11574 Builder.CreateStore(XRead, V.Var, V.IsVolatile);
11585 assert(
X.Var->getType()->isPointerTy() &&
11586 "OMP Atomic expects a pointer to target memory");
11587 Type *XElemTy =
X.ElemTy;
11590 "OMP atomic write expected a scalar type");
11598 unsigned LoadSize =
DL.getTypeStoreSize(XElemTy);
11601 OldVal->
getAlign(),
true , AllocaIP,
X.Var);
11609 Builder.CreateBitCast(Expr, IntCastTy,
"atomic.src.int.cast");
11620 AtomicUpdateCallbackTy &UpdateOp,
bool IsXBinopExpr,
11621 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11627 Type *XTy =
X.Var->getType();
11629 "OMP Atomic expects a pointer to target memory");
11630 Type *XElemTy =
X.ElemTy;
11633 "OMP atomic update expected a scalar or struct type");
11637 AllocaIP,
X.Var,
X.ElemTy, Expr, AO, RMWOp, UpdateOp,
X.IsVolatile,
11638 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11640 return AtomicResult.takeError();
11645Value *OpenMPIRBuilder::emitRMWOpAsInstruction(
Value *Src1,
Value *Src2,
11649 return Builder.CreateAdd(Src1, Src2);
11651 return Builder.CreateSub(Src1, Src2);
11653 return Builder.CreateAnd(Src1, Src2);
11655 return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
11657 return Builder.CreateOr(Src1, Src2);
11659 return Builder.CreateXor(Src1, Src2);
11661 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, Src1, Src2);
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);
11708Expected<std::pair<Value *, Value *>> OpenMPIRBuilder::emitAtomicUpdate(
11711 AtomicUpdateCallbackTy &UpdateOp,
bool VolatileX,
bool IsXBinopExpr,
11712 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11714 bool emitRMWOp =
false;
11731 emitRMWOp = XElemTy;
11735 emitRMWOp = (IsXBinopExpr && XElemTy);
11743 std::pair<Value *, Value *> Res;
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,
11750 if (
T.isAMDGPU()) {
11751 if (!IsFineGrainedMemory)
11752 RMWInst->
setMetadata(
"amdgpu.no.fine.grained.memory",
11754 if (!IsRemoteMemory)
11758 Res.first = RMWInst;
11763 Res.second = Res.first;
11765 Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
11768 Builder.CreateLoad(XElemTy,
X,
X->getName() +
".atomic.load");
11774 OpenMPIRBuilder::AtomicInfo atomicInfo(
11776 OldVal->
getAlign(),
true , AllocaIP,
X);
11777 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11780 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11787 AllocaInst *NewAtomicAddr =
Builder.CreateAlloca(XElemTy);
11788 NewAtomicAddr->
setName(
X->getName() +
"x.new.val");
11789 Builder.SetInsertPoint(ContBB);
11791 PHI->addIncoming(AtomicLoadRes.first, CurBB);
11793 Expected<Value *> CBResult = UpdateOp(OldExprVal,
Builder);
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());
11806 Res.first = OldExprVal;
11809 if (UnreachableInst *ExitTI =
11812 Builder.SetInsertPoint(ExitBB);
11814 Builder.SetInsertPoint(ExitTI);
11817 IntegerType *IntCastTy =
11820 Builder.CreateLoad(IntCastTy,
X,
X->getName() +
".atomic.load");
11830 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11837 AllocaInst *NewAtomicAddr =
Builder.CreateAlloca(XElemTy);
11838 NewAtomicAddr->
setName(
X->getName() +
"x.new.val");
11839 Builder.SetInsertPoint(ContBB);
11841 PHI->addIncoming(OldVal, CurBB);
11846 OldExprVal =
Builder.CreateBitCast(
PHI, XElemTy,
11847 X->getName() +
".atomic.fltCast");
11849 OldExprVal =
Builder.CreateIntToPtr(
PHI, XElemTy,
11850 X->getName() +
".atomic.ptrCast");
11854 Expected<Value *> CBResult = UpdateOp(OldExprVal,
Builder);
11857 Value *Upd = *CBResult;
11858 Builder.CreateStore(Upd, NewAtomicAddr);
11859 LoadInst *DesiredVal =
Builder.CreateLoad(IntCastTy, NewAtomicAddr);
11863 X,
PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
11864 Result->setVolatile(VolatileX);
11865 Value *PreviousVal =
Builder.CreateExtractValue(Result, 0);
11866 Value *SuccessFailureVal =
Builder.CreateExtractValue(Result, 1);
11867 PHI->addIncoming(PreviousVal,
Builder.GetInsertBlock());
11868 Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
11870 Res.first = OldExprVal;
11874 if (UnreachableInst *ExitTI =
11877 Builder.SetInsertPoint(ExitBB);
11879 Builder.SetInsertPoint(ExitTI);
11890 bool UpdateExpr,
bool IsPostfixUpdate,
bool IsXBinopExpr,
11891 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11896 Type *XTy =
X.Var->getType();
11898 "OMP Atomic expects a pointer to target memory");
11899 Type *XElemTy =
X.ElemTy;
11902 "OMP atomic capture expected a scalar or struct type");
11909 AllocaIP,
X.Var,
X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
X.IsVolatile,
11910 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11913 Value *CapturedVal =
11914 (IsPostfixUpdate ? AtomicResult->first : AtomicResult->second);
11915 Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
11924 bool IsFailOnly,
bool IsWeak) {
11928 IsPostfixUpdate, IsFailOnly, Failure, IsWeak);
11940 assert(
X.Var->getType()->isPointerTy() &&
11941 "OMP atomic expects a pointer to target memory");
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");
11948 bool IsInteger = E->getType()->isIntegerTy();
11950 if (
Op == OMPAtomicCompareOp::EQ) {
11953 Value *OldValue =
nullptr;
11954 Value *SuccessOrFail =
nullptr;
11992 X.Var->getName() +
".atomic.load");
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");
12005 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
12009 M.getContext(),
X.Var->getName() +
".atomic.nan",
F, ExitBB);
12011 M.getContext(),
X.Var->getName() +
".atomic.notnan",
F, ExitBB);
12013 M.getContext(),
X.Var->getName() +
".atomic.zero",
F, ExitBB);
12015 M.getContext(),
X.Var->getName() +
".atomic.normal",
F, ExitBB);
12019 Builder.SetInsertPoint(CurBB);
12020 Builder.CreateCondBr(EitherNaN, NaNBB, NotNaNBB);
12023 Builder.SetInsertPoint(NaNBB);
12027 Builder.SetInsertPoint(NotNaNBB);
12030 X.Var->getName() +
".atomic.xiszero");
12032 "atomic.e.iszero");
12033 Value *BothZero =
Builder.CreateAnd(XIsZero, EIsZero,
"atomic.both.zero");
12034 Builder.CreateCondBr(BothZero, ZeroBB, NormalBB);
12037 Builder.SetInsertPoint(ZeroBB);
12039 X.Var, XCurr, DBCast,
MaybeAlign(), AO, Failure);
12041 Value *OldZero =
Builder.CreateExtractValue(ResZero, 0);
12042 Value *OkZero =
Builder.CreateExtractValue(ResZero, 1);
12046 Builder.SetInsertPoint(NormalBB);
12048 X.Var, EBCast, DBCast,
MaybeAlign(), AO, Failure);
12050 Value *OldNormal =
Builder.CreateExtractValue(ResNormal, 0);
12051 Value *OkNormal =
Builder.CreateExtractValue(ResNormal, 1);
12057 Builder.CreatePHI(IntCastTy, 3,
X.Var->getName() +
".atomic.old");
12062 X.Var->getName() +
".atomic.ok");
12069 Builder.SetInsertPoint(ExitBB);
12074 OldValue =
Builder.CreateBitCast(OldIntPHI,
X.ElemTy,
12075 X.Var->getName() +
".atomic.old.fp");
12076 SuccessOrFail = SuccessPHI;
12084 Result =
Builder.CreateAtomicCmpXchg(
X.Var, EBCast, DBCast,
12090 Result->setWeak(IsWeak);
12093 OldValue =
Builder.CreateExtractValue(Result, 0);
12095 OldValue =
Builder.CreateBitCast(OldValue,
X.ElemTy);
12097 "OldValue and V must be of same type");
12098 if (IsPostfixUpdate) {
12099 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12101 SuccessOrFail =
Builder.CreateExtractValue(Result, 1);
12105 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
12107 CurBBTI,
X.Var->getName() +
".atomic.exit");
12113 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12115 Builder.SetInsertPoint(ContBB);
12116 Builder.CreateStore(OldValue, V.Var);
12122 Builder.SetInsertPoint(ExitBB);
12124 Builder.SetInsertPoint(ExitTI);
12127 Value *CapturedValue =
12128 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12129 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
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");
12139 Value *SuccessFailureVal =
12140 Builder.CreateExtractValue(Result, 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);
12153 "OldValue and V must be of same type");
12154 if (IsPostfixUpdate) {
12155 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12160 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
12162 CurBBTI,
X.Var->getName() +
".atomic.exit");
12168 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12170 Builder.SetInsertPoint(ContBB);
12171 Builder.CreateStore(OldValue, V.Var);
12177 Builder.SetInsertPoint(ExitBB);
12179 Builder.SetInsertPoint(ExitTI);
12182 Value *CapturedValue =
12183 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12184 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
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");
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);
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 ==");
12214 if (IsXBinopExpr) {
12243 Value *CapturedValue =
nullptr;
12244 if (IsPostfixUpdate) {
12245 CapturedValue = OldValue;
12270 Value *NonAtomicCmp =
Builder.CreateCmp(Pred, OldValue, E);
12271 CapturedValue =
Builder.CreateSelect(NonAtomicCmp, E, OldValue);
12273 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12295 if (&OuterAllocaBB ==
Builder.GetInsertBlock()) {
12322 bool SubClausesPresent =
12323 (NumTeamsLower || NumTeamsUpper || ThreadLimit || IfExpr);
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");
12330 if (NumTeamsUpper ==
nullptr)
12331 NumTeamsUpper =
Builder.getInt32(0);
12333 if (NumTeamsLower ==
nullptr)
12334 NumTeamsLower = NumTeamsUpper;
12338 "argument to if clause must be an integer value");
12342 IfExpr =
Builder.CreateICmpNE(IfExpr,
12343 ConstantInt::get(IfExpr->
getType(), 0));
12344 NumTeamsUpper =
Builder.CreateSelect(
12345 IfExpr, NumTeamsUpper,
Builder.getInt32(1),
"numTeamsUpper");
12348 NumTeamsLower =
Builder.CreateSelect(
12349 IfExpr, NumTeamsLower,
Builder.getInt32(1),
"numTeamsLower");
12352 if (ThreadLimit ==
nullptr)
12353 ThreadLimit =
Builder.getInt32(0);
12357 Value *NumTeamsLowerInt32 =
12359 Value *NumTeamsUpperInt32 =
12361 Value *ThreadLimitInt32 =
12368 {Ident, ThreadNum, NumTeamsLowerInt32, NumTeamsUpperInt32,
12369 ThreadLimitInt32});
12374 if (
Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12377 auto OI = std::make_unique<OutlineInfo>();
12378 OI->EntryBB = AllocaBB;
12379 OI->ExitBB = ExitBB;
12380 OI->OuterAllocBB = &OuterAllocaBB;
12386 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP,
"gid",
true));
12388 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP,
"tid",
true));
12390 auto HostPostOutlineCB = [
this, Ident,
12391 ToBeDeleted](
Function &OutlinedFn)
mutable {
12396 "there must be a single user for the outlined function");
12401 "Outlined function must have two or three arguments only");
12403 bool HasShared = OutlinedFn.
arg_size() == 3;
12411 assert(StaleCI &&
"Error while outlining - no CallInst user found for the "
12412 "outlined function.");
12413 Builder.SetInsertPoint(StaleCI);
12420 omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),
12423 Builder.ClearInsertionPoint();
12425 I->eraseFromParent();
12428 if (!
Config.isTargetDevice())
12429 OI->PostOutlineCB = HostPostOutlineCB;
12433 Builder.SetInsertPoint(ExitBB);
12444 BasicBlock *OuterAllocaBB = OuterAllocIP.getNodeParent();
12446 if (OuterAllocaBB ==
Builder.GetInsertBlock()) {
12461 if (
Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
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());
12476 Builder.SetInsertPoint(ExitBB);
12483 std::string VarName) {
12492 return MapNamesArrayGlobal;
12497void OpenMPIRBuilder::initializeTypes(
Module &M) {
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); \
12512 T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed); \
12514 VarName##Ptr = PointerType::get(Ctx, DefaultTargetAS);
12515#include "llvm/Frontend/OpenMP/OMPKinds.def"
12526 while (!Worklist.
empty()) {
12530 if (
BlockSet.insert(SuccBB).second)
12535std::unique_ptr<CodeExtractor>
12537 bool ArgsInZeroAddressSpace,
12539 return std::make_unique<CodeExtractor>(
12549 Suffix.
str(), ArgsInZeroAddressSpace);
12552std::unique_ptr<CodeExtractor> DeviceSharedMemOutlineInfo::createCodeExtractor(
12554 return std::make_unique<DeviceSharedMemCodeExtractor>(
12555 OMPBuilder, Blocks,
nullptr,
12563 OuterDeallocBBs.empty()
12566 Suffix.
str(), ArgsInZeroAddressSpace);
12570 uint64_t
Size, int32_t Flags,
12576 Name.empty() ? Addr->
getName() : Name,
Size, Flags, 0);
12588 Fn->
addFnAttr(
"uniform-work-group-size");
12589 Fn->
addFnAttr(Attribute::MustProgress);
12607 auto &&GetMDInt = [
this](
unsigned V) {
12614 NamedMDNode *MD =
M.getOrInsertNamedMetadata(
"omp_offload.info");
12615 auto &&TargetRegionMetadataEmitter =
12616 [&
C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
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())};
12637 OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);
12646 auto &&DeviceGlobalVarMetadataEmitter =
12647 [&
C, &OrderedEntries, &GetMDInt, &GetMDString, MD](
12657 Metadata *
Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),
12658 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
12662 OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);
12669 DeviceGlobalVarMetadataEmitter);
12671 for (
const auto &E : OrderedEntries) {
12672 assert(E.first &&
"All ordered entries must exist!");
12673 if (
const auto *CE =
12676 if (!CE->getID() || !CE->getAddress()) {
12680 if (!
M.getNamedValue(FnName))
12688 }
else if (
const auto *CE =
dyn_cast<
12697 if (
Config.isTargetDevice() &&
Config.hasRequiresUnifiedSharedMemory())
12699 if (!CE->getAddress()) {
12704 if (CE->getVarSize() == 0)
12708 assert(((
Config.isTargetDevice() && !CE->getAddress()) ||
12709 (!
Config.isTargetDevice() && CE->getAddress())) &&
12710 "Declaret target link address is set.");
12711 if (
Config.isTargetDevice())
12713 if (!CE->getAddress()) {
12720 if (!CE->getAddress()) {
12733 if ((
GV->hasLocalLinkage() ||
GV->hasHiddenVisibility()) &&
12737 OMPTargetGlobalVarEntryIndirectVTable))
12746 Flags, CE->getLinkage(), CE->getVarName());
12749 Flags, CE->getLinkage());
12760 if (
Config.hasRequiresFlags() && !
Config.isTargetDevice())
12766 Config.getRequiresFlags());
12776 OS <<
"_" <<
Count;
12781 unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);
12784 EntryInfo.
Line, NewCount);
12792 auto FileIDInfo = CallBack();
12793 uint64_t FileID = 0;
12795 ID =
Status->getUniqueID();
12796 FileID =
Status->getUniqueID().getFile();
12800 FileID =
hash_value(std::get<0>(FileIDInfo));
12804 std::get<1>(FileIDInfo));
12809 for (uint64_t Remain =
12810 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12812 !(Remain & 1); Remain = Remain >> 1)
12830 if (
static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12832 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12839 if (
static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12845 Flags &=
~omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
12846 Flags |= MemberOfFlag;
12852 bool IsDeclaration,
bool IsExternallyVisible,
12854 std::vector<GlobalVariable *> &GeneratedRefs,
bool OpenMPSIMD,
12855 std::vector<Triple> TargetTriple,
Type *LlvmPtrTy,
12856 std::function<
Constant *()> GlobalInitializer,
12867 Config.hasRequiresUnifiedSharedMemory())) {
12872 if (!IsExternallyVisible)
12874 OS <<
"_decl_tgt_ref_ptr";
12877 Value *Ptr =
M.getNamedValue(PtrName);
12886 if (!
Config.isTargetDevice()) {
12887 if (GlobalInitializer)
12888 GV->setInitializer(GlobalInitializer());
12894 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12895 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12896 GlobalInitializer, VariableLinkage, LlvmPtrTy,
cast<Constant>(Ptr));
12908 bool IsDeclaration,
bool IsExternallyVisible,
12910 std::vector<GlobalVariable *> &GeneratedRefs,
bool OpenMPSIMD,
12911 std::vector<Triple> TargetTriple,
12912 std::function<
Constant *()> GlobalInitializer,
12916 (TargetTriple.empty() && !
Config.isTargetDevice()))
12927 !
Config.hasRequiresUnifiedSharedMemory()) {
12929 VarName = MangledName;
12932 if (!IsDeclaration)
12934 M.getDataLayout().getTypeSizeInBits(LlvmVal->
getValueType()), 8);
12937 Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->
getLinkage();
12941 if (
Config.isTargetDevice() &&
12950 if (!
M.getNamedValue(RefName)) {
12954 GvAddrRef->setConstant(
true);
12956 GvAddrRef->setInitializer(Addr);
12957 GeneratedRefs.push_back(GvAddrRef);
12966 if (
Config.isTargetDevice()) {
12967 VarName = (Addr) ? Addr->
getName() :
"";
12971 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12972 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12973 LlvmPtrTy, GlobalInitializer, VariableLinkage);
12974 VarName = (Addr) ? Addr->
getName() :
"";
12976 VarSize =
M.getDataLayout().getPointerSize();
12995 auto &&GetMDInt = [MN](
unsigned Idx) {
13000 auto &&GetMDString = [MN](
unsigned Idx) {
13002 return V->getString();
13005 switch (GetMDInt(0)) {
13009 case OffloadEntriesInfoManager::OffloadEntryInfo::
13010 OffloadingEntryInfoTargetRegion: {
13020 case OffloadEntriesInfoManager::OffloadEntryInfo::
13021 OffloadingEntryInfoDeviceGlobalVar:
13034 if (HostFilePath.
empty())
13038 if (std::error_code Err = Buf.getError()) {
13040 "OpenMPIRBuilder: " +
13048 if (std::error_code Err =
M.getError()) {
13050 (
"error parsing host file inside of OpenMPIRBuilder: " + Err.message())
13064 "expected a valid insertion block for creating an iterator loop");
13068 if (SplitIP == CurBB->
end())
13070 SplitIP = Terminator->getIterator();
13074 Builder.getCurrentDebugLocation(),
"omp.it.cont");
13086 T->eraseFromParent();
13101 bool ReachesLatch =
false;
13104 while (!Worklist.
empty()) {
13109 "iterator bodygen must leave at most one unterminated block",
13115 if (Succ == Latch) {
13116 ReachesLatch =
true;
13121 "iterator bodygen must not branch out of the loop body",
13123 if (Visited.
insert(Succ).second)
13129 Builder.SetInsertPoint(OpenBB);
13131 }
else if (!ReachesLatch) {
13141 return ContBB->
begin();
13151 for (
const auto &
ParamAttr : ParamAttrs) {
13194 return std::string(Out.str());
13202 unsigned VecRegSize;
13204 ISADataTy ISAData[] = {
13223 for (
char Mask :
Masked) {
13224 for (
const ISADataTy &
Data : ISAData) {
13227 Out <<
"_ZGV" <<
Data.ISA << Mask;
13229 assert(NumElts &&
"Non-zero simdlen/cdtsize expected");
13243template <
typename T>
13246 StringRef MangledName,
bool OutputBecomesInput,
13250 Out << Prefix << ISA << LMask << VLEN;
13251 if (OutputBecomesInput)
13253 Out << ParSeq <<
'_' << MangledName;
13262 bool OutputBecomesInput,
13267 OutputBecomesInput, Fn);
13269 OutputBecomesInput, Fn);
13273 OutputBecomesInput, Fn);
13275 OutputBecomesInput, Fn);
13279 OutputBecomesInput, Fn);
13281 OutputBecomesInput, Fn);
13286 OutputBecomesInput, Fn);
13297 char ISA,
unsigned NarrowestDataSize,
bool OutputBecomesInput) {
13298 assert((ISA ==
'n' || ISA ==
's') &&
"Expected ISA either 's' or 'n'.");
13310 OutputBecomesInput, Fn);
13317 OutputBecomesInput, Fn);
13319 OutputBecomesInput, Fn);
13323 OutputBecomesInput, Fn);
13327 OutputBecomesInput, Fn);
13336 OutputBecomesInput, Fn);
13343 MangledName, OutputBecomesInput, Fn);
13345 MangledName, OutputBecomesInput, Fn);
13349 MangledName, OutputBecomesInput, Fn);
13353 MangledName, OutputBecomesInput, Fn);
13363 return OffloadEntriesTargetRegion.empty() &&
13364 OffloadEntriesDeviceGlobalVar.empty();
13367unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(
13369 auto It = OffloadEntriesTargetRegionCount.find(
13370 getTargetRegionEntryCountKey(EntryInfo));
13371 if (It == OffloadEntriesTargetRegionCount.end())
13376void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(
13378 OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =
13379 EntryInfo.
Count + 1;
13385 OffloadEntriesTargetRegion[EntryInfo] =
13388 ++OffloadingEntriesNum;
13394 assert(EntryInfo.
Count == 0 &&
"expected default EntryInfo");
13397 EntryInfo.
Count = getTargetRegionEntryInfoCount(EntryInfo);
13401 if (OMPBuilder->Config.isTargetDevice()) {
13406 auto &Entry = OffloadEntriesTargetRegion[EntryInfo];
13407 Entry.setAddress(Addr);
13409 Entry.setFlags(Flags);
13415 "Target region entry already registered!");
13417 OffloadEntriesTargetRegion[EntryInfo] = Entry;
13418 ++OffloadingEntriesNum;
13420 incrementTargetRegionEntryInfoCount(EntryInfo);
13427 EntryInfo.
Count = getTargetRegionEntryInfoCount(EntryInfo);
13429 auto It = OffloadEntriesTargetRegion.find(EntryInfo);
13430 if (It == OffloadEntriesTargetRegion.end()) {
13434 if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))
13442 for (
const auto &It : OffloadEntriesTargetRegion) {
13443 Action(It.first, It.second);
13449 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
13450 ++OffloadingEntriesNum;
13456 if (OMPBuilder->Config.isTargetDevice()) {
13460 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13462 if (Entry.getVarSize() == 0) {
13463 Entry.setVarSize(VarSize);
13464 Entry.setLinkage(Linkage);
13468 Entry.setVarSize(VarSize);
13469 Entry.setLinkage(Linkage);
13470 Entry.setAddress(Addr);
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);
13485 OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,
13486 Addr, VarSize, Flags, Linkage,
13489 OffloadEntriesDeviceGlobalVar.try_emplace(
13490 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage,
"");
13491 ++OffloadingEntriesNum;
13498 for (
const auto &E : OffloadEntriesDeviceGlobalVar)
13499 Action(E.getKey(), E.getValue());
13506void CanonicalLoopInfo::reportUnsupportedVirtualCollapse()
const {
13508 assert(VirtualCollapse &&
"Requires Virtual collapse state");
13510 "virtual collapse must be the final structural loop transformation");
13513void CanonicalLoopInfo::collectControlBlocks(
13515 if (VirtualCollapse)
13516 reportUnsupportedVirtualCollapse();
13522 BBs.
append({getPreheader(), Header,
Cond, Latch, Exit, getAfter()});
13525BasicBlock *CanonicalLoopInfo::getVirtualCollapseInit()
const {
13526 return VirtualCollapse ? VirtualCollapse->Count->getParent() :
nullptr;
13531 if (VirtualCollapse)
13532 return getVirtualCollapseInit()->getSinglePredecessor();
13541void CanonicalLoopInfo::setTripCount(
Value *TripCount) {
13553void CanonicalLoopInfo::mapIndVar(
13563 for (
Use &U : OldIV->
uses()) {
13567 if (
User->getParent() == getCond())
13569 if (
User->getParent() == getLatch())
13575 Value *NewIV = Updater(OldIV);
13578 for (Use *U : ReplacableUses)
13592 bool IsVirtual = VirtualCollapse.has_value();
13598 IndVarEntry = Guard->getSuccessor(0);
13601 assert(Guard->getSuccessor(1) == Exit);
13602 assert(VirtualCollapse->Begin->getParent() ==
Init);
13604 {VirtualCollapse->Begin, VirtualCollapse->Count}) {
13606 assert(Copy->getOpcode() == Instruction::Add &&
Zero &&
Zero->isZero() &&
13607 "Virtual range copies must add zero");
13611 NonEmpty->getOperand(0) == VirtualCollapse->Count &&
13613 "Collapsed guard must skip empty ranges with zero count");
13625 "Preheader must terminate with unconditional branch");
13628 "Preheader must jump to collapsed initialization");
13631 "Preheader must jump to header");
13635 "Header must terminate with unconditional branch");
13636 assert(Header->getSingleSuccessor() == Cond &&
13637 "Header must jump to exiting block");
13640 assert(Cond->getSinglePredecessor() == Header &&
13641 "Exiting block only reachable from header");
13644 "Exiting block must terminate with conditional branch");
13646 "Exiting block's first successor jump to the body");
13648 "Exiting block's second successor must exit the loop");
13652 "Body only reachable from exiting block");
13657 "Latch must terminate with unconditional branch");
13658 assert(Latch->getSingleSuccessor() == Header &&
"Latch must jump to header");
13661 assert(Latch->getSinglePredecessor() !=
nullptr);
13666 "Exit block must terminate with unconditional branch");
13667 assert(Exit->getSingleSuccessor() == After &&
13668 "Exit block must jump to after block");
13672 "After block only reachable from exit block");
13676 assert(IndVar &&
"Canonical induction variable not found?");
13678 "Induction variable must be an integer");
13680 "Induction variable must be a PHI in the loop header");
13687 auto *NextIndVar =
cast<PHINode>(IndVar)->getIncomingValue(1);
13696 assert(TripCount &&
"Loop trip count not found?");
13698 "Trip count and induction variable must have the same type");
13702 "Exit condition must be a signed less-than comparison");
13704 "Exit condition must compare the induction variable");
13706 "Exit condition must compare with the trip count");
13715 VirtualCollapse.reset();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
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...
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
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
SmallVector< MachineOperand, 4 > Cond
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)
FunctionAnalysisManager FAM
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.
StringSet - A set-like wrapper for the StringMap.
static SymbolRef::Type getType(const Symbol *Sym)
Defines the virtual file system interface vfs::FileSystem.
static const uint32_t IV[8]
Class for arbitrary precision integers.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
An arbitrary precision integer that knows its signedness.
static APSInt getUnsigned(uint64_t X)
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.
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & back() const
Get the last element.
const T & front() const
Get the first element.
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
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)
LLVM_ABI void EmitAtomicStoreLibcall(AtomicOrdering AO, Value *Source)
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ 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
@ 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.
@ 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.
This class holds the attributes for a particular argument, parameter, function, or return value.
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.
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 begin()
Instruction iterator methods.
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.
reverse_iterator rbegin()
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
const Instruction & back() const
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.
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
InstListType::reverse_iterator reverse_iterator
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...
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.
InstListType::iterator iterator
Instruction iterators...
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 ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
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.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_ULE
unsigned less or equal
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
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.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
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.
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
Subprogram description. Uses SubclassData1.
uint32_t getAlignInBits() const
StringRef getName() const
A parsed version of the target data layout string in and methods for querying it.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
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.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
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.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const BasicBlock & getEntryBlock() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
DISubprogram * getSubprogram() const
Get the attached subprogram.
AttributeList getAttributes() const
Return the attribute list for this Function.
const Function & getFunction() const
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Type * getReturnType() const
Returns the type of the ret val.
void setCallingConv(CallingConv::ID CC)
Argument * getArg(unsigned i) const
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.
@ ProtectedVisibility
The GV is protected.
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Common base class shared among various IRBuilders.
InsertPoint saveIP() const
Returns the current insert point.
BasicBlock::iterator InsertPoint
InsertPoint - A saved insertion point.
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
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()
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.
This is an important class for using LLVM in a threaded context.
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.
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.
LLVM_ABI MDNode * createCallbackEncoding(unsigned CalleeArgNo, ArrayRef< int > Arguments, bool VarArgsArePassed)
Return metadata describing a callback (see llvm::AbstractCallSite).
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
ArrayRef< MDOperand > operands() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
This class implements a map that also provides access to all stored values in a deterministic order.
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
iterator_range< op_iterator > operands()
LLVM_ABI void addOperand(MDNode *M)
Device global variable entries info.
Target region entries info.
Base class of the entries info.
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 OpenMPIRBuilderConfig()
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)
bool isTargetDevice() const
LLVM_ABI void setHasRequiresDynamicAllocators(bool Value)
LLVM_ABI bool hasRequiresReverseOffload() const
bool hasRequiresFlags() 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 ~OpenMPIRBuilder()
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.
@ EMIT_MD_DECLARE_TARGET_ERROR
@ EMIT_MD_GLOBAL_VAR_INDIRECT_ERROR
@ EMIT_MD_GLOBAL_VAR_LINK_ERROR
@ EMIT_MD_TARGET_REGION_ERROR
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
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.
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.
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
bool empty() const
Determine if the SetVector is empty or not.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
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...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void append(StringRef RHS)
Append from a StringRef.
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 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",...
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
size_t count(char C) const
Return the number of occurrences of C in the string.
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
StringSet - A wrapper for StringMap that provides set-like functionality.
bool contains(StringRef key) const
Check if the set contains the given key.
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.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Type * getElementType(unsigned N) const
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.
bool isPPC() const
Tests whether the target is PowerPC (32- or 64-bit LE or BE).
bool isX86() const
Tests whether the target is x86 (32- or 64-bit).
bool isWasm() const
Tests whether the target is wasm (32- and 64-bit).
bool isSystemZ() const
Tests whether the target is SystemZ.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI Type * getStructElementType(unsigned N) const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isStructTy() const
True if this is an instance of StructType.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
bool isVoidTy() const
Return true if this is 'void'.
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.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
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...
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
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.
#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.
@ 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.
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.
@ 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)
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
@ OMP_TGT_EXEC_MODE_GENERIC
Function * Kernel
Summary of a kernel (=entry point for target offloading).
WorksharingLoopType
A type of worksharing loop construct.
OMPAtomicCompareOp
Atomic compare operations. Currently OpenMP only supports ==, >, and <.
EnumSet< Property > Properties
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
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.
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.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
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.
@ LLVM_MARK_AS_BITMASK_ENUM
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,...
unsigned getPointerAddressSpace(const Type *T)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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...
testing::Matcher< const detail::ErrorHolder & > Failed()
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 ...
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.
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...
std::string utostr(uint64_t X, bool isNeg=false)
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
bool isa_and_nonnull(const Y &Val)
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
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
auto dyn_cast_or_null(const Y &Val)
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.
AtomicOrderingCABI toCABI(AtomicOrdering AO)
auto reverse(ContainerTy &&C)
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.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
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...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
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).
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
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.
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
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
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.
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
std::optional< StringRef > getAtomicScopeIRString(const Triple &T, AtomicScope S, bool IsSingleAddressSpace=false)
Returns the LLVM IR syncscope string that T uses to spell S.
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
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
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.
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.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
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.
SmallVector< DependData > Deps
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...
MapNonContiguousArrayTy Offsets
MapNonContiguousArrayTy Counts
MapNonContiguousArrayTy Strides
This structure contains combined information generated for mappable clauses, including base pointers,...
MapDeviceInfoArrayTy DevicePointers
MapValuesArrayTy BasePointers
MapValuesArrayTy Pointers
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.
BasicBlock * OuterAllocBB
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...
omp::OMPTgtExecModeFlags ExecFlags
SmallVector< int32_t, 3 > MaxTeams
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.
SmallVector< Value *, 3 > MaxTeams
Value * LoopTripCount
Total number of iterations of the SPMD or Generic-SPMD kernel or null if it is a generic kernel.
SmallVector< Value *, 3 > TargetThreadLimit
SmallVector< Value *, 3 > TeamsThreadLimit
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),...