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";
1070 if (
Config.isTargetDevice())
1071 applyDeclareTargetGlobalReplacements();
1073 if (
Config.EmitLLVMUsedMetaInfo.value_or(
false)) {
1074 std::vector<WeakTrackingVH> LLVMCompilerUsed = {
1075 M.getGlobalVariable(
"__openmp_nvptx_data_transfer_temporary_storage")};
1076 emitUsed(
"llvm.compiler.used", LLVMCompilerUsed);
1093 assert(Original && Replacement &&
1094 "Null values provided to registerDeclareTargetGlobalReplacement");
1098void OpenMPIRBuilder::applyDeclareTargetGlobalReplacements() {
1104 "A null value was inserted into DeclareTargetGlobalReplacements");
1108 if (!OldGV || !NewGV)
1142 for (
unsigned I = 0, E =
PHI->getNumIncomingValues();
I < E; ++
I) {
1143 if (
PHI->getIncomingValue(
I) != OldGV)
1148 Builder.SetCurrentDebugLocation(
PHI->getDebugLoc());
1150 PHI->setIncomingValue(
I, EdgeLoad);
1156 Builder.SetCurrentDebugLocation(Insn->getDebugLoc());
1172 "Non-default address space declare target global");
1174 unsigned DestAS = ASC->getType()->getPointerAddressSpace();
1175 if (DestAS == 0 && NewGVAS != OldGVAS) {
1176 ASC->replaceAllUsesWith(
Load);
1177 ASC->eraseFromParent();
1182 Insn->replaceUsesOfWith(OldGV,
Load);
1198 ConstantInt::get(I32Ty,
Value), Name);
1211 for (
unsigned I = 0, E =
List.size();
I != E; ++
I)
1215 if (UsedArray.
empty())
1222 GV->setSection(
"llvm.metadata");
1228 auto *Int8Ty =
Builder.getInt8Ty();
1231 ConstantInt::get(Int8Ty, Mode),
Twine(KernelName,
"_exec_mode"));
1239 unsigned Reserve2Flags) {
1241 LocFlags |= OMP_IDENT_FLAG_KMPC;
1248 ConstantInt::get(Int32,
uint32_t(LocFlags)),
1249 ConstantInt::get(Int32, Reserve2Flags),
1250 ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
1252 size_t SrcLocStrArgIdx = 4;
1253 if (OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx)
1257 SrcLocStr, OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx));
1264 if (
GV.getValueType() == OpenMPIRBuilder::Ident &&
GV.hasInitializer())
1265 if (
GV.getInitializer() == Initializer)
1270 M, OpenMPIRBuilder::Ident,
1273 M.getDataLayout().getDefaultGlobalsAddressSpace());
1285 SrcLocStrSize = LocStr.
size();
1294 if (
GV.isConstant() &&
GV.hasInitializer() &&
1295 GV.getInitializer() == Initializer)
1298 SrcLocStr =
Builder.CreateGlobalString(
1299 LocStr,
"",
M.getDataLayout().getDefaultGlobalsAddressSpace(),
1307 unsigned Line,
unsigned Column,
1313 Buffer.
append(FunctionName);
1315 Buffer.
append(std::to_string(Line));
1317 Buffer.
append(std::to_string(Column));
1325 StringRef UnknownLoc =
";unknown;unknown;0;0;;";
1336 !DIL->getFilename().empty() ? DIL->getFilename() :
M.getName();
1341 DIL->getColumn(), SrcLocStrSize);
1347 Loc.IP.getNodeParent()->getParent());
1353 "omp_global_thread_num");
1361 "expected one result pointer type per in_reduction item");
1364 if (OrigPtrs.
empty())
1365 return Builder.saveIP();
1384 for (
unsigned Idx = 0; Idx < OrigPtrs.
size(); ++Idx) {
1387 Value *OrigPtr = OrigPtrs[Idx];
1389 OrigPtrTy && OrigPtrTy->getAddressSpace() != 0)
1390 OrigPtr = Builder.CreateAddrSpaceCast(OrigPtr, PtrTy);
1392 Value *
Priv = Builder.CreateCall(GetThData, {Gtid, NullDesc, OrigPtr},
1398 ResPtrTy && ResPtrTy->getAddressSpace() != 0)
1399 Priv = Builder.CreateAddrSpaceCast(
Priv, ResultPtrTys[Idx]);
1401 MapPrivateCB(Idx,
Priv);
1408 bool ForceSimpleCall,
bool CheckCancelFlag) {
1418 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
1421 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
1424 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
1427 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
1430 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
1443 bool UseCancelBarrier =
1448 ? OMPRTL___kmpc_cancel_barrier
1449 : OMPRTL___kmpc_barrier),
1452 if (UseCancelBarrier && CheckCancelFlag)
1462 omp::Directive CanceledDirective) {
1467 auto *UI =
Builder.CreateUnreachable();
1475 Builder.SetInsertPoint(ElseTI);
1476 auto ElseIP =
Builder.saveIP();
1484 Builder.SetInsertPoint(ThenTI);
1486 Value *CancelKind =
nullptr;
1487 switch (CanceledDirective) {
1488#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1489 case DirectiveEnum: \
1490 CancelKind = Builder.getInt32(Value); \
1492#include "llvm/Frontend/OpenMP/OMPKinds.def"
1509 Builder.SetInsertPoint(UI->getParent());
1510 UI->eraseFromParent();
1517 omp::Directive CanceledDirective) {
1522 auto *UI =
Builder.CreateUnreachable();
1525 Value *CancelKind =
nullptr;
1526 switch (CanceledDirective) {
1527#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1528 case DirectiveEnum: \
1529 CancelKind = Builder.getInt32(Value); \
1531#include "llvm/Frontend/OpenMP/OMPKinds.def"
1548 Builder.SetInsertPoint(UI->getParent());
1549 UI->eraseFromParent();
1562 auto *KernelArgsPtr =
1563 Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs,
nullptr,
"kernel_args");
1568 Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr,
I);
1571 M.getDataLayout().getPrefTypeAlign(KernelArgs[
I]->getType()));
1575 NumThreads, HostPtr, KernelArgsPtr};
1602 assert(OutlinedFnID &&
"Invalid outlined function ID!");
1606 Value *Return =
nullptr;
1626 Builder, AllocaIP, Return, RTLoc, DeviceID, Args.NumTeams.front(),
1627 Args.NumThreads.front(), OutlinedFnID, ArgsVector));
1634 Builder.CreateCondBr(
Failed, OffloadFailedBlock, OffloadContBlock);
1636 auto CurFn =
Builder.GetInsertBlock()->getParent();
1643 emitBlock(OffloadContBlock, CurFn,
true);
1648 Value *CancelFlag, omp::Directive CanceledDirective) {
1650 "Unexpected cancellation!");
1670 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
1679 Builder.SetInsertPoint(CancellationBlock);
1680 Builder.CreateBr(*FiniBBOrErr);
1695 size_t NumArgs = OutlinedFn.
arg_size();
1696 assert((NumArgs == 2 || NumArgs == 3) &&
1697 "expected a 2-3 argument parallel outlined function");
1698 bool UseArgStruct = NumArgs == 3;
1703 {Builder.getInt16Ty(), Builder.getInt32Ty()},
1707 OutlinedFn.
getName() +
".wrapper", OMPIRBuilder->
M);
1709 WrapperFn->addParamAttr(0, Attribute::NoUndef);
1710 WrapperFn->addParamAttr(0, Attribute::ZExt);
1711 WrapperFn->addParamAttr(1, Attribute::NoUndef);
1715 Builder.SetInsertPoint(EntryBB);
1718 Value *AddrAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1720 AddrAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1721 AddrAlloca, Builder.getPtrTy(0),
1722 AddrAlloca->
getName() +
".ascast");
1724 Value *ZeroAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1726 ZeroAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1727 ZeroAlloca, Builder.getPtrTy(0),
1728 ZeroAlloca->
getName() +
".ascast");
1730 Value *ArgsAlloca =
nullptr;
1732 ArgsAlloca = Builder.CreateAlloca(Builder.getPtrTy(),
1733 nullptr,
"global_args");
1734 ArgsAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1735 ArgsAlloca, Builder.getPtrTy(0),
1736 ArgsAlloca->
getName() +
".ascast");
1740 Builder.CreateStore(WrapperFn->getArg(1), AddrAlloca);
1741 Builder.CreateStore(Builder.getInt32(0), ZeroAlloca);
1745 llvm::omp::RuntimeFunction::OMPRTL___kmpc_get_shared_variables),
1753 Value *StructArg = Builder.CreateLoad(Builder.getPtrTy(), ArgsAlloca);
1754 StructArg = Builder.CreateInBoundsGEP(Builder.getPtrTy(), StructArg,
1755 {Builder.getInt64(0)});
1756 StructArg = Builder.CreateLoad(Builder.getPtrTy(), StructArg,
"structArg");
1757 Args.push_back(StructArg);
1761 Builder.CreateCall(&OutlinedFn, Args);
1762 Builder.CreateRetVoid();
1777 "Expected at least tid and bounded tid as arguments");
1778 unsigned NumCapturedVars = OutlinedFn.
arg_size() - 2;
1786 OutlinedFn.
addFnAttr(Attribute::NoUnwind);
1789 assert(CI &&
"Expected call instruction to outlined function");
1790 CI->
getParent()->setName(
"omp_parallel");
1792 Builder.SetInsertPoint(CI);
1793 Type *PtrTy = OMPIRBuilder->VoidPtr;
1796 OpenMPIRBuilder ::InsertPointTy CurrentIP = Builder.saveIP();
1800 Value *Args = ArgsAlloca;
1804 Args = Builder.CreatePointerCast(ArgsAlloca, PtrTy);
1805 Builder.restoreIP(CurrentIP);
1808 for (
unsigned Idx = 0; Idx < NumCapturedVars; Idx++) {
1810 Value *StoreAddress = Builder.CreateConstInBoundsGEP2_64(
1812 Builder.CreateStore(
V, StoreAddress);
1816 IfCondition ? Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32)
1817 : Builder.getInt32(1);
1818 Value *NumThreadsArg =
1819 NumThreads ? Builder.CreateZExtOrTrunc(NumThreads, OMPIRBuilder->Int32)
1820 : Builder.getInt32(-1);
1830 Value *Parallel60CallArgs[] = {
1835 Builder.getInt32(-1),
1839 Builder.getInt64(NumCapturedVars),
1840 Builder.getInt32(0)};
1848 << *Builder.GetInsertBlock()->getParent() <<
"\n");
1851 Builder.SetInsertPoint(PrivTID);
1853 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1860 I->eraseFromParent();
1883 if (!
F->hasMetadata(LLVMContext::MD_callback)) {
1891 F->addMetadata(LLVMContext::MD_callback,
1900 OutlinedFn.
addFnAttr(Attribute::NoUnwind);
1903 "Expected at least tid and bounded tid as arguments");
1904 unsigned NumCapturedVars = OutlinedFn.
arg_size() - 2;
1927 if (NumCapturedVars) {
1928 assert(NumCapturedVars == 1 &&
"Expected an aggregate capture argument");
1931 ->getAllocatedType()
1933 "Expected a stack-allocated capture structure");
1939 CI->
getParent()->setName(
"omp_parallel");
1940 Builder.SetInsertPoint(CI);
1943 Value *ForkCallArgs[] = {Ident, Builder.getInt32(NumCapturedVars),
1947 RealArgs.
append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1949 Value *
Cond = Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32);
1956 auto PtrTy = OMPIRBuilder->VoidPtr;
1957 if (IfCondition && NumCapturedVars == 0) {
1965 << *Builder.GetInsertBlock()->getParent() <<
"\n");
1968 Builder.SetInsertPoint(PrivTID);
1970 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1977 I->eraseFromParent();
1985 Value *NumThreads, omp::ProcBindKind ProcBind,
bool IsCancellable) {
1994 const bool NeedThreadID = NumThreads ||
Config.isTargetDevice() ||
1995 (ProcBind != OMP_PROC_BIND_default);
2002 bool ArgsInZeroAddressSpace =
Config.isTargetDevice();
2006 if (NumThreads && !
Config.isTargetDevice()) {
2009 Builder.CreateIntCast(NumThreads, Int32,
false)};
2014 if (ProcBind != OMP_PROC_BIND_default) {
2018 ConstantInt::get(Int32,
unsigned(ProcBind),
true)};
2028 BasicBlock *OuterAllocaBlock = OuterAllocIP.getNodeParent();
2040 Builder.CreateAlloca(Int32,
nullptr,
"zero.addr");
2043 if (ArgsInZeroAddressSpace &&
M.getDataLayout().getAllocaAddrSpace() != 0) {
2046 TIDAddrAlloca, PointerType ::get(
M.getContext(), 0),
"tid.addr.ascast");
2050 PointerType ::get(
M.getContext(), 0),
2051 "zero.addr.ascast");
2064 UI->setDebugLoc(
Loc.DL);
2076 if (IP == IP.getNodeParent()->end()) {
2080 IP =
I->getIterator();
2082 assert(IP.getNodeParent()->getTerminator()->getNumSuccessors() == 1 &&
2083 IP.getNodeParent()->getTerminator()->getSuccessor(0) == PRegExitBB &&
2084 "Unexpected insertion point for finalization call!");
2096 Builder.CreateAlloca(Int32,
nullptr,
"tid.addr.local");
2102 Builder.CreateLoad(Int32, ZeroAddr,
"zero.addr.use");
2120 LLVM_DEBUG(
dbgs() <<
"Before body codegen: " << *OuterFn <<
"\n");
2123 assert(BodyGenCB &&
"Expected body generation callback!");
2125 if (
Error Err = BodyGenCB(InnerAllocaIP, CodeGenIP, PRegExitBB))
2128 LLVM_DEBUG(
dbgs() <<
"After body codegen: " << *OuterFn <<
"\n");
2132 bool UsesDeviceSharedMemory =
2134 std::unique_ptr<OutlineInfo> OI =
2135 UsesDeviceSharedMemory
2136 ? std::make_unique<DeviceSharedMemOutlineInfo>(*
this)
2137 : std::make_unique<OutlineInfo>();
2139 if (
Config.isTargetDevice()) {
2141 OI->PostOutlineCB = [=, ToBeDeletedVec =
2142 std::move(ToBeDeleted)](
Function &OutlinedFn) {
2144 IfCondition, NumThreads, PrivTID, PrivTIDAddr,
2145 ThreadID, ToBeDeletedVec);
2149 OI->PostOutlineCB = [=, ToBeDeletedVec =
2150 std::move(ToBeDeleted)](
Function &OutlinedFn) {
2152 PrivTID, PrivTIDAddr, ToBeDeletedVec);
2156 OI->FixUpNonEntryAllocas =
true;
2157 OI->OuterAllocBB = OuterAllocaBlock;
2158 OI->EntryBB = PRegEntryBB;
2159 OI->ExitBB = PRegExitBB;
2160 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.
size());
2161 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.
end());
2165 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
2177 ".omp_par", ArgsInZeroAddressSpace);
2182 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
2184 Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands,
2189 return GV->getValueType() == OpenMPIRBuilder::Ident;
2194 LLVM_DEBUG(
dbgs() <<
"Before privatization: " << *OuterFn <<
"\n");
2200 if (&V == TIDAddr || &V == ZeroAddr) {
2201 OI->ExcludeArgsFromAggregate.push_back(&V);
2206 for (
Use &U : V.uses())
2208 if (ParallelRegionBlockSet.
count(UserI->getParent()))
2218 if (!V.getType()->isPointerTy()) {
2222 Builder.restoreIP(OuterAllocIP);
2224 if (UsesDeviceSharedMemory) {
2227 V.getName() +
".reloaded");
2228 for (
BasicBlock *DeallocBlock : OuterDeallocBlocks) {
2229 assert(DeallocBlock->getParent() ==
2230 OuterAllocIP.getNodeParent()->getParent() &&
2231 "Dealloc block must be in the allocation's function to reuse "
2232 "its debug location");
2234 Builder.getCurrentDebugLocation()},
2238 Ptr =
Builder.CreateAlloca(V.getType(),
nullptr,
2239 V.getName() +
".reloaded");
2248 Builder.restoreIP(InnerAllocaIP);
2249 Inner =
Builder.CreateLoad(V.getType(), Ptr);
2252 Value *ReplacementValue =
nullptr;
2255 ReplacementValue = PrivTID;
2258 PrivCB(InnerAllocaIP,
Builder.saveIP(), V, *Inner, ReplacementValue);
2263 InnerAllocaIP.getNodeParent()->getTerminator()->getIterator();
2265 assert(ReplacementValue &&
2266 "Expected copy/create callback to set replacement value!");
2267 if (ReplacementValue == &V)
2272 UPtr->set(ReplacementValue);
2295 for (
Value *Output : Outputs)
2299 "OpenMP outlining should not produce live-out values!");
2301 LLVM_DEBUG(
dbgs() <<
"After privatization: " << *OuterFn <<
"\n");
2303 for (
auto *BB : Blocks)
2304 dbgs() <<
" PBR: " << BB->getName() <<
"\n";
2312 assert(FiniInfo.DK == OMPD_parallel &&
2313 "Unexpected finalization stack state!");
2324 Builder.CreateBr(*FiniBBOrErr);
2327 Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
2334 UI->eraseFromParent();
2347 if (
Config.IsGPU.value_or(
M.getTargetTriple().isGPU())) {
2350 Builder.CreateFence(AO,
M.getContext().getOrInsertSyncScopeID(ScopeName));
2368 Builder.getInt32(
static_cast<unsigned>(Scope))};
2391 Value *Severity = ConstantInt::get(Int32, IsFatal ? 2 : 1);
2393 Value *Args[] = {Ident, Severity, MessageArg};
2422 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
2424 Builder.CreateStore(DepValPtr, Addr);
2427 DependInfo, Entry,
static_cast<unsigned int>(RTLDependInfoFields::Len));
2429 ConstantInt::get(SizeTy,
2434 DependInfo, Entry,
static_cast<unsigned int>(RTLDependInfoFields::Flags));
2436 static_cast<unsigned int>(Dep.
DepKind)),
2449 if (Dependencies.
empty())
2469 Type *DependInfo = OMPBuilder.DependInfo;
2471 Value *DepArray =
nullptr;
2477 Builder.SetInsertPoint(
2478 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator());
2479 DepArray = Builder.CreateAlloca(DepArrayTy,
nullptr,
".dep.arr.addr");
2482 for (
const auto &[DepIdx, Dep] :
enumerate(Dependencies)) {
2484 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2509 Value *DepArray =
nullptr;
2510 Type *DepArrayTy =
nullptr;
2511 Value *NumDeps =
nullptr;
2514 NumDeps = Dependencies.
NumDeps;
2515 }
else if (!Dependencies.
Deps.empty()) {
2517 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
2521 Builder.GetInsertBlock()->getParent()->getEntryBlock();
2523 DepArray =
Builder.CreateAlloca(DepArrayTy,
nullptr,
".dep.arr.addr");
2526 for (
const auto &[DepIdx, Dep] :
enumerate(Dependencies.
Deps)) {
2528 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2542 ConstantInt::get(
Builder.getInt32Ty(), 0),
2544 ConstantInt::get(
Builder.getInt32Ty(), IsNowait)};
2547 omp::RuntimeFunction::OMPRTL___kmpc_omp_taskwait_deps_51),
2557 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2569 auto *VoidPtrTy =
PointerType::get(Builder.getContext(), ProgramAddressSpace);
2572 Builder.getVoidTy(), {VoidPtrTy, VoidPtrTy, Builder.getInt32Ty()},
2576 "omp_taskloop_dup", M);
2579 Value *LastprivateFlagArg = DupFunction->
getArg(2);
2580 DestTaskArg->
setName(
"dest_task");
2581 SrcTaskArg->
setName(
"src_task");
2582 LastprivateFlagArg->
setName(
"lastprivate_flag");
2585 Builder.SetInsertPoint(
2588 auto GetTaskContextPtrFromArg = [&](
Value *Arg) ->
Value * {
2589 Type *TaskWithPrivatesTy =
2591 Value *TaskPrivates = Builder.CreateGEP(
2592 TaskWithPrivatesTy, Arg, {Builder.getInt32(0), Builder.getInt32(1)});
2593 Value *ContextPtr = Builder.CreateGEP(
2594 PrivatesTy, TaskPrivates,
2595 {Builder.getInt32(0), Builder.getInt32(PrivatesIndex)});
2599 Value *DestTaskContextPtr = GetTaskContextPtrFromArg(DestTaskArg);
2600 Value *SrcTaskContextPtr = GetTaskContextPtrFromArg(SrcTaskArg);
2602 DestTaskContextPtr->
setName(
"destPtr");
2603 SrcTaskContextPtr->
setName(
"srcPtr");
2607 Expected<IRBuilderBase::InsertPoint> AfterIPOrError =
2608 DupCB(AllocaIP, CodeGenIP, DestTaskContextPtr, SrcTaskContextPtr);
2609 if (!AfterIPOrError)
2611 Builder.restoreIP(*AfterIPOrError);
2621 llvm::function_ref<llvm::Expected<llvm::CanonicalLoopInfo *>()> LoopInfo,
2623 Value *GrainSize,
bool NoGroup,
int Sched,
Value *Final,
bool Mergeable,
2625 Value *TaskContextStructPtrVal,
bool FreeAgent) {
2630 uint32_t SrcLocStrSize;
2644 if (
Error Err = BodyGenCB(TaskloopAllocaIP, TaskloopBodyIP, TaskloopExitBB))
2647 llvm::Expected<llvm::CanonicalLoopInfo *> result = LoopInfo();
2652 llvm::CanonicalLoopInfo *CLI = result.
get();
2653 if (CLI->VirtualCollapse)
2654 CLI->reportUnsupportedVirtualCollapse();
2655 auto OI = std::make_unique<OutlineInfo>();
2656 OI->EntryBB = TaskloopAllocaBB;
2657 OI->OuterAllocBB = AllocaIP.getNodeParent();
2658 OI->ExitBB = TaskloopExitBB;
2659 OI->OuterDeallocBBs.reserve(DeallocBlocks.
size());
2660 copy(DeallocBlocks, OI->OuterDeallocBBs.end());
2663 SmallVector<Instruction *> ToBeDeleted;
2666 Builder, AllocaIP, ToBeDeleted, TaskloopAllocaIP,
"global.tid",
false));
2668 TaskloopAllocaIP,
"lb",
false,
true);
2670 TaskloopAllocaIP,
"ub",
false,
true);
2672 TaskloopAllocaIP,
"step",
false,
true);
2675 OI->Inputs.insert(FakeLB);
2676 OI->Inputs.insert(FakeUB);
2677 OI->Inputs.insert(FakeStep);
2678 if (TaskContextStructPtrVal)
2679 OI->Inputs.insert(TaskContextStructPtrVal);
2680 assert(((TaskContextStructPtrVal && DupCB) ||
2681 (!TaskContextStructPtrVal && !DupCB)) &&
2682 "Task context struct ptr and duplication callback must be both set "
2688 unsigned ProgramAddressSpace =
M.getDataLayout().getProgramAddressSpace();
2692 {FakeLB->getType(), FakeUB->getType(), FakeStep->getType(), PointerTy});
2693 Expected<Value *> TaskDupFnOrErr = createTaskDuplicationFunction(
2696 if (!TaskDupFnOrErr) {
2699 Value *TaskDupFn = *TaskDupFnOrErr;
2701 OI->PostOutlineCB = [
this, Ident, LBVal, UBVal, StepVal, Untied,
2702 TaskloopAllocaBB, CLI, TaskDupFn, ToBeDeleted, IfCond,
2703 GrainSize, NoGroup, Sched, FakeLB, FakeUB, FakeStep,
2704 FakeSharedsTy, Final, Mergeable, Priority,
2706 FreeAgent](
Function &OutlinedFn)
mutable {
2708 assert(OutlinedFn.hasOneUse() &&
2709 "there must be a single user for the outlined function");
2716 Value *CastedLBVal =
2717 Builder.CreateIntCast(LBVal,
Builder.getInt64Ty(),
true,
"lb64");
2718 Value *CastedUBVal =
2719 Builder.CreateIntCast(UBVal,
Builder.getInt64Ty(),
true,
"ub64");
2720 Value *CastedStepVal =
2721 Builder.CreateIntCast(StepVal,
Builder.getInt64Ty(),
true,
"step64");
2723 Builder.SetInsertPoint(StaleCI);
2736 Builder.CreateCall(TaskgroupFn, {Ident, ThreadID});
2761 divideCeil(
M.getDataLayout().getTypeSizeInBits(Task), 8));
2763 AllocaInst *ArgStructAlloca =
2765 assert(ArgStructAlloca &&
2766 "Unable to find the alloca instruction corresponding to arguments "
2767 "for extracted function");
2768 std::optional<TypeSize> ArgAllocSize =
2771 "Unable to determine size of arguments for extracted function");
2772 Value *SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
2777 CallInst *TaskData =
Builder.CreateCall(
2778 TaskAllocFn, {Ident, ThreadID,
Flags,
2779 TaskSize, SharedsSize,
2784 Value *TaskShareds =
Builder.CreateLoad(VoidPtr, TaskData);
2790 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(0)});
2793 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(1)});
2796 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(2)});
2802 IfCond ?
Builder.CreateIntCast(IfCond,
Builder.getInt32Ty(),
true)
2808 Value *GrainSizeVal =
2809 GrainSize ?
Builder.CreateIntCast(GrainSize,
Builder.getInt64Ty(),
true)
2811 Value *TaskDup = TaskDupFn;
2813 Value *
Args[] = {Ident, ThreadID, TaskData, IfCondVal, Lb, Ub,
2814 Loadstep, NoGroupVal, SchedVal, GrainSizeVal, TaskDup};
2819 Builder.CreateCall(TaskloopFn, Args);
2826 Builder.CreateCall(EndTaskgroupFn, {Ident, ThreadID});
2831 Builder.SetInsertPoint(TaskloopAllocaBB->begin());
2833 LoadInst *SharedsOutlined =
2834 Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
2835 OutlinedFn.getArg(1)->replaceUsesWithIf(
2837 [SharedsOutlined](Use &U) {
return U.getUser() != SharedsOutlined; });
2840 Type *IVTy =
IV->getType();
2846 Value *TaskLB =
nullptr;
2847 Value *TaskUB =
nullptr;
2848 Value *TaskStep =
nullptr;
2849 Value *LoadTaskLB =
nullptr;
2850 Value *LoadTaskUB =
nullptr;
2851 Value *LoadTaskStep =
nullptr;
2852 for (Instruction &
I : *TaskloopAllocaBB) {
2853 if (
I.getOpcode() == Instruction::GetElementPtr) {
2856 switch (CI->getZExtValue()) {
2868 }
else if (
I.getOpcode() == Instruction::Load) {
2870 if (
Load.getPointerOperand() == TaskLB) {
2871 assert(TaskLB !=
nullptr &&
"Expected value for TaskLB");
2873 }
else if (
Load.getPointerOperand() == TaskUB) {
2874 assert(TaskUB !=
nullptr &&
"Expected value for TaskUB");
2876 }
else if (
Load.getPointerOperand() == TaskStep) {
2877 assert(TaskStep !=
nullptr &&
"Expected value for TaskStep");
2883 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2885 assert(LoadTaskLB !=
nullptr &&
"Expected value for LoadTaskLB");
2886 assert(LoadTaskUB !=
nullptr &&
"Expected value for LoadTaskUB");
2887 assert(LoadTaskStep !=
nullptr &&
"Expected value for LoadTaskStep");
2889 Builder.CreateSub(LoadTaskUB, LoadTaskLB), LoadTaskStep);
2890 Value *TripCount =
Builder.CreateAdd(TripCountMinusOne, One,
"trip_cnt");
2891 Value *CastedTripCount =
Builder.CreateIntCast(TripCount, IVTy,
true);
2892 Value *CastedTaskLB =
Builder.CreateIntCast(LoadTaskLB, IVTy,
true);
2894 CLI->setTripCount(CastedTripCount);
2896 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
2898 if (NumOfCollapseLoops > 1) {
2904 Builder.CreateSub(CastedTaskLB, ConstantInt::get(IVTy, 1)));
2907 for (
auto IVUse = CLI->getIndVar()->uses().begin();
2908 IVUse != CLI->getIndVar()->uses().end(); IVUse++) {
2909 User *IVUser = IVUse->getUser();
2911 if (
Op->getOpcode() == Instruction::URem ||
2912 Op->getOpcode() == Instruction::UDiv) {
2917 for (User *User : UsersToReplace) {
2918 User->replaceUsesOfWith(CLI->getIndVar(), IVPlusTaskLB);
2935 assert(CLI->getIndVar()->getNumUses() == 3 &&
2936 "Canonical loop should have exactly three uses of the ind var");
2937 for (User *IVUser : CLI->getIndVar()->users()) {
2939 if (
Mul->getOpcode() == Instruction::Mul) {
2940 for (User *MulUser :
Mul->users()) {
2942 if (
Add->getOpcode() == Instruction::Add) {
2943 Add->setOperand(1, CastedTaskLB);
2952 FakeLB->replaceAllUsesWith(CastedLBVal);
2953 FakeUB->replaceAllUsesWith(CastedUBVal);
2954 FakeStep->replaceAllUsesWith(CastedStepVal);
2956 I->eraseFromParent();
2967 M.getContext(),
M.getDataLayout().getPointerSizeInBits());
2977 bool Mergeable,
Value *EventHandle,
Value *Priority,
bool FreeAgent) {
3008 if (
Error Err = BodyGenCB(TaskAllocaIP, TaskBodyIP, TaskExitBB))
3011 auto OI = std::make_unique<OutlineInfo>();
3012 OI->EntryBB = TaskAllocaBB;
3013 OI->OuterAllocBB = AllocaIP.getNodeParent();
3014 OI->ExitBB = TaskExitBB;
3015 OI->OuterDeallocBBs.reserve(DeallocBlocks.
size());
3016 copy(DeallocBlocks, OI->OuterDeallocBBs.
end());
3021 Builder, AllocaIP, ToBeDeleted, TaskAllocaIP,
"global.tid",
false));
3023 OI->PostOutlineCB = [
this, Ident, Tied, Final, IfCondition, Dependencies,
3024 Affinities, Mergeable, Priority, EventHandle, FreeAgent,
3026 ToBeDeleted](
Function &OutlinedFn)
mutable {
3028 assert(OutlinedFn.hasOneUse() &&
3029 "there must be a single user for the outlined function");
3034 bool HasShareds = StaleCI->
arg_size() > 1;
3035 Builder.SetInsertPoint(StaleCI);
3062 bool UseMergedIf0Path = ConstIfCondition && ConstIfCondition->isZero();
3066 Flags =
Builder.CreateOr(FinalFlag, Flags);
3069 if (Mergeable || UseMergedIf0Path)
3083 divideCeil(
M.getDataLayout().getTypeSizeInBits(Task), 8));
3092 assert(ArgStructAlloca &&
3093 "Unable to find the alloca instruction corresponding to arguments "
3094 "for extracted function");
3095 std::optional<TypeSize> ArgAllocSize =
3098 "Unable to determine size of arguments for extracted function");
3099 SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
3105 TaskAllocFn, {Ident, ThreadID, Flags,
3106 TaskSize, SharedsSize,
3109 if (Affinities.
Count && Affinities.
Info) {
3111 OMPRTL___kmpc_omp_reg_task_with_affinity);
3122 OMPRTL___kmpc_task_allow_completion_event);
3126 Builder.CreatePointerBitCastOrAddrSpaceCast(EventHandle,
3128 EventVal =
Builder.CreatePtrToInt(EventVal,
Builder.getInt64Ty());
3129 Builder.CreateStore(EventVal, EventHandleAddr);
3135 Value *TaskShareds =
Builder.CreateLoad(VoidPtr, TaskData);
3157 VoidPtr, VoidPtr,
Builder.getInt32Ty(), VoidPtr, VoidPtr);
3159 TaskStructType, TaskGEP, {
Zero, ConstantInt::get(Int32Ty, 4)});
3162 Value *CmplrData =
Builder.CreateInBoundsGEP(CmplrStructType,
3164 Builder.CreateStore(Priority, CmplrData);
3167 Value *DepArray =
nullptr;
3168 Value *NumDeps =
nullptr;
3171 NumDeps = Dependencies.
NumDeps;
3172 }
else if (!Dependencies.
Deps.empty()) {
3174 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
3194 if (IfCondition && !UseMergedIf0Path) {
3199 Builder.GetInsertPoint()->getParent()->getTerminator();
3200 Instruction *ThenTI = IfTerminator, *ElseTI =
nullptr;
3201 Builder.SetInsertPoint(IfTerminator);
3204 Builder.SetInsertPoint(ElseTI);
3211 {Ident, ThreadID, NumDeps, DepArray,
3212 ConstantInt::get(
Builder.getInt32Ty(), 0),
3227 Builder.SetInsertPoint(ThenTI);
3235 {Ident, ThreadID, TaskData, NumDeps, DepArray,
3236 ConstantInt::get(
Builder.getInt32Ty(), 0),
3249 LoadInst *Shareds =
Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
3250 OutlinedFn.getArg(1)->replaceUsesWithIf(
3251 Shareds, [Shareds](
Use &U) {
return U.getUser() != Shareds; });
3257 Builder.ClearInsertionPoint();
3259 I->eraseFromParent();
3285 if (
Error Err = BodyGenCB(AllocaIP,
Builder.saveIP(), DeallocBlocks))
3288 Builder.SetInsertPoint(TaskgroupExitBB);
3331 unsigned CaseNumber = 0;
3332 for (
auto SectionCB : SectionCBs) {
3334 M.getContext(),
"omp_section_loop.body.case", CurFn,
Continue);
3336 Builder.SetInsertPoint(CaseBB);
3349 Value *LB = ConstantInt::get(I32Ty, 0);
3350 Value *UB = ConstantInt::get(I32Ty, SectionCBs.
size());
3351 Value *ST = ConstantInt::get(I32Ty, 1);
3353 Loc, LoopBodyGenCB, LB, UB, ST,
true,
false, AllocaIP,
"section_loop");
3358 applyStaticWorkshareLoop(
Loc.DL, *
LoopInfo, AllocaIP,
3359 WorksharingLoopType::ForStaticLoop, !IsNowait);
3365 assert(LoopFini &&
"Bad structure of static workshare loop finalization");
3369 assert(FiniInfo.DK == OMPD_sections &&
3370 "Unexpected finalization stack state!");
3371 if (
Error Err = FiniInfo.mergeFiniBB(
Builder, LoopFini))
3385 if (IP != IP.getNodeParent()->end())
3396 auto *CaseBB =
Loc.IP.getNodeParent();
3397 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
3398 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
3400 IP =
I->getIterator();
3404 Directive OMPD = Directive::OMPD_sections;
3407 return EmitOMPInlinedRegion(OMPD,
nullptr,
nullptr, BodyGenCB, FiniCBWrapper,
3418Value *OpenMPIRBuilder::getGPUThreadID() {
3421 OMPRTL___kmpc_get_hardware_thread_id_in_block),
3425Value *OpenMPIRBuilder::getGPUWarpSize() {
3430Value *OpenMPIRBuilder::getNVPTXWarpID() {
3431 unsigned LaneIDBits =
Log2_32(
Config.getGridValue().GV_Warp_Size);
3432 return Builder.CreateAShr(getGPUThreadID(), LaneIDBits,
"nvptx_warp_id");
3435Value *OpenMPIRBuilder::getNVPTXLaneID() {
3436 unsigned LaneIDBits =
Log2_32(
Config.getGridValue().GV_Warp_Size);
3437 assert(LaneIDBits < 32 &&
"Invalid LaneIDBits size in NVPTX device.");
3438 unsigned LaneIDMask = ~0
u >> (32u - LaneIDBits);
3439 return Builder.CreateAnd(getGPUThreadID(),
Builder.getInt32(LaneIDMask),
3446 uint64_t FromSize =
M.getDataLayout().getTypeStoreSize(FromType);
3447 uint64_t ToSize =
M.getDataLayout().getTypeStoreSize(ToType);
3448 assert(FromSize > 0 &&
"From size must be greater than zero");
3449 assert(ToSize > 0 &&
"To size must be greater than zero");
3450 if (FromType == ToType)
3452 if (FromSize == ToSize)
3453 return Builder.CreateBitCast(From, ToType);
3455 return Builder.CreateIntCast(From, ToType,
true);
3461 Value *ValCastItem =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3462 CastItem,
Builder.getPtrTy(0));
3463 Builder.CreateStore(From, ValCastItem);
3464 return Builder.CreateLoad(ToType, CastItem);
3471 uint64_t Size =
M.getDataLayout().getTypeStoreSize(ElementType);
3472 assert(
Size <= 8 &&
"Unsupported bitwidth in shuffle instruction");
3476 Value *ElemCast = castValueToType(AllocaIP, Element, CastTy);
3478 Builder.CreateIntCast(getGPUWarpSize(),
Builder.getInt16Ty(),
true);
3480 Size <= 4 ? RuntimeFunction::OMPRTL___kmpc_shuffle_int32
3481 : RuntimeFunction::OMPRTL___kmpc_shuffle_int64);
3482 Value *WarpSizeCast =
3484 Value *ShuffleCall =
3489 return castValueToType(AllocaIP, ShuffleCall, ElementType);
3496 uint64_t Size =
M.getDataLayout().getTypeStoreSize(ElemType);
3508 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3509 Value *ElemPtr = DstAddr;
3510 Value *Ptr = SrcAddr;
3511 for (
unsigned IntSize = 8; IntSize >= 1; IntSize /= 2) {
3515 Ptr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3518 Builder.CreateGEP(ElemType, SrcAddr, {ConstantInt::get(IndexTy, 1)});
3519 ElemPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3523 if ((
Size / IntSize) > 1) {
3524 Value *PtrEnd =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3525 SrcAddrGEP,
Builder.getPtrTy());
3542 Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr,
Builder.getPtrTy()));
3544 Builder.CreateICmpSGT(PtrDiff,
Builder.getInt64(IntSize - 1)), ThenBB,
3547 Value *Res = createRuntimeShuffleFunction(
3550 IntType, Ptr,
M.getDataLayout().getPrefTypeAlign(ElemType)),
3552 Builder.CreateAlignedStore(Res, ElemPtr,
3553 M.getDataLayout().getPrefTypeAlign(ElemType));
3555 Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3556 Value *LocalElemPtr =
3557 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3565 Value *Res = createRuntimeShuffleFunction(
3566 AllocaIP,
Builder.CreateLoad(IntType, Ptr), IntType,
Offset);
3567 Builder.CreateStore(Res, ElemPtr);
3568 Ptr =
Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3570 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3576Error OpenMPIRBuilder::emitReductionListCopy(
3581 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3582 Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
3586 for (
auto En :
enumerate(ReductionInfos)) {
3588 Value *SrcElementAddr =
nullptr;
3589 AllocaInst *DestAlloca =
nullptr;
3590 Value *DestElementAddr =
nullptr;
3591 Value *DestElementPtrAddr =
nullptr;
3593 bool ShuffleInElement =
false;
3596 bool UpdateDestListPtr =
false;
3600 ReductionArrayTy, SrcBase,
3601 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3602 SrcElementAddr =
Builder.CreateLoad(
Builder.getPtrTy(), SrcElementPtrAddr);
3606 DestElementPtrAddr =
Builder.CreateInBoundsGEP(
3607 ReductionArrayTy, DestBase,
3608 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3609 bool IsByRefElem = (!IsByRef.
empty() && IsByRef[En.index()]);
3615 Type *DestAllocaType =
3616 IsByRefElem ? RI.ByRefAllocatedType : RI.ElementType;
3617 DestAlloca =
Builder.CreateAlloca(DestAllocaType,
nullptr,
3618 ".omp.reduction.element");
3620 M.getDataLayout().getPrefTypeAlign(DestAllocaType));
3621 DestElementAddr = DestAlloca;
3624 DestElementAddr->
getName() +
".ascast");
3626 ShuffleInElement =
true;
3627 UpdateDestListPtr =
true;
3639 if (ShuffleInElement) {
3640 Type *ShuffleType = RI.ElementType;
3641 Value *ShuffleSrcAddr = SrcElementAddr;
3642 Value *ShuffleDestAddr = DestElementAddr;
3643 AllocaInst *LocalStorage =
nullptr;
3646 assert(RI.ByRefElementType &&
"Expected by-ref element type to be set");
3647 assert(RI.ByRefAllocatedType &&
3648 "Expected by-ref allocated type to be set");
3653 ShuffleType = RI.ByRefElementType;
3655 if (RI.DataPtrPtrGen) {
3658 Builder.saveIP(), ShuffleSrcAddr, ShuffleSrcAddr);
3661 return GenResult.takeError();
3670 LocalStorage =
Builder.CreateAlloca(ShuffleType);
3672 ShuffleDestAddr = LocalStorage;
3677 ShuffleDestAddr = DestElementAddr;
3681 shuffleAndStore(AllocaIP, ShuffleSrcAddr, ShuffleDestAddr, ShuffleType,
3682 RemoteLaneOffset, ReductionArrayTy, IsByRefElem);
3684 if (IsByRefElem && RI.DataPtrPtrGen) {
3686 Value *DestDescriptorAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3687 DestAlloca,
Builder.getPtrTy(),
".ascast");
3690 DestDescriptorAddr, LocalStorage, SrcElementAddr,
3691 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
3694 return GenResult.takeError();
3697 switch (RI.EvaluationKind) {
3699 Value *Elem =
Builder.CreateLoad(RI.ElementType, SrcElementAddr);
3701 Builder.CreateStore(Elem, DestElementAddr);
3705 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
3706 RI.ElementType, SrcElementAddr, 0, 0,
".realp");
3708 RI.ElementType->getStructElementType(0), SrcRealPtr,
".real");
3710 RI.ElementType, SrcElementAddr, 0, 1,
".imagp");
3712 RI.ElementType->getStructElementType(1), SrcImgPtr,
".imag");
3714 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
3715 RI.ElementType, DestElementAddr, 0, 0,
".realp");
3716 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
3717 RI.ElementType, DestElementAddr, 0, 1,
".imagp");
3718 Builder.CreateStore(SrcReal, DestRealPtr);
3719 Builder.CreateStore(SrcImg, DestImgPtr);
3724 M.getDataLayout().getTypeStoreSize(RI.ElementType));
3726 DestElementAddr,
M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3727 SrcElementAddr,
M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3739 if (UpdateDestListPtr) {
3740 Value *CastDestAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3741 DestElementAddr,
Builder.getPtrTy(),
3742 DestElementAddr->
getName() +
".ascast");
3743 Builder.CreateStore(CastDestAddr, DestElementPtrAddr);
3750Expected<Function *> OpenMPIRBuilder::emitInterWarpCopyFunction(
3753 IRBuilder<>::InsertPointGuard IPG(
Builder);
3754 LLVMContext &Ctx =
M.getContext();
3756 Builder.getVoidTy(), {Builder.getPtrTy(), Builder.getInt32Ty()},
3760 "_omp_reduction_inter_warp_copy_func", &
M);
3766 Builder.SetInsertPoint(EntryBB);
3784 StringRef TransferMediumName =
3785 "__openmp_nvptx_data_transfer_temporary_storage";
3786 GlobalVariable *TransferMedium =
M.getGlobalVariable(TransferMediumName);
3787 unsigned WarpSize =
Config.getGridValue().GV_Warp_Size;
3789 if (!TransferMedium) {
3790 TransferMedium =
new GlobalVariable(
3798 Value *GPUThreadID = getGPUThreadID();
3800 Value *LaneID = getNVPTXLaneID();
3802 Value *WarpID = getNVPTXWarpID();
3808 AllocaInst *ReduceListAlloca =
Builder.CreateAlloca(
3809 Arg0Type,
nullptr, ReduceListArg->
getName() +
".addr");
3810 AllocaInst *NumWarpsAlloca =
3811 Builder.CreateAlloca(Arg1Type,
nullptr, NumWarpsArg->
getName() +
".addr");
3812 Value *ReduceListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3813 ReduceListAlloca, Arg0Type, ReduceListAlloca->
getName() +
".ascast");
3814 Value *NumWarpsAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3815 NumWarpsAlloca,
Builder.getPtrTy(0),
3816 NumWarpsAlloca->
getName() +
".ascast");
3817 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
3818 Builder.CreateStore(NumWarpsArg, NumWarpsAddrCast);
3827 for (
auto En :
enumerate(ReductionInfos)) {
3833 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
3834 unsigned RealTySize =
M.getDataLayout().getTypeAllocSize(
3835 IsByRefElem ? RI.ByRefElementType : RI.ElementType);
3836 for (
unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /= 2) {
3839 unsigned NumIters = RealTySize / TySize;
3842 Value *Cnt =
nullptr;
3843 Value *CntAddr =
nullptr;
3850 Builder.CreateAlloca(
Builder.getInt32Ty(),
nullptr,
".cnt.addr");
3852 CntAddr =
Builder.CreateAddrSpaceCast(CntAddr,
Builder.getPtrTy(),
3853 CntAddr->
getName() +
".ascast");
3865 Cnt, ConstantInt::get(
Builder.getInt32Ty(), NumIters));
3866 Builder.CreateCondBr(Cmp, BodyBB, ExitBB);
3873 omp::Directive::OMPD_unknown,
3877 return BarrierIP1.takeError();
3883 Value *IsWarpMaster =
Builder.CreateIsNull(LaneID,
"warp_master");
3884 Builder.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3888 auto *RedListArrayTy =
3891 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3893 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3894 {ConstantInt::get(IndexTy, 0),
3895 ConstantInt::get(IndexTy, En.index())});
3899 if (IsByRefElem && RI.DataPtrPtrGen) {
3901 RI.DataPtrPtrGen(
Builder.saveIP(), ElemPtr, ElemPtr);
3904 return GenRes.takeError();
3915 ArrayTy, TransferMedium, {
Builder.getInt64(0), WarpID});
3920 Builder.CreateStore(Elem, MediumPtr,
3932 omp::Directive::OMPD_unknown,
3936 return BarrierIP2.takeError();
3943 Value *NumWarpsVal =
3946 Value *IsActiveThread =
3947 Builder.CreateICmpULT(GPUThreadID, NumWarpsVal,
"is_active_thread");
3948 Builder.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3955 ArrayTy, TransferMedium, {
Builder.getInt64(0), GPUThreadID});
3957 Value *TargetElemPtrPtr =
3958 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3959 {ConstantInt::get(IndexTy, 0),
3960 ConstantInt::get(IndexTy, En.index())});
3961 Value *TargetElemPtrVal =
3963 Value *TargetElemPtr = TargetElemPtrVal;
3965 if (IsByRefElem && RI.DataPtrPtrGen) {
3967 RI.DataPtrPtrGen(
Builder.saveIP(), TargetElemPtr, TargetElemPtr);
3970 return GenRes.takeError();
3972 TargetElemPtr =
Builder.CreateLoad(
Builder.getPtrTy(), TargetElemPtr);
3980 Value *SrcMediumValue =
3981 Builder.CreateLoad(CType, SrcMediumPtrVal,
true);
3982 Builder.CreateStore(SrcMediumValue, TargetElemPtr);
3992 Cnt, ConstantInt::get(
Builder.getInt32Ty(), 1));
3993 Builder.CreateStore(Cnt, CntAddr,
false);
3995 auto *CurFn =
Builder.GetInsertBlock()->getParent();
3999 RealTySize %= TySize;
4008Expected<Function *> OpenMPIRBuilder::emitShuffleAndReduceFunction(
4011 LLVMContext &Ctx =
M.getContext();
4012 IRBuilder<>::InsertPointGuard IPG(
Builder);
4013 FunctionType *FuncTy =
4015 {Builder.getPtrTy(), Builder.getInt16Ty(),
4016 Builder.getInt16Ty(), Builder.getInt16Ty()},
4020 "_omp_reduction_shuffle_and_reduce_func", &
M);
4031 Builder.SetInsertPoint(EntryBB);
4043 Type *ReduceListArgType = ReduceListArg->
getType();
4047 ReduceListArgType,
nullptr, ReduceListArg->
getName() +
".addr");
4048 Value *LaneIdAlloca =
Builder.CreateAlloca(LaneIDArgType,
nullptr,
4049 LaneIDArg->
getName() +
".addr");
4051 LaneIDArgType,
nullptr, RemoteLaneOffsetArg->
getName() +
".addr");
4052 Value *AlgoVerAlloca =
Builder.CreateAlloca(LaneIDArgType,
nullptr,
4053 AlgoVerArg->
getName() +
".addr");
4060 RedListArrayTy,
nullptr,
".omp.reduction.remote_reduce_list");
4062 Value *ReduceListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4063 ReduceListAlloca, ReduceListArgType,
4064 ReduceListAlloca->
getName() +
".ascast");
4065 Value *LaneIdAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4066 LaneIdAlloca, LaneIDArgPtrType, LaneIdAlloca->
getName() +
".ascast");
4067 Value *RemoteLaneOffsetAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4068 RemoteLaneOffsetAlloca, LaneIDArgPtrType,
4069 RemoteLaneOffsetAlloca->
getName() +
".ascast");
4070 Value *AlgoVerAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4071 AlgoVerAlloca, LaneIDArgPtrType, AlgoVerAlloca->
getName() +
".ascast");
4072 Value *RemoteListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4073 RemoteReductionListAlloca,
Builder.getPtrTy(),
4074 RemoteReductionListAlloca->
getName() +
".ascast");
4076 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
4077 Builder.CreateStore(LaneIDArg, LaneIdAddrCast);
4078 Builder.CreateStore(RemoteLaneOffsetArg, RemoteLaneOffsetAddrCast);
4079 Builder.CreateStore(AlgoVerArg, AlgoVerAddrCast);
4081 Value *ReduceList =
Builder.CreateLoad(ReduceListArgType, ReduceListAddrCast);
4082 Value *LaneId =
Builder.CreateLoad(LaneIDArgType, LaneIdAddrCast);
4083 Value *RemoteLaneOffset =
4084 Builder.CreateLoad(LaneIDArgType, RemoteLaneOffsetAddrCast);
4085 Value *AlgoVer =
Builder.CreateLoad(LaneIDArgType, AlgoVerAddrCast);
4092 Error EmitRedLsCpRes = emitReductionListCopy(
4094 ReduceList, RemoteListAddrCast, IsByRef,
4095 {RemoteLaneOffset,
nullptr,
nullptr});
4098 return EmitRedLsCpRes;
4123 Value *LaneComp =
Builder.CreateICmpULT(LaneId, RemoteLaneOffset);
4128 Value *Algo2AndLaneIdComp =
Builder.CreateAnd(Algo2, LaneIdComp);
4129 Value *RemoteOffsetComp =
4131 Value *CondAlgo2 =
Builder.CreateAnd(Algo2AndLaneIdComp, RemoteOffsetComp);
4132 Value *CA0OrCA1 =
Builder.CreateOr(CondAlgo0, CondAlgo1);
4133 Value *CondReduce =
Builder.CreateOr(CA0OrCA1, CondAlgo2);
4139 Builder.CreateCondBr(CondReduce, ThenBB, ElseBB);
4141 Value *LocalReduceListPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4142 ReduceList,
Builder.getPtrTy());
4143 Value *RemoteReduceListPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4144 RemoteListAddrCast,
Builder.getPtrTy());
4146 ->addFnAttr(Attribute::NoUnwind);
4157 Value *LaneIdGtOffset =
Builder.CreateICmpUGE(LaneId, RemoteLaneOffset);
4158 Value *CondCopy =
Builder.CreateAnd(Algo1, LaneIdGtOffset);
4163 Builder.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
4167 EmitRedLsCpRes = emitReductionListCopy(
4169 RemoteListAddrCast, ReduceList, IsByRef);
4172 return EmitRedLsCpRes;
4187OpenMPIRBuilder::generateReductionDescriptor(
4189 Type *DescriptorType,
4195 Value *DescriptorSize =
4196 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(DescriptorType));
4198 DescriptorAddr,
M.getDataLayout().getPrefTypeAlign(DescriptorType),
4199 SrcDescriptorAddr,
M.getDataLayout().getPrefTypeAlign(DescriptorType),
4203 Value *DataPtrField;
4205 DataPtrPtrGen(
Builder.saveIP(), DescriptorAddr, DataPtrField);
4208 return GenResult.takeError();
4211 DataPtr,
Builder.getPtrTy(),
".ascast"),
4217Expected<Value *> OpenMPIRBuilder::createReductionDescriptorCopy(
4219 Value *SrcDescriptorAddr,
Type *DescriptorPtrTy,
const Twine &Name) {
4223 AllocaInst *DescriptorAlloca =
4224 Builder.CreateAlloca(RI.ByRefAllocatedType,
nullptr, Name);
4226 M.getDataLayout().getPrefTypeAlign(RI.ByRefAllocatedType));
4227 Value *DescriptorAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4228 DescriptorAlloca, DescriptorPtrTy,
4229 DescriptorAlloca->
getName() +
".ascast");
4234 generateReductionDescriptor(DescriptorAddr, DataPtr, SrcDescriptorAddr,
4235 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
4237 return GenResult.takeError();
4239 return DescriptorAddr;
4242Expected<Function *> OpenMPIRBuilder::emitListToGlobalCopyFunction(
4245 IRBuilder<>::InsertPointGuard IPG(
Builder);
4246 LLVMContext &Ctx =
M.getContext();
4249 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4253 "_omp_reduction_list_to_global_copy_func", &
M);
4260 Builder.SetInsertPoint(EntryBlock);
4271 BufferArg->
getName() +
".addr");
4275 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4276 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4277 BufferArgAlloca,
Builder.getPtrTy(),
4278 BufferArgAlloca->
getName() +
".ascast");
4279 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4280 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4281 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4282 ReduceListArgAlloca,
Builder.getPtrTy(),
4283 ReduceListArgAlloca->
getName() +
".ascast");
4285 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4286 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4287 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4289 Value *LocalReduceList =
4291 Value *BufferArgVal =
4295 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4296 for (
auto En :
enumerate(ReductionInfos)) {
4298 auto *RedListArrayTy =
4302 RedListArrayTy, LocalReduceList,
4303 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4309 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferArgVal, Idxs);
4311 ReductionsBufferTy, BufferVD, 0, En.index());
4313 switch (RI.EvaluationKind) {
4315 Value *TargetElement;
4317 if (IsByRef.
empty() || !IsByRef[En.index()]) {
4318 TargetElement =
Builder.CreateLoad(RI.ElementType, ElemPtr);
4320 if (RI.DataPtrPtrGen) {
4322 RI.DataPtrPtrGen(
Builder.saveIP(), ElemPtr, ElemPtr);
4325 return GenResult.takeError();
4329 TargetElement =
Builder.CreateLoad(RI.ByRefElementType, ElemPtr);
4332 Builder.CreateStore(TargetElement, GlobVal);
4336 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4337 RI.ElementType, ElemPtr, 0, 0,
".realp");
4339 RI.ElementType->getStructElementType(0), SrcRealPtr,
".real");
4341 RI.ElementType, ElemPtr, 0, 1,
".imagp");
4343 RI.ElementType->getStructElementType(1), SrcImgPtr,
".imag");
4345 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4346 RI.ElementType, GlobVal, 0, 0,
".realp");
4347 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
4348 RI.ElementType, GlobVal, 0, 1,
".imagp");
4349 Builder.CreateStore(SrcReal, DestRealPtr);
4350 Builder.CreateStore(SrcImg, DestImgPtr);
4355 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(RI.ElementType));
4357 GlobVal,
M.getDataLayout().getPrefTypeAlign(RI.ElementType), ElemPtr,
4358 M.getDataLayout().getPrefTypeAlign(RI.ElementType), SizeVal,
false);
4368Expected<Function *> OpenMPIRBuilder::emitListToGlobalReduceFunction(
4371 IRBuilder<>::InsertPointGuard IPG(
Builder);
4372 LLVMContext &Ctx =
M.getContext();
4375 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4379 "_omp_reduction_list_to_global_reduce_func", &
M);
4386 Builder.SetInsertPoint(EntryBlock);
4397 BufferArg->
getName() +
".addr");
4401 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4402 auto *RedListArrayTy =
4407 Value *LocalReduceList =
4408 Builder.CreateAlloca(RedListArrayTy,
nullptr,
".omp.reduction.red_list");
4412 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4413 BufferArgAlloca,
Builder.getPtrTy(),
4414 BufferArgAlloca->
getName() +
".ascast");
4415 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4416 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4417 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4418 ReduceListArgAlloca,
Builder.getPtrTy(),
4419 ReduceListArgAlloca->
getName() +
".ascast");
4420 Value *LocalReduceListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4421 LocalReduceList,
Builder.getPtrTy(),
4422 LocalReduceList->
getName() +
".ascast");
4424 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4425 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4426 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4431 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4432 for (
auto En :
enumerate(ReductionInfos)) {
4435 Value *TargetElementPtrPtr =
Builder.CreateInBoundsGEP(
4436 RedListArrayTy, LocalReduceListAddrCast,
4437 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4439 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4441 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4442 ReductionsBufferTy, BufferVD, 0, En.index());
4444 if (!IsByRef.
empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4448 Value *SrcElementPtrPtr =
4449 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
4450 {ConstantInt::get(IndexTy, 0),
4451 ConstantInt::get(IndexTy, En.index())});
4452 Value *SrcDescriptorAddr =
4456 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4457 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr,
Builder.getPtrTy());
4461 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4463 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4471 ->addFnAttr(Attribute::NoUnwind);
4476Expected<Function *> OpenMPIRBuilder::emitGlobalToListCopyFunction(
4479 IRBuilder<>::InsertPointGuard IPG(
Builder);
4480 LLVMContext &Ctx =
M.getContext();
4483 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4487 "_omp_reduction_global_to_list_copy_func", &
M);
4494 Builder.SetInsertPoint(EntryBlock);
4505 BufferArg->
getName() +
".addr");
4509 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4510 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4511 BufferArgAlloca,
Builder.getPtrTy(),
4512 BufferArgAlloca->
getName() +
".ascast");
4513 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4514 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4515 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4516 ReduceListArgAlloca,
Builder.getPtrTy(),
4517 ReduceListArgAlloca->
getName() +
".ascast");
4518 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4519 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4520 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4522 Value *LocalReduceList =
4527 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4528 for (
auto En :
enumerate(ReductionInfos)) {
4529 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
4530 auto *RedListArrayTy =
4534 RedListArrayTy, LocalReduceList,
4535 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4540 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4541 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4542 ReductionsBufferTy, BufferVD, 0, En.index());
4548 if (!IsByRef.
empty() && IsByRef[En.index()]) {
4555 return GenResult.takeError();
4561 Value *TargetElement =
Builder.CreateLoad(ElemType, GlobValPtr);
4562 Builder.CreateStore(TargetElement, ElemPtr);
4566 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4575 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4577 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
4579 Builder.CreateStore(SrcReal, DestRealPtr);
4580 Builder.CreateStore(SrcImg, DestImgPtr);
4587 ElemPtr,
M.getDataLayout().getPrefTypeAlign(RI.
ElementType),
4588 GlobValPtr,
M.getDataLayout().getPrefTypeAlign(RI.
ElementType),
4599Expected<Function *> OpenMPIRBuilder::emitGlobalToListReduceFunction(
4602 IRBuilder<>::InsertPointGuard IPG(
Builder);
4603 LLVMContext &Ctx =
M.getContext();
4606 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4610 "_omp_reduction_global_to_list_reduce_func", &
M);
4617 Builder.SetInsertPoint(EntryBlock);
4628 BufferArg->
getName() +
".addr");
4632 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4638 Value *LocalReduceList =
4639 Builder.CreateAlloca(RedListArrayTy,
nullptr,
".omp.reduction.red_list");
4643 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4644 BufferArgAlloca,
Builder.getPtrTy(),
4645 BufferArgAlloca->
getName() +
".ascast");
4646 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4647 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4648 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4649 ReduceListArgAlloca,
Builder.getPtrTy(),
4650 ReduceListArgAlloca->
getName() +
".ascast");
4651 Value *ReductionList =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4652 LocalReduceList,
Builder.getPtrTy(),
4653 LocalReduceList->
getName() +
".ascast");
4655 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4656 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4657 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4662 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4663 for (
auto En :
enumerate(ReductionInfos)) {
4666 Value *TargetElementPtrPtr =
Builder.CreateInBoundsGEP(
4667 RedListArrayTy, ReductionList,
4668 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4671 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4672 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4673 ReductionsBufferTy, BufferVD, 0, En.index());
4675 if (!IsByRef.
empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4677 Value *ReduceListVal =
4679 Value *SrcElementPtrPtr =
4680 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceListVal,
4681 {ConstantInt::get(IndexTy, 0),
4682 ConstantInt::get(IndexTy, En.index())});
4683 Value *SrcDescriptorAddr =
4687 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4688 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr,
Builder.getPtrTy());
4692 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4694 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4702 ->addFnAttr(Attribute::NoUnwind);
4707std::string OpenMPIRBuilder::getReductionFuncName(StringRef Name)
const {
4708 std::string Suffix =
4710 return (Name + Suffix).str();
4713Expected<Function *> OpenMPIRBuilder::createReductionFunction(
4716 AttributeList FuncAttrs) {
4717 IRBuilder<>::InsertPointGuard IPG(
Builder);
4719 {Builder.getPtrTy(), Builder.getPtrTy()},
4721 std::string
Name = getReductionFuncName(ReducerName);
4730 Builder.SetInsertPoint(EntryBB);
4735 Value *LHSArrayPtr =
nullptr;
4736 Value *RHSArrayPtr =
nullptr;
4743 Builder.CreateAlloca(Arg0Type,
nullptr, Arg0->
getName() +
".addr");
4745 Builder.CreateAlloca(Arg1Type,
nullptr, Arg1->
getName() +
".addr");
4746 Value *LHSAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4747 LHSAlloca, Arg0Type, LHSAlloca->
getName() +
".ascast");
4748 Value *RHSAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4749 RHSAlloca, Arg1Type, RHSAlloca->
getName() +
".ascast");
4750 Builder.CreateStore(Arg0, LHSAddrCast);
4751 Builder.CreateStore(Arg1, RHSAddrCast);
4752 LHSArrayPtr =
Builder.CreateLoad(Arg0Type, LHSAddrCast);
4753 RHSArrayPtr =
Builder.CreateLoad(Arg1Type, RHSAddrCast);
4757 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4759 for (
auto En :
enumerate(ReductionInfos)) {
4762 RedArrayTy, RHSArrayPtr,
4763 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4765 Value *RHSPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4766 RHSI8Ptr, RI.PrivateVariable->getType(),
4767 RHSI8Ptr->
getName() +
".ascast");
4770 RedArrayTy, LHSArrayPtr,
4771 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4773 Value *LHSPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4774 LHSI8Ptr, RI.Variable->getType(), LHSI8Ptr->
getName() +
".ascast");
4783 if (!IsByRef.
empty() && !IsByRef[En.index()]) {
4784 LHS =
Builder.CreateLoad(RI.ElementType, LHSPtr);
4785 RHS =
Builder.CreateLoad(RI.ElementType, RHSPtr);
4792 return AfterIP.takeError();
4793 if (!
Builder.GetInsertBlock())
4794 return ReductionFunc;
4798 if (!IsByRef.
empty() && !IsByRef[En.index()])
4799 Builder.CreateStore(Reduced, LHSPtr);
4804 for (
auto En :
enumerate(ReductionInfos)) {
4805 unsigned Index = En.index();
4807 Value *LHSFixupPtr, *RHSFixupPtr;
4808 Builder.restoreIP(RI.ReductionGenClang(
4809 Builder.saveIP(), Index, &LHSFixupPtr, &RHSFixupPtr, ReductionFunc));
4814 LHSPtrs[Index], [ReductionFunc](
const Use &U) {
4819 RHSPtrs[Index], [ReductionFunc](
const Use &U) {
4833 return ReductionFunc;
4841 assert(RI.Variable &&
"expected non-null variable");
4842 assert(RI.PrivateVariable &&
"expected non-null private variable");
4843 assert((RI.ReductionGen || RI.ReductionGenClang) &&
4844 "expected non-null reduction generator callback");
4847 RI.Variable->getType() == RI.PrivateVariable->getType() &&
4848 "expected variables and their private equivalents to have the same "
4851 assert(RI.Variable->getType()->isPointerTy() &&
4852 "expected variables to be pointers");
4869 ArrayRef<bool> IsByRef,
bool IsNoWait,
bool IsTeamsReduction,
bool IsSPMD,
4871 Value *SrcLocInfo) {
4886 if (ReductionInfos.
size() == 0)
4900 AttrBuilder AttrBldr(Ctx);
4902 AttrBldr.addAttribute(Attr);
4903 AttrBldr.removeAttribute(Attribute::OptimizeNone);
4904 FuncAttrs = FuncAttrs.addFnAttributes(Ctx, AttrBldr);
4907 Builder.GetInsertBlock()->getParent()->getName(), ReductionInfos, IsByRef,
4909 if (!ReductionResult)
4911 Function *ReductionFunc = *ReductionResult;
4914 if (GridValue.has_value())
4915 Config.setGridValue(GridValue.value());
4930 Builder.getPtrTy(
M.getDataLayout().getProgramAddressSpace());
4932 Value *ReductionList;
4936 Value *ReductionListAlloca =
4937 Builder.CreateAlloca(RedArrayTy,
nullptr,
".omp.reduction.red_list");
4938 ReductionList =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4939 ReductionListAlloca, PtrTy, ReductionListAlloca->
getName() +
".ascast");
4942 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4943 for (
auto En :
enumerate(ReductionInfos)) {
4946 RedArrayTy, ReductionList,
4947 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4950 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
4955 Builder.CreatePointerBitCastOrAddrSpaceCast(PrivateVar, PtrTy);
4956 Builder.CreateStore(CastElem, ElemPtr);
4959 ReductionInfos, ReductionFunc, FuncAttrs, IsByRef);
4965 emitInterWarpCopyFunction(
Loc, ReductionInfos, FuncAttrs, IsByRef);
4970 Value *RL =
Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList, PtrTy);
4979 unsigned MaxDataSize = 0;
4981 for (
auto En :
enumerate(ReductionInfos)) {
4985 Type *RedTypeArg = (!IsByRef.
empty() && IsByRef[En.index()])
4986 ? En.value().ByRefElementType
4987 : En.value().ElementType;
4988 auto Size =
M.getDataLayout().getTypeStoreSize(RedTypeArg);
4989 if (
Size > MaxDataSize)
4993 Value *ReductionDataSize =
4994 Builder.getInt64(MaxDataSize * ReductionInfos.
size());
4998 Function *CopyScratchToListFunc =
nullptr;
5000 Value *ScratchForCopyBack =
nullptr;
5003 Value *RLForCopyBack = RL;
5005 bool IsAtomicReduction =
5008 if (!IsTeamsReduction) {
5009 Value *SarFuncCast =
5010 Builder.CreatePointerBitCastOrAddrSpaceCast(*SarFunc, FuncPtrTy);
5012 Builder.CreatePointerBitCastOrAddrSpaceCast(WcFunc, FuncPtrTy);
5013 Value *Args[] = {SrcLocInfo, ReductionDataSize, RL, SarFuncCast,
5016 RuntimeFunction::OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2);
5018 }
else if (IsAtomicReduction) {
5022 RuntimeFunction::OMPRTL___kmpc_is_team_main_thread);
5026 Ctx, ReductionTypeArgs,
"struct._globalized_locals_ty");
5029 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5034 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5039 ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs, IsByRef);
5060 Value *RuntimeRL = RL;
5063 Value *PerThreadScratch;
5069 Value *PerThreadScratchAlloca =
5070 Builder.CreateAlloca(ReductionsBufferTy,
nullptr,
5071 ".omp.reduction.scratch");
5072 PerThreadScratch =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5073 PerThreadScratchAlloca, PtrTy,
5074 PerThreadScratchAlloca->
getName() +
".ascast");
5077 Value *PerThreadRedListAlloca =
5078 Builder.CreateAlloca(RedArrayTy,
nullptr,
5079 ".omp.reduction.per_thread_red_list");
5080 RuntimeRL =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5081 PerThreadRedListAlloca, PtrTy,
5082 PerThreadRedListAlloca->
getName() +
".ascast");
5087 for (
auto En :
enumerate(ReductionInfos)) {
5089 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
5092 ReductionsBufferTy, PerThreadScratch, 0, En.index());
5093 Value *Slot =
Builder.CreateConstInBoundsGEP2_32(RedArrayTy, RuntimeRL,
5096 Value *RuntimeListEntry = FieldPtr;
5098 Value *SrcDescriptor =
5101 AllocaIP, RI, FieldPtr, SrcDescriptor, PtrTy);
5104 RuntimeListEntry = *Descriptor;
5106 Builder.CreateStore(RuntimeListEntry, Slot);
5112 Type *CopyArg0Ty = (*LtGCFunc)->getFunctionType()->getParamType(0);
5113 Type *CopyArg2Ty = (*LtGCFunc)->getFunctionType()->getParamType(2);
5114 ScratchForCopyBack =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5115 PerThreadScratch, CopyArg0Ty);
5117 Builder.CreatePointerBitCastOrAddrSpaceCast(RL, CopyArg2Ty);
5125 *LtGCFunc, {ScratchForCopyBack,
Builder.getInt32(0), RLForCopyBack});
5126 CopyScratchToListFunc = *GtLCFunc;
5129 Value *Args3[] = {SrcLocInfo, RuntimeRL, *SarFunc, WcFunc,
5130 *LtGCFunc, *GtLCFunc, *GtLRFunc};
5133 RuntimeFunction::OMPRTL___kmpc_gpu_xteam_reduce_nowait);
5153 if (ScratchForCopyBack) {
5156 CopyScratchToListFunc,
5157 {ScratchForCopyBack,
Builder.getInt32(0), RLForCopyBack});
5161 for (
auto En :
enumerate(ReductionInfos)) {
5167 if (IsAtomicReduction) {
5183 Value *LHSPtr, *RHSPtr;
5185 &LHSPtr, &RHSPtr, CurFunc));
5191 RedValue =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5193 if (RHSPtr->
getType() != RHS->getType())
5195 Builder.CreatePointerBitCastOrAddrSpaceCast(RHS, RHSPtr->
getType());
5206 if (IsByRef.
empty() || !IsByRef[En.index()]) {
5208 "red.value." +
Twine(En.index()));
5219 if (!IsByRef.
empty() && !IsByRef[En.index()])
5224 if (ContinuationBlock) {
5225 Builder.CreateBr(ContinuationBlock);
5226 Builder.SetInsertPoint(ContinuationBlock);
5228 Config.setEmitLLVMUsed();
5239 ".omp.reduction.func", &M);
5250 Builder.SetInsertPoint(ReductionFuncBlock);
5252 Value *LHSArrayPtr =
nullptr;
5253 Value *RHSArrayPtr =
nullptr;
5264 Builder.CreateAlloca(Arg0Type,
nullptr, Arg0->
getName() +
".addr");
5266 Builder.CreateAlloca(Arg1Type,
nullptr, Arg1->
getName() +
".addr");
5267 Value *LHSAddrCast =
5268 Builder.CreatePointerBitCastOrAddrSpaceCast(LHSAlloca, Arg0Type);
5269 Value *RHSAddrCast =
5270 Builder.CreatePointerBitCastOrAddrSpaceCast(RHSAlloca, Arg1Type);
5271 Builder.CreateStore(Arg0, LHSAddrCast);
5272 Builder.CreateStore(Arg1, RHSAddrCast);
5273 LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);
5274 RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);
5276 LHSArrayPtr = ReductionFunc->
getArg(0);
5277 RHSArrayPtr = ReductionFunc->
getArg(1);
5280 unsigned NumReductions = ReductionInfos.
size();
5283 for (
auto En :
enumerate(ReductionInfos)) {
5285 Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5286 RedArrayTy, LHSArrayPtr, 0, En.index());
5287 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);
5288 Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5291 Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5292 RedArrayTy, RHSArrayPtr, 0, En.index());
5293 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);
5294 Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5303 Builder.restoreIP(*AfterIP);
5305 if (!Builder.GetInsertBlock())
5309 if (!IsByRef[En.index()])
5310 Builder.CreateStore(Reduced, LHSPtr);
5312 Builder.CreateRetVoid();
5319 bool IsNoWait,
bool IsTeamsReduction) {
5323 IsByRef, IsNoWait, IsTeamsReduction);
5330 if (ReductionInfos.
size() == 0)
5340 unsigned NumReductions = ReductionInfos.
size();
5342 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getTerminator());
5343 Value *RedArray =
Builder.CreateAlloca(RedArrayTy,
nullptr,
"red.array");
5350 for (
auto En :
enumerate(ReductionInfos)) {
5351 unsigned Index = En.index();
5353 Value *RedArrayElemPtr =
Builder.CreateConstInBoundsGEP2_64(
5354 RedArrayTy, RedArray, 0, Index,
"red.array.elem." +
Twine(Index));
5361 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
5371 ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
5376 unsigned RedArrayByteSize =
DL.getTypeStoreSize(RedArrayTy);
5377 Constant *RedArraySize = ConstantInt::get(IndexTy, RedArrayByteSize);
5379 Value *Lock = getOMPCriticalRegionLock(
".reduction");
5381 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
5382 : RuntimeFunction::OMPRTL___kmpc_reduce);
5385 {Ident, ThreadId, NumVariables, RedArraySize,
5386 RedArray, ReductionFunc, Lock},
5397 Builder.CreateSwitch(ReduceCall, ContinuationBlock, 2);
5398 Switch->addCase(
Builder.getInt32(1), NonAtomicRedBlock);
5399 Switch->addCase(
Builder.getInt32(2), AtomicRedBlock);
5404 Builder.SetInsertPoint(NonAtomicRedBlock);
5405 for (
auto En :
enumerate(ReductionInfos)) {
5411 if (!IsByRef[En.index()]) {
5413 "red.value." +
Twine(En.index()));
5415 Value *PrivateRedValue =
5417 "red.private.value." +
Twine(En.index()));
5425 if (!
Builder.GetInsertBlock())
5428 if (!IsByRef[En.index()])
5432 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
5433 : RuntimeFunction::OMPRTL___kmpc_end_reduce);
5435 Builder.CreateBr(ContinuationBlock);
5440 Builder.SetInsertPoint(AtomicRedBlock);
5441 if (CanGenerateAtomic &&
llvm::none_of(IsByRef, [](
bool P) {
return P; })) {
5448 if (!
Builder.GetInsertBlock())
5451 Builder.CreateBr(ContinuationBlock);
5464 if (!
Builder.GetInsertBlock())
5467 Builder.SetInsertPoint(ContinuationBlock);
5478 Directive OMPD = Directive::OMPD_master;
5483 Value *Args[] = {Ident, ThreadId};
5491 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5503 Directive OMPD = Directive::OMPD_masked;
5509 Value *ArgsEnd[] = {Ident, ThreadId};
5517 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5527 Call->setDoesNotThrow();
5542 bool IsInclusive,
ScanInfo *ScanRedInfo) {
5544 llvm::Error Err = emitScanBasedDirectiveDeclsIR(AllocaIP, ScanVars,
5545 ScanVarsType, ScanRedInfo);
5556 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5559 Type *DestTy = ScanVarsType[i];
5560 Value *Val =
Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5563 Builder.CreateStore(Src, Val);
5568 Builder.GetInsertBlock()->getParent());
5571 IV = ScanRedInfo->
IV;
5574 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5577 Type *DestTy = ScanVarsType[i];
5579 Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5581 Builder.CreateStore(Src, ScanVars[i]);
5595 Builder.GetInsertBlock()->getParent());
5600Error OpenMPIRBuilder::emitScanBasedDirectiveDeclsIR(
5604 Builder.restoreIP(AllocaIP);
5606 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5608 Builder.CreateAlloca(Builder.getPtrTy(),
nullptr,
"vla");
5615 Builder.restoreIP(CodeGenIP);
5617 Builder.CreateAdd(ScanRedInfo->
Span, Builder.getInt32(1));
5618 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5620 Value *Allocsize = Builder.CreateTypeSize(
5621 IntPtrTy, M.getDataLayout().getTypeAllocSize(ScanVarsType[i]));
5623 Builder.CreateMalloc(
IntPtrTy, Allocsize, AllocSpan,
nullptr,
"arr");
5624 Builder.CreateStore(Buff, (*(ScanRedInfo->
ScanBuffPtrs))[ScanVars[i]]);
5651Error OpenMPIRBuilder::emitScanBasedDirectiveFinalsIR(
5657 Value *PrivateVar = RedInfo.PrivateVariable;
5658 Value *OrigVar = RedInfo.Variable;
5662 Type *SrcTy = RedInfo.ElementType;
5667 Builder.CreateStore(Src, OrigVar);
5728 llvm::ConstantInt::get(ScanRedInfo->
Span->
getType(), 1));
5729 Builder.SetInsertPoint(InputBB);
5732 Builder.SetInsertPoint(LoopBB);
5748 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5750 Builder.SetInsertPoint(InnerLoopBB);
5754 Value *ReductionVal = RedInfo.PrivateVariable;
5757 Type *DestTy = RedInfo.ElementType;
5760 Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5763 Builder.CreateInBoundsGEP(DestTy, Buff, OffsetIval,
"arrayOffset");
5768 RedInfo.ReductionGen(
Builder.saveIP(), LHS, RHS, Result);
5771 Builder.CreateStore(Result, LHSPtr);
5774 IVal, llvm::ConstantInt::get(
Builder.getInt32Ty(), 1));
5776 CmpI =
Builder.CreateICmpUGE(NextIVal, Pow2K);
5777 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5780 Counter, llvm::ConstantInt::get(Counter->
getType(), 1));
5786 Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
5807 Error Err = emitScanBasedDirectiveFinalsIR(ReductionInfos, ScanRedInfo);
5814Error OpenMPIRBuilder::emitScanBasedDirectiveIR(
5826 Error Err = InputLoopGen();
5837 Error Err = ScanLoopGen(Builder);
5844void OpenMPIRBuilder::createScanBBs(ScanInfo *ScanRedInfo) {
5881 Builder.SetInsertPoint(Preheader);
5884 Builder.SetInsertPoint(Header);
5885 PHINode *IndVarPHI =
Builder.CreatePHI(IndVarTy, 2,
"omp_" + Name +
".iv");
5886 IndVarPHI->
addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
5891 Builder.CreateICmpULT(IndVarPHI, TripCount,
"omp_" + Name +
".cmp");
5892 Builder.CreateCondBr(Cmp, Body, Exit);
5897 Builder.SetInsertPoint(Latch);
5907 bool HasNSW =
Config.hasNoSignedWrap();
5910 unsigned BitWidth = CI->getType()->getIntegerBitWidth();
5912 if (CI->getValue().ugt(SignedMax))
5914 }
else if (IsCollapsed) {
5919 Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
5920 "omp_" + Name +
".next",
true, HasNSW);
5931 CL->Header = Header;
5950 NextBB, NextBB, Name);
5982 Value *Start,
Value *Stop,
Value *Step,
bool IsSigned,
bool InclusiveStop,
5991 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
5992 ScanRedInfo->
Span = TripCount;
5998 ScanRedInfo->
IV =
IV;
5999 createScanBBs(ScanRedInfo);
6002 assert(Terminator->getNumSuccessors() == 1);
6003 BasicBlock *ContinueBlock = Terminator->getSuccessor(0);
6006 Builder.GetInsertBlock()->getParent());
6009 Builder.GetInsertBlock()->getParent());
6010 Builder.CreateBr(ContinueBlock);
6016 const auto &&InputLoopGen = [&]() ->
Error {
6019 InclusiveStop, ComputeIP, Name,
true, ScanRedInfo);
6023 Builder.restoreIP((*LoopInfo)->getAfterIP());
6029 InclusiveStop, ComputeIP, Name,
true, ScanRedInfo);
6033 Builder.restoreIP((*LoopInfo)->getAfterIP());
6037 Error Err = emitScanBasedDirectiveIR(InputLoopGen, ScanLoopGen, ScanRedInfo);
6045 bool IsSigned,
bool InclusiveStop,
const Twine &Name) {
6055 assert(IndVarTy == Stop->
getType() &&
"Stop type mismatch");
6056 assert(IndVarTy == Step->
getType() &&
"Step type mismatch");
6076 Incr =
Builder.CreateSelect(IsNeg,
Builder.CreateNeg(Step), Step);
6079 Span =
Builder.CreateSub(UB, LB,
"",
false,
true);
6083 Span =
Builder.CreateSub(Stop, Start,
"",
true);
6088 Value *CountIfLooping;
6089 if (InclusiveStop) {
6090 CountIfLooping =
Builder.CreateAdd(
Builder.CreateUDiv(Span, Incr), One);
6096 CountIfLooping =
Builder.CreateSelect(OneCmp, One, CountIfTwo);
6099 return Builder.CreateSelect(ZeroCmp,
Zero, CountIfLooping,
6100 "omp_" + Name +
".tripcount");
6105 Value *Start,
Value *Stop,
Value *Step,
bool IsSigned,
bool InclusiveStop,
6112 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
6117 Config.hasNoSignedWrap());
6118 Value *IndVar =
Builder.CreateAdd(Span, Start,
"",
false,
6119 Config.hasNoSignedWrap());
6121 ScanRedInfo->
IV = IndVar;
6122 return BodyGenCB(
Builder.saveIP(), IndVar);
6128 Builder.getCurrentDebugLocation());
6139 unsigned Bitwidth = Ty->getIntegerBitWidth();
6142 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_4u);
6145 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_8u);
6155 unsigned Bitwidth = Ty->getIntegerBitWidth();
6158 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
6161 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
6169 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6171 "Require dedicated allocate IP");
6177 uint32_t SrcLocStrSize;
6181 case WorksharingLoopType::ForStaticLoop:
6182 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6184 case WorksharingLoopType::DistributeStaticLoop:
6185 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6187 case WorksharingLoopType::DistributeForStaticLoop:
6188 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6195 FunctionCallee StaticInit =
6196 LoopType == WorksharingLoopType::DistributeForStaticLoop
6199 FunctionCallee StaticFini =
6203 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6206 Value *PLastIter =
Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6207 Value *PLowerBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.lowerbound");
6208 Value *PUpperBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.upperbound");
6209 Value *PStride =
Builder.CreateAlloca(IVTy,
nullptr,
"p.stride");
6218 Constant *One = ConstantInt::get(IVTy, 1);
6221 Builder.CreateStore(UpperBound, PUpperBound);
6222 Builder.CreateStore(One, PStride);
6228 (LoopType == WorksharingLoopType::DistributeStaticLoop)
6229 ? OMPScheduleType::OrderedDistribute
6232 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6236 auto BuildInitCall = [LoopType, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6237 PUpperBound, IVTy, PStride, One,
Zero, StaticInit,
6240 PLowerBound, PUpperBound});
6241 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6242 Value *PDistUpperBound =
6243 Builder.CreateAlloca(IVTy,
nullptr,
"p.distupperbound");
6244 Args.push_back(PDistUpperBound);
6249 BuildInitCall(SchedulingType,
Builder);
6250 if (HasDistSchedule &&
6251 LoopType != WorksharingLoopType::DistributeStaticLoop) {
6252 Constant *DistScheduleSchedType = ConstantInt::get(
6257 BuildInitCall(DistScheduleSchedType,
Builder);
6260 Value *InclusiveUpperBound =
Builder.CreateLoad(IVTy, PUpperBound);
6262 Value *TripCount =
Builder.CreateAdd(TripCountMinusOne, One);
6263 if (CLI->VirtualCollapse) {
6264 bindCollapsedRange(CLI,
LowerBound, TripCount);
6269 CLI->setTripCount(TripCount);
6276 if (!CLI->VirtualCollapse)
6277 CLI->mapIndVar([&](Instruction *OldIV) ->
Value * {
6281 Config.hasNoSignedWrap());
6292 omp::Directive::OMPD_for,
false,
6295 return BarrierIP.takeError();
6326 Reachable.insert(
Block);
6340OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
6344 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6345 assert((ChunkSize || DistScheduleChunkSize) &&
"Chunk size is required");
6350 Type *IVTy =
IV->getType();
6352 "Max supported tripcount bitwidth is 64 bits");
6354 :
Type::getInt64Ty(Ctx);
6357 Constant *One = ConstantInt::get(InternalIVTy, 1);
6362 SmallVector<Instruction *> UIs;
6363 for (BasicBlock &BB : *
F)
6364 if (!BB.hasTerminator())
6365 UIs.
push_back(
new UnreachableInst(
F->getContext(), &BB));
6370 LoopInfo &&LI = LIA.
run(*
F,
FAM);
6371 for (Instruction *
I : UIs)
6372 I->eraseFromParent();
6375 if (ChunkSize || DistScheduleChunkSize)
6380 FunctionCallee StaticInit =
6382 FunctionCallee StaticFini =
6388 Value *PLastIter =
Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6389 Value *PLowerBound =
6390 Builder.CreateAlloca(InternalIVTy,
nullptr,
"p.lowerbound");
6391 Value *PUpperBound =
6392 Builder.CreateAlloca(InternalIVTy,
nullptr,
"p.upperbound");
6393 Value *PStride =
Builder.CreateAlloca(InternalIVTy,
nullptr,
"p.stride");
6402 ChunkSize ? ChunkSize :
Zero, InternalIVTy,
"chunksize");
6403 Value *CastedDistScheduleChunkSize =
Builder.CreateZExtOrTrunc(
6404 DistScheduleChunkSize ? DistScheduleChunkSize :
Zero, InternalIVTy,
6405 "distschedulechunksize");
6406 Value *CastedTripCount =
6407 Builder.CreateZExt(OrigTripCount, InternalIVTy,
"tripcount");
6410 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6412 ConstantInt::get(I32Type,
static_cast<int>(DistScheduleSchedType));
6414 Value *OrigUpperBound =
Builder.CreateSub(CastedTripCount, One);
6417 Builder.CreateSelect(IsTripCountZero,
Zero, OrigUpperBound);
6418 Builder.CreateStore(UpperBound, PUpperBound);
6419 Builder.CreateStore(One, PStride);
6423 uint32_t SrcLocStrSize;
6426 if (DistScheduleSchedType != OMPScheduleType::None) {
6427 Flag |= OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6432 auto BuildInitCall = [StaticInit, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6433 PUpperBound, PStride, One,
6434 this](
Value *SchedulingType,
Value *ChunkSize,
6437 StaticInit, {SrcLoc, ThreadNum,
6438 SchedulingType, PLastIter,
6439 PLowerBound, PUpperBound,
6443 BuildInitCall(SchedulingType, CastedChunkSize,
Builder);
6444 if (DistScheduleSchedType != OMPScheduleType::None &&
6445 SchedType != OMPScheduleType::OrderedDistributeChunked &&
6446 SchedType != OMPScheduleType::OrderedDistribute) {
6450 BuildInitCall(DistSchedulingType, CastedDistScheduleChunkSize,
Builder);
6454 Value *FirstChunkStart =
6455 Builder.CreateLoad(InternalIVTy, PLowerBound,
"omp_firstchunk.lb");
6456 Value *FirstChunkStop =
6457 Builder.CreateLoad(InternalIVTy, PUpperBound,
"omp_firstchunk.ub");
6458 Value *FirstChunkEnd =
Builder.CreateAdd(FirstChunkStop, One);
6460 Builder.CreateSub(FirstChunkEnd, FirstChunkStart,
"omp_chunk.range");
6461 Value *NextChunkStride =
6462 Builder.CreateLoad(InternalIVTy, PStride,
"omp_dispatch.stride");
6466 Value *DispatchCounter;
6474 DispatchCounter = Counter;
6477 FirstChunkStart, CastedTripCount, NextChunkStride,
6500 Value *ChunkEnd =
Builder.CreateAdd(DispatchCounter, ChunkRange);
6501 Value *IsLastChunk =
6502 Builder.CreateICmpUGE(ChunkEnd, CastedTripCount,
"omp_chunk.is_last");
6503 Value *CountUntilOrigTripCount =
6504 Builder.CreateSub(CastedTripCount, DispatchCounter);
6506 IsLastChunk, CountUntilOrigTripCount, ChunkRange,
"omp_chunk.tripcount");
6507 Value *BackcastedChunkTC =
6508 Builder.CreateTrunc(ChunkTripCount, IVTy,
"omp_chunk.tripcount.trunc");
6509 CLI->setTripCount(BackcastedChunkTC);
6514 Value *BackcastedDispatchCounter =
6515 Builder.CreateTrunc(DispatchCounter, IVTy,
"omp_dispatch.iv.trunc");
6516 CLI->mapIndVar([&](Instruction *) ->
Value * {
6518 return Builder.CreateAdd(
IV, BackcastedDispatchCounter);
6531 return AfterIP.takeError();
6546static FunctionCallee
6549 unsigned Bitwidth = Ty->getIntegerBitWidth();
6552 case WorksharingLoopType::ForStaticLoop:
6555 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_4u);
6558 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_8u);
6560 case WorksharingLoopType::DistributeStaticLoop:
6563 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_4u);
6566 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_8u);
6568 case WorksharingLoopType::DistributeForStaticLoop:
6571 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_4u);
6574 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_8u);
6577 if (Bitwidth != 32 && Bitwidth != 64) {
6589 Function &LoopBodyFn,
bool NoLoop) {
6600 if (LoopType == WorksharingLoopType::DistributeStaticLoop) {
6601 RealArgs.
push_back(ConstantInt::get(TripCountTy, 0));
6602 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6603 Builder.restoreIP(std::prev(InsertBlock->
end()));
6608 M, omp::RuntimeFunction::OMPRTL_omp_get_num_threads);
6609 Builder.restoreIP(std::prev(InsertBlock->
end()));
6613 Builder.CreateZExtOrTrunc(NumThreads, TripCountTy,
"num.threads.cast"));
6614 RealArgs.
push_back(ConstantInt::get(TripCountTy, 0));
6615 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6616 RealArgs.
push_back(ConstantInt::get(TripCountTy, 0));
6617 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), NoLoop));
6619 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6643 Builder.restoreIP(Preheader->
end());
6646 Builder.CreateBr(CLI->
getExit());
6654 CleanUpInfo.
collectBlocks(RegionBlockSet, BlocksToBeRemoved);
6662 "Expected unique undroppable user of outlined function");
6664 assert(OutlinedFnCallInstruction &&
"Expected outlined function call");
6666 "Expected outlined function call to be located in loop preheader");
6668 if (OutlinedFnCallInstruction->
arg_size() > 1)
6675 LoopBodyArg, TripCount, OutlinedFn, NoLoop);
6677 for (
auto &ToBeDeletedItem : ToBeDeleted)
6678 ToBeDeletedItem->eraseFromParent();
6685 bool NeedsLastIter) {
6686 uint32_t SrcLocStrSize;
6690 if (NeedsLastIter) {
6693 AllocaInst *PLastIter =
6694 Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6698 Builder.CreateStore(ConstantInt::get(I32Type, 0), PLastIter);
6703 Builder.CreateSub(TripCount, ConstantInt::get(TripCount->
getType(), 1));
6706 Builder.CreateStore(
Builder.CreateZExt(IsLast, I32Type), PLastIter);
6711 case WorksharingLoopType::ForStaticLoop:
6712 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6714 case WorksharingLoopType::DistributeStaticLoop:
6715 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6717 case WorksharingLoopType::DistributeForStaticLoop:
6718 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6723 auto OI = std::make_unique<OutlineInfo>();
6728 SmallVector<Instruction *, 4> ToBeDeleted;
6730 OI->OuterAllocBB = AllocaIP.getNodeParent();
6753 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
6755 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
6757 CodeExtractorAnalysisCache CEAC(*OuterFn);
6758 CodeExtractor Extractor(Blocks,
6772 SetVector<Value *> SinkingCands, HoistingCands;
6776 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
6783 for (
auto Use :
Users) {
6785 if (ParallelRegionBlockSet.
count(Inst->getParent())) {
6786 Inst->replaceUsesOfWith(CLI->
getIndVar(), NewLoopCntLoad);
6792 OI->ExcludeArgsFromAggregate.push_back(NewLoopCntLoad);
6799 OI->PostOutlineCB = [=, ToBeDeletedVec =
6800 std::move(ToBeDeleted)](
Function &OutlinedFn) {
6817 return BarrierIP.takeError();
6824 bool NeedsBarrier, omp::ScheduleKind SchedKind,
Value *ChunkSize,
6825 bool HasSimdModifier,
bool HasMonotonicModifier,
6826 bool HasNonmonotonicModifier,
bool HasOrderedClause,
6828 Value *DistScheduleChunkSize,
bool NeedsLastIter) {
6829 if (CLI->VirtualCollapse &&
6830 (
Config.isTargetDevice() ||
6831 (SchedKind != omp::OMP_SCHEDULE_Static &&
6832 SchedKind != omp::OMP_SCHEDULE_Default) ||
6833 ChunkSize || HasOrderedClause || HasDistSchedule ||
6834 DistScheduleChunkSize || LoopType != WorksharingLoopType::ForStaticLoop))
6836 "Virtual collapse requires unchunked static worksharing");
6837 if (
Config.isTargetDevice())
6838 return applyWorkshareLoopTarget(
DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6839 NoLoop, NeedsLastIter);
6841 SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
6842 HasNonmonotonicModifier, HasOrderedClause, DistScheduleChunkSize);
6844 bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
6845 OMPScheduleType::ModifierOrdered;
6847 if (HasDistSchedule) {
6848 DistScheduleSchedType = DistScheduleChunkSize
6849 ? OMPScheduleType::OrderedDistributeChunked
6850 : OMPScheduleType::OrderedDistribute;
6852 switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
6853 case OMPScheduleType::BaseStatic:
6854 case OMPScheduleType::BaseDistribute:
6855 assert((!ChunkSize || !DistScheduleChunkSize) &&
6856 "No chunk size with static-chunked schedule");
6857 if (IsOrdered && !HasDistSchedule)
6858 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6859 NeedsBarrier, ChunkSize);
6861 if (DistScheduleChunkSize)
6862 return applyStaticChunkedWorkshareLoop(
6863 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6864 DistScheduleChunkSize, DistScheduleSchedType);
6865 return applyStaticWorkshareLoop(
DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6868 case OMPScheduleType::BaseStaticChunked:
6869 case OMPScheduleType::BaseDistributeChunked:
6870 if (IsOrdered && !HasDistSchedule)
6871 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6872 NeedsBarrier, ChunkSize);
6874 return applyStaticChunkedWorkshareLoop(
6875 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6876 DistScheduleChunkSize, DistScheduleSchedType);
6878 case OMPScheduleType::BaseRuntime:
6879 case OMPScheduleType::BaseAuto:
6880 case OMPScheduleType::BaseGreedy:
6881 case OMPScheduleType::BaseBalanced:
6882 case OMPScheduleType::BaseSteal:
6883 case OMPScheduleType::BaseRuntimeSimd:
6885 "schedule type does not support user-defined chunk sizes");
6887 case OMPScheduleType::BaseGuidedSimd:
6888 case OMPScheduleType::BaseDynamicChunked:
6889 case OMPScheduleType::BaseGuidedChunked:
6890 case OMPScheduleType::BaseGuidedIterativeChunked:
6891 case OMPScheduleType::BaseGuidedAnalyticalChunked:
6892 case OMPScheduleType::BaseStaticBalancedChunked:
6893 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6894 NeedsBarrier, ChunkSize);
6907 unsigned Bitwidth = Ty->getIntegerBitWidth();
6910 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
6913 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
6921static FunctionCallee
6923 unsigned Bitwidth = Ty->getIntegerBitWidth();
6926 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
6929 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
6936static FunctionCallee
6938 unsigned Bitwidth = Ty->getIntegerBitWidth();
6941 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
6944 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
6949OpenMPIRBuilder::applyDynamicWorkshareLoop(
DebugLoc DL, CanonicalLoopInfo *CLI,
6952 bool NeedsBarrier,
Value *Chunk) {
6953 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6955 "Require dedicated allocate IP");
6957 "Require valid schedule type");
6959 bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
6960 OMPScheduleType::ModifierOrdered;
6965 uint32_t SrcLocStrSize;
6972 Type *IVTy =
IV->getType();
6977 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6979 Value *PLastIter =
Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6980 Value *PLowerBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.lowerbound");
6981 Value *PUpperBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.upperbound");
6982 Value *PStride =
Builder.CreateAlloca(IVTy,
nullptr,
"p.stride");
6991 Constant *One = ConstantInt::get(IVTy, 1);
6992 Builder.CreateStore(One, PLowerBound);
6994 Builder.CreateStore(UpperBound, PUpperBound);
6995 Builder.CreateStore(One, PStride);
7013 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
7025 Builder.SetInsertPoint(OuterCond->getFirstInsertionPt());
7028 {SrcLoc, ThreadNum, PLastIter, PLowerBound, PUpperBound, PStride});
7029 Constant *Zero32 = ConstantInt::get(I32Type, 0);
7032 Builder.CreateSub(
Builder.CreateLoad(IVTy, PLowerBound), One,
"lb");
7033 Builder.CreateCondBr(MoreWork, Header, Exit);
7039 PI->setIncomingBlock(0, OuterCond);
7045 Br->setSuccessor(OuterCond);
7050 Builder.SetInsertPoint(
Cond->getFirstInsertionPt());
7051 UpperBound =
Builder.CreateLoad(IVTy, PUpperBound,
"ub");
7054 CI->setOperand(1, UpperBound);
7058 assert(BI->getSuccessor(1) == Exit);
7059 BI->setSuccessor(1, OuterCond);
7073 omp::Directive::OMPD_for,
false,
7076 return BarrierIP.takeError();
7139 "Virtual collapse requires unobserved canonical loop controls");
7148 if (
Loops.front()->getBody()->getUniqueSuccessor() !=
7150 Loops.back()->getAfter()->getSingleSuccessor() != Plan.
Latches.front())
7157 const VirtualRowPlan &Plan,
7161 DebugLoc DL = Builder.getCurrentDebugLocation();
7167 Builder.SetInsertPoint(Entry);
7169 Builder.CreateURem(Begin, TripCounts.
back(),
"omp_collapsed.begin.1");
7171 Builder.CreateUDiv(Begin, TripCounts.
back(),
"omp_collapsed.begin.0");
7174 Value *InitialRemaining =
7175 Builder.CreateAdd(
Count, InnerBegin,
"omp_collapsed.row.remaining");
7176 Builder.CreateBr(OuterHeader);
7179 Builder.SetCurrentDebugLocation(
DL);
7181 Builder.CreatePHI(IVType, 2,
"omp_collapsed.row.remaining.0");
7187 Builder.CreatePHI(IVType, 2,
"omp_collapsed.row.start.1.0");
7188 Start->addIncoming(InnerBegin, Entry);
7189 Start->addIncoming(
Zero, Plan.Latches.front());
7190 Plan.IndVars.back()->setIncomingValue(0, Start);
7195 BasicBlock *InnerHeader = Plan.IndVars.back()->getParent();
7199 Builder.SetInsertPoint(InnerEntry);
7201 Builder.CreateBr(InnerHeader);
7202 InnerBr->setSuccessor(InnerEntry);
7203 Plan.IndVars.back()->setIncomingBlock(0, InnerEntry);
7205 Builder.SetInsertPoint(Plan.Preheaders.back()->getTerminator());
7208 "omp_collapsed.row.is_final");
7210 IsFinalRow, Remaining, TripCounts.
back(),
"omp_collapsed.row.stop");
7211 Plan.InnerCmp->setOperand(1, InnerStop);
7219 "omp_collapsed.row.remaining.next",
7227 Builder.SetInsertPoint(Guard);
7229 Plan.IndVars.front()->setIncomingValue(0, OuterBegin);
7230 Plan.IndVars.front()->setIncomingBlock(0, Entry);
7233CanonicalLoopInfo *OpenMPIRBuilder::createVirtualCollapsedLoop(
7236 Value *CollapsedTripCount) {
7244 BasicBlock *Preheader = Plan.Preheaders.front();
7259 "omp_collapsed.range.begin");
7261 Builder.Insert(BinaryOperator::CreateAdd(CollapsedTripCount,
Zero),
7262 "omp_collapsed.range.count");
7265 Result->VirtualCollapse =
7266 CanonicalLoopInfo::VirtualCollapseInfo{Begin,
Count};
7270 createVirtualRowExecutor(Result, Plan, TripCounts, Begin,
Count, Entry);
7280void OpenMPIRBuilder::bindCollapsedRange(CanonicalLoopInfo *
Loop,
Value *Begin,
7283 Loop->VirtualCollapse->Begin->setOperand(0, Begin);
7284 Loop->VirtualCollapse->Count->setOperand(0,
Count);
7290 assert(
Loops.size() >= 1 &&
"At least one loop required");
7291 size_t NumLoops =
Loops.size();
7295 return Loops.front();
7297 if (
Config.CollapseMapping == CollapseIVMapping::Virtual) {
7298 if (
Loops.size() != 2)
7300 "Virtual collapse requires two constant-count loops");
7303 if (
Loop->VirtualCollapse)
7304 Loop->reportUnsupportedVirtualCollapse();
7308 "Virtual collapse requires two constant-count loops");
7313 Value *CollapsedTripCount =
7315 return createVirtualCollapsedLoop(
DL,
Loops, Plan, TripCounts,
7316 CollapsedTripCount);
7329 Loop->collectControlBlocks(OldControlBBs);
7333 if (ComputeIP.isValid())
7340 Value *CollapsedTripCount =
nullptr;
7343 "All loops to collapse must be valid canonical loops");
7344 Value *OrigTripCount = L->getTripCount();
7345 if (!CollapsedTripCount) {
7346 CollapsedTripCount = OrigTripCount;
7351 CollapsedTripCount =
7352 Builder.CreateNUWMul(CollapsedTripCount, OrigTripCount);
7358 OrigPreheader->
getNextNode(), OrigAfter,
"collapsed",
7365 Builder.restoreIP(Result->getBodyIP());
7367 Value *Leftover = Result->getIndVar();
7369 NewIndVars.
resize(NumLoops);
7370 for (
int i = NumLoops - 1; i >= 1; --i) {
7371 Value *OrigTripCount =
Loops[i]->getTripCount();
7373 Value *NewIndVar =
Builder.CreateURem(Leftover, OrigTripCount);
7374 NewIndVars[i] = NewIndVar;
7376 Leftover =
Builder.CreateUDiv(Leftover, OrigTripCount);
7379 NewIndVars[0] = Leftover;
7388 BasicBlock *ContinueBlock = Result->getBody();
7390 auto ContinueWith = [&ContinueBlock, &ContinuePred,
DL](
BasicBlock *Dest,
7397 ContinueBlock =
nullptr;
7398 ContinuePred = NextSrc;
7405 for (
size_t i = 0; i < NumLoops - 1; ++i)
7406 ContinueWith(
Loops[i]->getBody(),
Loops[i + 1]->getHeader());
7412 for (
size_t i = NumLoops - 1; i > 0; --i)
7413 ContinueWith(
Loops[i]->getAfter(),
Loops[i - 1]->getLatch());
7416 ContinueWith(Result->getLatch(),
nullptr);
7423 for (
size_t i = 0; i < NumLoops; ++i)
7424 Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
7438std::vector<CanonicalLoopInfo *>
7442 "Must pass as many tile sizes as there are loops");
7443 int NumLoops =
Loops.size();
7444 assert(NumLoops >= 1 &&
"At least one loop to tile required");
7456 Loop->collectControlBlocks(OldControlBBs);
7464 assert(L->isValid() &&
"All input loops must be valid canonical loops");
7465 OrigTripCounts.
push_back(L->getTripCount());
7476 for (
int i = 0; i < NumLoops - 1; ++i) {
7489 for (
int i = 0; i < NumLoops; ++i) {
7490 Value *TileSize = TileSizes[i];
7491 Value *OrigTripCount = OrigTripCounts[i];
7494 Value *FloorCompleteTripCount =
Builder.CreateUDiv(OrigTripCount, TileSize);
7495 Value *FloorTripRem =
Builder.CreateURem(OrigTripCount, TileSize);
7504 Value *FloorTripOverflow =
7505 Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
7507 FloorTripOverflow =
Builder.CreateZExt(FloorTripOverflow, IVType);
7508 Value *FloorTripCount =
7509 Builder.CreateAdd(FloorCompleteTripCount, FloorTripOverflow,
7510 "omp_floor" +
Twine(i) +
".tripcount",
true);
7513 FloorCompleteCount.
push_back(FloorCompleteTripCount);
7519 std::vector<CanonicalLoopInfo *> Result;
7520 Result.reserve(NumLoops * 2);
7533 auto EmbeddNewLoop =
7534 [
this,
DL,
F, InnerEnter, &Enter, &
Continue, &OutroInsertBefore](
7537 DL, TripCount,
F, InnerEnter, OutroInsertBefore, Name);
7542 Enter = EmbeddedLoop->
getBody();
7544 OutroInsertBefore = EmbeddedLoop->
getLatch();
7545 return EmbeddedLoop;
7549 const Twine &NameBase) {
7552 EmbeddNewLoop(
P.value(), NameBase +
Twine(
P.index()));
7553 Result.push_back(EmbeddedLoop);
7557 EmbeddNewLoops(FloorCount,
"floor");
7563 for (
int i = 0; i < NumLoops; ++i) {
7565 Value *TileSize = TileSizes[i];
7567 Value *FloorIsEpilogue =
7569 Value *TileTripCount =
7570 Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
7576 EmbeddNewLoops(TileCounts,
"tile");
7581 for (std::pair<BasicBlock *, BasicBlock *>
P : InbetweenCode) {
7590 BodyEnter =
nullptr;
7591 BodyEntered = ExitBB;
7603 Builder.restoreIP(Result.back()->getBodyIP());
7604 for (
int i = 0; i < NumLoops; ++i) {
7607 Value *OrigIndVar = OrigIndVars[i];
7658 assert(
Loop->isValid() &&
"Expecting a valid CanonicalLoopInfo");
7662 assert(Latch &&
"A valid CanonicalLoopInfo must have a unique latch");
7670 if (
I.mayReadOrWriteMemory()) {
7674 I.setMetadata(LLVMContext::MD_access_group,
AccessGroup);
7688 Loop->collectControlBlocks(oldControlBBs);
7693 assert(L->isValid() &&
"All input loops must be valid canonical loops");
7694 origTripCounts.
push_back(L->getTripCount());
7703 Builder.SetInsertPoint(TCBlock);
7704 Value *fusedTripCount =
nullptr;
7706 assert(L->isValid() &&
"All loops to fuse must be valid canonical loops");
7707 Value *origTripCount = L->getTripCount();
7708 if (!fusedTripCount) {
7709 fusedTripCount = origTripCount;
7712 Value *condTP =
Builder.CreateICmpSGT(fusedTripCount, origTripCount);
7713 fusedTripCount =
Builder.CreateSelect(condTP, fusedTripCount, origTripCount,
7727 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7728 Loops[i]->getPreheader()->moveBefore(TCBlock);
7729 Loops[i]->getAfter()->moveBefore(TCBlock);
7733 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7745 for (
size_t i = 0; i <
Loops.size(); ++i) {
7747 F->getContext(),
"omp.fused.inner.cond",
F,
Loops[i]->getBody());
7748 Builder.SetInsertPoint(condBlock);
7756 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7757 Builder.SetInsertPoint(condBBs[i]);
7758 Builder.CreateCondBr(condValues[i],
Loops[i]->getBody(), condBBs[i + 1]);
7774 "omp.fused.pre_latch");
7791 assert(
Loop->isValid() &&
"Expecting a valid CanonicalLoopInfo");
7792 if (
Loop->VirtualCollapse)
7815 const Twine &NamePrefix) {
7844 C, NamePrefix +
".if.then",
Cond->getParent(),
Cond->getNextNode());
7846 C, NamePrefix +
".if.else",
Cond->getParent(), CanonicalLoop->
getExit());
7849 Builder.SetInsertPoint(SplitBeforeIt);
7851 Builder.CreateCondBr(IfCond, ThenBlock, ElseBlock);
7854 spliceBB(IP, ThenBlock,
false, Builder.getCurrentDebugLocation());
7857 Builder.SetInsertPoint(ElseBlock);
7863 ExistingBlocks.
reserve(L->getNumBlocks() + 1);
7865 ExistingBlocks.
append(L->block_begin(), L->block_end());
7871 assert(LoopCond && LoopHeader &&
"Invalid loop structure");
7873 if (
Block == L->getLoopPreheader() ||
Block == L->getLoopLatch() ||
7880 if (
Block == ThenBlock)
7881 NewBB->
setName(NamePrefix +
".if.else");
7884 VMap[
Block] = NewBB;
7892 L->getLoopLatch()->splitBasicBlockBefore(
L->getLoopLatch()->begin(),
7893 NamePrefix +
".pre_latch");
7897 L->addBasicBlockToLoop(ThenBlock, LI);
7903 if (TargetTriple.
isX86()) {
7904 if (Features.
lookup(
"avx512f"))
7906 else if (Features.
lookup(
"avx"))
7910 if (TargetTriple.
isPPC())
7912 if (TargetTriple.
isWasm())
7921 Value *IfCond, OrderKind Order,
7923 if (CanonicalLoop->VirtualCollapse)
7924 CanonicalLoop->reportUnsupportedVirtualCollapse();
7933 if (!BB.hasTerminator())
7949 I->eraseFromParent();
7952 if (AlignedVars.
size()) {
7954 for (
auto &AlignedItem : AlignedVars) {
7955 Value *AlignedPtr = AlignedItem.first;
7959 Builder.CreateAlignmentAssumption(
F->getDataLayout(), AlignedPtr,
7967 createIfVersion(CanonicalLoop, IfCond, VMap, LIA, LI, L,
"simd");
7980 Reachable.insert(
Block);
7990 if ((Safelen ==
nullptr) || (Order == OrderKind::OMP_ORDER_concurrent))
8006 if (Simdlen || Safelen) {
8010 ConstantInt *VectorizeWidth = Simdlen ==
nullptr ? Safelen : Simdlen;
8022 assert(Factor >= 0 &&
"Unroll factor must not be negative");
8038 Ctx, {
MDString::get(Ctx,
"llvm.loop.unroll.count"), FactorConst}));
8041 addUnrollMetadata(
Loop, LoopMetadata);
8046 if (
Loop->VirtualCollapse)
8047 Loop->reportUnsupportedVirtualCollapse();
8053 *UnrolledCLI =
Loop;
8058 "unrolling only makes sense with a factor of 2 or larger");
8060 Type *IndVarTy =
Loop->getIndVarType();
8067 std::vector<CanonicalLoopInfo *>
LoopNest =
8082 Ctx, {
MDString::get(Ctx,
"llvm.loop.unroll.count"), FactorConst})});
8085 (*UnrolledCLI)->assertOK();
8103 Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
8122 if (!CPVars.
empty()) {
8127 Directive OMPD = Directive::OMPD_single;
8132 Value *Args[] = {Ident, ThreadId};
8141 if (
Error Err = FiniCB(IP))
8162 EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCBWrapper,
8169 for (
size_t I = 0, E = CPVars.
size();
I < E; ++
I)
8172 ConstantInt::get(Int64, 0), CPVars[
I],
8175 }
else if (!IsNowait) {
8178 omp::Directive::OMPD_unknown,
false,
8196 Directive::OMPD_scope,
nullptr,
nullptr,
8197 BodyGenCB, FiniCB,
false,
true,
8205 omp::Directive::OMPD_unknown,
8221 Directive OMPD = Directive::OMPD_critical;
8226 Value *LockVar = getOMPCriticalRegionLock(CriticalName);
8227 Value *Args[] = {Ident, ThreadId, LockVar};
8244 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8252 const Twine &Name,
bool IsDependSource) {
8255 [](
Value *SV) {
return SV->getType()->isIntegerTy(64); }) &&
8256 "OpenMP runtime requires depend vec with i64 type");
8269 for (
unsigned I = 0;
I < NumLoops; ++
I) {
8283 Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
8301 Directive OMPD = Directive::OMPD_ordered_blockassoc;
8310 Value *Args[] = {Ident, ThreadId};
8320 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8327 bool HasFinalize,
bool IsCancellable) {
8334 BasicBlock *EntryBB = Builder.GetInsertBlock();
8338 SplitPos->
setDebugLoc(Builder.getCurrentDebugLocation());
8345 emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
8357 "Unexpected control flow graph state!!");
8359 emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
8361 return AfterIP.takeError();
8366 "Unexpected Insertion point location!");
8369 auto InsertBB = merged ? ExitPredBB : ExitBB;
8372 Builder.SetInsertPoint(InsertBB);
8378 Directive OMPD,
Value *EntryCall, BasicBlock *ExitBB,
bool Conditional) {
8380 if (!Conditional || !EntryCall)
8386 auto *UI =
new UnreachableInst(
Builder.getContext(), ThenBB);
8396 Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
8400 UI->eraseFromParent();
8408 omp::Directive OMPD,
InsertPointTy FinIP, Instruction *ExitCall,
8416 "Unexpected finalization stack state!");
8419 assert(Fi.DK == OMPD &&
"Unexpected Directive for Finalization call!");
8423 return std::move(Err);
8470 "copyin.not.master.end");
8477 Builder.SetInsertPoint(OMP_Entry);
8480 Value *cmp =
Builder.CreateICmpNE(MasterPtr, PrivatePtr);
8481 Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
8483 Builder.SetInsertPoint(CopyBegin);
8501 Value *Args[] = {ThreadId,
Size, Allocator};
8524 return Builder.CreateCall(Fn, Args, Name);
8538 Value *Args[] = {ThreadId, Addr, Allocator};
8545 const Twine &Name) {
8553 M.getContext(),
M.getDataLayout().getPrefTypeAlign(Int64)));
8559 const Twine &Name) {
8561 Loc,
Builder.getInt64(
M.getDataLayout().getTypeAllocSize(VarType)), Name);
8566 const Twine &Name) {
8572 return Builder.CreateCall(Fn, Args, Name);
8577 const Twine &Name) {
8579 Loc, Addr,
Builder.getInt64(
M.getDataLayout().getTypeAllocSize(VarType)),
8586 Value *DependenceAddress,
bool HaveNowaitClause) {
8596 else if (
Device->getType() != Int32)
8599 if (NumDependences ==
nullptr) {
8600 NumDependences = ConstantInt::get(Int32, 0);
8604 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8606 Ident, ThreadId, InteropVar, InteropTypeVal,
8607 Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
8616 Value *NumDependences,
Value *DependenceAddress,
bool HaveNowaitClause) {
8626 else if (
Device->getType() != Int32)
8628 if (NumDependences ==
nullptr) {
8629 NumDependences = ConstantInt::get(Int32, 0);
8633 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8635 Ident, ThreadId, InteropVar,
Device,
8636 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8645 Value *NumDependences,
8646 Value *DependenceAddress,
8647 bool HaveNowaitClause) {
8656 else if (
Device->getType() != Int32)
8658 if (NumDependences ==
nullptr) {
8659 NumDependences = ConstantInt::get(Int32, 0);
8663 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8665 Ident, ThreadId, InteropVar,
Device,
8666 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8696 assert(!Attrs.MaxThreads.empty() && !Attrs.MaxTeams.empty() &&
8697 "expected num_threads and num_teams to be specified");
8717 const std::string DebugPrefix =
"_debug__";
8718 if (KernelName.
ends_with(DebugPrefix)) {
8719 KernelName = KernelName.
drop_back(DebugPrefix.length());
8720 Kernel =
M.getFunction(KernelName);
8726 if (Attrs.MinTeams.front() > 1 || Attrs.MaxTeams.front() > 0)
8728 Attrs.MaxTeams.front());
8731 int32_t MaxThreadsVal = Attrs.MaxThreads.front();
8741 Attrs.MinThreads.front());
8746 if (MaxThreadsVal > 0 &&
8749 MaxThreadsVal = int32_t(
8750 std::min<int64_t>(int64_t(MaxThreadsVal) + 64,
8753 if (MaxThreadsVal > 0)
8768 Twine DynamicEnvironmentName = KernelName +
"_dynamic_environment";
8769 Constant *DynamicEnvironmentInitializer =
8773 DynamicEnvironmentInitializer, DynamicEnvironmentName,
8775 DL.getDefaultGlobalsAddressSpace());
8779 DynamicEnvironmentGV->
getType() == DynamicEnvironmentPtr
8780 ? DynamicEnvironmentGV
8782 DynamicEnvironmentPtr);
8785 ConfigurationEnvironment, {
8786 UseGenericStateMachineVal,
8787 MayUseNestedParallelismVal,
8796 KernelEnvironment, {
8797 ConfigurationEnvironmentInitializer,
8801 std::string KernelEnvironmentName =
8802 (KernelName +
"_kernel_environment").str();
8805 KernelEnvironmentInitializer, KernelEnvironmentName,
8807 DL.getDefaultGlobalsAddressSpace());
8810 return KernelEnvironmentGV->
getType() == KernelEnvironmentPtr
8811 ? KernelEnvironmentGV
8813 KernelEnvironmentPtr);
8820 if (!KernelEnvironment)
8828 omp::RuntimeFunction::OMPRTL___kmpc_target_init);
8830 Value *KernelLaunchEnvironment =
8833 KernelLaunchEnvironment =
8834 KernelLaunchEnvironment->
getType() == KernelLaunchEnvParamTy
8835 ? KernelLaunchEnvironment
8836 :
Builder.CreateAddrSpaceCast(KernelLaunchEnvironment,
8837 KernelLaunchEnvParamTy);
8839 Fn, {KernelEnvironment, KernelLaunchEnvironment});
8851 auto *UI =
Builder.CreateUnreachable();
8857 Builder.SetInsertPoint(WorkerExitBB);
8861 Builder.SetInsertPoint(CheckBBTI);
8862 Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
8864 CheckBBTI->eraseFromParent();
8865 UI->eraseFromParent();
8873 int32_t TeamsReductionDataSize) {
8878 omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
8882 if (!TeamsReductionDataSize)
8888 const std::string DebugPrefix =
"_debug__";
8890 KernelName = KernelName.
drop_back(DebugPrefix.length());
8891 auto *KernelEnvironmentGV =
8892 M.getNamedGlobal((KernelName +
"_kernel_environment").str());
8893 assert(KernelEnvironmentGV &&
"Expected kernel environment global\n");
8894 auto *KernelEnvironmentInitializer = KernelEnvironmentGV->getInitializer();
8896 KernelEnvironmentInitializer,
8897 ConstantInt::get(Int32, TeamsReductionDataSize), {0, 7});
8898 KernelEnvironmentGV->setInitializer(NewInitializer);
8903 if (
Kernel.hasFnAttribute(Name)) {
8904 int32_t OldLimit =
Kernel.getFnAttributeAsParsedInteger(Name);
8910std::pair<int32_t, int32_t>
8912 int32_t ThreadLimit =
8913 Kernel.getFnAttributeAsParsedInteger(
"omp_target_thread_limit");
8916 const auto &Attr =
Kernel.getFnAttribute(
"amdgpu-flat-work-group-size");
8917 if (!Attr.isValid() || !Attr.isStringAttribute())
8918 return {0, ThreadLimit};
8919 auto [LBStr, UBStr] = Attr.getValueAsString().split(
',');
8922 return {0, ThreadLimit};
8923 UB = ThreadLimit ? std::min(ThreadLimit, UB) : UB;
8931 return {0, ThreadLimit ? std::min(ThreadLimit, UB) : UB};
8933 return {0, ThreadLimit};
8939 Kernel.addFnAttr(
"omp_target_thread_limit", std::to_string(UB));
8942 Kernel.addFnAttr(
"amdgpu-flat-work-group-size",
8950std::pair<int32_t, int32_t>
8953 return {0,
Kernel.getFnAttributeAsParsedInteger(
"omp_target_num_teams")};
8957 int32_t LB, int32_t UB) {
8965 Kernel.addFnAttr(
"omp_target_num_teams", std::to_string(LB));
8968void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
8977 else if (
T.isNVPTX())
8979 else if (
T.isSPIRV())
8985 StringRef EntryFnIDName) {
8986 if (
Config.isTargetDevice()) {
8987 assert(OutlinedFn &&
"The outlined function must exist if embedded");
8991 return new GlobalVariable(
8996Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(
Function *OutlinedFn,
8997 StringRef EntryFnName) {
9001 assert(!
M.getGlobalVariable(EntryFnName,
true) &&
9002 "Named kernel already exists?");
9003 return new GlobalVariable(
9016 if (
Config.isTargetDevice() || !
Config.openMPOffloadMandatory()) {
9020 OutlinedFn = *CBResult;
9022 OutlinedFn =
nullptr;
9028 if (!IsOffloadEntry)
9031 std::string EntryFnIDName =
9033 ? std::string(EntryFnName)
9037 EntryFnName, EntryFnIDName);
9045 setOutlinedTargetRegionFunctionAttributes(OutlinedFn);
9046 auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
9047 auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
9049 EntryInfo, EntryAddr, OutlinedFnID,
9051 return OutlinedFnID;
9069 bool IsStandAlone = !BodyGenCB;
9076 MapInfo = &GenMapInfoCB(
Builder.saveIP());
9078 AllocaIP,
Builder.saveIP(), *MapInfo, Info, CustomMapperCB,
9079 true, DeviceAddrCB))
9086 Value *PointerNum =
Builder.getInt32(Info.NumberOfPtrs);
9096 SrcLocInfo, DeviceID,
9103 assert(MapperFunc &&
"MapperFunc missing for standalone target data");
9107 if (Info.HasNoWait) {
9117 if (Info.HasNoWait) {
9121 emitBlock(OffloadContBlock, CurFn,
true);
9127 bool RequiresOuterTargetTask = Info.HasNoWait;
9128 if (!RequiresOuterTargetTask)
9129 cantFail(TaskBodyCB(
nullptr,
nullptr,
9133 {}, RTArgs, Info.HasNoWait));
9136 omp::OMPRTL___tgt_target_data_begin_mapper);
9140 for (
auto DeviceMap : Info.DevicePtrInfoMap) {
9144 Builder.CreateStore(LI, DeviceMap.second.second);
9181 Value *PointerNum =
Builder.getInt32(Info.NumberOfPtrs);
9190 Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,
9213 return emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);
9214 return BeginThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9229 return emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);
9230 return EndThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9233 return emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);
9234 return BeginThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9245 bool IsGPUDistribute) {
9246 assert((IVSize == 32 || IVSize == 64) &&
9247 "IV size is not compatible with the omp runtime");
9249 if (IsGPUDistribute)
9251 ? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_4
9252 : omp::OMPRTL___kmpc_distribute_static_init_4u)
9253 : (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_8
9254 : omp::OMPRTL___kmpc_distribute_static_init_8u);
9256 Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_4
9257 : omp::OMPRTL___kmpc_for_static_init_4u)
9258 : (IVSigned ? omp::OMPRTL___kmpc_for_static_init_8
9259 : omp::OMPRTL___kmpc_for_static_init_8u);
9266 assert((IVSize == 32 || IVSize == 64) &&
9267 "IV size is not compatible with the omp runtime");
9269 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_4
9270 : omp::OMPRTL___kmpc_dispatch_init_4u)
9271 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_8
9272 : omp::OMPRTL___kmpc_dispatch_init_8u);
9279 assert((IVSize == 32 || IVSize == 64) &&
9280 "IV size is not compatible with the omp runtime");
9282 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_4
9283 : omp::OMPRTL___kmpc_dispatch_next_4u)
9284 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_8
9285 : omp::OMPRTL___kmpc_dispatch_next_8u);
9292 assert((IVSize == 32 || IVSize == 64) &&
9293 "IV size is not compatible with the omp runtime");
9295 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_4
9296 : omp::OMPRTL___kmpc_dispatch_fini_4u)
9297 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_8
9298 : omp::OMPRTL___kmpc_dispatch_fini_8u);
9309 DenseMap<
Value *, std::tuple<Value *, unsigned>> &ValueReplacementMap) {
9317 auto GetUpdatedDIVariable = [&](
DILocalVariable *OldVar,
unsigned arg) {
9321 if (NewVar && (arg == NewVar->
getArg()))
9331 auto UpdateDebugRecord = [&](
auto *DR) {
9334 for (
auto Loc : DR->location_ops()) {
9335 auto Iter = ValueReplacementMap.find(
Loc);
9336 if (Iter != ValueReplacementMap.end()) {
9337 DR->replaceVariableLocationOp(
Loc, std::get<0>(Iter->second));
9338 ArgNo = std::get<1>(Iter->second) + 1;
9342 DR->setVariable(GetUpdatedDIVariable(OldVar, ArgNo));
9347 if (DVR->getNumVariableLocationOps() != 1u) {
9348 DVR->setKillLocation();
9351 Value *
Loc = DVR->getVariableLocationOp(0u);
9358 RequiredBB = &DVR->getFunction()->getEntryBlock();
9360 if (RequiredBB && RequiredBB != CurBB) {
9372 UpdateDebugRecord(&DVR);
9373 MoveDebugRecordToCorrectBlock(&DVR);
9376 for (
auto *DVR : DVRsToDelete)
9377 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);
9381 Module *M = Func->getParent();
9384 DB.createQualifiedType(dwarf::DW_TAG_pointer_type,
nullptr);
9385 unsigned ArgNo = Func->arg_size();
9387 NewSP,
"dyn_ptr", ArgNo, NewSP->
getFile(), 0, VoidPtrTy,
9388 false, DINode::DIFlags::FlagArtificial);
9390 Argument *LastArg = Func->getArg(Func->arg_size() - 1);
9391 DB.insertDeclare(LastArg, Var, DB.createExpression(),
Loc,
9413 for (
auto &Arg : Inputs)
9414 ParameterTypes.
push_back(Arg->getType()->isPointerTy()
9418 for (
auto &Arg : Inputs)
9419 ParameterTypes.
push_back(Arg->getType());
9427 auto BB = Builder.GetInsertBlock();
9428 auto M = BB->getModule();
9439 if (TargetCpuAttr.isStringAttribute())
9440 Func->addFnAttr(TargetCpuAttr);
9442 auto TargetFeaturesAttr = ParentFn->
getFnAttribute(
"target-features");
9443 if (TargetFeaturesAttr.isStringAttribute())
9444 Func->addFnAttr(TargetFeaturesAttr);
9449 OMPBuilder.
emitUsed(
"llvm.compiler.used", {ExecMode});
9459 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9463 Builder.SetInsertPoint(EntryBB);
9474 BasicBlock *UserCodeEntryBB = Builder.GetInsertBlock();
9483 splitBB(Builder,
true,
"outlined.body");
9485 CBFunc(Builder.saveIP(), OutlinedBodyBB->
begin(), ExitBB);
9488 Builder.SetInsertPoint(ExitBB);
9496 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9503 Builder.CreateRetVoid();
9507 auto AllocaIP = Builder.saveIP();
9512 const auto &ArgRange =
make_range(Func->arg_begin(), Func->arg_end() - 1);
9544 if (Instr->getFunction() == Func)
9545 Instr->replaceUsesOfWith(
Input, InputCopy);
9551 for (
auto InArg :
zip(Inputs, ArgRange)) {
9553 Argument &Arg = std::get<1>(InArg);
9554 Value *InputCopy =
nullptr;
9557 Arg,
Input, InputCopy, AllocaIP, Builder.saveIP(), ExitBB->
begin());
9560 Builder.restoreIP(*AfterIP);
9561 ValueReplacementMap[
Input] = std::make_tuple(InputCopy, Arg.
getArgNo());
9581 DeferredReplacement.push_back(std::make_pair(
Input, InputCopy));
9588 ReplaceValue(
Input, InputCopy, Func);
9592 for (
auto Deferred : DeferredReplacement)
9593 ReplaceValue(std::get<0>(Deferred), std::get<1>(Deferred), Func);
9596 ValueReplacementMap);
9603 Value *TaskWithPrivates) {
9621 const size_t NumOffloadingArrays,
const int SharedArgsOperandNo) {
9626 assert((!NumOffloadingArrays || PrivatesTy) &&
9627 "PrivatesTy cannot be nullptr when there are offloadingArrays"
9657 Type *TaskPtrTy = OMPBuilder.TaskPtr;
9658 [[maybe_unused]]
Type *TaskTy = OMPBuilder.Task;
9664 ".omp_target_task_proxy_func", M);
9665 Value *ThreadId = ProxyFn->getArg(0);
9666 Value *TaskWithPrivates = ProxyFn->getArg(1);
9667 ThreadId->
setName(
"thread.id");
9668 TaskWithPrivates->
setName(
"task");
9670 bool HasShareds = SharedArgsOperandNo > 0;
9671 bool HasOffloadingArrays = NumOffloadingArrays > 0;
9675 Builder.SetInsertPoint(EntryBB);
9682 if (HasOffloadingArrays) {
9683 assert(TaskTy != TaskWithPrivatesTy &&
9684 "If there are offloading arrays to pass to the target"
9685 "TaskTy cannot be the same as TaskWithPrivatesTy");
9688 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskWithPrivates, 1);
9689 for (
unsigned int i = 0; i < NumOffloadingArrays; ++i)
9691 Builder.CreateStructGEP(PrivatesTy, Privates, i));
9695 auto *ArgStructAlloca =
9697 assert(ArgStructAlloca &&
9698 "Unable to find the alloca instruction corresponding to arguments "
9699 "for extracted function");
9701 std::optional<TypeSize> ArgAllocSize =
9703 assert(ArgStructType && ArgAllocSize &&
9704 "Unable to determine size of arguments for extracted function");
9705 uint64_t StructSize = ArgAllocSize->getFixedValue();
9708 Builder.CreateAlloca(ArgStructType,
nullptr,
"structArg");
9710 Value *SharedsSize = Builder.getInt64(StructSize);
9715 Builder.CreateMemCpy(
9716 NewArgStructAlloca, NewArgStructAlloca->
getAlign(), LoadShared,
9718 KernelLaunchArgs.
push_back(NewArgStructAlloca);
9721 Builder.CreateRetVoid();
9727 return GEP->getSourceElementType();
9729 return Alloca->getAllocatedType();
9753 if (OffloadingArraysToPrivatize.
empty() && DescriptorTypes.
empty())
9754 return OMPIRBuilder.Task;
9757 for (
Value *
V : OffloadingArraysToPrivatize) {
9758 assert(
V->getType()->isPointerTy() &&
9759 "Expected pointer to array to privatize. Got a non-pointer value "
9762 assert(ArrayTy &&
"ArrayType cannot be nullptr");
9769 "struct.task_with_privates");
9784 EntryFnName, Inputs, CBFunc,
9785 ArgAccessorFuncCB, OutlinedFnLoc);
9789 EntryInfo, GenerateOutlinedFunction, IsOffloadEntry, OutlinedFn,
9928 auto OI = std::make_unique<OutlineInfo>();
9929 OI->EntryBB = TargetTaskAllocaBB;
9930 OI->OuterAllocBB = AllocaIP.getNodeParent();
9935 Builder, AllocaIP, ToBeDeleted, TargetTaskAllocaIP,
"global.tid",
false));
9938 Builder.restoreIP(TargetTaskBodyIP);
9939 if (
Error Err = TaskBodyCB(DeviceID, RTLoc, TargetTaskAllocaIP))
9957 bool NeedsTargetTask = HasNoWait && DeviceID;
9958 if (NeedsTargetTask) {
9964 OffloadingArraysToPrivatize.
push_back(V);
9965 OI->ExcludeArgsFromAggregate.push_back(V);
9970 if (!NeedsTargetTask)
9971 NonContiguousDescriptors.clear();
9972 OI->PostOutlineCB = [
this, ToBeDeleted, Dependencies, NeedsTargetTask,
9973 DeviceID, OffloadingArraysToPrivatize,
9974 NonContiguousDescriptors,
9978 "there must be a single user for the outlined function");
9992 const unsigned int NumStaleCIArgs = StaleCI->
arg_size();
9993 bool HasShareds = NumStaleCIArgs > OffloadingArraysToPrivatize.
size() + 1;
9995 NumStaleCIArgs == (OffloadingArraysToPrivatize.
size() + 2)) &&
9996 "Wrong number of arguments for StaleCI when shareds are present");
9997 int SharedArgOperandNo =
9998 HasShareds ? OffloadingArraysToPrivatize.
size() + 1 : 0;
10003 for (
const auto &Descriptor : NonContiguousDescriptors)
10004 DescriptorTypes.
push_back(Descriptor.Storage->getAllocatedType());
10006 *
this, OffloadingArraysToPrivatize, DescriptorTypes);
10009 if (!OffloadingArraysToPrivatize.
empty())
10014 *
this,
Builder, StaleCI, PrivatesTy, TaskWithPrivatesTy,
10015 OffloadingArraysToPrivatize.
size(), SharedArgOperandNo);
10017 LLVM_DEBUG(
dbgs() <<
"Proxy task entry function created: " << *ProxyFn
10020 Builder.SetInsertPoint(StaleCI);
10037 OMPRTL___kmpc_omp_target_task_alloc);
10049 M.getDataLayout().getTypeStoreSize(TaskWithPrivatesTy));
10056 auto *ArgStructAlloca =
10058 assert(ArgStructAlloca &&
10059 "Unable to find the alloca instruction corresponding to arguments "
10060 "for extracted function");
10061 std::optional<TypeSize> ArgAllocSize =
10064 "Unable to determine size of arguments for extracted function");
10065 SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
10084 TaskSize, SharedsSize,
10087 if (NeedsTargetTask) {
10088 assert(DeviceID &&
"Expected non-empty device ID.");
10101 if (!OffloadingArraysToPrivatize.
empty()) {
10103 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskData, 1);
10104 Value *PrivatePointersArray =
nullptr;
10105 for (
unsigned int i = 0; i < OffloadingArraysToPrivatize.
size(); ++i) {
10106 Value *PtrToPrivatize = OffloadingArraysToPrivatize[i];
10113 "ElementType should match ArrayType");
10116 Value *Dst =
Builder.CreateStructGEP(PrivatesTy, Privates, i);
10119 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(ElementType)));
10120 if (PtrToPrivatize == PointersArray)
10121 PrivatePointersArray = Dst;
10126 assert(PrivatePointersArray &&
"missing task-private pointer array");
10128 PrivatesTy, Privates, OffloadingArraysToPrivatize.
size() +
I);
10130 Dst,
Alignment, Descriptor.Storage, Descriptor.Storage->getAlign(),
10131 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(
10132 Descriptor.Storage->getAllocatedType())));
10135 Descriptor.MapIndex);
10140 Value *DepArray =
nullptr;
10141 Value *NumDeps =
nullptr;
10144 NumDeps = Dependencies.
NumDeps;
10145 }
else if (!Dependencies.
Deps.empty()) {
10147 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
10158 if (!NeedsTargetTask) {
10167 ConstantInt::get(
Builder.getInt32Ty(), 0),
10180 }
else if (DepArray) {
10188 {Ident, ThreadID, TaskData, NumDeps, DepArray,
10189 ConstantInt::get(
Builder.getInt32Ty(), 0),
10197 Builder.ClearInsertionPoint();
10200 I->eraseFromParent();
10205 << *(
Builder.GetInsertBlock()) <<
"\n");
10207 << *(
Builder.getModule()) <<
"\n");
10218 CustomMapperCB, IsNonContiguous, DeviceAddrCB))
10241 Builder.restoreIP(IP);
10247 return Builder.saveIP();
10250 bool HasDependencies = !Dependencies.
empty();
10251 bool RequiresOuterTargetTask = HasNoWait || HasDependencies;
10268 if (OutlinedFnID && DeviceID)
10270 EmitTargetCallFallbackCB, KArgs,
10271 DeviceID, RTLoc, TargetTaskAllocaIP);
10279 return EmitTargetCallFallbackCB(OMPBuilder.
Builder.
saveIP());
10286 auto &&EmitTargetCallElse =
10293 if (RequiresOuterTargetTask) {
10300 Dependencies, EmptyRTArgs, HasNoWait);
10302 return EmitTargetCallFallbackCB(Builder.saveIP());
10305 Builder.restoreIP(AfterIP);
10309 auto &&EmitTargetCallThen =
10313 Info.HasNoWait = HasNoWait;
10318 AllocaIP, Builder.saveIP(), Info, RTArgs, MapInfo, CustomMapperCB,
10324 for (
auto [DefaultVal, RuntimeVal] :
10326 NumTeamsC.
push_back(RuntimeVal ? RuntimeVal
10327 : Builder.getInt32(DefaultVal));
10331 auto InitMaxThreadsClause = [&Builder](
Value *
Clause) {
10333 Clause = Builder.CreateIntCast(
Clause, Builder.getInt32Ty(),
10337 auto CombineMaxThreadsClauses = [&Builder](
Value *
Clause,
Value *&Result) {
10340 Result ? Builder.CreateSelect(Builder.CreateICmpULT(Result,
Clause),
10348 Value *MaxThreadsClause =
10350 ? InitMaxThreadsClause(RuntimeAttrs.
MaxThreads.front())
10353 for (
auto [TeamsVal, TargetVal] :
zip_equal(
10355 Value *TeamsThreadLimitClause = InitMaxThreadsClause(TeamsVal);
10356 Value *NumThreads = InitMaxThreadsClause(TargetVal);
10358 CombineMaxThreadsClauses(TeamsThreadLimitClause, NumThreads);
10359 CombineMaxThreadsClauses(MaxThreadsClause, NumThreads);
10361 NumThreadsC.
push_back(NumThreads ? NumThreads : Builder.getInt32(0));
10364 unsigned NumTargetItems = Info.NumberOfPtrs;
10365 Value *RTLoc = RTLocOverride;
10376 Builder.getInt64Ty(),
10378 : Builder.getInt64(0);
10382 DynCGroupMem = Builder.getInt32(0);
10385 NumTargetItems, RTArgs, TripCount, NumTeamsC, NumThreadsC, DynCGroupMem,
10386 HasNoWait,
false,
false,
10387 DynCGroupMemFallback);
10394 if (RequiresOuterTargetTask)
10396 RTLoc, AllocaIP, Dependencies,
10397 KArgs.
RTArgs, Info.HasNoWait);
10400 Builder, OutlinedFnID, EmitTargetCallFallbackCB, KArgs,
10401 RuntimeAttrs.
DeviceID, RTLoc, AllocaIP);
10404 Builder.restoreIP(AfterIP);
10412 return EmitTargetCallElse(AllocaIP, Builder.saveIP(), DeallocBlocks);
10416 return EmitTargetCallThen(AllocaIP, Builder.saveIP(), DeallocBlocks);
10418 return OMPBuilder.
emitIfClause(IfCond, EmitTargetCallThen, EmitTargetCallElse,
10432 bool HasNowait,
Value *DynCGroupMem,
10434 Value *RTLocOverride) {
10439 Builder.restoreIP(CodeGenIP);
10447 *
this,
Builder, IsOffloadEntry, EntryInfo, DefaultAttrs, OutlinedFn,
10448 OutlinedFnID, Inputs, CBFunc, ArgAccessorFuncCB, OutlinedFnLoc))
10454 if (!
Config.isTargetDevice()) {
10456 *
this,
Builder, RTLocOverride, AllocaIP, DeallocBlocks, Info,
10457 DefaultAttrs, RuntimeAttrs, IfCond, OutlinedFn, OutlinedFnID,
10458 Inputs, GenMapInfoCB, CustomMapperCB, Dependencies, HasNowait,
10459 DynCGroupMem, DynCGroupMemFallback))
10475 return OS.
str().str();
10480 return OpenMPIRBuilder::getNameWithSeparators(Parts,
Config.firstSeparator(),
10486 auto &Elem = *
InternalVars.try_emplace(Name,
nullptr).first;
10488 assert(Elem.second->getValueType() == Ty &&
10489 "OMP internal variable has different type than requested");
10502 :
M.getTargetTriple().isAMDGPU()
10504 :
DL.getDefaultGlobalsAddressSpace();
10505 auto Linkage = this->
M.getTargetTriple().isWasm()
10513 const llvm::Align PtrAlign =
DL.getPointerABIAlignment(AddressSpaceVal);
10514 GV->setAlignment(std::max(TypeAlign, PtrAlign));
10518 return Elem.second;
10521Value *OpenMPIRBuilder::getOMPCriticalRegionLock(
StringRef CriticalName) {
10522 std::string Prefix =
Twine(
"gomp_critical_user_", CriticalName).
str();
10523 std::string Name = getNameWithSeparators({Prefix,
"var"},
".",
".");
10534 return SizePtrToInt;
10539 std::string VarName) {
10547 return MaptypesArrayGlobal;
10552 unsigned NumOperands,
10561 ArrI8PtrTy,
nullptr,
".offload_baseptrs");
10565 ArrI64Ty,
nullptr,
".offload_sizes");
10576 int64_t DeviceID,
unsigned NumOperands) {
10582 Value *ArgsBaseGEP =
10584 {Builder.getInt32(0), Builder.getInt32(0)});
10587 {Builder.getInt32(0), Builder.getInt32(0)});
10588 Value *ArgSizesGEP =
10590 {Builder.getInt32(0), Builder.getInt32(0)});
10594 Builder.getInt32(NumOperands),
10595 ArgsBaseGEP, ArgsGEP, ArgSizesGEP,
10596 MaptypesArg, MapnamesArg, NullPtr});
10603 assert((!ForEndCall || Info.separateBeginEndCalls()) &&
10604 "expected region end call to runtime only when end call is separate");
10606 auto VoidPtrTy = UnqualPtrTy;
10607 auto VoidPtrPtrTy = UnqualPtrTy;
10609 auto Int64PtrTy = UnqualPtrTy;
10612 if (!Info.NumberOfPtrs) {
10624 Info.RTArgs.BasePointersArray,
10627 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
10631 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
10635 ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd
10636 : Info.RTArgs.MapTypesArray,
10642 if (!Info.EmitDebug)
10646 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,
10651 if (!Info.HasMapper)
10655 Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);
10676 "struct.descriptor_dim");
10678 enum { OffsetFD = 0, CountFD, StrideFD };
10682 for (
unsigned I = 0, L = 0, E = NonContigInfo.
Dims.
size();
I < E; ++
I) {
10685 if (NonContigInfo.
Dims[
I] == 1)
10690 Builder.CreateAlloca(ArrayTy,
nullptr,
"dims");
10691 Info.RTArgs.NonContiguousDescriptors.push_back({
I, DimsAddr});
10692 Builder.restoreIP(CodeGenIP);
10693 for (
unsigned II = 0, EE = NonContigInfo.
Dims[
I];
II < EE; ++
II) {
10694 unsigned RevIdx = EE -
II - 1;
10698 Value *OffsetLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);
10700 NonContigInfo.
Offsets[L][RevIdx], OffsetLVal,
10701 M.getDataLayout().getPrefTypeAlign(OffsetLVal->
getType()));
10703 Value *CountLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);
10705 NonContigInfo.
Counts[L][RevIdx], CountLVal,
10706 M.getDataLayout().getPrefTypeAlign(CountLVal->
getType()));
10708 Value *StrideLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);
10710 NonContigInfo.
Strides[L][RevIdx], StrideLVal,
10711 M.getDataLayout().getPrefTypeAlign(CountLVal->
getType()));
10714 Builder.restoreIP(CodeGenIP);
10715 Value *DAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
10716 DimsAddr,
Builder.getPtrTy());
10719 Info.RTArgs.PointersArray, 0,
I);
10721 DAddr,
P,
M.getDataLayout().getPrefTypeAlign(
Builder.getPtrTy()));
10726void OpenMPIRBuilder::emitUDMapperArrayInitOrDel(
10730 StringRef Prefix = IsInit ?
".init" :
".del";
10736 Builder.CreateICmpSGT(
Size, Builder.getInt64(1),
"omp.arrayinit.isarray");
10737 Value *DeleteBit = Builder.CreateAnd(
10740 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10741 OpenMPOffloadMappingFlags::OMP_MAP_DELETE)));
10746 Value *BaseIsBegin = Builder.CreateICmpNE(
Base, Begin);
10747 Cond = Builder.CreateOr(IsArray, BaseIsBegin);
10748 DeleteCond = Builder.CreateIsNull(
10753 DeleteCond =
Builder.CreateIsNotNull(
10769 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10770 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10771 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10772 MapTypeArg =
Builder.CreateOr(
10775 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10776 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT)));
10780 Value *OffloadingArgs[] = {MapperHandle,
Base, Begin,
10781 ArraySize, MapTypeArg, MapName};
10792 bool PreserveMemberOfFlags,
bool PropagatePresentToPointeeStorage,
10793 bool PropagatePresentToNonPointeeStorage) {
10807 MapperFn->
addFnAttr(Attribute::NoInline);
10808 MapperFn->
addFnAttr(Attribute::NoUnwind);
10819 Builder.SetInsertPoint(EntryBB);
10834 Value *PtrBegin = BeginIn;
10840 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn,
Size,
10841 MapType, MapName, ElementSize, HeadBB,
10852 Builder.CreateICmpEQ(PtrBegin, PtrEnd,
"omp.arraymap.isempty");
10853 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
10859 Builder.CreatePHI(PtrBegin->
getType(), 2,
"omp.arraymap.ptrcurrent");
10860 PtrPHI->addIncoming(PtrBegin, HeadBB);
10865 return Info.takeError();
10871 Value *ShiftedPreviousSize =
nullptr;
10935 auto pushComponent = [&](
Value *CurBaseArg,
Value *CurBeginArg,
10937 uint64_t RawType,
bool HasAttachPtrFlag,
10940 constexpr uint64_t MemberOfMask =
10941 static_cast<uint64_t
>(OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF);
10942 constexpr uint64_t AttachBit =
10943 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10944 OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
10945 constexpr uint64_t PtrAndObjBit =
10946 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10947 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ);
10949 Value *MemberMapType;
10950 if (PreserveMemberOfFlags || (RawType & AttachBit) || HasAttachPtrFlag) {
10951 if (RawType & MemberOfMask)
10952 MemberMapType =
Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10954 MemberMapType = OriMapType;
10956 MemberMapType =
Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10974 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10975 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10976 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10986 Builder.CreateCondBr(IsAlloc, AllocBB, AllocElseBB);
10992 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10993 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10994 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11000 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11001 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11002 Builder.CreateCondBr(IsTo, ToBB, ToElseBB);
11008 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11009 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11015 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11016 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11017 Builder.CreateCondBr(IsFrom, FromBB, EndBB);
11023 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11024 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11032 CurMapType->
addIncoming(MemberMapType, ToElseBB);
11071 uint64_t ModifierBits =
11072 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11073 OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS |
11074 OpenMPOffloadMappingFlags::OMP_MAP_DELETE |
11075 OpenMPOffloadMappingFlags::OMP_MAP_CLOSE);
11076 bool IsPresentEligibleStorage = !(RawType & (AttachBit | PtrAndObjBit));
11077 bool PropagatePresent =
11078 IsPresentEligibleStorage &&
11079 (HasAttachPtrFlag ? PropagatePresentToPointeeStorage
11080 : PropagatePresentToNonPointeeStorage);
11081 if (PropagatePresent)
11083 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11084 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11085 Value *ImportedModifierBits =
11088 CurMapType, ImportedModifierBits,
"omp.maptype.with.modifiers");
11093 Value *FinalMapType =
11094 (RawType & AttachBit) ? CurMapType : CurMapTypeWithModifiers;
11096 Value *OffloadingArgs[] = {MapperHandle, CurBaseArg, CurBeginArg,
11097 CurSizeArg, FinalMapType, CurNameArg};
11098 if (ChildMapperFn) {
11115 unsigned FirstStaticIdx = 0;
11116 if (Info->LeadingParentCond) {
11117 assert(PreserveMemberOfFlags &&
11118 "conditional leading parent requires pre-shaped MEMBER_OF flags");
11119 assert(!Info->BasePointers.empty() &&
"no leading parent component");
11124 Builder.CreateCondBr(Info->LeadingParentCond, PushBB, ContBB);
11126 Value *CurNameArg = Info->Names.size()
11130 Info->BasePointers[0], Info->Pointers[0], Info->Sizes[0], CurNameArg,
11131 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11133 Info->HasAttachPtr[0],
nullptr);
11137 FirstStaticIdx = 1;
11145 Value *OffloadingArgs[] = {MapperHandle};
11149 if (Info->LeadingParentCond)
11150 PreviousSize =
Builder.CreateSub(PreviousSize,
Builder.getInt64(1));
11151 ShiftedPreviousSize =
11155 for (
unsigned I = FirstStaticIdx;
I < Info->BasePointers.size(); ++
I) {
11156 Value *CurNameArg = Info->Names.size()
11160 if (!ChildMapperFn)
11162 LastBB = pushComponent(
11163 Info->BasePointers[
I], Info->Pointers[
I], Info->Sizes[
I], CurNameArg,
11164 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11166 Info->HasAttachPtr[
I], *ChildMapperFn);
11183 Entry[0], Entry[1], Entry[2],
11185 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11195 LastBB =
Builder.GetInsertBlock();
11201 "omp.arraymap.next");
11202 PtrPHI->addIncoming(PtrNext, LastBB);
11203 Value *IsDone =
Builder.CreateICmpEQ(PtrNext, PtrEnd,
"omp.arraymap.isdone");
11205 Builder.CreateCondBr(IsDone, ExitBB, BodyBB);
11210 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn,
Size,
11211 MapType, MapName, ElementSize, DoneBB,
11224 bool IsNonContiguous,
11228 Info.clearArrayInfo();
11231 if (Info.NumberOfPtrs == 0)
11240 Info.RTArgs.BasePointersArray =
Builder.CreateAlloca(
11241 PointerArrayType,
nullptr,
".offload_baseptrs");
11243 Info.RTArgs.PointersArray =
Builder.CreateAlloca(
11244 PointerArrayType,
nullptr,
".offload_ptrs");
11246 PointerArrayType,
nullptr,
".offload_mappers");
11247 Info.RTArgs.MappersArray = MappersArray;
11254 ConstantInt::get(Int64Ty, 0));
11256 for (
unsigned I = 0, E = CombinedInfo.
Sizes.
size();
I < E; ++
I) {
11257 bool IsNonContigEntry =
11259 (
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11261 OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG) != 0);
11264 if (IsNonContigEntry) {
11266 "Index must be in-bounds for NON_CONTIG Dims array");
11268 assert(DimCount > 0 &&
"NON_CONTIG DimCount must be > 0");
11269 ConstSizes[
I] = ConstantInt::get(Int64Ty, DimCount);
11274 ConstSizes[
I] = CI;
11278 RuntimeSizes.
set(
I);
11281 if (RuntimeSizes.
all()) {
11283 Info.RTArgs.SizesArray =
Builder.CreateAlloca(
11284 SizeArrayType,
nullptr,
".offload_sizes");
11290 auto *SizesArrayGbl =
11295 if (!RuntimeSizes.
any()) {
11296 Info.RTArgs.SizesArray = SizesArrayGbl;
11298 unsigned IndexSize =
M.getDataLayout().getIndexSizeInBits(0);
11299 Align OffloadSizeAlign =
M.getDataLayout().getABIIntegerTypeAlignment(64);
11302 SizeArrayType,
nullptr,
".offload_sizes");
11306 Buffer,
M.getDataLayout().getPrefTypeAlign(Buffer->
getType()),
11307 SizesArrayGbl, OffloadSizeAlign,
11312 Info.RTArgs.SizesArray = Buffer;
11320 for (
auto mapFlag : CombinedInfo.
Types)
11322 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11326 Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
11332 Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
11333 Info.EmitDebug =
true;
11335 Info.RTArgs.MapNamesArray =
11337 Info.EmitDebug =
false;
11342 if (Info.separateBeginEndCalls()) {
11343 bool EndMapTypesDiffer =
false;
11344 for (uint64_t &
Type : Mapping) {
11345 if (
Type &
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11346 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT)) {
11347 Type &= ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11348 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11349 EndMapTypesDiffer =
true;
11352 if (EndMapTypesDiffer) {
11354 Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
11359 for (
unsigned I = 0;
I < Info.NumberOfPtrs; ++
I) {
11362 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.BasePointersArray,
11364 Builder.CreateAlignedStore(BPVal, BP,
11365 M.getDataLayout().getPrefTypeAlign(PtrTy));
11367 if (Info.requiresDevicePointerInfo()) {
11369 CodeGenIP =
Builder.saveIP();
11371 Info.DevicePtrInfoMap[BPVal] = {BP,
Builder.CreateAlloca(PtrTy)};
11374 DeviceAddrCB(
I, Info.DevicePtrInfoMap[BPVal].second);
11376 Info.DevicePtrInfoMap[BPVal] = {BP, BP};
11378 DeviceAddrCB(
I, BP);
11384 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray, 0,
11387 Builder.CreateAlignedStore(PVal,
P,
11388 M.getDataLayout().getPrefTypeAlign(PtrTy));
11390 if (RuntimeSizes.
test(
I)) {
11392 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
11398 S,
M.getDataLayout().getPrefTypeAlign(PtrTy));
11401 unsigned IndexSize =
M.getDataLayout().getIndexSizeInBits(0);
11404 auto CustomMFunc = CustomMapperCB(
I);
11406 return CustomMFunc.takeError();
11408 MFunc =
Builder.CreatePointerCast(*CustomMFunc, PtrTy);
11411 PointerArrayType, MappersArray,
11414 MFunc, MAddr,
M.getDataLayout().getPrefTypeAlign(MAddr->
getType()));
11418 Info.NumberOfPtrs == 0)
11435 Builder.ClearInsertionPoint();
11466 auto CondConstant = CI->getSExtValue();
11468 return ThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
11470 return ElseGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
11480 Builder.CreateCondBr(
Cond, ThenBlock, ElseBlock);
11483 if (
Error Err = ThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks)) {
11493 if (
Error Err = ElseGen(AllocaIP,
Builder.saveIP(), DeallocBlocks)) {
11511 assert(
X.Var->getType()->isPointerTy() &&
11512 "OMP Atomic expects a pointer to target memory");
11513 Type *XElemTy =
X.ElemTy;
11516 "OMP atomic read expected a scalar type");
11518 Value *XRead =
nullptr;
11522 Builder.CreateLoad(XElemTy,
X.Var,
X.IsVolatile,
"omp.atomic.read");
11531 unsigned LoadSize =
DL.getTypeStoreSize(XElemTy);
11534 OldVal->
getAlign(),
true , AllocaIP,
X.Var);
11536 XRead = AtomicLoadRes.first;
11543 Builder.CreateLoad(IntCastTy,
X.Var,
X.IsVolatile,
"omp.atomic.load");
11546 XRead =
Builder.CreateBitCast(XLoad, XElemTy,
"atomic.flt.cast");
11548 XRead =
Builder.CreateIntToPtr(XLoad, XElemTy,
"atomic.ptr.cast");
11551 Builder.CreateStore(XRead, V.Var, V.IsVolatile);
11562 assert(
X.Var->getType()->isPointerTy() &&
11563 "OMP Atomic expects a pointer to target memory");
11564 Type *XElemTy =
X.ElemTy;
11567 "OMP atomic write expected a scalar type");
11575 unsigned LoadSize =
DL.getTypeStoreSize(XElemTy);
11578 OldVal->
getAlign(),
true , AllocaIP,
X.Var);
11586 Builder.CreateBitCast(Expr, IntCastTy,
"atomic.src.int.cast");
11597 AtomicUpdateCallbackTy &UpdateOp,
bool IsXBinopExpr,
11598 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11604 Type *XTy =
X.Var->getType();
11606 "OMP Atomic expects a pointer to target memory");
11607 Type *XElemTy =
X.ElemTy;
11610 "OMP atomic update expected a scalar or struct type");
11614 AllocaIP,
X.Var,
X.ElemTy, Expr, AO, RMWOp, UpdateOp,
X.IsVolatile,
11615 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11617 return AtomicResult.takeError();
11622Value *OpenMPIRBuilder::emitRMWOpAsInstruction(
Value *Src1,
Value *Src2,
11626 return Builder.CreateAdd(Src1, Src2);
11628 return Builder.CreateSub(Src1, Src2);
11630 return Builder.CreateAnd(Src1, Src2);
11632 return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
11634 return Builder.CreateOr(Src1, Src2);
11636 return Builder.CreateXor(Src1, Src2);
11638 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, Src1, Src2);
11640 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, Src1, Src2);
11642 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, Src1, Src2);
11644 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, Src1, Src2);
11646 return Builder.CreateFAdd(Src1, Src2);
11648 return Builder.CreateFSub(Src1, Src2);
11650 return Builder.CreateMaxNum(Src1, Src2);
11652 return Builder.CreateMinNum(Src1, Src2);
11654 return Builder.CreateMaximum(Src1, Src2);
11656 return Builder.CreateMinimum(Src1, Src2);
11685Expected<std::pair<Value *, Value *>> OpenMPIRBuilder::emitAtomicUpdate(
11688 AtomicUpdateCallbackTy &UpdateOp,
bool VolatileX,
bool IsXBinopExpr,
11689 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11691 bool emitRMWOp =
false;
11708 emitRMWOp = XElemTy;
11712 emitRMWOp = (IsXBinopExpr && XElemTy);
11720 std::pair<Value *, Value *> Res;
11722 AtomicRMWInst *RMWInst =
11723 Builder.CreateAtomicRMW(RMWOp,
X, Expr, llvm::MaybeAlign(), AO);
11724 if (IsIgnoreDenormalMode)
11725 RMWInst->
setMetadata(llvm::LLVMContext::MD_atomic_ignore_denormal_mode,
11727 if (
T.isAMDGPU()) {
11728 if (!IsFineGrainedMemory)
11729 RMWInst->
setMetadata(
"amdgpu.no.fine.grained.memory",
11731 if (!IsRemoteMemory)
11735 Res.first = RMWInst;
11740 Res.second = Res.first;
11742 Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
11745 Builder.CreateLoad(XElemTy,
X,
X->getName() +
".atomic.load");
11751 OpenMPIRBuilder::AtomicInfo atomicInfo(
11753 OldVal->
getAlign(),
true , AllocaIP,
X);
11754 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11757 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11764 AllocaInst *NewAtomicAddr =
Builder.CreateAlloca(XElemTy);
11765 NewAtomicAddr->
setName(
X->getName() +
"x.new.val");
11766 Builder.SetInsertPoint(ContBB);
11768 PHI->addIncoming(AtomicLoadRes.first, CurBB);
11770 Expected<Value *> CBResult = UpdateOp(OldExprVal,
Builder);
11773 Value *Upd = *CBResult;
11774 Builder.CreateStore(Upd, NewAtomicAddr);
11777 auto Result = atomicInfo.EmitAtomicCompareExchangeLibcall(
11778 AtomicLoadRes.second, NewAtomicAddr, AO, Failure);
11779 LoadInst *PHILoad =
Builder.CreateLoad(XElemTy,
Result.first);
11780 PHI->addIncoming(PHILoad,
Builder.GetInsertBlock());
11783 Res.first = OldExprVal;
11786 if (UnreachableInst *ExitTI =
11789 Builder.SetInsertPoint(ExitBB);
11791 Builder.SetInsertPoint(ExitTI);
11794 IntegerType *IntCastTy =
11797 Builder.CreateLoad(IntCastTy,
X,
X->getName() +
".atomic.load");
11807 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11814 AllocaInst *NewAtomicAddr =
Builder.CreateAlloca(XElemTy);
11815 NewAtomicAddr->
setName(
X->getName() +
"x.new.val");
11816 Builder.SetInsertPoint(ContBB);
11818 PHI->addIncoming(OldVal, CurBB);
11823 OldExprVal =
Builder.CreateBitCast(
PHI, XElemTy,
11824 X->getName() +
".atomic.fltCast");
11826 OldExprVal =
Builder.CreateIntToPtr(
PHI, XElemTy,
11827 X->getName() +
".atomic.ptrCast");
11831 Expected<Value *> CBResult = UpdateOp(OldExprVal,
Builder);
11834 Value *Upd = *CBResult;
11835 Builder.CreateStore(Upd, NewAtomicAddr);
11836 LoadInst *DesiredVal =
Builder.CreateLoad(IntCastTy, NewAtomicAddr);
11840 X,
PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
11841 Result->setVolatile(VolatileX);
11842 Value *PreviousVal =
Builder.CreateExtractValue(Result, 0);
11843 Value *SuccessFailureVal =
Builder.CreateExtractValue(Result, 1);
11844 PHI->addIncoming(PreviousVal,
Builder.GetInsertBlock());
11845 Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
11847 Res.first = OldExprVal;
11851 if (UnreachableInst *ExitTI =
11854 Builder.SetInsertPoint(ExitBB);
11856 Builder.SetInsertPoint(ExitTI);
11867 bool UpdateExpr,
bool IsPostfixUpdate,
bool IsXBinopExpr,
11868 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11873 Type *XTy =
X.Var->getType();
11875 "OMP Atomic expects a pointer to target memory");
11876 Type *XElemTy =
X.ElemTy;
11879 "OMP atomic capture expected a scalar or struct type");
11886 AllocaIP,
X.Var,
X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
X.IsVolatile,
11887 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11890 Value *CapturedVal =
11891 (IsPostfixUpdate ? AtomicResult->first : AtomicResult->second);
11892 Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
11901 bool IsFailOnly,
bool IsWeak) {
11905 IsPostfixUpdate, IsFailOnly, Failure, IsWeak);
11917 assert(
X.Var->getType()->isPointerTy() &&
11918 "OMP atomic expects a pointer to target memory");
11921 assert(V.Var->getType()->isPointerTy() &&
"v.var must be of pointer type");
11922 assert(V.ElemTy ==
X.ElemTy &&
"x and v must be of same type");
11925 bool IsInteger = E->getType()->isIntegerTy();
11927 if (
Op == OMPAtomicCompareOp::EQ) {
11930 Value *OldValue =
nullptr;
11931 Value *SuccessOrFail =
nullptr;
11969 X.Var->getName() +
".atomic.load");
11975 Value *EIsNaN =
Builder.CreateFCmpUNO(E, E,
"atomic.e.isnan");
11976 Value *XIsNaN =
Builder.CreateFCmpUNO(XFP, XFP,
"atomic.x.isnan");
11977 Value *EitherNaN =
Builder.CreateOr(EIsNaN, XIsNaN,
"atomic.either.nan");
11982 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11986 M.getContext(),
X.Var->getName() +
".atomic.nan",
F, ExitBB);
11988 M.getContext(),
X.Var->getName() +
".atomic.notnan",
F, ExitBB);
11990 M.getContext(),
X.Var->getName() +
".atomic.zero",
F, ExitBB);
11992 M.getContext(),
X.Var->getName() +
".atomic.normal",
F, ExitBB);
11996 Builder.SetInsertPoint(CurBB);
11997 Builder.CreateCondBr(EitherNaN, NaNBB, NotNaNBB);
12000 Builder.SetInsertPoint(NaNBB);
12004 Builder.SetInsertPoint(NotNaNBB);
12007 X.Var->getName() +
".atomic.xiszero");
12009 "atomic.e.iszero");
12010 Value *BothZero =
Builder.CreateAnd(XIsZero, EIsZero,
"atomic.both.zero");
12011 Builder.CreateCondBr(BothZero, ZeroBB, NormalBB);
12014 Builder.SetInsertPoint(ZeroBB);
12016 X.Var, XCurr, DBCast,
MaybeAlign(), AO, Failure);
12018 Value *OldZero =
Builder.CreateExtractValue(ResZero, 0);
12019 Value *OkZero =
Builder.CreateExtractValue(ResZero, 1);
12023 Builder.SetInsertPoint(NormalBB);
12025 X.Var, EBCast, DBCast,
MaybeAlign(), AO, Failure);
12027 Value *OldNormal =
Builder.CreateExtractValue(ResNormal, 0);
12028 Value *OkNormal =
Builder.CreateExtractValue(ResNormal, 1);
12034 Builder.CreatePHI(IntCastTy, 3,
X.Var->getName() +
".atomic.old");
12039 X.Var->getName() +
".atomic.ok");
12046 Builder.SetInsertPoint(ExitBB);
12051 OldValue =
Builder.CreateBitCast(OldIntPHI,
X.ElemTy,
12052 X.Var->getName() +
".atomic.old.fp");
12053 SuccessOrFail = SuccessPHI;
12061 Result =
Builder.CreateAtomicCmpXchg(
X.Var, EBCast, DBCast,
12067 Result->setWeak(IsWeak);
12070 OldValue =
Builder.CreateExtractValue(Result, 0);
12072 OldValue =
Builder.CreateBitCast(OldValue,
X.ElemTy);
12074 "OldValue and V must be of same type");
12075 if (IsPostfixUpdate) {
12076 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12078 SuccessOrFail =
Builder.CreateExtractValue(Result, 1);
12082 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
12084 CurBBTI,
X.Var->getName() +
".atomic.exit");
12090 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12092 Builder.SetInsertPoint(ContBB);
12093 Builder.CreateStore(OldValue, V.Var);
12099 Builder.SetInsertPoint(ExitBB);
12101 Builder.SetInsertPoint(ExitTI);
12104 Value *CapturedValue =
12105 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12106 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12112 assert(R.Var->getType()->isPointerTy() &&
12113 "r.var must be of pointer type");
12114 assert(R.ElemTy->isIntegerTy() &&
"r must be of integral type");
12116 Value *SuccessFailureVal =
12117 Builder.CreateExtractValue(Result, 1);
12118 Value *ResultCast =
12119 R.IsSigned ?
Builder.CreateSExt(SuccessFailureVal, R.ElemTy)
12120 :
Builder.CreateZExt(SuccessFailureVal, R.ElemTy);
12121 Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
12130 "OldValue and V must be of same type");
12131 if (IsPostfixUpdate) {
12132 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12137 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
12139 CurBBTI,
X.Var->getName() +
".atomic.exit");
12145 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12147 Builder.SetInsertPoint(ContBB);
12148 Builder.CreateStore(OldValue, V.Var);
12154 Builder.SetInsertPoint(ExitBB);
12156 Builder.SetInsertPoint(ExitTI);
12159 Value *CapturedValue =
12160 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12161 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12167 assert(R.Var->getType()->isPointerTy() &&
12168 "r.var must be of pointer type");
12169 assert(R.ElemTy->isIntegerTy() &&
"r must be of integral type");
12171 Value *ResultCast = R.IsSigned
12172 ?
Builder.CreateSExt(SuccessOrFail, R.ElemTy)
12173 :
Builder.CreateZExt(SuccessOrFail, R.ElemTy);
12174 Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
12178 assert((
Op == OMPAtomicCompareOp::MAX ||
Op == OMPAtomicCompareOp::MIN) &&
12179 "Op should be either max or min at this point");
12180 assert(!IsFailOnly &&
"IsFailOnly is only valid when the comparison is ==");
12191 if (IsXBinopExpr) {
12220 Value *CapturedValue =
nullptr;
12221 if (IsPostfixUpdate) {
12222 CapturedValue = OldValue;
12247 Value *NonAtomicCmp =
Builder.CreateCmp(Pred, OldValue, E);
12248 CapturedValue =
Builder.CreateSelect(NonAtomicCmp, E, OldValue);
12250 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12272 if (&OuterAllocaBB ==
Builder.GetInsertBlock()) {
12299 bool SubClausesPresent =
12300 (NumTeamsLower || NumTeamsUpper || ThreadLimit || IfExpr);
12302 if (!
Config.isTargetDevice() && SubClausesPresent) {
12303 assert((NumTeamsLower ==
nullptr || NumTeamsUpper !=
nullptr) &&
12304 "if lowerbound is non-null, then upperbound must also be non-null "
12305 "for bounds on num_teams");
12307 if (NumTeamsUpper ==
nullptr)
12308 NumTeamsUpper =
Builder.getInt32(0);
12310 if (NumTeamsLower ==
nullptr)
12311 NumTeamsLower = NumTeamsUpper;
12315 "argument to if clause must be an integer value");
12319 IfExpr =
Builder.CreateICmpNE(IfExpr,
12320 ConstantInt::get(IfExpr->
getType(), 0));
12321 NumTeamsUpper =
Builder.CreateSelect(
12322 IfExpr, NumTeamsUpper,
Builder.getInt32(1),
"numTeamsUpper");
12325 NumTeamsLower =
Builder.CreateSelect(
12326 IfExpr, NumTeamsLower,
Builder.getInt32(1),
"numTeamsLower");
12329 if (ThreadLimit ==
nullptr)
12330 ThreadLimit =
Builder.getInt32(0);
12334 Value *NumTeamsLowerInt32 =
12336 Value *NumTeamsUpperInt32 =
12338 Value *ThreadLimitInt32 =
12345 {Ident, ThreadNum, NumTeamsLowerInt32, NumTeamsUpperInt32,
12346 ThreadLimitInt32});
12351 if (
Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12354 auto OI = std::make_unique<OutlineInfo>();
12355 OI->EntryBB = AllocaBB;
12356 OI->ExitBB = ExitBB;
12357 OI->OuterAllocBB = &OuterAllocaBB;
12363 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP,
"gid",
true));
12365 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP,
"tid",
true));
12367 auto HostPostOutlineCB = [
this, Ident,
12368 ToBeDeleted](
Function &OutlinedFn)
mutable {
12373 "there must be a single user for the outlined function");
12378 "Outlined function must have two or three arguments only");
12380 bool HasShared = OutlinedFn.
arg_size() == 3;
12388 assert(StaleCI &&
"Error while outlining - no CallInst user found for the "
12389 "outlined function.");
12390 Builder.SetInsertPoint(StaleCI);
12397 omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),
12400 Builder.ClearInsertionPoint();
12402 I->eraseFromParent();
12405 if (!
Config.isTargetDevice())
12406 OI->PostOutlineCB = HostPostOutlineCB;
12410 Builder.SetInsertPoint(ExitBB);
12421 BasicBlock *OuterAllocaBB = OuterAllocIP.getNodeParent();
12423 if (OuterAllocaBB ==
Builder.GetInsertBlock()) {
12438 if (
Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12443 if (
Config.isTargetDevice()) {
12444 auto OI = std::make_unique<OutlineInfo>();
12445 OI->OuterAllocBB = OuterAllocIP.getNodeParent();
12446 OI->EntryBB = AllocaBB;
12447 OI->ExitBB = ExitBB;
12448 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.
size());
12449 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.
end());
12453 Builder.SetInsertPoint(ExitBB);
12460 std::string VarName) {
12469 return MapNamesArrayGlobal;
12474void OpenMPIRBuilder::initializeTypes(
Module &M) {
12478 unsigned ProgramAS = M.getDataLayout().getProgramAddressSpace();
12479#define OMP_TYPE(VarName, InitValue) VarName = InitValue;
12480#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
12481 VarName##Ty = ArrayType::get(ElemTy, ArraySize); \
12482 VarName##PtrTy = PointerType::get(Ctx, DefaultTargetAS);
12483#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
12484 VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg); \
12485 VarName##Ptr = PointerType::get(Ctx, ProgramAS);
12486#define OMP_STRUCT_TYPE(VarName, StructName, Packed, ...) \
12487 T = StructType::getTypeByName(Ctx, StructName); \
12489 T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed); \
12491 VarName##Ptr = PointerType::get(Ctx, DefaultTargetAS);
12492#include "llvm/Frontend/OpenMP/OMPKinds.def"
12503 while (!Worklist.
empty()) {
12507 if (
BlockSet.insert(SuccBB).second)
12512std::unique_ptr<CodeExtractor>
12514 bool ArgsInZeroAddressSpace,
12516 return std::make_unique<CodeExtractor>(
12526 Suffix.
str(), ArgsInZeroAddressSpace);
12529std::unique_ptr<CodeExtractor> DeviceSharedMemOutlineInfo::createCodeExtractor(
12531 return std::make_unique<DeviceSharedMemCodeExtractor>(
12532 OMPBuilder, Blocks,
nullptr,
12540 OuterDeallocBBs.empty()
12543 Suffix.
str(), ArgsInZeroAddressSpace);
12547 uint64_t
Size, int32_t Flags,
12553 Name.empty() ? Addr->
getName() : Name,
Size, Flags, 0);
12565 Fn->
addFnAttr(
"uniform-work-group-size");
12566 Fn->
addFnAttr(Attribute::MustProgress);
12584 auto &&GetMDInt = [
this](
unsigned V) {
12591 NamedMDNode *MD =
M.getOrInsertNamedMetadata(
"omp_offload.info");
12592 auto &&TargetRegionMetadataEmitter =
12593 [&
C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
12608 GetMDInt(E.getKind()), GetMDInt(EntryInfo.DeviceID),
12609 GetMDInt(EntryInfo.FileID), GetMDString(EntryInfo.ParentName),
12610 GetMDInt(EntryInfo.Line), GetMDInt(EntryInfo.Count),
12611 GetMDInt(E.getOrder())};
12614 OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);
12623 auto &&DeviceGlobalVarMetadataEmitter =
12624 [&
C, &OrderedEntries, &GetMDInt, &GetMDString, MD](
12634 Metadata *
Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),
12635 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
12639 OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);
12646 DeviceGlobalVarMetadataEmitter);
12648 for (
const auto &E : OrderedEntries) {
12649 assert(E.first &&
"All ordered entries must exist!");
12650 if (
const auto *CE =
12653 if (!CE->getID() || !CE->getAddress()) {
12657 if (!
M.getNamedValue(FnName))
12665 }
else if (
const auto *CE =
dyn_cast<
12674 if (
Config.isTargetDevice() &&
Config.hasRequiresUnifiedSharedMemory())
12676 if (!CE->getAddress()) {
12681 if (CE->getVarSize() == 0)
12685 assert(((
Config.isTargetDevice() && !CE->getAddress()) ||
12686 (!
Config.isTargetDevice() && CE->getAddress())) &&
12687 "Declaret target link address is set.");
12688 if (
Config.isTargetDevice())
12690 if (!CE->getAddress()) {
12697 if (!CE->getAddress()) {
12710 if ((
GV->hasLocalLinkage() ||
GV->hasHiddenVisibility()) &&
12714 OMPTargetGlobalVarEntryIndirectVTable))
12723 Flags, CE->getLinkage(), CE->getVarName());
12726 Flags, CE->getLinkage());
12737 if (
Config.hasRequiresFlags() && !
Config.isTargetDevice())
12743 Config.getRequiresFlags());
12753 OS <<
"_" <<
Count;
12758 unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);
12761 EntryInfo.
Line, NewCount);
12769 auto FileIDInfo = CallBack();
12770 uint64_t FileID = 0;
12772 ID =
Status->getUniqueID();
12773 FileID =
Status->getUniqueID().getFile();
12777 FileID =
hash_value(std::get<0>(FileIDInfo));
12781 std::get<1>(FileIDInfo));
12786 for (uint64_t Remain =
12787 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12789 !(Remain & 1); Remain = Remain >> 1)
12807 if (
static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12809 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12816 if (
static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12822 Flags &=
~omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
12823 Flags |= MemberOfFlag;
12829 bool IsDeclaration,
bool IsExternallyVisible,
12831 std::vector<GlobalVariable *> &GeneratedRefs,
bool OpenMPSIMD,
12832 std::vector<Triple> TargetTriple,
Type *LlvmPtrTy,
12833 std::function<
Constant *()> GlobalInitializer,
12844 Config.hasRequiresUnifiedSharedMemory())) {
12849 if (!IsExternallyVisible)
12851 OS <<
"_decl_tgt_ref_ptr";
12854 Value *Ptr =
M.getNamedValue(PtrName);
12863 if (!
Config.isTargetDevice()) {
12864 if (GlobalInitializer)
12865 GV->setInitializer(GlobalInitializer());
12871 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12872 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12873 GlobalInitializer, VariableLinkage, LlvmPtrTy,
cast<Constant>(Ptr));
12885 bool IsDeclaration,
bool IsExternallyVisible,
12887 std::vector<GlobalVariable *> &GeneratedRefs,
bool OpenMPSIMD,
12888 std::vector<Triple> TargetTriple,
12889 std::function<
Constant *()> GlobalInitializer,
12893 (TargetTriple.empty() && !
Config.isTargetDevice()))
12904 !
Config.hasRequiresUnifiedSharedMemory()) {
12906 VarName = MangledName;
12909 if (!IsDeclaration)
12911 M.getDataLayout().getTypeSizeInBits(LlvmVal->
getValueType()), 8);
12914 Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->
getLinkage();
12918 if (
Config.isTargetDevice() &&
12927 if (!
M.getNamedValue(RefName)) {
12931 GvAddrRef->setConstant(
true);
12933 GvAddrRef->setInitializer(Addr);
12934 GeneratedRefs.push_back(GvAddrRef);
12943 if (
Config.isTargetDevice()) {
12944 VarName = (Addr) ? Addr->
getName() :
"";
12948 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12949 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12950 LlvmPtrTy, GlobalInitializer, VariableLinkage);
12951 VarName = (Addr) ? Addr->
getName() :
"";
12953 VarSize =
M.getDataLayout().getPointerSize();
12972 auto &&GetMDInt = [MN](
unsigned Idx) {
12977 auto &&GetMDString = [MN](
unsigned Idx) {
12979 return V->getString();
12982 switch (GetMDInt(0)) {
12986 case OffloadEntriesInfoManager::OffloadEntryInfo::
12987 OffloadingEntryInfoTargetRegion: {
12997 case OffloadEntriesInfoManager::OffloadEntryInfo::
12998 OffloadingEntryInfoDeviceGlobalVar:
13011 if (HostFilePath.
empty())
13015 if (std::error_code Err = Buf.getError()) {
13017 "OpenMPIRBuilder: " +
13025 if (std::error_code Err =
M.getError()) {
13027 (
"error parsing host file inside of OpenMPIRBuilder: " + Err.message())
13041 "expected a valid insertion block for creating an iterator loop");
13045 if (SplitIP == CurBB->
end())
13047 SplitIP = Terminator->getIterator();
13051 Builder.getCurrentDebugLocation(),
"omp.it.cont");
13063 T->eraseFromParent();
13078 bool ReachesLatch =
false;
13081 while (!Worklist.
empty()) {
13086 "iterator bodygen must leave at most one unterminated block",
13092 if (Succ == Latch) {
13093 ReachesLatch =
true;
13098 "iterator bodygen must not branch out of the loop body",
13100 if (Visited.
insert(Succ).second)
13106 Builder.SetInsertPoint(OpenBB);
13108 }
else if (!ReachesLatch) {
13118 return ContBB->
begin();
13128 for (
const auto &
ParamAttr : ParamAttrs) {
13171 return std::string(Out.str());
13179 unsigned VecRegSize;
13181 ISADataTy ISAData[] = {
13200 for (
char Mask :
Masked) {
13201 for (
const ISADataTy &
Data : ISAData) {
13204 Out <<
"_ZGV" <<
Data.ISA << Mask;
13206 assert(NumElts &&
"Non-zero simdlen/cdtsize expected");
13220template <
typename T>
13223 StringRef MangledName,
bool OutputBecomesInput,
13227 Out << Prefix << ISA << LMask << VLEN;
13228 if (OutputBecomesInput)
13230 Out << ParSeq <<
'_' << MangledName;
13239 bool OutputBecomesInput,
13244 OutputBecomesInput, Fn);
13246 OutputBecomesInput, Fn);
13250 OutputBecomesInput, Fn);
13252 OutputBecomesInput, Fn);
13256 OutputBecomesInput, Fn);
13258 OutputBecomesInput, Fn);
13263 OutputBecomesInput, Fn);
13274 char ISA,
unsigned NarrowestDataSize,
bool OutputBecomesInput) {
13275 assert((ISA ==
'n' || ISA ==
's') &&
"Expected ISA either 's' or 'n'.");
13287 OutputBecomesInput, Fn);
13294 OutputBecomesInput, Fn);
13296 OutputBecomesInput, Fn);
13300 OutputBecomesInput, Fn);
13304 OutputBecomesInput, Fn);
13313 OutputBecomesInput, Fn);
13320 MangledName, OutputBecomesInput, Fn);
13322 MangledName, OutputBecomesInput, Fn);
13326 MangledName, OutputBecomesInput, Fn);
13330 MangledName, OutputBecomesInput, Fn);
13340 return OffloadEntriesTargetRegion.empty() &&
13341 OffloadEntriesDeviceGlobalVar.empty();
13344unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(
13346 auto It = OffloadEntriesTargetRegionCount.find(
13347 getTargetRegionEntryCountKey(EntryInfo));
13348 if (It == OffloadEntriesTargetRegionCount.end())
13353void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(
13355 OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =
13356 EntryInfo.
Count + 1;
13362 OffloadEntriesTargetRegion[EntryInfo] =
13365 ++OffloadingEntriesNum;
13371 assert(EntryInfo.
Count == 0 &&
"expected default EntryInfo");
13374 EntryInfo.
Count = getTargetRegionEntryInfoCount(EntryInfo);
13378 if (OMPBuilder->Config.isTargetDevice()) {
13383 auto &Entry = OffloadEntriesTargetRegion[EntryInfo];
13384 Entry.setAddress(Addr);
13386 Entry.setFlags(Flags);
13392 "Target region entry already registered!");
13394 OffloadEntriesTargetRegion[EntryInfo] = Entry;
13395 ++OffloadingEntriesNum;
13397 incrementTargetRegionEntryInfoCount(EntryInfo);
13404 EntryInfo.
Count = getTargetRegionEntryInfoCount(EntryInfo);
13406 auto It = OffloadEntriesTargetRegion.find(EntryInfo);
13407 if (It == OffloadEntriesTargetRegion.end()) {
13411 if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))
13419 for (
const auto &It : OffloadEntriesTargetRegion) {
13420 Action(It.first, It.second);
13426 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
13427 ++OffloadingEntriesNum;
13433 if (OMPBuilder->Config.isTargetDevice()) {
13437 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13439 if (Entry.getVarSize() == 0) {
13440 Entry.setVarSize(VarSize);
13441 Entry.setLinkage(Linkage);
13445 Entry.setVarSize(VarSize);
13446 Entry.setLinkage(Linkage);
13447 Entry.setAddress(Addr);
13450 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13451 assert(Entry.isValid() && Entry.getFlags() == Flags &&
13452 "Entry not initialized!");
13453 if (Entry.getVarSize() == 0) {
13454 Entry.setVarSize(VarSize);
13455 Entry.setLinkage(Linkage);
13462 OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,
13463 Addr, VarSize, Flags, Linkage,
13466 OffloadEntriesDeviceGlobalVar.try_emplace(
13467 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage,
"");
13468 ++OffloadingEntriesNum;
13475 for (
const auto &E : OffloadEntriesDeviceGlobalVar)
13476 Action(E.getKey(), E.getValue());
13483void CanonicalLoopInfo::reportUnsupportedVirtualCollapse()
const {
13485 assert(VirtualCollapse &&
"Requires Virtual collapse state");
13487 "virtual collapse must be the final structural loop transformation");
13490void CanonicalLoopInfo::collectControlBlocks(
13492 if (VirtualCollapse)
13493 reportUnsupportedVirtualCollapse();
13499 BBs.
append({getPreheader(), Header,
Cond, Latch, Exit, getAfter()});
13502BasicBlock *CanonicalLoopInfo::getVirtualCollapseInit()
const {
13503 return VirtualCollapse ? VirtualCollapse->Count->getParent() :
nullptr;
13508 if (VirtualCollapse)
13509 return getVirtualCollapseInit()->getSinglePredecessor();
13518void CanonicalLoopInfo::setTripCount(
Value *TripCount) {
13530void CanonicalLoopInfo::mapIndVar(
13540 for (
Use &U : OldIV->
uses()) {
13544 if (
User->getParent() == getCond())
13546 if (
User->getParent() == getLatch())
13552 Value *NewIV = Updater(OldIV);
13555 for (Use *U : ReplacableUses)
13569 bool IsVirtual = VirtualCollapse.has_value();
13575 IndVarEntry = Guard->getSuccessor(0);
13578 assert(Guard->getSuccessor(1) == Exit);
13579 assert(VirtualCollapse->Begin->getParent() ==
Init);
13581 {VirtualCollapse->Begin, VirtualCollapse->Count}) {
13583 assert(Copy->getOpcode() == Instruction::Add &&
Zero &&
Zero->isZero() &&
13584 "Virtual range copies must add zero");
13588 NonEmpty->getOperand(0) == VirtualCollapse->Count &&
13590 "Collapsed guard must skip empty ranges with zero count");
13602 "Preheader must terminate with unconditional branch");
13605 "Preheader must jump to collapsed initialization");
13608 "Preheader must jump to header");
13612 "Header must terminate with unconditional branch");
13613 assert(Header->getSingleSuccessor() == Cond &&
13614 "Header must jump to exiting block");
13617 assert(Cond->getSinglePredecessor() == Header &&
13618 "Exiting block only reachable from header");
13621 "Exiting block must terminate with conditional branch");
13623 "Exiting block's first successor jump to the body");
13625 "Exiting block's second successor must exit the loop");
13629 "Body only reachable from exiting block");
13634 "Latch must terminate with unconditional branch");
13635 assert(Latch->getSingleSuccessor() == Header &&
"Latch must jump to header");
13638 assert(Latch->getSinglePredecessor() !=
nullptr);
13643 "Exit block must terminate with unconditional branch");
13644 assert(Exit->getSingleSuccessor() == After &&
13645 "Exit block must jump to after block");
13649 "After block only reachable from exit block");
13653 assert(IndVar &&
"Canonical induction variable not found?");
13655 "Induction variable must be an integer");
13657 "Induction variable must be a PHI in the loop header");
13664 auto *NextIndVar =
cast<PHINode>(IndVar)->getIncomingValue(1);
13673 assert(TripCount &&
"Loop trip count not found?");
13675 "Trip count and induction variable must have the same type");
13679 "Exit condition must be a signed less-than comparison");
13681 "Exit condition must compare the induction variable");
13683 "Exit condition must compare with the trip count");
13692 VirtualCollapse.reset();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
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)
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 ...
SmallVector< MachineOperand, 4 > Cond
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.
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....
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 CallInst * createRuntimeFunctionCall(FunctionCallee Callee, ArrayRef< Value * > Args, StringRef Name="")
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.
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)
@ 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.
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
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
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),...