60#define DEBUG_TYPE "openmp-ir-builder"
67 cl::desc(
"Use optimistic attributes describing "
68 "'as-if' properties of runtime calls."),
72 "openmp-ir-builder-use-default-max-threads",
cl::Hidden,
83 if (!IP1.isValid() || !IP2.isValid())
90 switch (SchedType & ~OMPScheduleType::MonotonicityMask) {
91 case OMPScheduleType::UnorderedStaticChunked:
92 case OMPScheduleType::UnorderedStatic:
93 case OMPScheduleType::UnorderedDynamicChunked:
94 case OMPScheduleType::UnorderedGuidedChunked:
95 case OMPScheduleType::UnorderedRuntime:
96 case OMPScheduleType::UnorderedAuto:
97 case OMPScheduleType::UnorderedTrapezoidal:
98 case OMPScheduleType::UnorderedGreedy:
99 case OMPScheduleType::UnorderedBalanced:
100 case OMPScheduleType::UnorderedGuidedIterativeChunked:
101 case OMPScheduleType::UnorderedGuidedAnalyticalChunked:
102 case OMPScheduleType::UnorderedSteal:
103 case OMPScheduleType::UnorderedStaticBalancedChunked:
104 case OMPScheduleType::UnorderedGuidedSimd:
105 case OMPScheduleType::UnorderedRuntimeSimd:
106 case OMPScheduleType::OrderedStaticChunked:
107 case OMPScheduleType::OrderedStatic:
108 case OMPScheduleType::OrderedDynamicChunked:
109 case OMPScheduleType::OrderedGuidedChunked:
110 case OMPScheduleType::OrderedRuntime:
111 case OMPScheduleType::OrderedAuto:
112 case OMPScheduleType::OrderdTrapezoidal:
113 case OMPScheduleType::NomergeUnorderedStaticChunked:
114 case OMPScheduleType::NomergeUnorderedStatic:
115 case OMPScheduleType::NomergeUnorderedDynamicChunked:
116 case OMPScheduleType::NomergeUnorderedGuidedChunked:
117 case OMPScheduleType::NomergeUnorderedRuntime:
118 case OMPScheduleType::NomergeUnorderedAuto:
119 case OMPScheduleType::NomergeUnorderedTrapezoidal:
120 case OMPScheduleType::NomergeUnorderedGreedy:
121 case OMPScheduleType::NomergeUnorderedBalanced:
122 case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:
123 case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:
124 case OMPScheduleType::NomergeUnorderedSteal:
125 case OMPScheduleType::NomergeOrderedStaticChunked:
126 case OMPScheduleType::NomergeOrderedStatic:
127 case OMPScheduleType::NomergeOrderedDynamicChunked:
128 case OMPScheduleType::NomergeOrderedGuidedChunked:
129 case OMPScheduleType::NomergeOrderedRuntime:
130 case OMPScheduleType::NomergeOrderedAuto:
131 case OMPScheduleType::NomergeOrderedTrapezoidal:
132 case OMPScheduleType::OrderedDistributeChunked:
133 case OMPScheduleType::OrderedDistribute:
141 SchedType & OMPScheduleType::MonotonicityMask;
142 if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
156 Builder.restoreIP(IP);
160 if (Builder.GetInsertPoint() != BB->
end())
170 unsigned Line = FSP->getScopeLine() ? FSP->getScopeLine() : FSP->getLine();
171 Builder.SetCurrentDebugLocation(
177 return T.isAMDGPU() ||
T.isNVPTX() ||
T.isSPIRV();
183 Kernel->getFnAttribute(
"target-features").getValueAsString();
184 if (Features.
count(
"+wavefrontsize64"))
199 bool HasSimdModifier,
bool HasDistScheduleChunks) {
201 switch (ClauseKind) {
202 case OMP_SCHEDULE_Default:
203 case OMP_SCHEDULE_Static:
204 return HasChunks ? OMPScheduleType::BaseStaticChunked
205 : OMPScheduleType::BaseStatic;
206 case OMP_SCHEDULE_Dynamic:
207 return OMPScheduleType::BaseDynamicChunked;
208 case OMP_SCHEDULE_Guided:
209 return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd
210 : OMPScheduleType::BaseGuidedChunked;
211 case OMP_SCHEDULE_Auto:
213 case OMP_SCHEDULE_Runtime:
214 return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd
215 : OMPScheduleType::BaseRuntime;
216 case OMP_SCHEDULE_Distribute:
217 return HasDistScheduleChunks ? OMPScheduleType::BaseDistributeChunked
218 : OMPScheduleType::BaseDistribute;
226 bool HasOrderedClause) {
227 assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
228 OMPScheduleType::None &&
229 "Must not have ordering nor monotonicity flags already set");
232 ? OMPScheduleType::ModifierOrdered
233 : OMPScheduleType::ModifierUnordered;
237 if (OrderingScheduleType ==
238 (OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))
239 return OMPScheduleType::OrderedGuidedChunked;
240 else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |
241 OMPScheduleType::ModifierOrdered))
242 return OMPScheduleType::OrderedRuntime;
244 return OrderingScheduleType;
250 bool HasSimdModifier,
bool HasMonotonic,
251 bool HasNonmonotonic,
bool HasOrderedClause) {
252 assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==
253 OMPScheduleType::None &&
254 "Must not have monotonicity flags already set");
255 assert((!HasMonotonic || !HasNonmonotonic) &&
256 "Monotonic and Nonmonotonic are contradicting each other");
259 return ScheduleType | OMPScheduleType::ModifierMonotonic;
260 }
else if (HasNonmonotonic) {
261 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
271 if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
272 (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
278 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
286 bool HasSimdModifier,
bool HasMonotonicModifier,
287 bool HasNonmonotonicModifier,
bool HasOrderedClause,
288 bool HasDistScheduleChunks) {
290 ClauseKind, HasChunks, HasSimdModifier, HasDistScheduleChunks);
294 OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
295 HasNonmonotonicModifier, HasOrderedClause);
303static std::optional<omp::OMPTgtExecModeFlags>
308 if (
Call->getCalledFunction()->getName() ==
"__kmpc_target_init") {
309 TargetInitCall =
Call;
334 std::optional<omp::OMPTgtExecModeFlags> ExecMode =
346 if (
Instruction *Term = Source->getTerminatorOrNull()) {
355 NewBr->setDebugLoc(
DL);
360 assert(New->getFirstInsertionPt() == New->begin() &&
361 "Target BB must not have PHI nodes");
377 New->splice(New->begin(), Old, IP, Old->
end());
381 NewBr->setDebugLoc(
DL);
393 Builder.SetInsertPoint(Old);
397 Builder.SetCurrentDebugLocation(
DebugLoc);
407 New->replaceSuccessorsPhiUsesWith(Old, New);
419 Builder.SetInsertPoint(Old);
422 Builder.SetCurrentDebugLocation(
DebugLoc);
434 Builder.SetInsertPoint(Old);
437 Builder.SetCurrentDebugLocation(
DebugLoc);
454 const Twine &Name =
"",
bool AsPtr =
true,
455 bool Is64Bit =
false) {
456 Builder.restoreIP(OuterAllocaIP);
460 Builder.CreateAlloca(IntTy,
nullptr, Name +
".addr");
464 FakeVal = FakeValAddr;
469 FakeValAddr, Builder.getPtrTy(), Name +
".ascast"));
473 FakeVal = Builder.CreateLoad(IntTy, FakeValAddr, Name +
".val");
478 Builder.restoreIP(InnerAllocaIP);
481 UseFakeVal = Builder.CreateLoad(IntTy, FakeVal, Name +
".use");
484 FakeVal, Is64Bit ? Builder.getInt64(10) : Builder.getInt32(10)));
497enum OpenMPOffloadingRequiresDirFlags {
499 OMP_REQ_UNDEFINED = 0x000,
501 OMP_REQ_NONE = 0x001,
503 OMP_REQ_REVERSE_OFFLOAD = 0x002,
505 OMP_REQ_UNIFIED_ADDRESS = 0x004,
507 OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
509 OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
516 DominatorTree *DT =
nullptr,
bool AggregateArgs =
false,
517 BlockFrequencyInfo *BFI =
nullptr,
518 BranchProbabilityInfo *BPI =
nullptr,
519 AssumptionCache *AC =
nullptr,
bool AllowVarArgs =
false,
520 bool AllowAlloca =
false,
521 BasicBlock *AllocationBlock =
nullptr,
523 std::string Suffix =
"",
bool ArgsInZeroAddressSpace =
false)
524 : CodeExtractor(BBs, DT, AggregateArgs, BFI, BPI, AC, AllowVarArgs,
525 AllowAlloca, AllocationBlock, DeallocationBlocks, Suffix,
526 ArgsInZeroAddressSpace),
527 OMPBuilder(OMPBuilder) {}
529 virtual ~OMPCodeExtractor() =
default;
532 OpenMPIRBuilder &OMPBuilder;
535class DeviceSharedMemCodeExtractor :
public OMPCodeExtractor {
537 using OMPCodeExtractor::OMPCodeExtractor;
538 virtual ~DeviceSharedMemCodeExtractor() =
default;
542 allocateVar(IRBuilder<>::InsertPoint AllocaIP,
DebugLoc DL,
Type *VarType,
543 const Twine &Name = Twine(
""),
544 AddrSpaceCastInst **CastedAlloc =
nullptr)
override {
545 return OMPBuilder.createOMPAllocShared({AllocaIP,
DL}, VarType,
Name);
548 virtual Instruction *deallocateVar(IRBuilder<>::InsertPoint DeallocIP,
550 Type *VarType)
override {
551 return OMPBuilder.createOMPFreeShared({DeallocIP,
DL}, Var, VarType);
558 OpenMPIRBuilder &OMPBuilder;
560 DeviceSharedMemOutlineInfo(OpenMPIRBuilder &OMPBuilder)
561 : OMPBuilder(OMPBuilder) {}
562 virtual ~DeviceSharedMemOutlineInfo() =
default;
564 virtual std::unique_ptr<CodeExtractor>
566 bool ArgsInZeroAddressSpace,
567 Twine Suffix = Twine(
""))
override;
573 : RequiresFlags(OMP_REQ_UNDEFINED) {}
577 bool HasRequiresReverseOffload,
bool HasRequiresUnifiedAddress,
578 bool HasRequiresUnifiedSharedMemory,
bool HasRequiresDynamicAllocators)
581 RequiresFlags(OMP_REQ_UNDEFINED) {
582 if (HasRequiresReverseOffload)
583 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
584 if (HasRequiresUnifiedAddress)
585 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
586 if (HasRequiresUnifiedSharedMemory)
587 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
588 if (HasRequiresDynamicAllocators)
589 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
593 return RequiresFlags & OMP_REQ_REVERSE_OFFLOAD;
597 return RequiresFlags & OMP_REQ_UNIFIED_ADDRESS;
601 return RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY;
605 return RequiresFlags & OMP_REQ_DYNAMIC_ALLOCATORS;
610 :
static_cast<int64_t
>(OMP_REQ_NONE);
615 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
617 RequiresFlags &= ~OMP_REQ_REVERSE_OFFLOAD;
622 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
624 RequiresFlags &= ~OMP_REQ_UNIFIED_ADDRESS;
629 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
631 RequiresFlags &= ~OMP_REQ_UNIFIED_SHARED_MEMORY;
636 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
638 RequiresFlags &= ~OMP_REQ_DYNAMIC_ALLOCATORS;
651 constexpr size_t MaxDim = 3;
656 Value *DynCGroupMemFallbackFlag =
658 DynCGroupMemFallbackFlag =
Builder.CreateShl(DynCGroupMemFallbackFlag, 2);
663 StrictBlocksFlag =
Builder.CreateShl(StrictBlocksFlag, 6);
664 StrictThreadsFlag =
Builder.CreateShl(StrictThreadsFlag, 7);
666 Value *Flags =
Builder.CreateOr(HasNoWaitFlag, DynCGroupMemFallbackFlag);
667 Flags =
Builder.CreateOr(Flags, StrictBlocksFlag);
668 Flags =
Builder.CreateOr(Flags, StrictThreadsFlag);
674 Value *NumThreads3D =
705 auto FnAttrs = Attrs.getFnAttrs();
706 auto RetAttrs = Attrs.getRetAttrs();
708 for (
size_t ArgNo = 0; ArgNo < Fn.
arg_size(); ++ArgNo)
713 bool Param =
true) ->
void {
714 bool HasSignExt = AS.hasAttribute(Attribute::SExt);
715 bool HasZeroExt = AS.hasAttribute(Attribute::ZExt);
716 if (HasSignExt || HasZeroExt) {
717 assert(AS.getNumAttributes() == 1 &&
718 "Currently not handling extension attr combined with others.");
720 if (
auto AK = TargetLibraryInfo::getExtAttrForI32Param(
T, HasSignExt))
723 TargetLibraryInfo::getExtAttrForI32Return(
T, HasSignExt))
730#define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
731#include "llvm/Frontend/OpenMP/OMPKinds.def"
735#define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \
737 FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet); \
738 addAttrSet(RetAttrs, RetAttrSet, false); \
739 for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo) \
740 addAttrSet(ArgAttrs[ArgNo], ArgAttrSets[ArgNo]); \
741 Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs)); \
743#include "llvm/Frontend/OpenMP/OMPKinds.def"
756#define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \
758 FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__}, \
762#include "llvm/Frontend/OpenMP/OMPKinds.def"
765 return M.getOrInsertFunction(Name, FnTy, [&](
Function &Fn) {
768 if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
777 LLVMContext::MD_callback,
779 2, {-1, -1},
true)}));
794 Builder.SetInsertPoint(FiniBB);
806 FiniBB = OtherFiniBB;
808 Builder.SetInsertPoint(FiniBB->getFirstNonPHIIt());
816 auto EndIt = FiniBB->end();
817 if (FiniBB->size() >= 1)
818 if (
auto Prev = std::prev(EndIt); Prev->isTerminator())
823 FiniBB->replaceAllUsesWith(OtherFiniBB);
824 FiniBB->eraseFromParent();
825 FiniBB = OtherFiniBB;
832 assert(Fn &&
"Failed to create OpenMP runtime function pointer");
855 for (
auto Inst =
Block->getReverseIterator()->begin();
856 Inst !=
Block->getReverseIterator()->end();) {
885 Block.getParent()->getEntryBlock().getTerminator()->getIterator();
906 DeferredOutlines.
push_back(std::move(OI));
910 ParallelRegionBlockSet.
clear();
912 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
922 bool ArgsInZeroAddressSpace =
Config.isTargetDevice();
923 std::unique_ptr<CodeExtractor> Extractor =
924 OI->createCodeExtractor(Blocks, ArgsInZeroAddressSpace,
".omp_par");
928 <<
" Exit: " << OI->ExitBB->getName() <<
"\n");
929 assert(Extractor->isEligible() &&
930 "Expected OpenMP outlining to be possible!");
932 for (
auto *V : OI->ExcludeArgsFromAggregate)
933 Extractor->excludeArgFromAggregate(V);
936 Extractor->extractCodeRegion(CEAC, OI->Inputs, OI->Outputs);
940 if (TargetCpuAttr.isStringAttribute())
943 auto TargetFeaturesAttr = OuterFn->
getFnAttribute(
"target-features");
944 if (TargetFeaturesAttr.isStringAttribute())
945 OutlinedFn->
addFnAttr(TargetFeaturesAttr);
948 LLVM_DEBUG(
dbgs() <<
" Outlined function: " << *OutlinedFn <<
"\n");
950 "OpenMP outlined functions should not return a value!");
955 M.getFunctionList().insertAfter(OuterFn->
getIterator(), OutlinedFn);
962 assert(OI->EntryBB->getUniquePredecessor() == &ArtificialEntry);
969 "Expected instructions to add in the outlined region entry");
976 if (
I.isTerminator()) {
978 if (
Instruction *TI = OI->EntryBB->getTerminatorOrNull())
979 TI->adoptDbgRecords(&ArtificialEntry,
I.getIterator(),
false);
983 I.moveBeforePreserving(*OI->EntryBB,
984 OI->EntryBB->getFirstInsertionPt());
987 OI->EntryBB->moveBefore(&ArtificialEntry);
994 if (OI->PostOutlineCB)
995 OI->PostOutlineCB(*OutlinedFn);
997 if (OI->FixUpNonEntryAllocas)
1027 errs() <<
"Error of kind: " << Kind
1028 <<
" when emitting offload entries and metadata during "
1029 "OMPIRBuilder finalization \n";
1037 if (
Config.isTargetDevice())
1038 applyDeclareTargetGlobalReplacements();
1040 if (
Config.EmitLLVMUsedMetaInfo.value_or(
false)) {
1041 std::vector<WeakTrackingVH> LLVMCompilerUsed = {
1042 M.getGlobalVariable(
"__openmp_nvptx_data_transfer_temporary_storage")};
1043 emitUsed(
"llvm.compiler.used", LLVMCompilerUsed);
1053 assert(Original && Replacement &&
1054 "Null values provided to registerDeclareTargetGlobalReplacement");
1058void OpenMPIRBuilder::applyDeclareTargetGlobalReplacements() {
1064 "A null value was inserted into DeclareTargetGlobalReplacements");
1068 if (!OldGV || !NewGV)
1102 for (
unsigned I = 0, E =
PHI->getNumIncomingValues();
I < E; ++
I) {
1103 if (
PHI->getIncomingValue(
I) != OldGV)
1108 Builder.SetCurrentDebugLocation(
PHI->getDebugLoc());
1110 PHI->setIncomingValue(
I, EdgeLoad);
1116 Builder.SetCurrentDebugLocation(Insn->getDebugLoc());
1132 "Non-default address space declare target global");
1134 unsigned DestAS = ASC->getType()->getPointerAddressSpace();
1135 if (DestAS == 0 && NewGVAS != OldGVAS) {
1136 ASC->replaceAllUsesWith(
Load);
1137 ASC->eraseFromParent();
1142 Insn->replaceUsesOfWith(OldGV,
Load);
1158 ConstantInt::get(I32Ty,
Value), Name);
1171 for (
unsigned I = 0, E =
List.size();
I != E; ++
I)
1175 if (UsedArray.
empty())
1182 GV->setSection(
"llvm.metadata");
1188 auto *Int8Ty =
Builder.getInt8Ty();
1191 ConstantInt::get(Int8Ty, Mode),
Twine(KernelName,
"_exec_mode"));
1199 unsigned Reserve2Flags) {
1201 LocFlags |= OMP_IDENT_FLAG_KMPC;
1208 ConstantInt::get(Int32,
uint32_t(LocFlags)),
1209 ConstantInt::get(Int32, Reserve2Flags),
1210 ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
1212 size_t SrcLocStrArgIdx = 4;
1213 if (OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx)
1217 SrcLocStr, OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx));
1224 if (
GV.getValueType() == OpenMPIRBuilder::Ident &&
GV.hasInitializer())
1225 if (
GV.getInitializer() == Initializer)
1230 M, OpenMPIRBuilder::Ident,
1233 M.getDataLayout().getDefaultGlobalsAddressSpace());
1245 SrcLocStrSize = LocStr.
size();
1254 if (
GV.isConstant() &&
GV.hasInitializer() &&
1255 GV.getInitializer() == Initializer)
1258 SrcLocStr =
Builder.CreateGlobalString(
1259 LocStr,
"",
M.getDataLayout().getDefaultGlobalsAddressSpace(),
1267 unsigned Line,
unsigned Column,
1273 Buffer.
append(FunctionName);
1275 Buffer.
append(std::to_string(Line));
1277 Buffer.
append(std::to_string(Column));
1285 StringRef UnknownLoc =
";unknown;unknown;0;0;;";
1296 !DIL->getFilename().empty() ? DIL->getFilename() :
M.getName();
1301 DIL->getColumn(), SrcLocStrSize);
1307 Loc.IP.getNodeParent()->getParent());
1313 "omp_global_thread_num");
1321 "expected one result pointer type per in_reduction item");
1324 if (OrigPtrs.
empty())
1325 return Builder.saveIP();
1344 for (
unsigned Idx = 0; Idx < OrigPtrs.
size(); ++Idx) {
1347 Value *OrigPtr = OrigPtrs[Idx];
1349 OrigPtrTy && OrigPtrTy->getAddressSpace() != 0)
1350 OrigPtr = Builder.CreateAddrSpaceCast(OrigPtr, PtrTy);
1352 Value *
Priv = Builder.CreateCall(GetThData, {Gtid, NullDesc, OrigPtr},
1358 ResPtrTy && ResPtrTy->getAddressSpace() != 0)
1359 Priv = Builder.CreateAddrSpaceCast(
Priv, ResultPtrTys[Idx]);
1361 MapPrivateCB(Idx,
Priv);
1368 bool ForceSimpleCall,
bool CheckCancelFlag) {
1378 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
1381 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
1384 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
1387 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
1390 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
1403 bool UseCancelBarrier =
1408 ? OMPRTL___kmpc_cancel_barrier
1409 : OMPRTL___kmpc_barrier),
1412 if (UseCancelBarrier && CheckCancelFlag)
1422 omp::Directive CanceledDirective) {
1427 auto *UI =
Builder.CreateUnreachable();
1435 Builder.SetInsertPoint(ElseTI);
1436 auto ElseIP =
Builder.saveIP();
1444 Builder.SetInsertPoint(ThenTI);
1446 Value *CancelKind =
nullptr;
1447 switch (CanceledDirective) {
1448#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1449 case DirectiveEnum: \
1450 CancelKind = Builder.getInt32(Value); \
1452#include "llvm/Frontend/OpenMP/OMPKinds.def"
1469 Builder.SetInsertPoint(UI->getParent());
1470 UI->eraseFromParent();
1477 omp::Directive CanceledDirective) {
1482 auto *UI =
Builder.CreateUnreachable();
1485 Value *CancelKind =
nullptr;
1486 switch (CanceledDirective) {
1487#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1488 case DirectiveEnum: \
1489 CancelKind = Builder.getInt32(Value); \
1491#include "llvm/Frontend/OpenMP/OMPKinds.def"
1508 Builder.SetInsertPoint(UI->getParent());
1509 UI->eraseFromParent();
1522 auto *KernelArgsPtr =
1523 Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs,
nullptr,
"kernel_args");
1528 Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr,
I);
1531 M.getDataLayout().getPrefTypeAlign(KernelArgs[
I]->getType()));
1535 NumThreads, HostPtr, KernelArgsPtr};
1562 assert(OutlinedFnID &&
"Invalid outlined function ID!");
1566 Value *Return =
nullptr;
1586 Builder, AllocaIP, Return, RTLoc, DeviceID, Args.NumTeams.front(),
1587 Args.NumThreads.front(), OutlinedFnID, ArgsVector));
1594 Builder.CreateCondBr(
Failed, OffloadFailedBlock, OffloadContBlock);
1596 auto CurFn =
Builder.GetInsertBlock()->getParent();
1603 emitBlock(OffloadContBlock, CurFn,
true);
1608 Value *CancelFlag, omp::Directive CanceledDirective) {
1610 "Unexpected cancellation!");
1630 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
1639 Builder.SetInsertPoint(CancellationBlock);
1640 Builder.CreateBr(*FiniBBOrErr);
1655 size_t NumArgs = OutlinedFn.
arg_size();
1656 assert((NumArgs == 2 || NumArgs == 3) &&
1657 "expected a 2-3 argument parallel outlined function");
1658 bool UseArgStruct = NumArgs == 3;
1663 {Builder.getInt16Ty(), Builder.getInt32Ty()},
1667 OutlinedFn.
getName() +
".wrapper", OMPIRBuilder->
M);
1669 WrapperFn->addParamAttr(0, Attribute::NoUndef);
1670 WrapperFn->addParamAttr(0, Attribute::ZExt);
1671 WrapperFn->addParamAttr(1, Attribute::NoUndef);
1675 Builder.SetInsertPoint(EntryBB);
1678 Value *AddrAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1680 AddrAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1681 AddrAlloca, Builder.getPtrTy(0),
1682 AddrAlloca->
getName() +
".ascast");
1684 Value *ZeroAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1686 ZeroAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1687 ZeroAlloca, Builder.getPtrTy(0),
1688 ZeroAlloca->
getName() +
".ascast");
1690 Value *ArgsAlloca =
nullptr;
1692 ArgsAlloca = Builder.CreateAlloca(Builder.getPtrTy(),
1693 nullptr,
"global_args");
1694 ArgsAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1695 ArgsAlloca, Builder.getPtrTy(0),
1696 ArgsAlloca->
getName() +
".ascast");
1700 Builder.CreateStore(WrapperFn->getArg(1), AddrAlloca);
1701 Builder.CreateStore(Builder.getInt32(0), ZeroAlloca);
1705 llvm::omp::RuntimeFunction::OMPRTL___kmpc_get_shared_variables),
1713 Value *StructArg = Builder.CreateLoad(Builder.getPtrTy(), ArgsAlloca);
1714 StructArg = Builder.CreateInBoundsGEP(Builder.getPtrTy(), StructArg,
1715 {Builder.getInt64(0)});
1716 StructArg = Builder.CreateLoad(Builder.getPtrTy(), StructArg,
"structArg");
1717 Args.push_back(StructArg);
1721 Builder.CreateCall(&OutlinedFn, Args);
1722 Builder.CreateRetVoid();
1737 "Expected at least tid and bounded tid as arguments");
1738 unsigned NumCapturedVars = OutlinedFn.
arg_size() - 2;
1746 OutlinedFn.
addFnAttr(Attribute::NoUnwind);
1749 assert(CI &&
"Expected call instruction to outlined function");
1750 CI->
getParent()->setName(
"omp_parallel");
1752 Builder.SetInsertPoint(CI);
1753 Type *PtrTy = OMPIRBuilder->VoidPtr;
1756 OpenMPIRBuilder ::InsertPointTy CurrentIP = Builder.saveIP();
1760 Value *Args = ArgsAlloca;
1764 Args = Builder.CreatePointerCast(ArgsAlloca, PtrTy);
1765 Builder.restoreIP(CurrentIP);
1768 for (
unsigned Idx = 0; Idx < NumCapturedVars; Idx++) {
1770 Value *StoreAddress = Builder.CreateConstInBoundsGEP2_64(
1772 Builder.CreateStore(
V, StoreAddress);
1776 IfCondition ? Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32)
1777 : Builder.getInt32(1);
1778 Value *NumThreadsArg =
1779 NumThreads ? Builder.CreateZExtOrTrunc(NumThreads, OMPIRBuilder->Int32)
1780 : Builder.getInt32(-1);
1790 Value *Parallel60CallArgs[] = {
1795 Builder.getInt32(-1),
1799 Builder.getInt64(NumCapturedVars),
1800 Builder.getInt32(0)};
1808 << *Builder.GetInsertBlock()->getParent() <<
"\n");
1811 Builder.SetInsertPoint(PrivTID);
1813 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1820 I->eraseFromParent();
1843 if (!
F->hasMetadata(LLVMContext::MD_callback)) {
1851 F->addMetadata(LLVMContext::MD_callback,
1860 OutlinedFn.
addFnAttr(Attribute::NoUnwind);
1863 "Expected at least tid and bounded tid as arguments");
1864 unsigned NumCapturedVars = OutlinedFn.
arg_size() - 2;
1887 if (NumCapturedVars) {
1888 assert(NumCapturedVars == 1 &&
"Expected an aggregate capture argument");
1891 ->getAllocatedType()
1893 "Expected a stack-allocated capture structure");
1899 CI->
getParent()->setName(
"omp_parallel");
1900 Builder.SetInsertPoint(CI);
1903 Value *ForkCallArgs[] = {Ident, Builder.getInt32(NumCapturedVars),
1907 RealArgs.
append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1909 Value *
Cond = Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32);
1916 auto PtrTy = OMPIRBuilder->VoidPtr;
1917 if (IfCondition && NumCapturedVars == 0) {
1925 << *Builder.GetInsertBlock()->getParent() <<
"\n");
1928 Builder.SetInsertPoint(PrivTID);
1930 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1937 I->eraseFromParent();
1945 Value *NumThreads, omp::ProcBindKind ProcBind,
bool IsCancellable) {
1954 const bool NeedThreadID = NumThreads ||
Config.isTargetDevice() ||
1955 (ProcBind != OMP_PROC_BIND_default);
1962 bool ArgsInZeroAddressSpace =
Config.isTargetDevice();
1966 if (NumThreads && !
Config.isTargetDevice()) {
1969 Builder.CreateIntCast(NumThreads, Int32,
false)};
1974 if (ProcBind != OMP_PROC_BIND_default) {
1978 ConstantInt::get(Int32,
unsigned(ProcBind),
true)};
1988 BasicBlock *OuterAllocaBlock = OuterAllocIP.getNodeParent();
2000 Builder.CreateAlloca(Int32,
nullptr,
"zero.addr");
2003 if (ArgsInZeroAddressSpace &&
M.getDataLayout().getAllocaAddrSpace() != 0) {
2006 TIDAddrAlloca, PointerType ::get(
M.getContext(), 0),
"tid.addr.ascast");
2010 PointerType ::get(
M.getContext(), 0),
2011 "zero.addr.ascast");
2024 UI->setDebugLoc(
Loc.DL);
2036 if (IP == IP.getNodeParent()->end()) {
2040 IP =
I->getIterator();
2042 assert(IP.getNodeParent()->getTerminator()->getNumSuccessors() == 1 &&
2043 IP.getNodeParent()->getTerminator()->getSuccessor(0) == PRegExitBB &&
2044 "Unexpected insertion point for finalization call!");
2056 Builder.CreateAlloca(Int32,
nullptr,
"tid.addr.local");
2062 Builder.CreateLoad(Int32, ZeroAddr,
"zero.addr.use");
2080 LLVM_DEBUG(
dbgs() <<
"Before body codegen: " << *OuterFn <<
"\n");
2083 assert(BodyGenCB &&
"Expected body generation callback!");
2085 if (
Error Err = BodyGenCB(InnerAllocaIP, CodeGenIP, PRegExitBB))
2088 LLVM_DEBUG(
dbgs() <<
"After body codegen: " << *OuterFn <<
"\n");
2092 bool UsesDeviceSharedMemory =
2094 std::unique_ptr<OutlineInfo> OI =
2095 UsesDeviceSharedMemory
2096 ? std::make_unique<DeviceSharedMemOutlineInfo>(*
this)
2097 : std::make_unique<OutlineInfo>();
2099 if (
Config.isTargetDevice()) {
2101 OI->PostOutlineCB = [=, ToBeDeletedVec =
2102 std::move(ToBeDeleted)](
Function &OutlinedFn) {
2104 IfCondition, NumThreads, PrivTID, PrivTIDAddr,
2105 ThreadID, ToBeDeletedVec);
2109 OI->PostOutlineCB = [=, ToBeDeletedVec =
2110 std::move(ToBeDeleted)](
Function &OutlinedFn) {
2112 PrivTID, PrivTIDAddr, ToBeDeletedVec);
2116 OI->FixUpNonEntryAllocas =
true;
2117 OI->OuterAllocBB = OuterAllocaBlock;
2118 OI->EntryBB = PRegEntryBB;
2119 OI->ExitBB = PRegExitBB;
2120 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.
size());
2121 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.
end());
2125 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
2137 ".omp_par", ArgsInZeroAddressSpace);
2142 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
2144 Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands,
2149 return GV->getValueType() == OpenMPIRBuilder::Ident;
2154 LLVM_DEBUG(
dbgs() <<
"Before privatization: " << *OuterFn <<
"\n");
2160 if (&V == TIDAddr || &V == ZeroAddr) {
2161 OI->ExcludeArgsFromAggregate.push_back(&V);
2166 for (
Use &U : V.uses())
2168 if (ParallelRegionBlockSet.
count(UserI->getParent()))
2178 if (!V.getType()->isPointerTy()) {
2182 Builder.restoreIP(OuterAllocIP);
2184 if (UsesDeviceSharedMemory) {
2187 V.getName() +
".reloaded");
2188 for (
BasicBlock *DeallocBlock : OuterDeallocBlocks) {
2189 assert(DeallocBlock->getParent() ==
2190 OuterAllocIP.getNodeParent()->getParent() &&
2191 "Dealloc block must be in the allocation's function to reuse "
2192 "its debug location");
2194 Builder.getCurrentDebugLocation()},
2198 Ptr =
Builder.CreateAlloca(V.getType(),
nullptr,
2199 V.getName() +
".reloaded");
2208 Builder.restoreIP(InnerAllocaIP);
2209 Inner =
Builder.CreateLoad(V.getType(), Ptr);
2212 Value *ReplacementValue =
nullptr;
2215 ReplacementValue = PrivTID;
2218 PrivCB(InnerAllocaIP,
Builder.saveIP(), V, *Inner, ReplacementValue);
2223 InnerAllocaIP.getNodeParent()->getTerminator()->getIterator();
2225 assert(ReplacementValue &&
2226 "Expected copy/create callback to set replacement value!");
2227 if (ReplacementValue == &V)
2232 UPtr->set(ReplacementValue);
2255 for (
Value *Output : Outputs)
2259 "OpenMP outlining should not produce live-out values!");
2261 LLVM_DEBUG(
dbgs() <<
"After privatization: " << *OuterFn <<
"\n");
2263 for (
auto *BB : Blocks)
2264 dbgs() <<
" PBR: " << BB->getName() <<
"\n";
2272 assert(FiniInfo.DK == OMPD_parallel &&
2273 "Unexpected finalization stack state!");
2284 Builder.CreateBr(*FiniBBOrErr);
2287 Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
2294 UI->eraseFromParent();
2326 Value *Severity = ConstantInt::get(Int32, IsFatal ? 2 : 1);
2328 Value *Args[] = {Ident, Severity, MessageArg};
2357 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
2359 Builder.CreateStore(DepValPtr, Addr);
2362 DependInfo, Entry,
static_cast<unsigned int>(RTLDependInfoFields::Len));
2364 ConstantInt::get(SizeTy,
2369 DependInfo, Entry,
static_cast<unsigned int>(RTLDependInfoFields::Flags));
2371 static_cast<unsigned int>(Dep.
DepKind)),
2384 if (Dependencies.
empty())
2404 Type *DependInfo = OMPBuilder.DependInfo;
2406 Value *DepArray =
nullptr;
2412 Builder.SetInsertPoint(
2413 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator());
2414 DepArray = Builder.CreateAlloca(DepArrayTy,
nullptr,
".dep.arr.addr");
2417 for (
const auto &[DepIdx, Dep] :
enumerate(Dependencies)) {
2419 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2444 Value *DepArray =
nullptr;
2445 Type *DepArrayTy =
nullptr;
2446 Value *NumDeps =
nullptr;
2449 NumDeps = Dependencies.
NumDeps;
2450 }
else if (!Dependencies.
Deps.empty()) {
2452 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
2456 Builder.GetInsertBlock()->getParent()->getEntryBlock();
2458 DepArray =
Builder.CreateAlloca(DepArrayTy,
nullptr,
".dep.arr.addr");
2461 for (
const auto &[DepIdx, Dep] :
enumerate(Dependencies.
Deps)) {
2463 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2477 ConstantInt::get(
Builder.getInt32Ty(), 0),
2479 ConstantInt::get(
Builder.getInt32Ty(), IsNowait)};
2482 omp::RuntimeFunction::OMPRTL___kmpc_omp_taskwait_deps_51),
2492 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2504 auto *VoidPtrTy =
PointerType::get(Builder.getContext(), ProgramAddressSpace);
2507 Builder.getVoidTy(), {VoidPtrTy, VoidPtrTy, Builder.getInt32Ty()},
2511 "omp_taskloop_dup", M);
2514 Value *LastprivateFlagArg = DupFunction->
getArg(2);
2515 DestTaskArg->
setName(
"dest_task");
2516 SrcTaskArg->
setName(
"src_task");
2517 LastprivateFlagArg->
setName(
"lastprivate_flag");
2520 Builder.SetInsertPoint(
2523 auto GetTaskContextPtrFromArg = [&](
Value *Arg) ->
Value * {
2524 Type *TaskWithPrivatesTy =
2526 Value *TaskPrivates = Builder.CreateGEP(
2527 TaskWithPrivatesTy, Arg, {Builder.getInt32(0), Builder.getInt32(1)});
2528 Value *ContextPtr = Builder.CreateGEP(
2529 PrivatesTy, TaskPrivates,
2530 {Builder.getInt32(0), Builder.getInt32(PrivatesIndex)});
2534 Value *DestTaskContextPtr = GetTaskContextPtrFromArg(DestTaskArg);
2535 Value *SrcTaskContextPtr = GetTaskContextPtrFromArg(SrcTaskArg);
2537 DestTaskContextPtr->
setName(
"destPtr");
2538 SrcTaskContextPtr->
setName(
"srcPtr");
2542 Expected<IRBuilderBase::InsertPoint> AfterIPOrError =
2543 DupCB(AllocaIP, CodeGenIP, DestTaskContextPtr, SrcTaskContextPtr);
2544 if (!AfterIPOrError)
2546 Builder.restoreIP(*AfterIPOrError);
2556 llvm::function_ref<llvm::Expected<llvm::CanonicalLoopInfo *>()> LoopInfo,
2558 Value *GrainSize,
bool NoGroup,
int Sched,
Value *Final,
bool Mergeable,
2560 Value *TaskContextStructPtrVal,
bool FreeAgent) {
2565 uint32_t SrcLocStrSize;
2579 if (
Error Err = BodyGenCB(TaskloopAllocaIP, TaskloopBodyIP, TaskloopExitBB))
2582 llvm::Expected<llvm::CanonicalLoopInfo *> result = LoopInfo();
2587 llvm::CanonicalLoopInfo *CLI = result.
get();
2588 if (CLI->VirtualCollapse)
2589 CLI->reportUnsupportedVirtualCollapse();
2590 auto OI = std::make_unique<OutlineInfo>();
2591 OI->EntryBB = TaskloopAllocaBB;
2592 OI->OuterAllocBB = AllocaIP.getNodeParent();
2593 OI->ExitBB = TaskloopExitBB;
2594 OI->OuterDeallocBBs.reserve(DeallocBlocks.
size());
2595 copy(DeallocBlocks, OI->OuterDeallocBBs.end());
2598 SmallVector<Instruction *> ToBeDeleted;
2601 Builder, AllocaIP, ToBeDeleted, TaskloopAllocaIP,
"global.tid",
false));
2603 TaskloopAllocaIP,
"lb",
false,
true);
2605 TaskloopAllocaIP,
"ub",
false,
true);
2607 TaskloopAllocaIP,
"step",
false,
true);
2610 OI->Inputs.insert(FakeLB);
2611 OI->Inputs.insert(FakeUB);
2612 OI->Inputs.insert(FakeStep);
2613 if (TaskContextStructPtrVal)
2614 OI->Inputs.insert(TaskContextStructPtrVal);
2615 assert(((TaskContextStructPtrVal && DupCB) ||
2616 (!TaskContextStructPtrVal && !DupCB)) &&
2617 "Task context struct ptr and duplication callback must be both set "
2623 unsigned ProgramAddressSpace =
M.getDataLayout().getProgramAddressSpace();
2627 {FakeLB->getType(), FakeUB->getType(), FakeStep->getType(), PointerTy});
2628 Expected<Value *> TaskDupFnOrErr = createTaskDuplicationFunction(
2631 if (!TaskDupFnOrErr) {
2634 Value *TaskDupFn = *TaskDupFnOrErr;
2636 OI->PostOutlineCB = [
this, Ident, LBVal, UBVal, StepVal, Untied,
2637 TaskloopAllocaBB, CLI, TaskDupFn, ToBeDeleted, IfCond,
2638 GrainSize, NoGroup, Sched, FakeLB, FakeUB, FakeStep,
2639 FakeSharedsTy, Final, Mergeable, Priority,
2641 FreeAgent](
Function &OutlinedFn)
mutable {
2643 assert(OutlinedFn.hasOneUse() &&
2644 "there must be a single user for the outlined function");
2651 Value *CastedLBVal =
2652 Builder.CreateIntCast(LBVal,
Builder.getInt64Ty(),
true,
"lb64");
2653 Value *CastedUBVal =
2654 Builder.CreateIntCast(UBVal,
Builder.getInt64Ty(),
true,
"ub64");
2655 Value *CastedStepVal =
2656 Builder.CreateIntCast(StepVal,
Builder.getInt64Ty(),
true,
"step64");
2658 Builder.SetInsertPoint(StaleCI);
2671 Builder.CreateCall(TaskgroupFn, {Ident, ThreadID});
2696 divideCeil(
M.getDataLayout().getTypeSizeInBits(Task), 8));
2698 AllocaInst *ArgStructAlloca =
2700 assert(ArgStructAlloca &&
2701 "Unable to find the alloca instruction corresponding to arguments "
2702 "for extracted function");
2703 std::optional<TypeSize> ArgAllocSize =
2706 "Unable to determine size of arguments for extracted function");
2707 Value *SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
2712 CallInst *TaskData =
Builder.CreateCall(
2713 TaskAllocFn, {Ident, ThreadID,
Flags,
2714 TaskSize, SharedsSize,
2719 Value *TaskShareds =
Builder.CreateLoad(VoidPtr, TaskData);
2725 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(0)});
2728 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(1)});
2731 FakeSharedsTy, TaskShareds, {
Builder.getInt32(0),
Builder.getInt32(2)});
2737 IfCond ?
Builder.CreateIntCast(IfCond,
Builder.getInt32Ty(),
true)
2743 Value *GrainSizeVal =
2744 GrainSize ?
Builder.CreateIntCast(GrainSize,
Builder.getInt64Ty(),
true)
2746 Value *TaskDup = TaskDupFn;
2748 Value *
Args[] = {Ident, ThreadID, TaskData, IfCondVal, Lb, Ub,
2749 Loadstep, NoGroupVal, SchedVal, GrainSizeVal, TaskDup};
2754 Builder.CreateCall(TaskloopFn, Args);
2761 Builder.CreateCall(EndTaskgroupFn, {Ident, ThreadID});
2766 Builder.SetInsertPoint(TaskloopAllocaBB->begin());
2768 LoadInst *SharedsOutlined =
2769 Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
2770 OutlinedFn.getArg(1)->replaceUsesWithIf(
2772 [SharedsOutlined](Use &U) {
return U.getUser() != SharedsOutlined; });
2775 Type *IVTy =
IV->getType();
2781 Value *TaskLB =
nullptr;
2782 Value *TaskUB =
nullptr;
2783 Value *TaskStep =
nullptr;
2784 Value *LoadTaskLB =
nullptr;
2785 Value *LoadTaskUB =
nullptr;
2786 Value *LoadTaskStep =
nullptr;
2787 for (Instruction &
I : *TaskloopAllocaBB) {
2788 if (
I.getOpcode() == Instruction::GetElementPtr) {
2791 switch (CI->getZExtValue()) {
2803 }
else if (
I.getOpcode() == Instruction::Load) {
2805 if (
Load.getPointerOperand() == TaskLB) {
2806 assert(TaskLB !=
nullptr &&
"Expected value for TaskLB");
2808 }
else if (
Load.getPointerOperand() == TaskUB) {
2809 assert(TaskUB !=
nullptr &&
"Expected value for TaskUB");
2811 }
else if (
Load.getPointerOperand() == TaskStep) {
2812 assert(TaskStep !=
nullptr &&
"Expected value for TaskStep");
2818 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2820 assert(LoadTaskLB !=
nullptr &&
"Expected value for LoadTaskLB");
2821 assert(LoadTaskUB !=
nullptr &&
"Expected value for LoadTaskUB");
2822 assert(LoadTaskStep !=
nullptr &&
"Expected value for LoadTaskStep");
2824 Builder.CreateSub(LoadTaskUB, LoadTaskLB), LoadTaskStep);
2825 Value *TripCount =
Builder.CreateAdd(TripCountMinusOne, One,
"trip_cnt");
2826 Value *CastedTripCount =
Builder.CreateIntCast(TripCount, IVTy,
true);
2827 Value *CastedTaskLB =
Builder.CreateIntCast(LoadTaskLB, IVTy,
true);
2829 CLI->setTripCount(CastedTripCount);
2831 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
2833 if (NumOfCollapseLoops > 1) {
2839 Builder.CreateSub(CastedTaskLB, ConstantInt::get(IVTy, 1)));
2842 for (
auto IVUse = CLI->getIndVar()->uses().begin();
2843 IVUse != CLI->getIndVar()->uses().end(); IVUse++) {
2844 User *IVUser = IVUse->getUser();
2846 if (
Op->getOpcode() == Instruction::URem ||
2847 Op->getOpcode() == Instruction::UDiv) {
2852 for (User *User : UsersToReplace) {
2853 User->replaceUsesOfWith(CLI->getIndVar(), IVPlusTaskLB);
2870 assert(CLI->getIndVar()->getNumUses() == 3 &&
2871 "Canonical loop should have exactly three uses of the ind var");
2872 for (User *IVUser : CLI->getIndVar()->users()) {
2874 if (
Mul->getOpcode() == Instruction::Mul) {
2875 for (User *MulUser :
Mul->users()) {
2877 if (
Add->getOpcode() == Instruction::Add) {
2878 Add->setOperand(1, CastedTaskLB);
2887 FakeLB->replaceAllUsesWith(CastedLBVal);
2888 FakeUB->replaceAllUsesWith(CastedUBVal);
2889 FakeStep->replaceAllUsesWith(CastedStepVal);
2891 I->eraseFromParent();
2902 M.getContext(),
M.getDataLayout().getPointerSizeInBits());
2912 bool Mergeable,
Value *EventHandle,
Value *Priority,
bool FreeAgent) {
2943 if (
Error Err = BodyGenCB(TaskAllocaIP, TaskBodyIP, TaskExitBB))
2946 auto OI = std::make_unique<OutlineInfo>();
2947 OI->EntryBB = TaskAllocaBB;
2948 OI->OuterAllocBB = AllocaIP.getNodeParent();
2949 OI->ExitBB = TaskExitBB;
2950 OI->OuterDeallocBBs.reserve(DeallocBlocks.
size());
2951 copy(DeallocBlocks, OI->OuterDeallocBBs.
end());
2956 Builder, AllocaIP, ToBeDeleted, TaskAllocaIP,
"global.tid",
false));
2958 OI->PostOutlineCB = [
this, Ident, Tied, Final, IfCondition, Dependencies,
2959 Affinities, Mergeable, Priority, EventHandle, FreeAgent,
2961 ToBeDeleted](
Function &OutlinedFn)
mutable {
2963 assert(OutlinedFn.hasOneUse() &&
2964 "there must be a single user for the outlined function");
2969 bool HasShareds = StaleCI->
arg_size() > 1;
2970 Builder.SetInsertPoint(StaleCI);
2997 bool UseMergedIf0Path = ConstIfCondition && ConstIfCondition->isZero();
3001 Flags =
Builder.CreateOr(FinalFlag, Flags);
3004 if (Mergeable || UseMergedIf0Path)
3018 divideCeil(
M.getDataLayout().getTypeSizeInBits(Task), 8));
3027 assert(ArgStructAlloca &&
3028 "Unable to find the alloca instruction corresponding to arguments "
3029 "for extracted function");
3030 std::optional<TypeSize> ArgAllocSize =
3033 "Unable to determine size of arguments for extracted function");
3034 SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
3040 TaskAllocFn, {Ident, ThreadID, Flags,
3041 TaskSize, SharedsSize,
3044 if (Affinities.
Count && Affinities.
Info) {
3046 OMPRTL___kmpc_omp_reg_task_with_affinity);
3057 OMPRTL___kmpc_task_allow_completion_event);
3061 Builder.CreatePointerBitCastOrAddrSpaceCast(EventHandle,
3063 EventVal =
Builder.CreatePtrToInt(EventVal,
Builder.getInt64Ty());
3064 Builder.CreateStore(EventVal, EventHandleAddr);
3070 Value *TaskShareds =
Builder.CreateLoad(VoidPtr, TaskData);
3092 VoidPtr, VoidPtr,
Builder.getInt32Ty(), VoidPtr, VoidPtr);
3094 TaskStructType, TaskGEP, {
Zero, ConstantInt::get(Int32Ty, 4)});
3097 Value *CmplrData =
Builder.CreateInBoundsGEP(CmplrStructType,
3099 Builder.CreateStore(Priority, CmplrData);
3102 Value *DepArray =
nullptr;
3103 Value *NumDeps =
nullptr;
3106 NumDeps = Dependencies.
NumDeps;
3107 }
else if (!Dependencies.
Deps.empty()) {
3109 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
3129 if (IfCondition && !UseMergedIf0Path) {
3134 Builder.GetInsertPoint()->getParent()->getTerminator();
3135 Instruction *ThenTI = IfTerminator, *ElseTI =
nullptr;
3136 Builder.SetInsertPoint(IfTerminator);
3139 Builder.SetInsertPoint(ElseTI);
3146 {Ident, ThreadID, NumDeps, DepArray,
3147 ConstantInt::get(
Builder.getInt32Ty(), 0),
3162 Builder.SetInsertPoint(ThenTI);
3170 {Ident, ThreadID, TaskData, NumDeps, DepArray,
3171 ConstantInt::get(
Builder.getInt32Ty(), 0),
3184 LoadInst *Shareds =
Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
3185 OutlinedFn.getArg(1)->replaceUsesWithIf(
3186 Shareds, [Shareds](
Use &U) {
return U.getUser() != Shareds; });
3192 Builder.ClearInsertionPoint();
3194 I->eraseFromParent();
3220 if (
Error Err = BodyGenCB(AllocaIP,
Builder.saveIP(), DeallocBlocks))
3223 Builder.SetInsertPoint(TaskgroupExitBB);
3266 unsigned CaseNumber = 0;
3267 for (
auto SectionCB : SectionCBs) {
3269 M.getContext(),
"omp_section_loop.body.case", CurFn,
Continue);
3271 Builder.SetInsertPoint(CaseBB);
3284 Value *LB = ConstantInt::get(I32Ty, 0);
3285 Value *UB = ConstantInt::get(I32Ty, SectionCBs.
size());
3286 Value *ST = ConstantInt::get(I32Ty, 1);
3288 Loc, LoopBodyGenCB, LB, UB, ST,
true,
false, AllocaIP,
"section_loop");
3293 applyStaticWorkshareLoop(
Loc.DL, *
LoopInfo, AllocaIP,
3294 WorksharingLoopType::ForStaticLoop, !IsNowait);
3300 assert(LoopFini &&
"Bad structure of static workshare loop finalization");
3304 assert(FiniInfo.DK == OMPD_sections &&
3305 "Unexpected finalization stack state!");
3306 if (
Error Err = FiniInfo.mergeFiniBB(
Builder, LoopFini))
3320 if (IP != IP.getNodeParent()->end())
3331 auto *CaseBB =
Loc.IP.getNodeParent();
3332 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
3333 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
3335 IP =
I->getIterator();
3339 Directive OMPD = Directive::OMPD_sections;
3342 return EmitOMPInlinedRegion(OMPD,
nullptr,
nullptr, BodyGenCB, FiniCBWrapper,
3353Value *OpenMPIRBuilder::getGPUThreadID() {
3356 OMPRTL___kmpc_get_hardware_thread_id_in_block),
3360Value *OpenMPIRBuilder::getGPUWarpSize() {
3365Value *OpenMPIRBuilder::getNVPTXWarpID() {
3366 unsigned LaneIDBits =
Log2_32(
Config.getGridValue().GV_Warp_Size);
3367 return Builder.CreateAShr(getGPUThreadID(), LaneIDBits,
"nvptx_warp_id");
3370Value *OpenMPIRBuilder::getNVPTXLaneID() {
3371 unsigned LaneIDBits =
Log2_32(
Config.getGridValue().GV_Warp_Size);
3372 assert(LaneIDBits < 32 &&
"Invalid LaneIDBits size in NVPTX device.");
3373 unsigned LaneIDMask = ~0
u >> (32u - LaneIDBits);
3374 return Builder.CreateAnd(getGPUThreadID(),
Builder.getInt32(LaneIDMask),
3381 uint64_t FromSize =
M.getDataLayout().getTypeStoreSize(FromType);
3382 uint64_t ToSize =
M.getDataLayout().getTypeStoreSize(ToType);
3383 assert(FromSize > 0 &&
"From size must be greater than zero");
3384 assert(ToSize > 0 &&
"To size must be greater than zero");
3385 if (FromType == ToType)
3387 if (FromSize == ToSize)
3388 return Builder.CreateBitCast(From, ToType);
3390 return Builder.CreateIntCast(From, ToType,
true);
3396 Value *ValCastItem =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3397 CastItem,
Builder.getPtrTy(0));
3398 Builder.CreateStore(From, ValCastItem);
3399 return Builder.CreateLoad(ToType, CastItem);
3406 uint64_t Size =
M.getDataLayout().getTypeStoreSize(ElementType);
3407 assert(
Size <= 8 &&
"Unsupported bitwidth in shuffle instruction");
3411 Value *ElemCast = castValueToType(AllocaIP, Element, CastTy);
3413 Builder.CreateIntCast(getGPUWarpSize(),
Builder.getInt16Ty(),
true);
3415 Size <= 4 ? RuntimeFunction::OMPRTL___kmpc_shuffle_int32
3416 : RuntimeFunction::OMPRTL___kmpc_shuffle_int64);
3417 Value *WarpSizeCast =
3419 Value *ShuffleCall =
3424 return castValueToType(AllocaIP, ShuffleCall, ElementType);
3431 uint64_t Size =
M.getDataLayout().getTypeStoreSize(ElemType);
3443 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3444 Value *ElemPtr = DstAddr;
3445 Value *Ptr = SrcAddr;
3446 for (
unsigned IntSize = 8; IntSize >= 1; IntSize /= 2) {
3450 Ptr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3453 Builder.CreateGEP(ElemType, SrcAddr, {ConstantInt::get(IndexTy, 1)});
3454 ElemPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3458 if ((
Size / IntSize) > 1) {
3459 Value *PtrEnd =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3460 SrcAddrGEP,
Builder.getPtrTy());
3477 Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr,
Builder.getPtrTy()));
3479 Builder.CreateICmpSGT(PtrDiff,
Builder.getInt64(IntSize - 1)), ThenBB,
3482 Value *Res = createRuntimeShuffleFunction(
3485 IntType, Ptr,
M.getDataLayout().getPrefTypeAlign(ElemType)),
3487 Builder.CreateAlignedStore(Res, ElemPtr,
3488 M.getDataLayout().getPrefTypeAlign(ElemType));
3490 Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3491 Value *LocalElemPtr =
3492 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3500 Value *Res = createRuntimeShuffleFunction(
3501 AllocaIP,
Builder.CreateLoad(IntType, Ptr), IntType,
Offset);
3502 Builder.CreateStore(Res, ElemPtr);
3503 Ptr =
Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3505 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3511Error OpenMPIRBuilder::emitReductionListCopy(
3516 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3517 Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
3521 for (
auto En :
enumerate(ReductionInfos)) {
3523 Value *SrcElementAddr =
nullptr;
3524 AllocaInst *DestAlloca =
nullptr;
3525 Value *DestElementAddr =
nullptr;
3526 Value *DestElementPtrAddr =
nullptr;
3528 bool ShuffleInElement =
false;
3531 bool UpdateDestListPtr =
false;
3535 ReductionArrayTy, SrcBase,
3536 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3537 SrcElementAddr =
Builder.CreateLoad(
Builder.getPtrTy(), SrcElementPtrAddr);
3541 DestElementPtrAddr =
Builder.CreateInBoundsGEP(
3542 ReductionArrayTy, DestBase,
3543 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3544 bool IsByRefElem = (!IsByRef.
empty() && IsByRef[En.index()]);
3550 Type *DestAllocaType =
3551 IsByRefElem ? RI.ByRefAllocatedType : RI.ElementType;
3552 DestAlloca =
Builder.CreateAlloca(DestAllocaType,
nullptr,
3553 ".omp.reduction.element");
3555 M.getDataLayout().getPrefTypeAlign(DestAllocaType));
3556 DestElementAddr = DestAlloca;
3559 DestElementAddr->
getName() +
".ascast");
3561 ShuffleInElement =
true;
3562 UpdateDestListPtr =
true;
3574 if (ShuffleInElement) {
3575 Type *ShuffleType = RI.ElementType;
3576 Value *ShuffleSrcAddr = SrcElementAddr;
3577 Value *ShuffleDestAddr = DestElementAddr;
3578 AllocaInst *LocalStorage =
nullptr;
3581 assert(RI.ByRefElementType &&
"Expected by-ref element type to be set");
3582 assert(RI.ByRefAllocatedType &&
3583 "Expected by-ref allocated type to be set");
3588 ShuffleType = RI.ByRefElementType;
3590 if (RI.DataPtrPtrGen) {
3593 Builder.saveIP(), ShuffleSrcAddr, ShuffleSrcAddr);
3596 return GenResult.takeError();
3605 LocalStorage =
Builder.CreateAlloca(ShuffleType);
3607 ShuffleDestAddr = LocalStorage;
3612 ShuffleDestAddr = DestElementAddr;
3616 shuffleAndStore(AllocaIP, ShuffleSrcAddr, ShuffleDestAddr, ShuffleType,
3617 RemoteLaneOffset, ReductionArrayTy, IsByRefElem);
3619 if (IsByRefElem && RI.DataPtrPtrGen) {
3621 Value *DestDescriptorAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3622 DestAlloca,
Builder.getPtrTy(),
".ascast");
3625 DestDescriptorAddr, LocalStorage, SrcElementAddr,
3626 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
3629 return GenResult.takeError();
3632 switch (RI.EvaluationKind) {
3634 Value *Elem =
Builder.CreateLoad(RI.ElementType, SrcElementAddr);
3636 Builder.CreateStore(Elem, DestElementAddr);
3640 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
3641 RI.ElementType, SrcElementAddr, 0, 0,
".realp");
3643 RI.ElementType->getStructElementType(0), SrcRealPtr,
".real");
3645 RI.ElementType, SrcElementAddr, 0, 1,
".imagp");
3647 RI.ElementType->getStructElementType(1), SrcImgPtr,
".imag");
3649 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
3650 RI.ElementType, DestElementAddr, 0, 0,
".realp");
3651 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
3652 RI.ElementType, DestElementAddr, 0, 1,
".imagp");
3653 Builder.CreateStore(SrcReal, DestRealPtr);
3654 Builder.CreateStore(SrcImg, DestImgPtr);
3659 M.getDataLayout().getTypeStoreSize(RI.ElementType));
3661 DestElementAddr,
M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3662 SrcElementAddr,
M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3674 if (UpdateDestListPtr) {
3675 Value *CastDestAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3676 DestElementAddr,
Builder.getPtrTy(),
3677 DestElementAddr->
getName() +
".ascast");
3678 Builder.CreateStore(CastDestAddr, DestElementPtrAddr);
3685Expected<Function *> OpenMPIRBuilder::emitInterWarpCopyFunction(
3688 IRBuilder<>::InsertPointGuard IPG(
Builder);
3689 LLVMContext &Ctx =
M.getContext();
3691 Builder.getVoidTy(), {Builder.getPtrTy(), Builder.getInt32Ty()},
3695 "_omp_reduction_inter_warp_copy_func", &
M);
3701 Builder.SetInsertPoint(EntryBB);
3719 StringRef TransferMediumName =
3720 "__openmp_nvptx_data_transfer_temporary_storage";
3721 GlobalVariable *TransferMedium =
M.getGlobalVariable(TransferMediumName);
3722 unsigned WarpSize =
Config.getGridValue().GV_Warp_Size;
3724 if (!TransferMedium) {
3725 TransferMedium =
new GlobalVariable(
3733 Value *GPUThreadID = getGPUThreadID();
3735 Value *LaneID = getNVPTXLaneID();
3737 Value *WarpID = getNVPTXWarpID();
3743 AllocaInst *ReduceListAlloca =
Builder.CreateAlloca(
3744 Arg0Type,
nullptr, ReduceListArg->
getName() +
".addr");
3745 AllocaInst *NumWarpsAlloca =
3746 Builder.CreateAlloca(Arg1Type,
nullptr, NumWarpsArg->
getName() +
".addr");
3747 Value *ReduceListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3748 ReduceListAlloca, Arg0Type, ReduceListAlloca->
getName() +
".ascast");
3749 Value *NumWarpsAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3750 NumWarpsAlloca,
Builder.getPtrTy(0),
3751 NumWarpsAlloca->
getName() +
".ascast");
3752 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
3753 Builder.CreateStore(NumWarpsArg, NumWarpsAddrCast);
3762 for (
auto En :
enumerate(ReductionInfos)) {
3768 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
3769 unsigned RealTySize =
M.getDataLayout().getTypeAllocSize(
3770 IsByRefElem ? RI.ByRefElementType : RI.ElementType);
3771 for (
unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /= 2) {
3774 unsigned NumIters = RealTySize / TySize;
3777 Value *Cnt =
nullptr;
3778 Value *CntAddr =
nullptr;
3785 Builder.CreateAlloca(
Builder.getInt32Ty(),
nullptr,
".cnt.addr");
3787 CntAddr =
Builder.CreateAddrSpaceCast(CntAddr,
Builder.getPtrTy(),
3788 CntAddr->
getName() +
".ascast");
3800 Cnt, ConstantInt::get(
Builder.getInt32Ty(), NumIters));
3801 Builder.CreateCondBr(Cmp, BodyBB, ExitBB);
3808 omp::Directive::OMPD_unknown,
3812 return BarrierIP1.takeError();
3818 Value *IsWarpMaster =
Builder.CreateIsNull(LaneID,
"warp_master");
3819 Builder.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3823 auto *RedListArrayTy =
3826 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
3828 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3829 {ConstantInt::get(IndexTy, 0),
3830 ConstantInt::get(IndexTy, En.index())});
3834 if (IsByRefElem && RI.DataPtrPtrGen) {
3836 RI.DataPtrPtrGen(
Builder.saveIP(), ElemPtr, ElemPtr);
3839 return GenRes.takeError();
3850 ArrayTy, TransferMedium, {
Builder.getInt64(0), WarpID});
3855 Builder.CreateStore(Elem, MediumPtr,
3867 omp::Directive::OMPD_unknown,
3871 return BarrierIP2.takeError();
3878 Value *NumWarpsVal =
3881 Value *IsActiveThread =
3882 Builder.CreateICmpULT(GPUThreadID, NumWarpsVal,
"is_active_thread");
3883 Builder.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3890 ArrayTy, TransferMedium, {
Builder.getInt64(0), GPUThreadID});
3892 Value *TargetElemPtrPtr =
3893 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3894 {ConstantInt::get(IndexTy, 0),
3895 ConstantInt::get(IndexTy, En.index())});
3896 Value *TargetElemPtrVal =
3898 Value *TargetElemPtr = TargetElemPtrVal;
3900 if (IsByRefElem && RI.DataPtrPtrGen) {
3902 RI.DataPtrPtrGen(
Builder.saveIP(), TargetElemPtr, TargetElemPtr);
3905 return GenRes.takeError();
3907 TargetElemPtr =
Builder.CreateLoad(
Builder.getPtrTy(), TargetElemPtr);
3915 Value *SrcMediumValue =
3916 Builder.CreateLoad(CType, SrcMediumPtrVal,
true);
3917 Builder.CreateStore(SrcMediumValue, TargetElemPtr);
3927 Cnt, ConstantInt::get(
Builder.getInt32Ty(), 1));
3928 Builder.CreateStore(Cnt, CntAddr,
false);
3930 auto *CurFn =
Builder.GetInsertBlock()->getParent();
3934 RealTySize %= TySize;
3943Expected<Function *> OpenMPIRBuilder::emitShuffleAndReduceFunction(
3946 LLVMContext &Ctx =
M.getContext();
3947 IRBuilder<>::InsertPointGuard IPG(
Builder);
3948 FunctionType *FuncTy =
3950 {Builder.getPtrTy(), Builder.getInt16Ty(),
3951 Builder.getInt16Ty(), Builder.getInt16Ty()},
3955 "_omp_reduction_shuffle_and_reduce_func", &
M);
3966 Builder.SetInsertPoint(EntryBB);
3978 Type *ReduceListArgType = ReduceListArg->
getType();
3982 ReduceListArgType,
nullptr, ReduceListArg->
getName() +
".addr");
3983 Value *LaneIdAlloca =
Builder.CreateAlloca(LaneIDArgType,
nullptr,
3984 LaneIDArg->
getName() +
".addr");
3986 LaneIDArgType,
nullptr, RemoteLaneOffsetArg->
getName() +
".addr");
3987 Value *AlgoVerAlloca =
Builder.CreateAlloca(LaneIDArgType,
nullptr,
3988 AlgoVerArg->
getName() +
".addr");
3995 RedListArrayTy,
nullptr,
".omp.reduction.remote_reduce_list");
3997 Value *ReduceListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
3998 ReduceListAlloca, ReduceListArgType,
3999 ReduceListAlloca->
getName() +
".ascast");
4000 Value *LaneIdAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4001 LaneIdAlloca, LaneIDArgPtrType, LaneIdAlloca->
getName() +
".ascast");
4002 Value *RemoteLaneOffsetAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4003 RemoteLaneOffsetAlloca, LaneIDArgPtrType,
4004 RemoteLaneOffsetAlloca->
getName() +
".ascast");
4005 Value *AlgoVerAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4006 AlgoVerAlloca, LaneIDArgPtrType, AlgoVerAlloca->
getName() +
".ascast");
4007 Value *RemoteListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4008 RemoteReductionListAlloca,
Builder.getPtrTy(),
4009 RemoteReductionListAlloca->
getName() +
".ascast");
4011 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
4012 Builder.CreateStore(LaneIDArg, LaneIdAddrCast);
4013 Builder.CreateStore(RemoteLaneOffsetArg, RemoteLaneOffsetAddrCast);
4014 Builder.CreateStore(AlgoVerArg, AlgoVerAddrCast);
4016 Value *ReduceList =
Builder.CreateLoad(ReduceListArgType, ReduceListAddrCast);
4017 Value *LaneId =
Builder.CreateLoad(LaneIDArgType, LaneIdAddrCast);
4018 Value *RemoteLaneOffset =
4019 Builder.CreateLoad(LaneIDArgType, RemoteLaneOffsetAddrCast);
4020 Value *AlgoVer =
Builder.CreateLoad(LaneIDArgType, AlgoVerAddrCast);
4027 Error EmitRedLsCpRes = emitReductionListCopy(
4029 ReduceList, RemoteListAddrCast, IsByRef,
4030 {RemoteLaneOffset,
nullptr,
nullptr});
4033 return EmitRedLsCpRes;
4058 Value *LaneComp =
Builder.CreateICmpULT(LaneId, RemoteLaneOffset);
4063 Value *Algo2AndLaneIdComp =
Builder.CreateAnd(Algo2, LaneIdComp);
4064 Value *RemoteOffsetComp =
4066 Value *CondAlgo2 =
Builder.CreateAnd(Algo2AndLaneIdComp, RemoteOffsetComp);
4067 Value *CA0OrCA1 =
Builder.CreateOr(CondAlgo0, CondAlgo1);
4068 Value *CondReduce =
Builder.CreateOr(CA0OrCA1, CondAlgo2);
4074 Builder.CreateCondBr(CondReduce, ThenBB, ElseBB);
4076 Value *LocalReduceListPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4077 ReduceList,
Builder.getPtrTy());
4078 Value *RemoteReduceListPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4079 RemoteListAddrCast,
Builder.getPtrTy());
4081 ->addFnAttr(Attribute::NoUnwind);
4092 Value *LaneIdGtOffset =
Builder.CreateICmpUGE(LaneId, RemoteLaneOffset);
4093 Value *CondCopy =
Builder.CreateAnd(Algo1, LaneIdGtOffset);
4098 Builder.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
4102 EmitRedLsCpRes = emitReductionListCopy(
4104 RemoteListAddrCast, ReduceList, IsByRef);
4107 return EmitRedLsCpRes;
4122OpenMPIRBuilder::generateReductionDescriptor(
4124 Type *DescriptorType,
4130 Value *DescriptorSize =
4131 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(DescriptorType));
4133 DescriptorAddr,
M.getDataLayout().getPrefTypeAlign(DescriptorType),
4134 SrcDescriptorAddr,
M.getDataLayout().getPrefTypeAlign(DescriptorType),
4138 Value *DataPtrField;
4140 DataPtrPtrGen(
Builder.saveIP(), DescriptorAddr, DataPtrField);
4143 return GenResult.takeError();
4146 DataPtr,
Builder.getPtrTy(),
".ascast"),
4152Expected<Value *> OpenMPIRBuilder::createReductionDescriptorCopy(
4154 Value *SrcDescriptorAddr,
Type *DescriptorPtrTy,
const Twine &Name) {
4158 AllocaInst *DescriptorAlloca =
4159 Builder.CreateAlloca(RI.ByRefAllocatedType,
nullptr, Name);
4161 M.getDataLayout().getPrefTypeAlign(RI.ByRefAllocatedType));
4162 Value *DescriptorAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4163 DescriptorAlloca, DescriptorPtrTy,
4164 DescriptorAlloca->
getName() +
".ascast");
4169 generateReductionDescriptor(DescriptorAddr, DataPtr, SrcDescriptorAddr,
4170 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
4172 return GenResult.takeError();
4174 return DescriptorAddr;
4177Expected<Function *> OpenMPIRBuilder::emitListToGlobalCopyFunction(
4180 IRBuilder<>::InsertPointGuard IPG(
Builder);
4181 LLVMContext &Ctx =
M.getContext();
4184 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4188 "_omp_reduction_list_to_global_copy_func", &
M);
4195 Builder.SetInsertPoint(EntryBlock);
4206 BufferArg->
getName() +
".addr");
4210 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4211 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4212 BufferArgAlloca,
Builder.getPtrTy(),
4213 BufferArgAlloca->
getName() +
".ascast");
4214 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4215 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4216 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4217 ReduceListArgAlloca,
Builder.getPtrTy(),
4218 ReduceListArgAlloca->
getName() +
".ascast");
4220 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4221 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4222 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4224 Value *LocalReduceList =
4226 Value *BufferArgVal =
4230 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4231 for (
auto En :
enumerate(ReductionInfos)) {
4233 auto *RedListArrayTy =
4237 RedListArrayTy, LocalReduceList,
4238 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4244 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferArgVal, Idxs);
4246 ReductionsBufferTy, BufferVD, 0, En.index());
4248 switch (RI.EvaluationKind) {
4250 Value *TargetElement;
4252 if (IsByRef.
empty() || !IsByRef[En.index()]) {
4253 TargetElement =
Builder.CreateLoad(RI.ElementType, ElemPtr);
4255 if (RI.DataPtrPtrGen) {
4257 RI.DataPtrPtrGen(
Builder.saveIP(), ElemPtr, ElemPtr);
4260 return GenResult.takeError();
4264 TargetElement =
Builder.CreateLoad(RI.ByRefElementType, ElemPtr);
4267 Builder.CreateStore(TargetElement, GlobVal);
4271 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4272 RI.ElementType, ElemPtr, 0, 0,
".realp");
4274 RI.ElementType->getStructElementType(0), SrcRealPtr,
".real");
4276 RI.ElementType, ElemPtr, 0, 1,
".imagp");
4278 RI.ElementType->getStructElementType(1), SrcImgPtr,
".imag");
4280 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4281 RI.ElementType, GlobVal, 0, 0,
".realp");
4282 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
4283 RI.ElementType, GlobVal, 0, 1,
".imagp");
4284 Builder.CreateStore(SrcReal, DestRealPtr);
4285 Builder.CreateStore(SrcImg, DestImgPtr);
4290 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(RI.ElementType));
4292 GlobVal,
M.getDataLayout().getPrefTypeAlign(RI.ElementType), ElemPtr,
4293 M.getDataLayout().getPrefTypeAlign(RI.ElementType), SizeVal,
false);
4303Expected<Function *> OpenMPIRBuilder::emitListToGlobalReduceFunction(
4306 IRBuilder<>::InsertPointGuard IPG(
Builder);
4307 LLVMContext &Ctx =
M.getContext();
4310 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4314 "_omp_reduction_list_to_global_reduce_func", &
M);
4321 Builder.SetInsertPoint(EntryBlock);
4332 BufferArg->
getName() +
".addr");
4336 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4337 auto *RedListArrayTy =
4342 Value *LocalReduceList =
4343 Builder.CreateAlloca(RedListArrayTy,
nullptr,
".omp.reduction.red_list");
4347 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4348 BufferArgAlloca,
Builder.getPtrTy(),
4349 BufferArgAlloca->
getName() +
".ascast");
4350 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4351 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4352 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4353 ReduceListArgAlloca,
Builder.getPtrTy(),
4354 ReduceListArgAlloca->
getName() +
".ascast");
4355 Value *LocalReduceListAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4356 LocalReduceList,
Builder.getPtrTy(),
4357 LocalReduceList->
getName() +
".ascast");
4359 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4360 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4361 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4366 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4367 for (
auto En :
enumerate(ReductionInfos)) {
4370 Value *TargetElementPtrPtr =
Builder.CreateInBoundsGEP(
4371 RedListArrayTy, LocalReduceListAddrCast,
4372 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4374 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4376 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4377 ReductionsBufferTy, BufferVD, 0, En.index());
4379 if (!IsByRef.
empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4383 Value *SrcElementPtrPtr =
4384 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
4385 {ConstantInt::get(IndexTy, 0),
4386 ConstantInt::get(IndexTy, En.index())});
4387 Value *SrcDescriptorAddr =
4391 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4392 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr,
Builder.getPtrTy());
4396 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4398 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4406 ->addFnAttr(Attribute::NoUnwind);
4411Expected<Function *> OpenMPIRBuilder::emitGlobalToListCopyFunction(
4414 IRBuilder<>::InsertPointGuard IPG(
Builder);
4415 LLVMContext &Ctx =
M.getContext();
4418 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4422 "_omp_reduction_global_to_list_copy_func", &
M);
4429 Builder.SetInsertPoint(EntryBlock);
4440 BufferArg->
getName() +
".addr");
4444 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4445 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4446 BufferArgAlloca,
Builder.getPtrTy(),
4447 BufferArgAlloca->
getName() +
".ascast");
4448 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4449 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4450 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4451 ReduceListArgAlloca,
Builder.getPtrTy(),
4452 ReduceListArgAlloca->
getName() +
".ascast");
4453 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4454 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4455 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4457 Value *LocalReduceList =
4462 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4463 for (
auto En :
enumerate(ReductionInfos)) {
4464 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
4465 auto *RedListArrayTy =
4469 RedListArrayTy, LocalReduceList,
4470 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4475 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4476 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4477 ReductionsBufferTy, BufferVD, 0, En.index());
4483 if (!IsByRef.
empty() && IsByRef[En.index()]) {
4490 return GenResult.takeError();
4496 Value *TargetElement =
Builder.CreateLoad(ElemType, GlobValPtr);
4497 Builder.CreateStore(TargetElement, ElemPtr);
4501 Value *SrcRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4510 Value *DestRealPtr =
Builder.CreateConstInBoundsGEP2_32(
4512 Value *DestImgPtr =
Builder.CreateConstInBoundsGEP2_32(
4514 Builder.CreateStore(SrcReal, DestRealPtr);
4515 Builder.CreateStore(SrcImg, DestImgPtr);
4522 ElemPtr,
M.getDataLayout().getPrefTypeAlign(RI.
ElementType),
4523 GlobValPtr,
M.getDataLayout().getPrefTypeAlign(RI.
ElementType),
4534Expected<Function *> OpenMPIRBuilder::emitGlobalToListReduceFunction(
4537 IRBuilder<>::InsertPointGuard IPG(
Builder);
4538 LLVMContext &Ctx =
M.getContext();
4541 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4545 "_omp_reduction_global_to_list_reduce_func", &
M);
4552 Builder.SetInsertPoint(EntryBlock);
4563 BufferArg->
getName() +
".addr");
4567 Builder.getPtrTy(),
nullptr, ReduceListArg->
getName() +
".addr");
4573 Value *LocalReduceList =
4574 Builder.CreateAlloca(RedListArrayTy,
nullptr,
".omp.reduction.red_list");
4578 Value *BufferArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4579 BufferArgAlloca,
Builder.getPtrTy(),
4580 BufferArgAlloca->
getName() +
".ascast");
4581 Value *IdxArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4582 IdxArgAlloca,
Builder.getPtrTy(), IdxArgAlloca->
getName() +
".ascast");
4583 Value *ReduceListArgAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4584 ReduceListArgAlloca,
Builder.getPtrTy(),
4585 ReduceListArgAlloca->
getName() +
".ascast");
4586 Value *ReductionList =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4587 LocalReduceList,
Builder.getPtrTy(),
4588 LocalReduceList->
getName() +
".ascast");
4590 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4591 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4592 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4597 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4598 for (
auto En :
enumerate(ReductionInfos)) {
4601 Value *TargetElementPtrPtr =
Builder.CreateInBoundsGEP(
4602 RedListArrayTy, ReductionList,
4603 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4606 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4607 Value *GlobValPtr =
Builder.CreateConstInBoundsGEP2_32(
4608 ReductionsBufferTy, BufferVD, 0, En.index());
4610 if (!IsByRef.
empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4612 Value *ReduceListVal =
4614 Value *SrcElementPtrPtr =
4615 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceListVal,
4616 {ConstantInt::get(IndexTy, 0),
4617 ConstantInt::get(IndexTy, En.index())});
4618 Value *SrcDescriptorAddr =
4622 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4623 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr,
Builder.getPtrTy());
4627 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4629 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4637 ->addFnAttr(Attribute::NoUnwind);
4642std::string OpenMPIRBuilder::getReductionFuncName(StringRef Name)
const {
4643 std::string Suffix =
4645 return (Name + Suffix).str();
4648Expected<Function *> OpenMPIRBuilder::createReductionFunction(
4651 AttributeList FuncAttrs) {
4652 IRBuilder<>::InsertPointGuard IPG(
Builder);
4654 {Builder.getPtrTy(), Builder.getPtrTy()},
4656 std::string
Name = getReductionFuncName(ReducerName);
4665 Builder.SetInsertPoint(EntryBB);
4670 Value *LHSArrayPtr =
nullptr;
4671 Value *RHSArrayPtr =
nullptr;
4678 Builder.CreateAlloca(Arg0Type,
nullptr, Arg0->
getName() +
".addr");
4680 Builder.CreateAlloca(Arg1Type,
nullptr, Arg1->
getName() +
".addr");
4681 Value *LHSAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4682 LHSAlloca, Arg0Type, LHSAlloca->
getName() +
".ascast");
4683 Value *RHSAddrCast =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4684 RHSAlloca, Arg1Type, RHSAlloca->
getName() +
".ascast");
4685 Builder.CreateStore(Arg0, LHSAddrCast);
4686 Builder.CreateStore(Arg1, RHSAddrCast);
4687 LHSArrayPtr =
Builder.CreateLoad(Arg0Type, LHSAddrCast);
4688 RHSArrayPtr =
Builder.CreateLoad(Arg1Type, RHSAddrCast);
4692 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4694 for (
auto En :
enumerate(ReductionInfos)) {
4697 RedArrayTy, RHSArrayPtr,
4698 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4700 Value *RHSPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4701 RHSI8Ptr, RI.PrivateVariable->getType(),
4702 RHSI8Ptr->
getName() +
".ascast");
4705 RedArrayTy, LHSArrayPtr,
4706 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4708 Value *LHSPtr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4709 LHSI8Ptr, RI.Variable->getType(), LHSI8Ptr->
getName() +
".ascast");
4718 if (!IsByRef.
empty() && !IsByRef[En.index()]) {
4719 LHS =
Builder.CreateLoad(RI.ElementType, LHSPtr);
4720 RHS =
Builder.CreateLoad(RI.ElementType, RHSPtr);
4727 return AfterIP.takeError();
4728 if (!
Builder.GetInsertBlock())
4729 return ReductionFunc;
4733 if (!IsByRef.
empty() && !IsByRef[En.index()])
4734 Builder.CreateStore(Reduced, LHSPtr);
4739 for (
auto En :
enumerate(ReductionInfos)) {
4740 unsigned Index = En.index();
4742 Value *LHSFixupPtr, *RHSFixupPtr;
4743 Builder.restoreIP(RI.ReductionGenClang(
4744 Builder.saveIP(), Index, &LHSFixupPtr, &RHSFixupPtr, ReductionFunc));
4749 LHSPtrs[Index], [ReductionFunc](
const Use &U) {
4754 RHSPtrs[Index], [ReductionFunc](
const Use &U) {
4768 return ReductionFunc;
4776 assert(RI.Variable &&
"expected non-null variable");
4777 assert(RI.PrivateVariable &&
"expected non-null private variable");
4778 assert((RI.ReductionGen || RI.ReductionGenClang) &&
4779 "expected non-null reduction generator callback");
4782 RI.Variable->getType() == RI.PrivateVariable->getType() &&
4783 "expected variables and their private equivalents to have the same "
4786 assert(RI.Variable->getType()->isPointerTy() &&
4787 "expected variables to be pointers");
4804 ArrayRef<bool> IsByRef,
bool IsNoWait,
bool IsTeamsReduction,
bool IsSPMD,
4806 Value *SrcLocInfo) {
4821 if (ReductionInfos.
size() == 0)
4835 AttrBuilder AttrBldr(Ctx);
4837 AttrBldr.addAttribute(Attr);
4838 AttrBldr.removeAttribute(Attribute::OptimizeNone);
4839 FuncAttrs = FuncAttrs.addFnAttributes(Ctx, AttrBldr);
4842 Builder.GetInsertBlock()->getParent()->getName(), ReductionInfos, IsByRef,
4844 if (!ReductionResult)
4846 Function *ReductionFunc = *ReductionResult;
4849 if (GridValue.has_value())
4850 Config.setGridValue(GridValue.value());
4865 Builder.getPtrTy(
M.getDataLayout().getProgramAddressSpace());
4867 Value *ReductionList;
4871 Value *ReductionListAlloca =
4872 Builder.CreateAlloca(RedArrayTy,
nullptr,
".omp.reduction.red_list");
4873 ReductionList =
Builder.CreatePointerBitCastOrAddrSpaceCast(
4874 ReductionListAlloca, PtrTy, ReductionListAlloca->
getName() +
".ascast");
4877 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
4878 for (
auto En :
enumerate(ReductionInfos)) {
4881 RedArrayTy, ReductionList,
4882 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4885 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
4890 Builder.CreatePointerBitCastOrAddrSpaceCast(PrivateVar, PtrTy);
4891 Builder.CreateStore(CastElem, ElemPtr);
4894 ReductionInfos, ReductionFunc, FuncAttrs, IsByRef);
4900 emitInterWarpCopyFunction(
Loc, ReductionInfos, FuncAttrs, IsByRef);
4905 Value *RL =
Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList, PtrTy);
4914 unsigned MaxDataSize = 0;
4916 for (
auto En :
enumerate(ReductionInfos)) {
4920 Type *RedTypeArg = (!IsByRef.
empty() && IsByRef[En.index()])
4921 ? En.value().ByRefElementType
4922 : En.value().ElementType;
4923 auto Size =
M.getDataLayout().getTypeStoreSize(RedTypeArg);
4924 if (
Size > MaxDataSize)
4928 Value *ReductionDataSize =
4929 Builder.getInt64(MaxDataSize * ReductionInfos.
size());
4933 Function *CopyScratchToListFunc =
nullptr;
4935 Value *ScratchForCopyBack =
nullptr;
4938 Value *RLForCopyBack = RL;
4940 bool IsAtomicReduction =
4943 if (!IsTeamsReduction) {
4944 Value *SarFuncCast =
4945 Builder.CreatePointerBitCastOrAddrSpaceCast(*SarFunc, FuncPtrTy);
4947 Builder.CreatePointerBitCastOrAddrSpaceCast(WcFunc, FuncPtrTy);
4948 Value *Args[] = {SrcLocInfo, ReductionDataSize, RL, SarFuncCast,
4951 RuntimeFunction::OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2);
4953 }
else if (IsAtomicReduction) {
4957 RuntimeFunction::OMPRTL___kmpc_is_team_main_thread);
4961 Ctx, ReductionTypeArgs,
"struct._globalized_locals_ty");
4964 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
4969 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
4974 ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs, IsByRef);
4995 Value *RuntimeRL = RL;
4998 Value *PerThreadScratch;
5004 Value *PerThreadScratchAlloca =
5005 Builder.CreateAlloca(ReductionsBufferTy,
nullptr,
5006 ".omp.reduction.scratch");
5007 PerThreadScratch =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5008 PerThreadScratchAlloca, PtrTy,
5009 PerThreadScratchAlloca->
getName() +
".ascast");
5012 Value *PerThreadRedListAlloca =
5013 Builder.CreateAlloca(RedArrayTy,
nullptr,
5014 ".omp.reduction.per_thread_red_list");
5015 RuntimeRL =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5016 PerThreadRedListAlloca, PtrTy,
5017 PerThreadRedListAlloca->
getName() +
".ascast");
5022 for (
auto En :
enumerate(ReductionInfos)) {
5024 bool IsByRefElem = !IsByRef.
empty() && IsByRef[En.index()];
5027 ReductionsBufferTy, PerThreadScratch, 0, En.index());
5028 Value *Slot =
Builder.CreateConstInBoundsGEP2_32(RedArrayTy, RuntimeRL,
5031 Value *RuntimeListEntry = FieldPtr;
5033 Value *SrcDescriptor =
5036 AllocaIP, RI, FieldPtr, SrcDescriptor, PtrTy);
5039 RuntimeListEntry = *Descriptor;
5041 Builder.CreateStore(RuntimeListEntry, Slot);
5047 Type *CopyArg0Ty = (*LtGCFunc)->getFunctionType()->getParamType(0);
5048 Type *CopyArg2Ty = (*LtGCFunc)->getFunctionType()->getParamType(2);
5049 ScratchForCopyBack =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5050 PerThreadScratch, CopyArg0Ty);
5052 Builder.CreatePointerBitCastOrAddrSpaceCast(RL, CopyArg2Ty);
5060 *LtGCFunc, {ScratchForCopyBack,
Builder.getInt32(0), RLForCopyBack});
5061 CopyScratchToListFunc = *GtLCFunc;
5064 Value *Args3[] = {SrcLocInfo, RuntimeRL, *SarFunc, WcFunc,
5065 *LtGCFunc, *GtLCFunc, *GtLRFunc};
5068 RuntimeFunction::OMPRTL___kmpc_gpu_xteam_reduce_nowait);
5088 if (ScratchForCopyBack) {
5091 CopyScratchToListFunc,
5092 {ScratchForCopyBack,
Builder.getInt32(0), RLForCopyBack});
5096 for (
auto En :
enumerate(ReductionInfos)) {
5102 if (IsAtomicReduction) {
5118 Value *LHSPtr, *RHSPtr;
5120 &LHSPtr, &RHSPtr, CurFunc));
5126 RedValue =
Builder.CreatePointerBitCastOrAddrSpaceCast(
5128 if (RHSPtr->
getType() != RHS->getType())
5130 Builder.CreatePointerBitCastOrAddrSpaceCast(RHS, RHSPtr->
getType());
5141 if (IsByRef.
empty() || !IsByRef[En.index()]) {
5143 "red.value." +
Twine(En.index()));
5154 if (!IsByRef.
empty() && !IsByRef[En.index()])
5159 if (ContinuationBlock) {
5160 Builder.CreateBr(ContinuationBlock);
5161 Builder.SetInsertPoint(ContinuationBlock);
5163 Config.setEmitLLVMUsed();
5174 ".omp.reduction.func", &M);
5185 Builder.SetInsertPoint(ReductionFuncBlock);
5187 Value *LHSArrayPtr =
nullptr;
5188 Value *RHSArrayPtr =
nullptr;
5199 Builder.CreateAlloca(Arg0Type,
nullptr, Arg0->
getName() +
".addr");
5201 Builder.CreateAlloca(Arg1Type,
nullptr, Arg1->
getName() +
".addr");
5202 Value *LHSAddrCast =
5203 Builder.CreatePointerBitCastOrAddrSpaceCast(LHSAlloca, Arg0Type);
5204 Value *RHSAddrCast =
5205 Builder.CreatePointerBitCastOrAddrSpaceCast(RHSAlloca, Arg1Type);
5206 Builder.CreateStore(Arg0, LHSAddrCast);
5207 Builder.CreateStore(Arg1, RHSAddrCast);
5208 LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);
5209 RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);
5211 LHSArrayPtr = ReductionFunc->
getArg(0);
5212 RHSArrayPtr = ReductionFunc->
getArg(1);
5215 unsigned NumReductions = ReductionInfos.
size();
5218 for (
auto En :
enumerate(ReductionInfos)) {
5220 Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5221 RedArrayTy, LHSArrayPtr, 0, En.index());
5222 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);
5223 Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5226 Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5227 RedArrayTy, RHSArrayPtr, 0, En.index());
5228 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);
5229 Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5238 Builder.restoreIP(*AfterIP);
5240 if (!Builder.GetInsertBlock())
5244 if (!IsByRef[En.index()])
5245 Builder.CreateStore(Reduced, LHSPtr);
5247 Builder.CreateRetVoid();
5254 bool IsNoWait,
bool IsTeamsReduction) {
5258 IsByRef, IsNoWait, IsTeamsReduction);
5265 if (ReductionInfos.
size() == 0)
5275 unsigned NumReductions = ReductionInfos.
size();
5277 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getTerminator());
5278 Value *RedArray =
Builder.CreateAlloca(RedArrayTy,
nullptr,
"red.array");
5285 for (
auto En :
enumerate(ReductionInfos)) {
5286 unsigned Index = En.index();
5288 Value *RedArrayElemPtr =
Builder.CreateConstInBoundsGEP2_64(
5289 RedArrayTy, RedArray, 0, Index,
"red.array.elem." +
Twine(Index));
5296 M.getDataLayout(),
M.getDataLayout().getDefaultGlobalsAddressSpace());
5306 ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
5311 unsigned RedArrayByteSize =
DL.getTypeStoreSize(RedArrayTy);
5312 Constant *RedArraySize = ConstantInt::get(IndexTy, RedArrayByteSize);
5314 Value *Lock = getOMPCriticalRegionLock(
".reduction");
5316 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
5317 : RuntimeFunction::OMPRTL___kmpc_reduce);
5320 {Ident, ThreadId, NumVariables, RedArraySize,
5321 RedArray, ReductionFunc, Lock},
5332 Builder.CreateSwitch(ReduceCall, ContinuationBlock, 2);
5333 Switch->addCase(
Builder.getInt32(1), NonAtomicRedBlock);
5334 Switch->addCase(
Builder.getInt32(2), AtomicRedBlock);
5339 Builder.SetInsertPoint(NonAtomicRedBlock);
5340 for (
auto En :
enumerate(ReductionInfos)) {
5346 if (!IsByRef[En.index()]) {
5348 "red.value." +
Twine(En.index()));
5350 Value *PrivateRedValue =
5352 "red.private.value." +
Twine(En.index()));
5360 if (!
Builder.GetInsertBlock())
5363 if (!IsByRef[En.index()])
5367 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
5368 : RuntimeFunction::OMPRTL___kmpc_end_reduce);
5370 Builder.CreateBr(ContinuationBlock);
5375 Builder.SetInsertPoint(AtomicRedBlock);
5376 if (CanGenerateAtomic &&
llvm::none_of(IsByRef, [](
bool P) {
return P; })) {
5383 if (!
Builder.GetInsertBlock())
5386 Builder.CreateBr(ContinuationBlock);
5399 if (!
Builder.GetInsertBlock())
5402 Builder.SetInsertPoint(ContinuationBlock);
5413 Directive OMPD = Directive::OMPD_master;
5418 Value *Args[] = {Ident, ThreadId};
5426 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5438 Directive OMPD = Directive::OMPD_masked;
5444 Value *ArgsEnd[] = {Ident, ThreadId};
5452 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5462 Call->setDoesNotThrow();
5477 bool IsInclusive,
ScanInfo *ScanRedInfo) {
5479 llvm::Error Err = emitScanBasedDirectiveDeclsIR(AllocaIP, ScanVars,
5480 ScanVarsType, ScanRedInfo);
5491 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5494 Type *DestTy = ScanVarsType[i];
5495 Value *Val =
Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5498 Builder.CreateStore(Src, Val);
5503 Builder.GetInsertBlock()->getParent());
5506 IV = ScanRedInfo->
IV;
5509 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5512 Type *DestTy = ScanVarsType[i];
5514 Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5516 Builder.CreateStore(Src, ScanVars[i]);
5530 Builder.GetInsertBlock()->getParent());
5535Error OpenMPIRBuilder::emitScanBasedDirectiveDeclsIR(
5539 Builder.restoreIP(AllocaIP);
5541 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5543 Builder.CreateAlloca(Builder.getPtrTy(),
nullptr,
"vla");
5550 Builder.restoreIP(CodeGenIP);
5552 Builder.CreateAdd(ScanRedInfo->
Span, Builder.getInt32(1));
5553 for (
size_t i = 0; i < ScanVars.
size(); i++) {
5555 Value *Allocsize = Builder.CreateTypeSize(
5556 IntPtrTy, M.getDataLayout().getTypeAllocSize(ScanVarsType[i]));
5558 Builder.CreateMalloc(
IntPtrTy, Allocsize, AllocSpan,
nullptr,
"arr");
5559 Builder.CreateStore(Buff, (*(ScanRedInfo->
ScanBuffPtrs))[ScanVars[i]]);
5586Error OpenMPIRBuilder::emitScanBasedDirectiveFinalsIR(
5592 Value *PrivateVar = RedInfo.PrivateVariable;
5593 Value *OrigVar = RedInfo.Variable;
5597 Type *SrcTy = RedInfo.ElementType;
5602 Builder.CreateStore(Src, OrigVar);
5663 llvm::ConstantInt::get(ScanRedInfo->
Span->
getType(), 1));
5664 Builder.SetInsertPoint(InputBB);
5667 Builder.SetInsertPoint(LoopBB);
5683 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5685 Builder.SetInsertPoint(InnerLoopBB);
5689 Value *ReductionVal = RedInfo.PrivateVariable;
5692 Type *DestTy = RedInfo.ElementType;
5695 Builder.CreateInBoundsGEP(DestTy, Buff,
IV,
"arrayOffset");
5698 Builder.CreateInBoundsGEP(DestTy, Buff, OffsetIval,
"arrayOffset");
5703 RedInfo.ReductionGen(
Builder.saveIP(), LHS, RHS, Result);
5706 Builder.CreateStore(Result, LHSPtr);
5709 IVal, llvm::ConstantInt::get(
Builder.getInt32Ty(), 1));
5711 CmpI =
Builder.CreateICmpUGE(NextIVal, Pow2K);
5712 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5715 Counter, llvm::ConstantInt::get(Counter->
getType(), 1));
5721 Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
5742 Error Err = emitScanBasedDirectiveFinalsIR(ReductionInfos, ScanRedInfo);
5749Error OpenMPIRBuilder::emitScanBasedDirectiveIR(
5761 Error Err = InputLoopGen();
5772 Error Err = ScanLoopGen(Builder);
5779void OpenMPIRBuilder::createScanBBs(ScanInfo *ScanRedInfo) {
5816 Builder.SetInsertPoint(Preheader);
5819 Builder.SetInsertPoint(Header);
5820 PHINode *IndVarPHI =
Builder.CreatePHI(IndVarTy, 2,
"omp_" + Name +
".iv");
5821 IndVarPHI->
addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
5826 Builder.CreateICmpULT(IndVarPHI, TripCount,
"omp_" + Name +
".cmp");
5827 Builder.CreateCondBr(Cmp, Body, Exit);
5832 Builder.SetInsertPoint(Latch);
5842 bool HasNSW =
Config.hasNoSignedWrap();
5845 unsigned BitWidth = CI->getType()->getIntegerBitWidth();
5847 if (CI->getValue().ugt(SignedMax))
5849 }
else if (IsCollapsed) {
5854 Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
5855 "omp_" + Name +
".next",
true, HasNSW);
5866 CL->Header = Header;
5885 NextBB, NextBB, Name);
5917 Value *Start,
Value *Stop,
Value *Step,
bool IsSigned,
bool InclusiveStop,
5926 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
5927 ScanRedInfo->
Span = TripCount;
5933 ScanRedInfo->
IV =
IV;
5934 createScanBBs(ScanRedInfo);
5937 assert(Terminator->getNumSuccessors() == 1);
5938 BasicBlock *ContinueBlock = Terminator->getSuccessor(0);
5941 Builder.GetInsertBlock()->getParent());
5944 Builder.GetInsertBlock()->getParent());
5945 Builder.CreateBr(ContinueBlock);
5951 const auto &&InputLoopGen = [&]() ->
Error {
5954 InclusiveStop, ComputeIP, Name,
true, ScanRedInfo);
5958 Builder.restoreIP((*LoopInfo)->getAfterIP());
5964 InclusiveStop, ComputeIP, Name,
true, ScanRedInfo);
5968 Builder.restoreIP((*LoopInfo)->getAfterIP());
5972 Error Err = emitScanBasedDirectiveIR(InputLoopGen, ScanLoopGen, ScanRedInfo);
5980 bool IsSigned,
bool InclusiveStop,
const Twine &Name) {
5990 assert(IndVarTy == Stop->
getType() &&
"Stop type mismatch");
5991 assert(IndVarTy == Step->
getType() &&
"Step type mismatch");
6011 Incr =
Builder.CreateSelect(IsNeg,
Builder.CreateNeg(Step), Step);
6014 Span =
Builder.CreateSub(UB, LB,
"",
false,
true);
6018 Span =
Builder.CreateSub(Stop, Start,
"",
true);
6023 Value *CountIfLooping;
6024 if (InclusiveStop) {
6025 CountIfLooping =
Builder.CreateAdd(
Builder.CreateUDiv(Span, Incr), One);
6031 CountIfLooping =
Builder.CreateSelect(OneCmp, One, CountIfTwo);
6034 return Builder.CreateSelect(ZeroCmp,
Zero, CountIfLooping,
6035 "omp_" + Name +
".tripcount");
6040 Value *Start,
Value *Stop,
Value *Step,
bool IsSigned,
bool InclusiveStop,
6047 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
6052 Config.hasNoSignedWrap());
6053 Value *IndVar =
Builder.CreateAdd(Span, Start,
"",
false,
6054 Config.hasNoSignedWrap());
6056 ScanRedInfo->
IV = IndVar;
6057 return BodyGenCB(
Builder.saveIP(), IndVar);
6063 Builder.getCurrentDebugLocation());
6074 unsigned Bitwidth = Ty->getIntegerBitWidth();
6077 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_4u);
6080 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_8u);
6090 unsigned Bitwidth = Ty->getIntegerBitWidth();
6093 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
6096 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
6104 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6106 "Require dedicated allocate IP");
6112 uint32_t SrcLocStrSize;
6116 case WorksharingLoopType::ForStaticLoop:
6117 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6119 case WorksharingLoopType::DistributeStaticLoop:
6120 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6122 case WorksharingLoopType::DistributeForStaticLoop:
6123 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6130 FunctionCallee StaticInit =
6131 LoopType == WorksharingLoopType::DistributeForStaticLoop
6134 FunctionCallee StaticFini =
6138 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6141 Value *PLastIter =
Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6142 Value *PLowerBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.lowerbound");
6143 Value *PUpperBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.upperbound");
6144 Value *PStride =
Builder.CreateAlloca(IVTy,
nullptr,
"p.stride");
6153 Constant *One = ConstantInt::get(IVTy, 1);
6156 Builder.CreateStore(UpperBound, PUpperBound);
6157 Builder.CreateStore(One, PStride);
6163 (LoopType == WorksharingLoopType::DistributeStaticLoop)
6164 ? OMPScheduleType::OrderedDistribute
6167 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6171 auto BuildInitCall = [LoopType, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6172 PUpperBound, IVTy, PStride, One,
Zero, StaticInit,
6175 PLowerBound, PUpperBound});
6176 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6177 Value *PDistUpperBound =
6178 Builder.CreateAlloca(IVTy,
nullptr,
"p.distupperbound");
6179 Args.push_back(PDistUpperBound);
6184 BuildInitCall(SchedulingType,
Builder);
6185 if (HasDistSchedule &&
6186 LoopType != WorksharingLoopType::DistributeStaticLoop) {
6187 Constant *DistScheduleSchedType = ConstantInt::get(
6192 BuildInitCall(DistScheduleSchedType,
Builder);
6195 Value *InclusiveUpperBound =
Builder.CreateLoad(IVTy, PUpperBound);
6197 Value *TripCount =
Builder.CreateAdd(TripCountMinusOne, One);
6198 if (CLI->VirtualCollapse) {
6199 bindCollapsedRange(CLI,
LowerBound, TripCount);
6204 CLI->setTripCount(TripCount);
6211 if (!CLI->VirtualCollapse)
6212 CLI->mapIndVar([&](Instruction *OldIV) ->
Value * {
6216 Config.hasNoSignedWrap());
6227 omp::Directive::OMPD_for,
false,
6230 return BarrierIP.takeError();
6261 Reachable.insert(
Block);
6275OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
6279 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6280 assert((ChunkSize || DistScheduleChunkSize) &&
"Chunk size is required");
6285 Type *IVTy =
IV->getType();
6287 "Max supported tripcount bitwidth is 64 bits");
6289 :
Type::getInt64Ty(Ctx);
6292 Constant *One = ConstantInt::get(InternalIVTy, 1);
6297 SmallVector<Instruction *> UIs;
6298 for (BasicBlock &BB : *
F)
6299 if (!BB.hasTerminator())
6300 UIs.
push_back(
new UnreachableInst(
F->getContext(), &BB));
6305 LoopInfo &&LI = LIA.
run(*
F,
FAM);
6306 for (Instruction *
I : UIs)
6307 I->eraseFromParent();
6310 if (ChunkSize || DistScheduleChunkSize)
6315 FunctionCallee StaticInit =
6317 FunctionCallee StaticFini =
6323 Value *PLastIter =
Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6324 Value *PLowerBound =
6325 Builder.CreateAlloca(InternalIVTy,
nullptr,
"p.lowerbound");
6326 Value *PUpperBound =
6327 Builder.CreateAlloca(InternalIVTy,
nullptr,
"p.upperbound");
6328 Value *PStride =
Builder.CreateAlloca(InternalIVTy,
nullptr,
"p.stride");
6337 ChunkSize ? ChunkSize :
Zero, InternalIVTy,
"chunksize");
6338 Value *CastedDistScheduleChunkSize =
Builder.CreateZExtOrTrunc(
6339 DistScheduleChunkSize ? DistScheduleChunkSize :
Zero, InternalIVTy,
6340 "distschedulechunksize");
6341 Value *CastedTripCount =
6342 Builder.CreateZExt(OrigTripCount, InternalIVTy,
"tripcount");
6345 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6347 ConstantInt::get(I32Type,
static_cast<int>(DistScheduleSchedType));
6349 Value *OrigUpperBound =
Builder.CreateSub(CastedTripCount, One);
6352 Builder.CreateSelect(IsTripCountZero,
Zero, OrigUpperBound);
6353 Builder.CreateStore(UpperBound, PUpperBound);
6354 Builder.CreateStore(One, PStride);
6358 uint32_t SrcLocStrSize;
6361 if (DistScheduleSchedType != OMPScheduleType::None) {
6362 Flag |= OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6367 auto BuildInitCall = [StaticInit, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6368 PUpperBound, PStride, One,
6369 this](
Value *SchedulingType,
Value *ChunkSize,
6372 StaticInit, {SrcLoc, ThreadNum,
6373 SchedulingType, PLastIter,
6374 PLowerBound, PUpperBound,
6378 BuildInitCall(SchedulingType, CastedChunkSize,
Builder);
6379 if (DistScheduleSchedType != OMPScheduleType::None &&
6380 SchedType != OMPScheduleType::OrderedDistributeChunked &&
6381 SchedType != OMPScheduleType::OrderedDistribute) {
6385 BuildInitCall(DistSchedulingType, CastedDistScheduleChunkSize,
Builder);
6389 Value *FirstChunkStart =
6390 Builder.CreateLoad(InternalIVTy, PLowerBound,
"omp_firstchunk.lb");
6391 Value *FirstChunkStop =
6392 Builder.CreateLoad(InternalIVTy, PUpperBound,
"omp_firstchunk.ub");
6393 Value *FirstChunkEnd =
Builder.CreateAdd(FirstChunkStop, One);
6395 Builder.CreateSub(FirstChunkEnd, FirstChunkStart,
"omp_chunk.range");
6396 Value *NextChunkStride =
6397 Builder.CreateLoad(InternalIVTy, PStride,
"omp_dispatch.stride");
6401 Value *DispatchCounter;
6409 DispatchCounter = Counter;
6412 FirstChunkStart, CastedTripCount, NextChunkStride,
6435 Value *ChunkEnd =
Builder.CreateAdd(DispatchCounter, ChunkRange);
6436 Value *IsLastChunk =
6437 Builder.CreateICmpUGE(ChunkEnd, CastedTripCount,
"omp_chunk.is_last");
6438 Value *CountUntilOrigTripCount =
6439 Builder.CreateSub(CastedTripCount, DispatchCounter);
6441 IsLastChunk, CountUntilOrigTripCount, ChunkRange,
"omp_chunk.tripcount");
6442 Value *BackcastedChunkTC =
6443 Builder.CreateTrunc(ChunkTripCount, IVTy,
"omp_chunk.tripcount.trunc");
6444 CLI->setTripCount(BackcastedChunkTC);
6449 Value *BackcastedDispatchCounter =
6450 Builder.CreateTrunc(DispatchCounter, IVTy,
"omp_dispatch.iv.trunc");
6451 CLI->mapIndVar([&](Instruction *) ->
Value * {
6453 return Builder.CreateAdd(
IV, BackcastedDispatchCounter);
6466 return AfterIP.takeError();
6481static FunctionCallee
6484 unsigned Bitwidth = Ty->getIntegerBitWidth();
6487 case WorksharingLoopType::ForStaticLoop:
6490 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_4u);
6493 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_8u);
6495 case WorksharingLoopType::DistributeStaticLoop:
6498 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_4u);
6501 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_8u);
6503 case WorksharingLoopType::DistributeForStaticLoop:
6506 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_4u);
6509 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_8u);
6512 if (Bitwidth != 32 && Bitwidth != 64) {
6524 Function &LoopBodyFn,
bool NoLoop) {
6535 if (LoopType == WorksharingLoopType::DistributeStaticLoop) {
6536 RealArgs.
push_back(ConstantInt::get(TripCountTy, 0));
6537 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6538 Builder.restoreIP(std::prev(InsertBlock->
end()));
6543 M, omp::RuntimeFunction::OMPRTL_omp_get_num_threads);
6544 Builder.restoreIP(std::prev(InsertBlock->
end()));
6548 Builder.CreateZExtOrTrunc(NumThreads, TripCountTy,
"num.threads.cast"));
6549 RealArgs.
push_back(ConstantInt::get(TripCountTy, 0));
6550 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6551 RealArgs.
push_back(ConstantInt::get(TripCountTy, 0));
6552 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), NoLoop));
6554 RealArgs.
push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6578 Builder.restoreIP(Preheader->
end());
6581 Builder.CreateBr(CLI->
getExit());
6589 CleanUpInfo.
collectBlocks(RegionBlockSet, BlocksToBeRemoved);
6597 "Expected unique undroppable user of outlined function");
6599 assert(OutlinedFnCallInstruction &&
"Expected outlined function call");
6601 "Expected outlined function call to be located in loop preheader");
6603 if (OutlinedFnCallInstruction->
arg_size() > 1)
6610 LoopBodyArg, TripCount, OutlinedFn, NoLoop);
6612 for (
auto &ToBeDeletedItem : ToBeDeleted)
6613 ToBeDeletedItem->eraseFromParent();
6620 bool NeedsLastIter) {
6621 uint32_t SrcLocStrSize;
6625 if (NeedsLastIter) {
6628 AllocaInst *PLastIter =
6629 Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6633 Builder.CreateStore(ConstantInt::get(I32Type, 0), PLastIter);
6638 Builder.CreateSub(TripCount, ConstantInt::get(TripCount->
getType(), 1));
6641 Builder.CreateStore(
Builder.CreateZExt(IsLast, I32Type), PLastIter);
6646 case WorksharingLoopType::ForStaticLoop:
6647 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6649 case WorksharingLoopType::DistributeStaticLoop:
6650 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6652 case WorksharingLoopType::DistributeForStaticLoop:
6653 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6658 auto OI = std::make_unique<OutlineInfo>();
6663 SmallVector<Instruction *, 4> ToBeDeleted;
6665 OI->OuterAllocBB = AllocaIP.getNodeParent();
6688 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
6690 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
6692 CodeExtractorAnalysisCache CEAC(*OuterFn);
6693 CodeExtractor Extractor(Blocks,
6707 SetVector<Value *> SinkingCands, HoistingCands;
6711 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
6718 for (
auto Use :
Users) {
6720 if (ParallelRegionBlockSet.
count(Inst->getParent())) {
6721 Inst->replaceUsesOfWith(CLI->
getIndVar(), NewLoopCntLoad);
6727 OI->ExcludeArgsFromAggregate.push_back(NewLoopCntLoad);
6734 OI->PostOutlineCB = [=, ToBeDeletedVec =
6735 std::move(ToBeDeleted)](
Function &OutlinedFn) {
6752 return BarrierIP.takeError();
6759 bool NeedsBarrier, omp::ScheduleKind SchedKind,
Value *ChunkSize,
6760 bool HasSimdModifier,
bool HasMonotonicModifier,
6761 bool HasNonmonotonicModifier,
bool HasOrderedClause,
6763 Value *DistScheduleChunkSize,
bool NeedsLastIter) {
6764 if (CLI->VirtualCollapse &&
6765 (
Config.isTargetDevice() ||
6766 (SchedKind != omp::OMP_SCHEDULE_Static &&
6767 SchedKind != omp::OMP_SCHEDULE_Default) ||
6768 ChunkSize || HasOrderedClause || HasDistSchedule ||
6769 DistScheduleChunkSize || LoopType != WorksharingLoopType::ForStaticLoop))
6771 "Virtual collapse requires unchunked static worksharing");
6772 if (
Config.isTargetDevice())
6773 return applyWorkshareLoopTarget(
DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6774 NoLoop, NeedsLastIter);
6776 SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
6777 HasNonmonotonicModifier, HasOrderedClause, DistScheduleChunkSize);
6779 bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
6780 OMPScheduleType::ModifierOrdered;
6782 if (HasDistSchedule) {
6783 DistScheduleSchedType = DistScheduleChunkSize
6784 ? OMPScheduleType::OrderedDistributeChunked
6785 : OMPScheduleType::OrderedDistribute;
6787 switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
6788 case OMPScheduleType::BaseStatic:
6789 case OMPScheduleType::BaseDistribute:
6790 assert((!ChunkSize || !DistScheduleChunkSize) &&
6791 "No chunk size with static-chunked schedule");
6792 if (IsOrdered && !HasDistSchedule)
6793 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6794 NeedsBarrier, ChunkSize);
6796 if (DistScheduleChunkSize)
6797 return applyStaticChunkedWorkshareLoop(
6798 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6799 DistScheduleChunkSize, DistScheduleSchedType);
6800 return applyStaticWorkshareLoop(
DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6803 case OMPScheduleType::BaseStaticChunked:
6804 case OMPScheduleType::BaseDistributeChunked:
6805 if (IsOrdered && !HasDistSchedule)
6806 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6807 NeedsBarrier, ChunkSize);
6809 return applyStaticChunkedWorkshareLoop(
6810 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6811 DistScheduleChunkSize, DistScheduleSchedType);
6813 case OMPScheduleType::BaseRuntime:
6814 case OMPScheduleType::BaseAuto:
6815 case OMPScheduleType::BaseGreedy:
6816 case OMPScheduleType::BaseBalanced:
6817 case OMPScheduleType::BaseSteal:
6818 case OMPScheduleType::BaseRuntimeSimd:
6820 "schedule type does not support user-defined chunk sizes");
6822 case OMPScheduleType::BaseGuidedSimd:
6823 case OMPScheduleType::BaseDynamicChunked:
6824 case OMPScheduleType::BaseGuidedChunked:
6825 case OMPScheduleType::BaseGuidedIterativeChunked:
6826 case OMPScheduleType::BaseGuidedAnalyticalChunked:
6827 case OMPScheduleType::BaseStaticBalancedChunked:
6828 return applyDynamicWorkshareLoop(
DL, CLI, AllocaIP, EffectiveScheduleType,
6829 NeedsBarrier, ChunkSize);
6842 unsigned Bitwidth = Ty->getIntegerBitWidth();
6845 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
6848 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
6856static FunctionCallee
6858 unsigned Bitwidth = Ty->getIntegerBitWidth();
6861 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
6864 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
6871static FunctionCallee
6873 unsigned Bitwidth = Ty->getIntegerBitWidth();
6876 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
6879 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
6884OpenMPIRBuilder::applyDynamicWorkshareLoop(
DebugLoc DL, CanonicalLoopInfo *CLI,
6887 bool NeedsBarrier,
Value *Chunk) {
6888 assert(CLI->
isValid() &&
"Requires a valid canonical loop");
6890 "Require dedicated allocate IP");
6892 "Require valid schedule type");
6894 bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
6895 OMPScheduleType::ModifierOrdered;
6900 uint32_t SrcLocStrSize;
6907 Type *IVTy =
IV->getType();
6912 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6914 Value *PLastIter =
Builder.CreateAlloca(I32Type,
nullptr,
"p.lastiter");
6915 Value *PLowerBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.lowerbound");
6916 Value *PUpperBound =
Builder.CreateAlloca(IVTy,
nullptr,
"p.upperbound");
6917 Value *PStride =
Builder.CreateAlloca(IVTy,
nullptr,
"p.stride");
6926 Constant *One = ConstantInt::get(IVTy, 1);
6927 Builder.CreateStore(One, PLowerBound);
6929 Builder.CreateStore(UpperBound, PUpperBound);
6930 Builder.CreateStore(One, PStride);
6948 ConstantInt::get(I32Type,
static_cast<int>(SchedType));
6960 Builder.SetInsertPoint(OuterCond->getFirstInsertionPt());
6963 {SrcLoc, ThreadNum, PLastIter, PLowerBound, PUpperBound, PStride});
6964 Constant *Zero32 = ConstantInt::get(I32Type, 0);
6967 Builder.CreateSub(
Builder.CreateLoad(IVTy, PLowerBound), One,
"lb");
6968 Builder.CreateCondBr(MoreWork, Header, Exit);
6974 PI->setIncomingBlock(0, OuterCond);
6980 Br->setSuccessor(OuterCond);
6985 Builder.SetInsertPoint(
Cond->getFirstInsertionPt());
6986 UpperBound =
Builder.CreateLoad(IVTy, PUpperBound,
"ub");
6989 CI->setOperand(1, UpperBound);
6993 assert(BI->getSuccessor(1) == Exit);
6994 BI->setSuccessor(1, OuterCond);
7008 omp::Directive::OMPD_for,
false,
7011 return BarrierIP.takeError();
7074 "Virtual collapse requires unobserved canonical loop controls");
7083 if (
Loops.front()->getBody()->getUniqueSuccessor() !=
7085 Loops.back()->getAfter()->getSingleSuccessor() != Plan.
Latches.front())
7092 const VirtualRowPlan &Plan,
7096 DebugLoc DL = Builder.getCurrentDebugLocation();
7102 Builder.SetInsertPoint(Entry);
7104 Builder.CreateURem(Begin, TripCounts.
back(),
"omp_collapsed.begin.1");
7106 Builder.CreateUDiv(Begin, TripCounts.
back(),
"omp_collapsed.begin.0");
7109 Value *InitialRemaining =
7110 Builder.CreateAdd(
Count, InnerBegin,
"omp_collapsed.row.remaining");
7111 Builder.CreateBr(OuterHeader);
7114 Builder.SetCurrentDebugLocation(
DL);
7116 Builder.CreatePHI(IVType, 2,
"omp_collapsed.row.remaining.0");
7122 Builder.CreatePHI(IVType, 2,
"omp_collapsed.row.start.1.0");
7123 Start->addIncoming(InnerBegin, Entry);
7124 Start->addIncoming(
Zero, Plan.Latches.front());
7125 Plan.IndVars.back()->setIncomingValue(0, Start);
7130 BasicBlock *InnerHeader = Plan.IndVars.back()->getParent();
7134 Builder.SetInsertPoint(InnerEntry);
7136 Builder.CreateBr(InnerHeader);
7137 InnerBr->setSuccessor(InnerEntry);
7138 Plan.IndVars.back()->setIncomingBlock(0, InnerEntry);
7140 Builder.SetInsertPoint(Plan.Preheaders.back()->getTerminator());
7143 "omp_collapsed.row.is_final");
7145 IsFinalRow, Remaining, TripCounts.
back(),
"omp_collapsed.row.stop");
7146 Plan.InnerCmp->setOperand(1, InnerStop);
7154 "omp_collapsed.row.remaining.next",
7162 Builder.SetInsertPoint(Guard);
7164 Plan.IndVars.front()->setIncomingValue(0, OuterBegin);
7165 Plan.IndVars.front()->setIncomingBlock(0, Entry);
7168CanonicalLoopInfo *OpenMPIRBuilder::createVirtualCollapsedLoop(
7171 Value *CollapsedTripCount) {
7179 BasicBlock *Preheader = Plan.Preheaders.front();
7194 "omp_collapsed.range.begin");
7196 Builder.Insert(BinaryOperator::CreateAdd(CollapsedTripCount,
Zero),
7197 "omp_collapsed.range.count");
7200 Result->VirtualCollapse =
7201 CanonicalLoopInfo::VirtualCollapseInfo{Begin,
Count};
7205 createVirtualRowExecutor(Result, Plan, TripCounts, Begin,
Count, Entry);
7215void OpenMPIRBuilder::bindCollapsedRange(CanonicalLoopInfo *
Loop,
Value *Begin,
7218 Loop->VirtualCollapse->Begin->setOperand(0, Begin);
7219 Loop->VirtualCollapse->Count->setOperand(0,
Count);
7225 assert(
Loops.size() >= 1 &&
"At least one loop required");
7226 size_t NumLoops =
Loops.size();
7230 return Loops.front();
7232 if (
Config.CollapseMapping == CollapseIVMapping::Virtual) {
7233 if (
Loops.size() != 2)
7235 "Virtual collapse requires two constant-count loops");
7238 if (
Loop->VirtualCollapse)
7239 Loop->reportUnsupportedVirtualCollapse();
7243 "Virtual collapse requires two constant-count loops");
7248 Value *CollapsedTripCount =
7250 return createVirtualCollapsedLoop(
DL,
Loops, Plan, TripCounts,
7251 CollapsedTripCount);
7264 Loop->collectControlBlocks(OldControlBBs);
7268 if (ComputeIP.isValid())
7275 Value *CollapsedTripCount =
nullptr;
7278 "All loops to collapse must be valid canonical loops");
7279 Value *OrigTripCount = L->getTripCount();
7280 if (!CollapsedTripCount) {
7281 CollapsedTripCount = OrigTripCount;
7286 CollapsedTripCount =
7287 Builder.CreateNUWMul(CollapsedTripCount, OrigTripCount);
7293 OrigPreheader->
getNextNode(), OrigAfter,
"collapsed",
7300 Builder.restoreIP(Result->getBodyIP());
7302 Value *Leftover = Result->getIndVar();
7304 NewIndVars.
resize(NumLoops);
7305 for (
int i = NumLoops - 1; i >= 1; --i) {
7306 Value *OrigTripCount =
Loops[i]->getTripCount();
7308 Value *NewIndVar =
Builder.CreateURem(Leftover, OrigTripCount);
7309 NewIndVars[i] = NewIndVar;
7311 Leftover =
Builder.CreateUDiv(Leftover, OrigTripCount);
7314 NewIndVars[0] = Leftover;
7323 BasicBlock *ContinueBlock = Result->getBody();
7325 auto ContinueWith = [&ContinueBlock, &ContinuePred,
DL](
BasicBlock *Dest,
7332 ContinueBlock =
nullptr;
7333 ContinuePred = NextSrc;
7340 for (
size_t i = 0; i < NumLoops - 1; ++i)
7341 ContinueWith(
Loops[i]->getBody(),
Loops[i + 1]->getHeader());
7347 for (
size_t i = NumLoops - 1; i > 0; --i)
7348 ContinueWith(
Loops[i]->getAfter(),
Loops[i - 1]->getLatch());
7351 ContinueWith(Result->getLatch(),
nullptr);
7358 for (
size_t i = 0; i < NumLoops; ++i)
7359 Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
7373std::vector<CanonicalLoopInfo *>
7377 "Must pass as many tile sizes as there are loops");
7378 int NumLoops =
Loops.size();
7379 assert(NumLoops >= 1 &&
"At least one loop to tile required");
7391 Loop->collectControlBlocks(OldControlBBs);
7399 assert(L->isValid() &&
"All input loops must be valid canonical loops");
7400 OrigTripCounts.
push_back(L->getTripCount());
7411 for (
int i = 0; i < NumLoops - 1; ++i) {
7424 for (
int i = 0; i < NumLoops; ++i) {
7425 Value *TileSize = TileSizes[i];
7426 Value *OrigTripCount = OrigTripCounts[i];
7429 Value *FloorCompleteTripCount =
Builder.CreateUDiv(OrigTripCount, TileSize);
7430 Value *FloorTripRem =
Builder.CreateURem(OrigTripCount, TileSize);
7439 Value *FloorTripOverflow =
7440 Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
7442 FloorTripOverflow =
Builder.CreateZExt(FloorTripOverflow, IVType);
7443 Value *FloorTripCount =
7444 Builder.CreateAdd(FloorCompleteTripCount, FloorTripOverflow,
7445 "omp_floor" +
Twine(i) +
".tripcount",
true);
7448 FloorCompleteCount.
push_back(FloorCompleteTripCount);
7454 std::vector<CanonicalLoopInfo *> Result;
7455 Result.reserve(NumLoops * 2);
7468 auto EmbeddNewLoop =
7469 [
this,
DL,
F, InnerEnter, &Enter, &
Continue, &OutroInsertBefore](
7472 DL, TripCount,
F, InnerEnter, OutroInsertBefore, Name);
7477 Enter = EmbeddedLoop->
getBody();
7479 OutroInsertBefore = EmbeddedLoop->
getLatch();
7480 return EmbeddedLoop;
7484 const Twine &NameBase) {
7487 EmbeddNewLoop(
P.value(), NameBase +
Twine(
P.index()));
7488 Result.push_back(EmbeddedLoop);
7492 EmbeddNewLoops(FloorCount,
"floor");
7498 for (
int i = 0; i < NumLoops; ++i) {
7500 Value *TileSize = TileSizes[i];
7502 Value *FloorIsEpilogue =
7504 Value *TileTripCount =
7505 Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
7511 EmbeddNewLoops(TileCounts,
"tile");
7516 for (std::pair<BasicBlock *, BasicBlock *>
P : InbetweenCode) {
7525 BodyEnter =
nullptr;
7526 BodyEntered = ExitBB;
7538 Builder.restoreIP(Result.back()->getBodyIP());
7539 for (
int i = 0; i < NumLoops; ++i) {
7542 Value *OrigIndVar = OrigIndVars[i];
7593 assert(
Loop->isValid() &&
"Expecting a valid CanonicalLoopInfo");
7597 assert(Latch &&
"A valid CanonicalLoopInfo must have a unique latch");
7605 if (
I.mayReadOrWriteMemory()) {
7609 I.setMetadata(LLVMContext::MD_access_group,
AccessGroup);
7623 Loop->collectControlBlocks(oldControlBBs);
7628 assert(L->isValid() &&
"All input loops must be valid canonical loops");
7629 origTripCounts.
push_back(L->getTripCount());
7638 Builder.SetInsertPoint(TCBlock);
7639 Value *fusedTripCount =
nullptr;
7641 assert(L->isValid() &&
"All loops to fuse must be valid canonical loops");
7642 Value *origTripCount = L->getTripCount();
7643 if (!fusedTripCount) {
7644 fusedTripCount = origTripCount;
7647 Value *condTP =
Builder.CreateICmpSGT(fusedTripCount, origTripCount);
7648 fusedTripCount =
Builder.CreateSelect(condTP, fusedTripCount, origTripCount,
7662 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7663 Loops[i]->getPreheader()->moveBefore(TCBlock);
7664 Loops[i]->getAfter()->moveBefore(TCBlock);
7668 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7680 for (
size_t i = 0; i <
Loops.size(); ++i) {
7682 F->getContext(),
"omp.fused.inner.cond",
F,
Loops[i]->getBody());
7683 Builder.SetInsertPoint(condBlock);
7691 for (
size_t i = 0; i <
Loops.size() - 1; ++i) {
7692 Builder.SetInsertPoint(condBBs[i]);
7693 Builder.CreateCondBr(condValues[i],
Loops[i]->getBody(), condBBs[i + 1]);
7709 "omp.fused.pre_latch");
7726 assert(
Loop->isValid() &&
"Expecting a valid CanonicalLoopInfo");
7727 if (
Loop->VirtualCollapse)
7750 const Twine &NamePrefix) {
7779 C, NamePrefix +
".if.then",
Cond->getParent(),
Cond->getNextNode());
7781 C, NamePrefix +
".if.else",
Cond->getParent(), CanonicalLoop->
getExit());
7784 Builder.SetInsertPoint(SplitBeforeIt);
7786 Builder.CreateCondBr(IfCond, ThenBlock, ElseBlock);
7789 spliceBB(IP, ThenBlock,
false, Builder.getCurrentDebugLocation());
7792 Builder.SetInsertPoint(ElseBlock);
7798 ExistingBlocks.
reserve(L->getNumBlocks() + 1);
7800 ExistingBlocks.
append(L->block_begin(), L->block_end());
7806 assert(LoopCond && LoopHeader &&
"Invalid loop structure");
7808 if (
Block == L->getLoopPreheader() ||
Block == L->getLoopLatch() ||
7815 if (
Block == ThenBlock)
7816 NewBB->
setName(NamePrefix +
".if.else");
7819 VMap[
Block] = NewBB;
7827 L->getLoopLatch()->splitBasicBlockBefore(
L->getLoopLatch()->begin(),
7828 NamePrefix +
".pre_latch");
7832 L->addBasicBlockToLoop(ThenBlock, LI);
7838 if (TargetTriple.
isX86()) {
7839 if (Features.
lookup(
"avx512f"))
7841 else if (Features.
lookup(
"avx"))
7845 if (TargetTriple.
isPPC())
7847 if (TargetTriple.
isWasm())
7856 Value *IfCond, OrderKind Order,
7858 if (CanonicalLoop->VirtualCollapse)
7859 CanonicalLoop->reportUnsupportedVirtualCollapse();
7868 if (!BB.hasTerminator())
7884 I->eraseFromParent();
7887 if (AlignedVars.
size()) {
7889 for (
auto &AlignedItem : AlignedVars) {
7890 Value *AlignedPtr = AlignedItem.first;
7894 Builder.CreateAlignmentAssumption(
F->getDataLayout(), AlignedPtr,
7902 createIfVersion(CanonicalLoop, IfCond, VMap, LIA, LI, L,
"simd");
7915 Reachable.insert(
Block);
7925 if ((Safelen ==
nullptr) || (Order == OrderKind::OMP_ORDER_concurrent))
7941 if (Simdlen || Safelen) {
7945 ConstantInt *VectorizeWidth = Simdlen ==
nullptr ? Safelen : Simdlen;
7957 assert(Factor >= 0 &&
"Unroll factor must not be negative");
7973 Ctx, {
MDString::get(Ctx,
"llvm.loop.unroll.count"), FactorConst}));
7976 addUnrollMetadata(
Loop, LoopMetadata);
7981 if (
Loop->VirtualCollapse)
7982 Loop->reportUnsupportedVirtualCollapse();
7988 *UnrolledCLI =
Loop;
7993 "unrolling only makes sense with a factor of 2 or larger");
7995 Type *IndVarTy =
Loop->getIndVarType();
8002 std::vector<CanonicalLoopInfo *>
LoopNest =
8017 Ctx, {
MDString::get(Ctx,
"llvm.loop.unroll.count"), FactorConst})});
8020 (*UnrolledCLI)->assertOK();
8038 Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
8057 if (!CPVars.
empty()) {
8062 Directive OMPD = Directive::OMPD_single;
8067 Value *Args[] = {Ident, ThreadId};
8076 if (
Error Err = FiniCB(IP))
8097 EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCBWrapper,
8104 for (
size_t I = 0, E = CPVars.
size();
I < E; ++
I)
8107 ConstantInt::get(Int64, 0), CPVars[
I],
8110 }
else if (!IsNowait) {
8113 omp::Directive::OMPD_unknown,
false,
8131 Directive::OMPD_scope,
nullptr,
nullptr,
8132 BodyGenCB, FiniCB,
false,
true,
8140 omp::Directive::OMPD_unknown,
8156 Directive OMPD = Directive::OMPD_critical;
8161 Value *LockVar = getOMPCriticalRegionLock(CriticalName);
8162 Value *Args[] = {Ident, ThreadId, LockVar};
8179 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8187 const Twine &Name,
bool IsDependSource) {
8190 [](
Value *SV) {
return SV->getType()->isIntegerTy(64); }) &&
8191 "OpenMP runtime requires depend vec with i64 type");
8204 for (
unsigned I = 0;
I < NumLoops; ++
I) {
8218 Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
8236 Directive OMPD = Directive::OMPD_ordered_blockassoc;
8245 Value *Args[] = {Ident, ThreadId};
8255 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8262 bool HasFinalize,
bool IsCancellable) {
8269 BasicBlock *EntryBB = Builder.GetInsertBlock();
8273 SplitPos->
setDebugLoc(Builder.getCurrentDebugLocation());
8280 emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
8292 "Unexpected control flow graph state!!");
8294 emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
8296 return AfterIP.takeError();
8301 "Unexpected Insertion point location!");
8304 auto InsertBB = merged ? ExitPredBB : ExitBB;
8307 Builder.SetInsertPoint(InsertBB);
8313 Directive OMPD,
Value *EntryCall, BasicBlock *ExitBB,
bool Conditional) {
8315 if (!Conditional || !EntryCall)
8321 auto *UI =
new UnreachableInst(
Builder.getContext(), ThenBB);
8331 Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
8335 UI->eraseFromParent();
8343 omp::Directive OMPD,
InsertPointTy FinIP, Instruction *ExitCall,
8351 "Unexpected finalization stack state!");
8354 assert(Fi.DK == OMPD &&
"Unexpected Directive for Finalization call!");
8358 return std::move(Err);
8405 "copyin.not.master.end");
8412 Builder.SetInsertPoint(OMP_Entry);
8415 Value *cmp =
Builder.CreateICmpNE(MasterPtr, PrivatePtr);
8416 Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
8418 Builder.SetInsertPoint(CopyBegin);
8436 Value *Args[] = {ThreadId,
Size, Allocator};
8459 return Builder.CreateCall(Fn, Args, Name);
8473 Value *Args[] = {ThreadId, Addr, Allocator};
8480 const Twine &Name) {
8488 M.getContext(),
M.getDataLayout().getPrefTypeAlign(Int64)));
8494 const Twine &Name) {
8496 Loc,
Builder.getInt64(
M.getDataLayout().getTypeAllocSize(VarType)), Name);
8501 const Twine &Name) {
8507 return Builder.CreateCall(Fn, Args, Name);
8512 const Twine &Name) {
8514 Loc, Addr,
Builder.getInt64(
M.getDataLayout().getTypeAllocSize(VarType)),
8521 Value *DependenceAddress,
bool HaveNowaitClause) {
8531 else if (
Device->getType() != Int32)
8534 if (NumDependences ==
nullptr) {
8535 NumDependences = ConstantInt::get(Int32, 0);
8539 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8541 Ident, ThreadId, InteropVar, InteropTypeVal,
8542 Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
8551 Value *NumDependences,
Value *DependenceAddress,
bool HaveNowaitClause) {
8561 else if (
Device->getType() != Int32)
8563 if (NumDependences ==
nullptr) {
8564 NumDependences = ConstantInt::get(Int32, 0);
8568 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8570 Ident, ThreadId, InteropVar,
Device,
8571 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8580 Value *NumDependences,
8581 Value *DependenceAddress,
8582 bool HaveNowaitClause) {
8591 else if (
Device->getType() != Int32)
8593 if (NumDependences ==
nullptr) {
8594 NumDependences = ConstantInt::get(Int32, 0);
8598 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8600 Ident, ThreadId, InteropVar,
Device,
8601 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8631 assert(!Attrs.MaxThreads.empty() && !Attrs.MaxTeams.empty() &&
8632 "expected num_threads and num_teams to be specified");
8652 const std::string DebugPrefix =
"_debug__";
8653 if (KernelName.
ends_with(DebugPrefix)) {
8654 KernelName = KernelName.
drop_back(DebugPrefix.length());
8655 Kernel =
M.getFunction(KernelName);
8661 if (Attrs.MinTeams.front() > 1 || Attrs.MaxTeams.front() > 0)
8663 Attrs.MaxTeams.front());
8666 int32_t MaxThreadsVal = Attrs.MaxThreads.front();
8676 Attrs.MinThreads.front());
8681 if (MaxThreadsVal > 0 &&
8684 MaxThreadsVal = int32_t(
8685 std::min<int64_t>(int64_t(MaxThreadsVal) + 64,
8688 if (MaxThreadsVal > 0)
8703 Twine DynamicEnvironmentName = KernelName +
"_dynamic_environment";
8704 Constant *DynamicEnvironmentInitializer =
8708 DynamicEnvironmentInitializer, DynamicEnvironmentName,
8710 DL.getDefaultGlobalsAddressSpace());
8714 DynamicEnvironmentGV->
getType() == DynamicEnvironmentPtr
8715 ? DynamicEnvironmentGV
8717 DynamicEnvironmentPtr);
8720 ConfigurationEnvironment, {
8721 UseGenericStateMachineVal,
8722 MayUseNestedParallelismVal,
8731 KernelEnvironment, {
8732 ConfigurationEnvironmentInitializer,
8736 std::string KernelEnvironmentName =
8737 (KernelName +
"_kernel_environment").str();
8740 KernelEnvironmentInitializer, KernelEnvironmentName,
8742 DL.getDefaultGlobalsAddressSpace());
8745 return KernelEnvironmentGV->
getType() == KernelEnvironmentPtr
8746 ? KernelEnvironmentGV
8748 KernelEnvironmentPtr);
8755 if (!KernelEnvironment)
8763 omp::RuntimeFunction::OMPRTL___kmpc_target_init);
8765 Value *KernelLaunchEnvironment =
8768 KernelLaunchEnvironment =
8769 KernelLaunchEnvironment->
getType() == KernelLaunchEnvParamTy
8770 ? KernelLaunchEnvironment
8771 :
Builder.CreateAddrSpaceCast(KernelLaunchEnvironment,
8772 KernelLaunchEnvParamTy);
8774 Fn, {KernelEnvironment, KernelLaunchEnvironment});
8786 auto *UI =
Builder.CreateUnreachable();
8792 Builder.SetInsertPoint(WorkerExitBB);
8796 Builder.SetInsertPoint(CheckBBTI);
8797 Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
8799 CheckBBTI->eraseFromParent();
8800 UI->eraseFromParent();
8808 int32_t TeamsReductionDataSize) {
8813 omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
8817 if (!TeamsReductionDataSize)
8823 const std::string DebugPrefix =
"_debug__";
8825 KernelName = KernelName.
drop_back(DebugPrefix.length());
8826 auto *KernelEnvironmentGV =
8827 M.getNamedGlobal((KernelName +
"_kernel_environment").str());
8828 assert(KernelEnvironmentGV &&
"Expected kernel environment global\n");
8829 auto *KernelEnvironmentInitializer = KernelEnvironmentGV->getInitializer();
8831 KernelEnvironmentInitializer,
8832 ConstantInt::get(Int32, TeamsReductionDataSize), {0, 7});
8833 KernelEnvironmentGV->setInitializer(NewInitializer);
8838 if (
Kernel.hasFnAttribute(Name)) {
8839 int32_t OldLimit =
Kernel.getFnAttributeAsParsedInteger(Name);
8845std::pair<int32_t, int32_t>
8847 int32_t ThreadLimit =
8848 Kernel.getFnAttributeAsParsedInteger(
"omp_target_thread_limit");
8851 const auto &Attr =
Kernel.getFnAttribute(
"amdgpu-flat-work-group-size");
8852 if (!Attr.isValid() || !Attr.isStringAttribute())
8853 return {0, ThreadLimit};
8854 auto [LBStr, UBStr] = Attr.getValueAsString().split(
',');
8857 return {0, ThreadLimit};
8858 UB = ThreadLimit ? std::min(ThreadLimit, UB) : UB;
8866 return {0, ThreadLimit ? std::min(ThreadLimit, UB) : UB};
8868 return {0, ThreadLimit};
8874 Kernel.addFnAttr(
"omp_target_thread_limit", std::to_string(UB));
8877 Kernel.addFnAttr(
"amdgpu-flat-work-group-size",
8885std::pair<int32_t, int32_t>
8888 return {0,
Kernel.getFnAttributeAsParsedInteger(
"omp_target_num_teams")};
8892 int32_t LB, int32_t UB) {
8900 Kernel.addFnAttr(
"omp_target_num_teams", std::to_string(LB));
8903void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
8912 else if (
T.isNVPTX())
8914 else if (
T.isSPIRV())
8920 StringRef EntryFnIDName) {
8921 if (
Config.isTargetDevice()) {
8922 assert(OutlinedFn &&
"The outlined function must exist if embedded");
8926 return new GlobalVariable(
8931Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(
Function *OutlinedFn,
8932 StringRef EntryFnName) {
8936 assert(!
M.getGlobalVariable(EntryFnName,
true) &&
8937 "Named kernel already exists?");
8938 return new GlobalVariable(
8951 if (
Config.isTargetDevice() || !
Config.openMPOffloadMandatory()) {
8955 OutlinedFn = *CBResult;
8957 OutlinedFn =
nullptr;
8963 if (!IsOffloadEntry)
8966 std::string EntryFnIDName =
8968 ? std::string(EntryFnName)
8972 EntryFnName, EntryFnIDName);
8980 setOutlinedTargetRegionFunctionAttributes(OutlinedFn);
8981 auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
8982 auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
8984 EntryInfo, EntryAddr, OutlinedFnID,
8986 return OutlinedFnID;
9004 bool IsStandAlone = !BodyGenCB;
9011 MapInfo = &GenMapInfoCB(
Builder.saveIP());
9013 AllocaIP,
Builder.saveIP(), *MapInfo, Info, CustomMapperCB,
9014 true, DeviceAddrCB))
9021 Value *PointerNum =
Builder.getInt32(Info.NumberOfPtrs);
9031 SrcLocInfo, DeviceID,
9038 assert(MapperFunc &&
"MapperFunc missing for standalone target data");
9042 if (Info.HasNoWait) {
9052 if (Info.HasNoWait) {
9056 emitBlock(OffloadContBlock, CurFn,
true);
9062 bool RequiresOuterTargetTask = Info.HasNoWait;
9063 if (!RequiresOuterTargetTask)
9064 cantFail(TaskBodyCB(
nullptr,
nullptr,
9068 {}, RTArgs, Info.HasNoWait));
9071 omp::OMPRTL___tgt_target_data_begin_mapper);
9075 for (
auto DeviceMap : Info.DevicePtrInfoMap) {
9079 Builder.CreateStore(LI, DeviceMap.second.second);
9116 Value *PointerNum =
Builder.getInt32(Info.NumberOfPtrs);
9125 Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,
9148 return emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);
9149 return BeginThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9164 return emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);
9165 return EndThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9168 return emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);
9169 return BeginThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
9180 bool IsGPUDistribute) {
9181 assert((IVSize == 32 || IVSize == 64) &&
9182 "IV size is not compatible with the omp runtime");
9184 if (IsGPUDistribute)
9186 ? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_4
9187 : omp::OMPRTL___kmpc_distribute_static_init_4u)
9188 : (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_8
9189 : omp::OMPRTL___kmpc_distribute_static_init_8u);
9191 Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_4
9192 : omp::OMPRTL___kmpc_for_static_init_4u)
9193 : (IVSigned ? omp::OMPRTL___kmpc_for_static_init_8
9194 : omp::OMPRTL___kmpc_for_static_init_8u);
9201 assert((IVSize == 32 || IVSize == 64) &&
9202 "IV size is not compatible with the omp runtime");
9204 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_4
9205 : omp::OMPRTL___kmpc_dispatch_init_4u)
9206 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_8
9207 : omp::OMPRTL___kmpc_dispatch_init_8u);
9214 assert((IVSize == 32 || IVSize == 64) &&
9215 "IV size is not compatible with the omp runtime");
9217 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_4
9218 : omp::OMPRTL___kmpc_dispatch_next_4u)
9219 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_8
9220 : omp::OMPRTL___kmpc_dispatch_next_8u);
9227 assert((IVSize == 32 || IVSize == 64) &&
9228 "IV size is not compatible with the omp runtime");
9230 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_4
9231 : omp::OMPRTL___kmpc_dispatch_fini_4u)
9232 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_8
9233 : omp::OMPRTL___kmpc_dispatch_fini_8u);
9244 DenseMap<
Value *, std::tuple<Value *, unsigned>> &ValueReplacementMap) {
9252 auto GetUpdatedDIVariable = [&](
DILocalVariable *OldVar,
unsigned arg) {
9256 if (NewVar && (arg == NewVar->
getArg()))
9266 auto UpdateDebugRecord = [&](
auto *DR) {
9269 for (
auto Loc : DR->location_ops()) {
9270 auto Iter = ValueReplacementMap.find(
Loc);
9271 if (Iter != ValueReplacementMap.end()) {
9272 DR->replaceVariableLocationOp(
Loc, std::get<0>(Iter->second));
9273 ArgNo = std::get<1>(Iter->second) + 1;
9277 DR->setVariable(GetUpdatedDIVariable(OldVar, ArgNo));
9282 if (DVR->getNumVariableLocationOps() != 1u) {
9283 DVR->setKillLocation();
9286 Value *
Loc = DVR->getVariableLocationOp(0u);
9293 RequiredBB = &DVR->getFunction()->getEntryBlock();
9295 if (RequiredBB && RequiredBB != CurBB) {
9307 UpdateDebugRecord(&DVR);
9308 MoveDebugRecordToCorrectBlock(&DVR);
9311 for (
auto *DVR : DVRsToDelete)
9312 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);
9316 Module *M = Func->getParent();
9319 DB.createQualifiedType(dwarf::DW_TAG_pointer_type,
nullptr);
9320 unsigned ArgNo = Func->arg_size();
9322 NewSP,
"dyn_ptr", ArgNo, NewSP->
getFile(), 0, VoidPtrTy,
9323 false, DINode::DIFlags::FlagArtificial);
9325 Argument *LastArg = Func->getArg(Func->arg_size() - 1);
9326 DB.insertDeclare(LastArg, Var, DB.createExpression(),
Loc,
9348 for (
auto &Arg : Inputs)
9349 ParameterTypes.
push_back(Arg->getType()->isPointerTy()
9353 for (
auto &Arg : Inputs)
9354 ParameterTypes.
push_back(Arg->getType());
9362 auto BB = Builder.GetInsertBlock();
9363 auto M = BB->getModule();
9374 if (TargetCpuAttr.isStringAttribute())
9375 Func->addFnAttr(TargetCpuAttr);
9377 auto TargetFeaturesAttr = ParentFn->
getFnAttribute(
"target-features");
9378 if (TargetFeaturesAttr.isStringAttribute())
9379 Func->addFnAttr(TargetFeaturesAttr);
9384 OMPBuilder.
emitUsed(
"llvm.compiler.used", {ExecMode});
9394 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9398 Builder.SetInsertPoint(EntryBB);
9409 BasicBlock *UserCodeEntryBB = Builder.GetInsertBlock();
9418 splitBB(Builder,
true,
"outlined.body");
9420 CBFunc(Builder.saveIP(), OutlinedBodyBB->
begin(), ExitBB);
9423 Builder.SetInsertPoint(ExitBB);
9431 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9438 Builder.CreateRetVoid();
9442 auto AllocaIP = Builder.saveIP();
9447 const auto &ArgRange =
make_range(Func->arg_begin(), Func->arg_end() - 1);
9479 if (Instr->getFunction() == Func)
9480 Instr->replaceUsesOfWith(
Input, InputCopy);
9486 for (
auto InArg :
zip(Inputs, ArgRange)) {
9488 Argument &Arg = std::get<1>(InArg);
9489 Value *InputCopy =
nullptr;
9492 Arg,
Input, InputCopy, AllocaIP, Builder.saveIP(), ExitBB->
begin());
9495 Builder.restoreIP(*AfterIP);
9496 ValueReplacementMap[
Input] = std::make_tuple(InputCopy, Arg.
getArgNo());
9516 DeferredReplacement.push_back(std::make_pair(
Input, InputCopy));
9523 ReplaceValue(
Input, InputCopy, Func);
9527 for (
auto Deferred : DeferredReplacement)
9528 ReplaceValue(std::get<0>(Deferred), std::get<1>(Deferred), Func);
9531 ValueReplacementMap);
9538 Value *TaskWithPrivates) {
9556 const size_t NumOffloadingArrays,
const int SharedArgsOperandNo) {
9561 assert((!NumOffloadingArrays || PrivatesTy) &&
9562 "PrivatesTy cannot be nullptr when there are offloadingArrays"
9592 Type *TaskPtrTy = OMPBuilder.TaskPtr;
9593 [[maybe_unused]]
Type *TaskTy = OMPBuilder.Task;
9599 ".omp_target_task_proxy_func", M);
9600 Value *ThreadId = ProxyFn->getArg(0);
9601 Value *TaskWithPrivates = ProxyFn->getArg(1);
9602 ThreadId->
setName(
"thread.id");
9603 TaskWithPrivates->
setName(
"task");
9605 bool HasShareds = SharedArgsOperandNo > 0;
9606 bool HasOffloadingArrays = NumOffloadingArrays > 0;
9610 Builder.SetInsertPoint(EntryBB);
9617 if (HasOffloadingArrays) {
9618 assert(TaskTy != TaskWithPrivatesTy &&
9619 "If there are offloading arrays to pass to the target"
9620 "TaskTy cannot be the same as TaskWithPrivatesTy");
9623 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskWithPrivates, 1);
9624 for (
unsigned int i = 0; i < NumOffloadingArrays; ++i)
9626 Builder.CreateStructGEP(PrivatesTy, Privates, i));
9630 auto *ArgStructAlloca =
9632 assert(ArgStructAlloca &&
9633 "Unable to find the alloca instruction corresponding to arguments "
9634 "for extracted function");
9636 std::optional<TypeSize> ArgAllocSize =
9638 assert(ArgStructType && ArgAllocSize &&
9639 "Unable to determine size of arguments for extracted function");
9640 uint64_t StructSize = ArgAllocSize->getFixedValue();
9643 Builder.CreateAlloca(ArgStructType,
nullptr,
"structArg");
9645 Value *SharedsSize = Builder.getInt64(StructSize);
9650 Builder.CreateMemCpy(
9651 NewArgStructAlloca, NewArgStructAlloca->
getAlign(), LoadShared,
9653 KernelLaunchArgs.
push_back(NewArgStructAlloca);
9656 Builder.CreateRetVoid();
9662 return GEP->getSourceElementType();
9664 return Alloca->getAllocatedType();
9688 if (OffloadingArraysToPrivatize.
empty() && DescriptorTypes.
empty())
9689 return OMPIRBuilder.Task;
9692 for (
Value *
V : OffloadingArraysToPrivatize) {
9693 assert(
V->getType()->isPointerTy() &&
9694 "Expected pointer to array to privatize. Got a non-pointer value "
9697 assert(ArrayTy &&
"ArrayType cannot be nullptr");
9704 "struct.task_with_privates");
9719 EntryFnName, Inputs, CBFunc,
9720 ArgAccessorFuncCB, OutlinedFnLoc);
9724 EntryInfo, GenerateOutlinedFunction, IsOffloadEntry, OutlinedFn,
9863 auto OI = std::make_unique<OutlineInfo>();
9864 OI->EntryBB = TargetTaskAllocaBB;
9865 OI->OuterAllocBB = AllocaIP.getNodeParent();
9870 Builder, AllocaIP, ToBeDeleted, TargetTaskAllocaIP,
"global.tid",
false));
9873 Builder.restoreIP(TargetTaskBodyIP);
9874 if (
Error Err = TaskBodyCB(DeviceID, RTLoc, TargetTaskAllocaIP))
9892 bool NeedsTargetTask = HasNoWait && DeviceID;
9893 if (NeedsTargetTask) {
9899 OffloadingArraysToPrivatize.
push_back(V);
9900 OI->ExcludeArgsFromAggregate.push_back(V);
9905 if (!NeedsTargetTask)
9906 NonContiguousDescriptors.clear();
9907 OI->PostOutlineCB = [
this, ToBeDeleted, Dependencies, NeedsTargetTask,
9908 DeviceID, OffloadingArraysToPrivatize,
9909 NonContiguousDescriptors,
9913 "there must be a single user for the outlined function");
9927 const unsigned int NumStaleCIArgs = StaleCI->
arg_size();
9928 bool HasShareds = NumStaleCIArgs > OffloadingArraysToPrivatize.
size() + 1;
9930 NumStaleCIArgs == (OffloadingArraysToPrivatize.
size() + 2)) &&
9931 "Wrong number of arguments for StaleCI when shareds are present");
9932 int SharedArgOperandNo =
9933 HasShareds ? OffloadingArraysToPrivatize.
size() + 1 : 0;
9938 for (
const auto &Descriptor : NonContiguousDescriptors)
9939 DescriptorTypes.
push_back(Descriptor.Storage->getAllocatedType());
9941 *
this, OffloadingArraysToPrivatize, DescriptorTypes);
9944 if (!OffloadingArraysToPrivatize.
empty())
9949 *
this,
Builder, StaleCI, PrivatesTy, TaskWithPrivatesTy,
9950 OffloadingArraysToPrivatize.
size(), SharedArgOperandNo);
9952 LLVM_DEBUG(
dbgs() <<
"Proxy task entry function created: " << *ProxyFn
9955 Builder.SetInsertPoint(StaleCI);
9972 OMPRTL___kmpc_omp_target_task_alloc);
9984 M.getDataLayout().getTypeStoreSize(TaskWithPrivatesTy));
9991 auto *ArgStructAlloca =
9993 assert(ArgStructAlloca &&
9994 "Unable to find the alloca instruction corresponding to arguments "
9995 "for extracted function");
9996 std::optional<TypeSize> ArgAllocSize =
9999 "Unable to determine size of arguments for extracted function");
10000 SharedsSize =
Builder.getInt64(ArgAllocSize->getFixedValue());
10019 TaskSize, SharedsSize,
10022 if (NeedsTargetTask) {
10023 assert(DeviceID &&
"Expected non-empty device ID.");
10036 if (!OffloadingArraysToPrivatize.
empty()) {
10038 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskData, 1);
10039 Value *PrivatePointersArray =
nullptr;
10040 for (
unsigned int i = 0; i < OffloadingArraysToPrivatize.
size(); ++i) {
10041 Value *PtrToPrivatize = OffloadingArraysToPrivatize[i];
10048 "ElementType should match ArrayType");
10051 Value *Dst =
Builder.CreateStructGEP(PrivatesTy, Privates, i);
10054 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(ElementType)));
10055 if (PtrToPrivatize == PointersArray)
10056 PrivatePointersArray = Dst;
10061 assert(PrivatePointersArray &&
"missing task-private pointer array");
10063 PrivatesTy, Privates, OffloadingArraysToPrivatize.
size() +
I);
10065 Dst,
Alignment, Descriptor.Storage, Descriptor.Storage->getAlign(),
10066 Builder.getInt64(
M.getDataLayout().getTypeStoreSize(
10067 Descriptor.Storage->getAllocatedType())));
10070 Descriptor.MapIndex);
10075 Value *DepArray =
nullptr;
10076 Value *NumDeps =
nullptr;
10079 NumDeps = Dependencies.
NumDeps;
10080 }
else if (!Dependencies.
Deps.empty()) {
10082 NumDeps =
Builder.getInt32(Dependencies.
Deps.size());
10093 if (!NeedsTargetTask) {
10102 ConstantInt::get(
Builder.getInt32Ty(), 0),
10115 }
else if (DepArray) {
10123 {Ident, ThreadID, TaskData, NumDeps, DepArray,
10124 ConstantInt::get(
Builder.getInt32Ty(), 0),
10132 Builder.ClearInsertionPoint();
10135 I->eraseFromParent();
10140 << *(
Builder.GetInsertBlock()) <<
"\n");
10142 << *(
Builder.getModule()) <<
"\n");
10153 CustomMapperCB, IsNonContiguous, DeviceAddrCB))
10176 Builder.restoreIP(IP);
10182 return Builder.saveIP();
10185 bool HasDependencies = !Dependencies.
empty();
10186 bool RequiresOuterTargetTask = HasNoWait || HasDependencies;
10203 if (OutlinedFnID && DeviceID)
10205 EmitTargetCallFallbackCB, KArgs,
10206 DeviceID, RTLoc, TargetTaskAllocaIP);
10214 return EmitTargetCallFallbackCB(OMPBuilder.
Builder.
saveIP());
10221 auto &&EmitTargetCallElse =
10228 if (RequiresOuterTargetTask) {
10235 Dependencies, EmptyRTArgs, HasNoWait);
10237 return EmitTargetCallFallbackCB(Builder.saveIP());
10240 Builder.restoreIP(AfterIP);
10244 auto &&EmitTargetCallThen =
10248 Info.HasNoWait = HasNoWait;
10253 AllocaIP, Builder.saveIP(), Info, RTArgs, MapInfo, CustomMapperCB,
10259 for (
auto [DefaultVal, RuntimeVal] :
10261 NumTeamsC.
push_back(RuntimeVal ? RuntimeVal
10262 : Builder.getInt32(DefaultVal));
10266 auto InitMaxThreadsClause = [&Builder](
Value *
Clause) {
10268 Clause = Builder.CreateIntCast(
Clause, Builder.getInt32Ty(),
10272 auto CombineMaxThreadsClauses = [&Builder](
Value *
Clause,
Value *&Result) {
10275 Result ? Builder.CreateSelect(Builder.CreateICmpULT(Result,
Clause),
10283 Value *MaxThreadsClause =
10285 ? InitMaxThreadsClause(RuntimeAttrs.
MaxThreads.front())
10288 for (
auto [TeamsVal, TargetVal] :
zip_equal(
10290 Value *TeamsThreadLimitClause = InitMaxThreadsClause(TeamsVal);
10291 Value *NumThreads = InitMaxThreadsClause(TargetVal);
10293 CombineMaxThreadsClauses(TeamsThreadLimitClause, NumThreads);
10294 CombineMaxThreadsClauses(MaxThreadsClause, NumThreads);
10296 NumThreadsC.
push_back(NumThreads ? NumThreads : Builder.getInt32(0));
10299 unsigned NumTargetItems = Info.NumberOfPtrs;
10300 Value *RTLoc = RTLocOverride;
10311 Builder.getInt64Ty(),
10313 : Builder.getInt64(0);
10317 DynCGroupMem = Builder.getInt32(0);
10320 NumTargetItems, RTArgs, TripCount, NumTeamsC, NumThreadsC, DynCGroupMem,
10321 HasNoWait,
false,
false,
10322 DynCGroupMemFallback);
10329 if (RequiresOuterTargetTask)
10331 RTLoc, AllocaIP, Dependencies,
10332 KArgs.
RTArgs, Info.HasNoWait);
10335 Builder, OutlinedFnID, EmitTargetCallFallbackCB, KArgs,
10336 RuntimeAttrs.
DeviceID, RTLoc, AllocaIP);
10339 Builder.restoreIP(AfterIP);
10347 return EmitTargetCallElse(AllocaIP, Builder.saveIP(), DeallocBlocks);
10351 return EmitTargetCallThen(AllocaIP, Builder.saveIP(), DeallocBlocks);
10353 return OMPBuilder.
emitIfClause(IfCond, EmitTargetCallThen, EmitTargetCallElse,
10367 bool HasNowait,
Value *DynCGroupMem,
10369 Value *RTLocOverride) {
10374 Builder.restoreIP(CodeGenIP);
10382 *
this,
Builder, IsOffloadEntry, EntryInfo, DefaultAttrs, OutlinedFn,
10383 OutlinedFnID, Inputs, CBFunc, ArgAccessorFuncCB, OutlinedFnLoc))
10389 if (!
Config.isTargetDevice()) {
10391 *
this,
Builder, RTLocOverride, AllocaIP, DeallocBlocks, Info,
10392 DefaultAttrs, RuntimeAttrs, IfCond, OutlinedFn, OutlinedFnID,
10393 Inputs, GenMapInfoCB, CustomMapperCB, Dependencies, HasNowait,
10394 DynCGroupMem, DynCGroupMemFallback))
10410 return OS.
str().str();
10415 return OpenMPIRBuilder::getNameWithSeparators(Parts,
Config.firstSeparator(),
10421 auto &Elem = *
InternalVars.try_emplace(Name,
nullptr).first;
10423 assert(Elem.second->getValueType() == Ty &&
10424 "OMP internal variable has different type than requested");
10437 :
M.getTargetTriple().isAMDGPU()
10439 :
DL.getDefaultGlobalsAddressSpace();
10440 auto Linkage = this->
M.getTargetTriple().isWasm()
10448 const llvm::Align PtrAlign =
DL.getPointerABIAlignment(AddressSpaceVal);
10449 GV->setAlignment(std::max(TypeAlign, PtrAlign));
10453 return Elem.second;
10456Value *OpenMPIRBuilder::getOMPCriticalRegionLock(
StringRef CriticalName) {
10457 std::string Prefix =
Twine(
"gomp_critical_user_", CriticalName).
str();
10458 std::string Name = getNameWithSeparators({Prefix,
"var"},
".",
".");
10469 return SizePtrToInt;
10474 std::string VarName) {
10482 return MaptypesArrayGlobal;
10487 unsigned NumOperands,
10496 ArrI8PtrTy,
nullptr,
".offload_baseptrs");
10500 ArrI64Ty,
nullptr,
".offload_sizes");
10511 int64_t DeviceID,
unsigned NumOperands) {
10517 Value *ArgsBaseGEP =
10519 {Builder.getInt32(0), Builder.getInt32(0)});
10522 {Builder.getInt32(0), Builder.getInt32(0)});
10523 Value *ArgSizesGEP =
10525 {Builder.getInt32(0), Builder.getInt32(0)});
10529 Builder.getInt32(NumOperands),
10530 ArgsBaseGEP, ArgsGEP, ArgSizesGEP,
10531 MaptypesArg, MapnamesArg, NullPtr});
10538 assert((!ForEndCall || Info.separateBeginEndCalls()) &&
10539 "expected region end call to runtime only when end call is separate");
10541 auto VoidPtrTy = UnqualPtrTy;
10542 auto VoidPtrPtrTy = UnqualPtrTy;
10544 auto Int64PtrTy = UnqualPtrTy;
10547 if (!Info.NumberOfPtrs) {
10559 Info.RTArgs.BasePointersArray,
10562 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
10566 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
10570 ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd
10571 : Info.RTArgs.MapTypesArray,
10577 if (!Info.EmitDebug)
10581 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,
10586 if (!Info.HasMapper)
10590 Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);
10611 "struct.descriptor_dim");
10613 enum { OffsetFD = 0, CountFD, StrideFD };
10617 for (
unsigned I = 0, L = 0, E = NonContigInfo.
Dims.
size();
I < E; ++
I) {
10620 if (NonContigInfo.
Dims[
I] == 1)
10625 Builder.CreateAlloca(ArrayTy,
nullptr,
"dims");
10626 Info.RTArgs.NonContiguousDescriptors.push_back({
I, DimsAddr});
10627 Builder.restoreIP(CodeGenIP);
10628 for (
unsigned II = 0, EE = NonContigInfo.
Dims[
I];
II < EE; ++
II) {
10629 unsigned RevIdx = EE -
II - 1;
10633 Value *OffsetLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);
10635 NonContigInfo.
Offsets[L][RevIdx], OffsetLVal,
10636 M.getDataLayout().getPrefTypeAlign(OffsetLVal->
getType()));
10638 Value *CountLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);
10640 NonContigInfo.
Counts[L][RevIdx], CountLVal,
10641 M.getDataLayout().getPrefTypeAlign(CountLVal->
getType()));
10643 Value *StrideLVal =
Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);
10645 NonContigInfo.
Strides[L][RevIdx], StrideLVal,
10646 M.getDataLayout().getPrefTypeAlign(CountLVal->
getType()));
10649 Builder.restoreIP(CodeGenIP);
10650 Value *DAddr =
Builder.CreatePointerBitCastOrAddrSpaceCast(
10651 DimsAddr,
Builder.getPtrTy());
10654 Info.RTArgs.PointersArray, 0,
I);
10656 DAddr,
P,
M.getDataLayout().getPrefTypeAlign(
Builder.getPtrTy()));
10661void OpenMPIRBuilder::emitUDMapperArrayInitOrDel(
10665 StringRef Prefix = IsInit ?
".init" :
".del";
10671 Builder.CreateICmpSGT(
Size, Builder.getInt64(1),
"omp.arrayinit.isarray");
10672 Value *DeleteBit = Builder.CreateAnd(
10675 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10676 OpenMPOffloadMappingFlags::OMP_MAP_DELETE)));
10681 Value *BaseIsBegin = Builder.CreateICmpNE(
Base, Begin);
10682 Cond = Builder.CreateOr(IsArray, BaseIsBegin);
10683 DeleteCond = Builder.CreateIsNull(
10688 DeleteCond =
Builder.CreateIsNotNull(
10704 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10705 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10706 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10707 MapTypeArg =
Builder.CreateOr(
10710 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10711 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT)));
10715 Value *OffloadingArgs[] = {MapperHandle,
Base, Begin,
10716 ArraySize, MapTypeArg, MapName};
10727 bool PreserveMemberOfFlags,
bool PropagatePresentToPointeeStorage,
10728 bool PropagatePresentToNonPointeeStorage) {
10742 MapperFn->
addFnAttr(Attribute::NoInline);
10743 MapperFn->
addFnAttr(Attribute::NoUnwind);
10754 Builder.SetInsertPoint(EntryBB);
10769 Value *PtrBegin = BeginIn;
10775 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn,
Size,
10776 MapType, MapName, ElementSize, HeadBB,
10787 Builder.CreateICmpEQ(PtrBegin, PtrEnd,
"omp.arraymap.isempty");
10788 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
10794 Builder.CreatePHI(PtrBegin->
getType(), 2,
"omp.arraymap.ptrcurrent");
10795 PtrPHI->addIncoming(PtrBegin, HeadBB);
10800 return Info.takeError();
10806 Value *ShiftedPreviousSize =
nullptr;
10870 auto pushComponent = [&](
Value *CurBaseArg,
Value *CurBeginArg,
10872 uint64_t RawType,
bool HasAttachPtrFlag,
10875 constexpr uint64_t MemberOfMask =
10876 static_cast<uint64_t
>(OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF);
10877 constexpr uint64_t AttachBit =
10878 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10879 OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
10880 constexpr uint64_t PtrAndObjBit =
10881 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10882 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ);
10884 Value *MemberMapType;
10885 if (PreserveMemberOfFlags || (RawType & AttachBit) || HasAttachPtrFlag) {
10886 if (RawType & MemberOfMask)
10887 MemberMapType =
Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10889 MemberMapType = OriMapType;
10891 MemberMapType =
Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10909 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10910 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10911 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10921 Builder.CreateCondBr(IsAlloc, AllocBB, AllocElseBB);
10927 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10928 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10929 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10935 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10936 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
10937 Builder.CreateCondBr(IsTo, ToBB, ToElseBB);
10943 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10944 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10950 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10951 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10952 Builder.CreateCondBr(IsFrom, FromBB, EndBB);
10958 ~
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
10959 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
10967 CurMapType->
addIncoming(MemberMapType, ToElseBB);
11006 uint64_t ModifierBits =
11007 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11008 OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS |
11009 OpenMPOffloadMappingFlags::OMP_MAP_DELETE |
11010 OpenMPOffloadMappingFlags::OMP_MAP_CLOSE);
11011 bool IsPresentEligibleStorage = !(RawType & (AttachBit | PtrAndObjBit));
11012 bool PropagatePresent =
11013 IsPresentEligibleStorage &&
11014 (HasAttachPtrFlag ? PropagatePresentToPointeeStorage
11015 : PropagatePresentToNonPointeeStorage);
11016 if (PropagatePresent)
11018 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11019 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11020 Value *ImportedModifierBits =
11023 CurMapType, ImportedModifierBits,
"omp.maptype.with.modifiers");
11028 Value *FinalMapType =
11029 (RawType & AttachBit) ? CurMapType : CurMapTypeWithModifiers;
11031 Value *OffloadingArgs[] = {MapperHandle, CurBaseArg, CurBeginArg,
11032 CurSizeArg, FinalMapType, CurNameArg};
11033 if (ChildMapperFn) {
11050 unsigned FirstStaticIdx = 0;
11051 if (Info->LeadingParentCond) {
11052 assert(PreserveMemberOfFlags &&
11053 "conditional leading parent requires pre-shaped MEMBER_OF flags");
11054 assert(!Info->BasePointers.empty() &&
"no leading parent component");
11059 Builder.CreateCondBr(Info->LeadingParentCond, PushBB, ContBB);
11061 Value *CurNameArg = Info->Names.size()
11065 Info->BasePointers[0], Info->Pointers[0], Info->Sizes[0], CurNameArg,
11066 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11068 Info->HasAttachPtr[0],
nullptr);
11072 FirstStaticIdx = 1;
11080 Value *OffloadingArgs[] = {MapperHandle};
11084 if (Info->LeadingParentCond)
11085 PreviousSize =
Builder.CreateSub(PreviousSize,
Builder.getInt64(1));
11086 ShiftedPreviousSize =
11090 for (
unsigned I = FirstStaticIdx;
I < Info->BasePointers.size(); ++
I) {
11091 Value *CurNameArg = Info->Names.size()
11095 if (!ChildMapperFn)
11097 LastBB = pushComponent(
11098 Info->BasePointers[
I], Info->Pointers[
I], Info->Sizes[
I], CurNameArg,
11099 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11101 Info->HasAttachPtr[
I], *ChildMapperFn);
11118 Entry[0], Entry[1], Entry[2],
11120 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11130 LastBB =
Builder.GetInsertBlock();
11136 "omp.arraymap.next");
11137 PtrPHI->addIncoming(PtrNext, LastBB);
11138 Value *IsDone =
Builder.CreateICmpEQ(PtrNext, PtrEnd,
"omp.arraymap.isdone");
11140 Builder.CreateCondBr(IsDone, ExitBB, BodyBB);
11145 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn,
Size,
11146 MapType, MapName, ElementSize, DoneBB,
11159 bool IsNonContiguous,
11163 Info.clearArrayInfo();
11166 if (Info.NumberOfPtrs == 0)
11175 Info.RTArgs.BasePointersArray =
Builder.CreateAlloca(
11176 PointerArrayType,
nullptr,
".offload_baseptrs");
11178 Info.RTArgs.PointersArray =
Builder.CreateAlloca(
11179 PointerArrayType,
nullptr,
".offload_ptrs");
11181 PointerArrayType,
nullptr,
".offload_mappers");
11182 Info.RTArgs.MappersArray = MappersArray;
11189 ConstantInt::get(Int64Ty, 0));
11191 for (
unsigned I = 0, E = CombinedInfo.
Sizes.
size();
I < E; ++
I) {
11192 bool IsNonContigEntry =
11194 (
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11196 OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG) != 0);
11199 if (IsNonContigEntry) {
11201 "Index must be in-bounds for NON_CONTIG Dims array");
11203 assert(DimCount > 0 &&
"NON_CONTIG DimCount must be > 0");
11204 ConstSizes[
I] = ConstantInt::get(Int64Ty, DimCount);
11209 ConstSizes[
I] = CI;
11213 RuntimeSizes.
set(
I);
11216 if (RuntimeSizes.
all()) {
11218 Info.RTArgs.SizesArray =
Builder.CreateAlloca(
11219 SizeArrayType,
nullptr,
".offload_sizes");
11225 auto *SizesArrayGbl =
11230 if (!RuntimeSizes.
any()) {
11231 Info.RTArgs.SizesArray = SizesArrayGbl;
11233 unsigned IndexSize =
M.getDataLayout().getIndexSizeInBits(0);
11234 Align OffloadSizeAlign =
M.getDataLayout().getABIIntegerTypeAlignment(64);
11237 SizeArrayType,
nullptr,
".offload_sizes");
11241 Buffer,
M.getDataLayout().getPrefTypeAlign(Buffer->
getType()),
11242 SizesArrayGbl, OffloadSizeAlign,
11247 Info.RTArgs.SizesArray = Buffer;
11255 for (
auto mapFlag : CombinedInfo.
Types)
11257 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11261 Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
11267 Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
11268 Info.EmitDebug =
true;
11270 Info.RTArgs.MapNamesArray =
11272 Info.EmitDebug =
false;
11277 if (Info.separateBeginEndCalls()) {
11278 bool EndMapTypesDiffer =
false;
11279 for (uint64_t &
Type : Mapping) {
11280 if (
Type &
static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>
>(
11281 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT)) {
11282 Type &= ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11283 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11284 EndMapTypesDiffer =
true;
11287 if (EndMapTypesDiffer) {
11289 Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
11294 for (
unsigned I = 0;
I < Info.NumberOfPtrs; ++
I) {
11297 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.BasePointersArray,
11299 Builder.CreateAlignedStore(BPVal, BP,
11300 M.getDataLayout().getPrefTypeAlign(PtrTy));
11302 if (Info.requiresDevicePointerInfo()) {
11304 CodeGenIP =
Builder.saveIP();
11306 Info.DevicePtrInfoMap[BPVal] = {BP,
Builder.CreateAlloca(PtrTy)};
11309 DeviceAddrCB(
I, Info.DevicePtrInfoMap[BPVal].second);
11311 Info.DevicePtrInfoMap[BPVal] = {BP, BP};
11313 DeviceAddrCB(
I, BP);
11319 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray, 0,
11322 Builder.CreateAlignedStore(PVal,
P,
11323 M.getDataLayout().getPrefTypeAlign(PtrTy));
11325 if (RuntimeSizes.
test(
I)) {
11327 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
11333 S,
M.getDataLayout().getPrefTypeAlign(PtrTy));
11336 unsigned IndexSize =
M.getDataLayout().getIndexSizeInBits(0);
11339 auto CustomMFunc = CustomMapperCB(
I);
11341 return CustomMFunc.takeError();
11343 MFunc =
Builder.CreatePointerCast(*CustomMFunc, PtrTy);
11346 PointerArrayType, MappersArray,
11349 MFunc, MAddr,
M.getDataLayout().getPrefTypeAlign(MAddr->
getType()));
11353 Info.NumberOfPtrs == 0)
11370 Builder.ClearInsertionPoint();
11401 auto CondConstant = CI->getSExtValue();
11403 return ThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
11405 return ElseGen(AllocaIP,
Builder.saveIP(), DeallocBlocks);
11415 Builder.CreateCondBr(
Cond, ThenBlock, ElseBlock);
11418 if (
Error Err = ThenGen(AllocaIP,
Builder.saveIP(), DeallocBlocks)) {
11428 if (
Error Err = ElseGen(AllocaIP,
Builder.saveIP(), DeallocBlocks)) {
11439bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
11443 "Unexpected Atomic Ordering.");
11445 bool Flush =
false;
11507 assert(
X.Var->getType()->isPointerTy() &&
11508 "OMP Atomic expects a pointer to target memory");
11509 Type *XElemTy =
X.ElemTy;
11512 "OMP atomic read expected a scalar type");
11514 Value *XRead =
nullptr;
11518 Builder.CreateLoad(XElemTy,
X.Var,
X.IsVolatile,
"omp.atomic.read");
11527 unsigned LoadSize =
DL.getTypeStoreSize(XElemTy);
11530 OldVal->
getAlign(),
true , AllocaIP,
X.Var);
11532 XRead = AtomicLoadRes.first;
11539 Builder.CreateLoad(IntCastTy,
X.Var,
X.IsVolatile,
"omp.atomic.load");
11542 XRead =
Builder.CreateBitCast(XLoad, XElemTy,
"atomic.flt.cast");
11544 XRead =
Builder.CreateIntToPtr(XLoad, XElemTy,
"atomic.ptr.cast");
11547 checkAndEmitFlushAfterAtomic(
Loc, AO, AtomicKind::Read);
11548 Builder.CreateStore(XRead, V.Var, V.IsVolatile);
11559 assert(
X.Var->getType()->isPointerTy() &&
11560 "OMP Atomic expects a pointer to target memory");
11561 Type *XElemTy =
X.ElemTy;
11564 "OMP atomic write expected a scalar type");
11572 unsigned LoadSize =
DL.getTypeStoreSize(XElemTy);
11575 OldVal->
getAlign(),
true , AllocaIP,
X.Var);
11583 Builder.CreateBitCast(Expr, IntCastTy,
"atomic.src.int.cast");
11588 checkAndEmitFlushAfterAtomic(
Loc, AO, AtomicKind::Write);
11595 AtomicUpdateCallbackTy &UpdateOp,
bool IsXBinopExpr,
11596 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11602 Type *XTy =
X.Var->getType();
11604 "OMP Atomic expects a pointer to target memory");
11605 Type *XElemTy =
X.ElemTy;
11608 "OMP atomic update expected a scalar or struct type");
11612 AllocaIP,
X.Var,
X.ElemTy, Expr, AO, RMWOp, UpdateOp,
X.IsVolatile,
11613 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11615 return AtomicResult.takeError();
11616 checkAndEmitFlushAfterAtomic(
Loc, AO, AtomicKind::Update);
11621Value *OpenMPIRBuilder::emitRMWOpAsInstruction(
Value *Src1,
Value *Src2,
11625 return Builder.CreateAdd(Src1, Src2);
11627 return Builder.CreateSub(Src1, Src2);
11629 return Builder.CreateAnd(Src1, Src2);
11631 return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
11633 return Builder.CreateOr(Src1, Src2);
11635 return Builder.CreateXor(Src1, Src2);
11637 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, Src1, Src2);
11639 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, Src1, Src2);
11641 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, Src1, Src2);
11643 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, Src1, Src2);
11645 return Builder.CreateFAdd(Src1, Src2);
11647 return Builder.CreateFSub(Src1, Src2);
11649 return Builder.CreateMaxNum(Src1, Src2);
11651 return Builder.CreateMinNum(Src1, Src2);
11653 return Builder.CreateMaximum(Src1, Src2);
11655 return Builder.CreateMinimum(Src1, Src2);
11684Expected<std::pair<Value *, Value *>> OpenMPIRBuilder::emitAtomicUpdate(
11687 AtomicUpdateCallbackTy &UpdateOp,
bool VolatileX,
bool IsXBinopExpr,
11688 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11690 bool emitRMWOp =
false;
11707 emitRMWOp = XElemTy;
11711 emitRMWOp = (IsXBinopExpr && XElemTy);
11719 std::pair<Value *, Value *> Res;
11721 AtomicRMWInst *RMWInst =
11722 Builder.CreateAtomicRMW(RMWOp,
X, Expr, llvm::MaybeAlign(), AO);
11723 if (IsIgnoreDenormalMode)
11724 RMWInst->
setMetadata(llvm::LLVMContext::MD_atomic_ignore_denormal_mode,
11726 if (
T.isAMDGPU()) {
11727 if (!IsFineGrainedMemory)
11728 RMWInst->
setMetadata(
"amdgpu.no.fine.grained.memory",
11730 if (!IsRemoteMemory)
11734 Res.first = RMWInst;
11739 Res.second = Res.first;
11741 Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
11744 Builder.CreateLoad(XElemTy,
X,
X->getName() +
".atomic.load");
11750 OpenMPIRBuilder::AtomicInfo atomicInfo(
11752 OldVal->
getAlign(),
true , AllocaIP,
X);
11753 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11756 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11763 AllocaInst *NewAtomicAddr =
Builder.CreateAlloca(XElemTy);
11764 NewAtomicAddr->
setName(
X->getName() +
"x.new.val");
11765 Builder.SetInsertPoint(ContBB);
11767 PHI->addIncoming(AtomicLoadRes.first, CurBB);
11769 Expected<Value *> CBResult = UpdateOp(OldExprVal,
Builder);
11772 Value *Upd = *CBResult;
11773 Builder.CreateStore(Upd, NewAtomicAddr);
11776 auto Result = atomicInfo.EmitAtomicCompareExchangeLibcall(
11777 AtomicLoadRes.second, NewAtomicAddr, AO, Failure);
11778 LoadInst *PHILoad =
Builder.CreateLoad(XElemTy,
Result.first);
11779 PHI->addIncoming(PHILoad,
Builder.GetInsertBlock());
11782 Res.first = OldExprVal;
11785 if (UnreachableInst *ExitTI =
11788 Builder.SetInsertPoint(ExitBB);
11790 Builder.SetInsertPoint(ExitTI);
11793 IntegerType *IntCastTy =
11796 Builder.CreateLoad(IntCastTy,
X,
X->getName() +
".atomic.load");
11806 CurBBTI = CurBBTI ? CurBBTI :
Builder.CreateUnreachable();
11813 AllocaInst *NewAtomicAddr =
Builder.CreateAlloca(XElemTy);
11814 NewAtomicAddr->
setName(
X->getName() +
"x.new.val");
11815 Builder.SetInsertPoint(ContBB);
11817 PHI->addIncoming(OldVal, CurBB);
11822 OldExprVal =
Builder.CreateBitCast(
PHI, XElemTy,
11823 X->getName() +
".atomic.fltCast");
11825 OldExprVal =
Builder.CreateIntToPtr(
PHI, XElemTy,
11826 X->getName() +
".atomic.ptrCast");
11830 Expected<Value *> CBResult = UpdateOp(OldExprVal,
Builder);
11833 Value *Upd = *CBResult;
11834 Builder.CreateStore(Upd, NewAtomicAddr);
11835 LoadInst *DesiredVal =
Builder.CreateLoad(IntCastTy, NewAtomicAddr);
11839 X,
PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
11840 Result->setVolatile(VolatileX);
11841 Value *PreviousVal =
Builder.CreateExtractValue(Result, 0);
11842 Value *SuccessFailureVal =
Builder.CreateExtractValue(Result, 1);
11843 PHI->addIncoming(PreviousVal,
Builder.GetInsertBlock());
11844 Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
11846 Res.first = OldExprVal;
11850 if (UnreachableInst *ExitTI =
11853 Builder.SetInsertPoint(ExitBB);
11855 Builder.SetInsertPoint(ExitTI);
11866 bool UpdateExpr,
bool IsPostfixUpdate,
bool IsXBinopExpr,
11867 bool IsIgnoreDenormalMode,
bool IsFineGrainedMemory,
bool IsRemoteMemory) {
11872 Type *XTy =
X.Var->getType();
11874 "OMP Atomic expects a pointer to target memory");
11875 Type *XElemTy =
X.ElemTy;
11878 "OMP atomic capture expected a scalar or struct type");
11885 AllocaIP,
X.Var,
X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
X.IsVolatile,
11886 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11889 Value *CapturedVal =
11890 (IsPostfixUpdate ? AtomicResult->first : AtomicResult->second);
11891 Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
11893 checkAndEmitFlushAfterAtomic(
Loc, AO, AtomicKind::Capture);
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);
12254 checkAndEmitFlushAfterAtomic(
Loc, AO, AtomicKind::Compare);
12274 if (&OuterAllocaBB ==
Builder.GetInsertBlock()) {
12301 bool SubClausesPresent =
12302 (NumTeamsLower || NumTeamsUpper || ThreadLimit || IfExpr);
12304 if (!
Config.isTargetDevice() && SubClausesPresent) {
12305 assert((NumTeamsLower ==
nullptr || NumTeamsUpper !=
nullptr) &&
12306 "if lowerbound is non-null, then upperbound must also be non-null "
12307 "for bounds on num_teams");
12309 if (NumTeamsUpper ==
nullptr)
12310 NumTeamsUpper =
Builder.getInt32(0);
12312 if (NumTeamsLower ==
nullptr)
12313 NumTeamsLower = NumTeamsUpper;
12317 "argument to if clause must be an integer value");
12321 IfExpr =
Builder.CreateICmpNE(IfExpr,
12322 ConstantInt::get(IfExpr->
getType(), 0));
12323 NumTeamsUpper =
Builder.CreateSelect(
12324 IfExpr, NumTeamsUpper,
Builder.getInt32(1),
"numTeamsUpper");
12327 NumTeamsLower =
Builder.CreateSelect(
12328 IfExpr, NumTeamsLower,
Builder.getInt32(1),
"numTeamsLower");
12331 if (ThreadLimit ==
nullptr)
12332 ThreadLimit =
Builder.getInt32(0);
12336 Value *NumTeamsLowerInt32 =
12338 Value *NumTeamsUpperInt32 =
12340 Value *ThreadLimitInt32 =
12347 {Ident, ThreadNum, NumTeamsLowerInt32, NumTeamsUpperInt32,
12348 ThreadLimitInt32});
12353 if (
Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12356 auto OI = std::make_unique<OutlineInfo>();
12357 OI->EntryBB = AllocaBB;
12358 OI->ExitBB = ExitBB;
12359 OI->OuterAllocBB = &OuterAllocaBB;
12365 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP,
"gid",
true));
12367 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP,
"tid",
true));
12369 auto HostPostOutlineCB = [
this, Ident,
12370 ToBeDeleted](
Function &OutlinedFn)
mutable {
12375 "there must be a single user for the outlined function");
12380 "Outlined function must have two or three arguments only");
12382 bool HasShared = OutlinedFn.
arg_size() == 3;
12390 assert(StaleCI &&
"Error while outlining - no CallInst user found for the "
12391 "outlined function.");
12392 Builder.SetInsertPoint(StaleCI);
12399 omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),
12402 Builder.ClearInsertionPoint();
12404 I->eraseFromParent();
12407 if (!
Config.isTargetDevice())
12408 OI->PostOutlineCB = HostPostOutlineCB;
12412 Builder.SetInsertPoint(ExitBB);
12423 BasicBlock *OuterAllocaBB = OuterAllocIP.getNodeParent();
12425 if (OuterAllocaBB ==
Builder.GetInsertBlock()) {
12440 if (
Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12445 if (
Config.isTargetDevice()) {
12446 auto OI = std::make_unique<OutlineInfo>();
12447 OI->OuterAllocBB = OuterAllocIP.getNodeParent();
12448 OI->EntryBB = AllocaBB;
12449 OI->ExitBB = ExitBB;
12450 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.
size());
12451 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.
end());
12455 Builder.SetInsertPoint(ExitBB);
12462 std::string VarName) {
12471 return MapNamesArrayGlobal;
12476void OpenMPIRBuilder::initializeTypes(
Module &M) {
12480 unsigned ProgramAS = M.getDataLayout().getProgramAddressSpace();
12481#define OMP_TYPE(VarName, InitValue) VarName = InitValue;
12482#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
12483 VarName##Ty = ArrayType::get(ElemTy, ArraySize); \
12484 VarName##PtrTy = PointerType::get(Ctx, DefaultTargetAS);
12485#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
12486 VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg); \
12487 VarName##Ptr = PointerType::get(Ctx, ProgramAS);
12488#define OMP_STRUCT_TYPE(VarName, StructName, Packed, ...) \
12489 T = StructType::getTypeByName(Ctx, StructName); \
12491 T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed); \
12493 VarName##Ptr = PointerType::get(Ctx, DefaultTargetAS);
12494#include "llvm/Frontend/OpenMP/OMPKinds.def"
12505 while (!Worklist.
empty()) {
12509 if (
BlockSet.insert(SuccBB).second)
12514std::unique_ptr<CodeExtractor>
12516 bool ArgsInZeroAddressSpace,
12518 return std::make_unique<CodeExtractor>(
12528 Suffix.
str(), ArgsInZeroAddressSpace);
12531std::unique_ptr<CodeExtractor> DeviceSharedMemOutlineInfo::createCodeExtractor(
12533 return std::make_unique<DeviceSharedMemCodeExtractor>(
12534 OMPBuilder, Blocks,
nullptr,
12542 OuterDeallocBBs.empty()
12545 Suffix.
str(), ArgsInZeroAddressSpace);
12549 uint64_t
Size, int32_t Flags,
12555 Name.empty() ? Addr->
getName() : Name,
Size, Flags, 0);
12567 Fn->
addFnAttr(
"uniform-work-group-size");
12568 Fn->
addFnAttr(Attribute::MustProgress);
12586 auto &&GetMDInt = [
this](
unsigned V) {
12593 NamedMDNode *MD =
M.getOrInsertNamedMetadata(
"omp_offload.info");
12594 auto &&TargetRegionMetadataEmitter =
12595 [&
C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
12610 GetMDInt(E.getKind()), GetMDInt(EntryInfo.DeviceID),
12611 GetMDInt(EntryInfo.FileID), GetMDString(EntryInfo.ParentName),
12612 GetMDInt(EntryInfo.Line), GetMDInt(EntryInfo.Count),
12613 GetMDInt(E.getOrder())};
12616 OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);
12625 auto &&DeviceGlobalVarMetadataEmitter =
12626 [&
C, &OrderedEntries, &GetMDInt, &GetMDString, MD](
12636 Metadata *
Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),
12637 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
12641 OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);
12648 DeviceGlobalVarMetadataEmitter);
12650 for (
const auto &E : OrderedEntries) {
12651 assert(E.first &&
"All ordered entries must exist!");
12652 if (
const auto *CE =
12655 if (!CE->getID() || !CE->getAddress()) {
12659 if (!
M.getNamedValue(FnName))
12667 }
else if (
const auto *CE =
dyn_cast<
12676 if (
Config.isTargetDevice() &&
Config.hasRequiresUnifiedSharedMemory())
12678 if (!CE->getAddress()) {
12683 if (CE->getVarSize() == 0)
12687 assert(((
Config.isTargetDevice() && !CE->getAddress()) ||
12688 (!
Config.isTargetDevice() && CE->getAddress())) &&
12689 "Declaret target link address is set.");
12690 if (
Config.isTargetDevice())
12692 if (!CE->getAddress()) {
12699 if (!CE->getAddress()) {
12712 if ((
GV->hasLocalLinkage() ||
GV->hasHiddenVisibility()) &&
12716 OMPTargetGlobalVarEntryIndirectVTable))
12725 Flags, CE->getLinkage(), CE->getVarName());
12728 Flags, CE->getLinkage());
12739 if (
Config.hasRequiresFlags() && !
Config.isTargetDevice())
12745 Config.getRequiresFlags());
12755 OS <<
"_" <<
Count;
12760 unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);
12763 EntryInfo.
Line, NewCount);
12771 auto FileIDInfo = CallBack();
12772 uint64_t FileID = 0;
12774 ID =
Status->getUniqueID();
12775 FileID =
Status->getUniqueID().getFile();
12779 FileID =
hash_value(std::get<0>(FileIDInfo));
12783 std::get<1>(FileIDInfo));
12788 for (uint64_t Remain =
12789 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12791 !(Remain & 1); Remain = Remain >> 1)
12809 if (
static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12811 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12818 if (
static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>
>(
12824 Flags &=
~omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
12825 Flags |= MemberOfFlag;
12831 bool IsDeclaration,
bool IsExternallyVisible,
12833 std::vector<GlobalVariable *> &GeneratedRefs,
bool OpenMPSIMD,
12834 std::vector<Triple> TargetTriple,
Type *LlvmPtrTy,
12835 std::function<
Constant *()> GlobalInitializer,
12846 Config.hasRequiresUnifiedSharedMemory())) {
12851 if (!IsExternallyVisible)
12853 OS <<
"_decl_tgt_ref_ptr";
12856 Value *Ptr =
M.getNamedValue(PtrName);
12865 if (!
Config.isTargetDevice()) {
12866 if (GlobalInitializer)
12867 GV->setInitializer(GlobalInitializer());
12873 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12874 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12875 GlobalInitializer, VariableLinkage, LlvmPtrTy,
cast<Constant>(Ptr));
12887 bool IsDeclaration,
bool IsExternallyVisible,
12889 std::vector<GlobalVariable *> &GeneratedRefs,
bool OpenMPSIMD,
12890 std::vector<Triple> TargetTriple,
12891 std::function<
Constant *()> GlobalInitializer,
12895 (TargetTriple.empty() && !
Config.isTargetDevice()))
12906 !
Config.hasRequiresUnifiedSharedMemory()) {
12908 VarName = MangledName;
12911 if (!IsDeclaration)
12913 M.getDataLayout().getTypeSizeInBits(LlvmVal->
getValueType()), 8);
12916 Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->
getLinkage();
12920 if (
Config.isTargetDevice() &&
12929 if (!
M.getNamedValue(RefName)) {
12933 GvAddrRef->setConstant(
true);
12935 GvAddrRef->setInitializer(Addr);
12936 GeneratedRefs.push_back(GvAddrRef);
12945 if (
Config.isTargetDevice()) {
12946 VarName = (Addr) ? Addr->
getName() :
"";
12950 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12951 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12952 LlvmPtrTy, GlobalInitializer, VariableLinkage);
12953 VarName = (Addr) ? Addr->
getName() :
"";
12955 VarSize =
M.getDataLayout().getPointerSize();
12974 auto &&GetMDInt = [MN](
unsigned Idx) {
12979 auto &&GetMDString = [MN](
unsigned Idx) {
12981 return V->getString();
12984 switch (GetMDInt(0)) {
12988 case OffloadEntriesInfoManager::OffloadEntryInfo::
12989 OffloadingEntryInfoTargetRegion: {
12999 case OffloadEntriesInfoManager::OffloadEntryInfo::
13000 OffloadingEntryInfoDeviceGlobalVar:
13013 if (HostFilePath.
empty())
13017 if (std::error_code Err = Buf.getError()) {
13019 "OpenMPIRBuilder: " +
13027 if (std::error_code Err =
M.getError()) {
13029 (
"error parsing host file inside of OpenMPIRBuilder: " + Err.message())
13043 "expected a valid insertion block for creating an iterator loop");
13047 if (SplitIP == CurBB->
end())
13049 SplitIP = Terminator->getIterator();
13053 Builder.getCurrentDebugLocation(),
"omp.it.cont");
13065 T->eraseFromParent();
13080 bool ReachesLatch =
false;
13083 while (!Worklist.
empty()) {
13088 "iterator bodygen must leave at most one unterminated block",
13094 if (Succ == Latch) {
13095 ReachesLatch =
true;
13100 "iterator bodygen must not branch out of the loop body",
13102 if (Visited.
insert(Succ).second)
13108 Builder.SetInsertPoint(OpenBB);
13110 }
else if (!ReachesLatch) {
13120 return ContBB->
begin();
13130 for (
const auto &
ParamAttr : ParamAttrs) {
13173 return std::string(Out.str());
13181 unsigned VecRegSize;
13183 ISADataTy ISAData[] = {
13202 for (
char Mask :
Masked) {
13203 for (
const ISADataTy &
Data : ISAData) {
13206 Out <<
"_ZGV" <<
Data.ISA << Mask;
13208 assert(NumElts &&
"Non-zero simdlen/cdtsize expected");
13222template <
typename T>
13225 StringRef MangledName,
bool OutputBecomesInput,
13229 Out << Prefix << ISA << LMask << VLEN;
13230 if (OutputBecomesInput)
13232 Out << ParSeq <<
'_' << MangledName;
13241 bool OutputBecomesInput,
13246 OutputBecomesInput, Fn);
13248 OutputBecomesInput, Fn);
13252 OutputBecomesInput, Fn);
13254 OutputBecomesInput, Fn);
13258 OutputBecomesInput, Fn);
13260 OutputBecomesInput, Fn);
13265 OutputBecomesInput, Fn);
13276 char ISA,
unsigned NarrowestDataSize,
bool OutputBecomesInput) {
13277 assert((ISA ==
'n' || ISA ==
's') &&
"Expected ISA either 's' or 'n'.");
13289 OutputBecomesInput, Fn);
13296 OutputBecomesInput, Fn);
13298 OutputBecomesInput, Fn);
13302 OutputBecomesInput, Fn);
13306 OutputBecomesInput, Fn);
13315 OutputBecomesInput, Fn);
13322 MangledName, OutputBecomesInput, Fn);
13324 MangledName, OutputBecomesInput, Fn);
13328 MangledName, OutputBecomesInput, Fn);
13332 MangledName, OutputBecomesInput, Fn);
13342 return OffloadEntriesTargetRegion.empty() &&
13343 OffloadEntriesDeviceGlobalVar.empty();
13346unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(
13348 auto It = OffloadEntriesTargetRegionCount.find(
13349 getTargetRegionEntryCountKey(EntryInfo));
13350 if (It == OffloadEntriesTargetRegionCount.end())
13355void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(
13357 OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =
13358 EntryInfo.
Count + 1;
13364 OffloadEntriesTargetRegion[EntryInfo] =
13367 ++OffloadingEntriesNum;
13373 assert(EntryInfo.
Count == 0 &&
"expected default EntryInfo");
13376 EntryInfo.
Count = getTargetRegionEntryInfoCount(EntryInfo);
13380 if (OMPBuilder->Config.isTargetDevice()) {
13385 auto &Entry = OffloadEntriesTargetRegion[EntryInfo];
13386 Entry.setAddress(Addr);
13388 Entry.setFlags(Flags);
13394 "Target region entry already registered!");
13396 OffloadEntriesTargetRegion[EntryInfo] = Entry;
13397 ++OffloadingEntriesNum;
13399 incrementTargetRegionEntryInfoCount(EntryInfo);
13406 EntryInfo.
Count = getTargetRegionEntryInfoCount(EntryInfo);
13408 auto It = OffloadEntriesTargetRegion.find(EntryInfo);
13409 if (It == OffloadEntriesTargetRegion.end()) {
13413 if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))
13421 for (
const auto &It : OffloadEntriesTargetRegion) {
13422 Action(It.first, It.second);
13428 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
13429 ++OffloadingEntriesNum;
13435 if (OMPBuilder->Config.isTargetDevice()) {
13439 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13441 if (Entry.getVarSize() == 0) {
13442 Entry.setVarSize(VarSize);
13443 Entry.setLinkage(Linkage);
13447 Entry.setVarSize(VarSize);
13448 Entry.setLinkage(Linkage);
13449 Entry.setAddress(Addr);
13452 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13453 assert(Entry.isValid() && Entry.getFlags() == Flags &&
13454 "Entry not initialized!");
13455 if (Entry.getVarSize() == 0) {
13456 Entry.setVarSize(VarSize);
13457 Entry.setLinkage(Linkage);
13464 OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,
13465 Addr, VarSize, Flags, Linkage,
13468 OffloadEntriesDeviceGlobalVar.try_emplace(
13469 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage,
"");
13470 ++OffloadingEntriesNum;
13477 for (
const auto &E : OffloadEntriesDeviceGlobalVar)
13478 Action(E.getKey(), E.getValue());
13485void CanonicalLoopInfo::reportUnsupportedVirtualCollapse()
const {
13487 assert(VirtualCollapse &&
"Requires Virtual collapse state");
13489 "virtual collapse must be the final structural loop transformation");
13492void CanonicalLoopInfo::collectControlBlocks(
13494 if (VirtualCollapse)
13495 reportUnsupportedVirtualCollapse();
13501 BBs.
append({getPreheader(), Header,
Cond, Latch, Exit, getAfter()});
13504BasicBlock *CanonicalLoopInfo::getVirtualCollapseInit()
const {
13505 return VirtualCollapse ? VirtualCollapse->Count->getParent() :
nullptr;
13510 if (VirtualCollapse)
13511 return getVirtualCollapseInit()->getSinglePredecessor();
13520void CanonicalLoopInfo::setTripCount(
Value *TripCount) {
13532void CanonicalLoopInfo::mapIndVar(
13542 for (
Use &U : OldIV->
uses()) {
13546 if (
User->getParent() == getCond())
13548 if (
User->getParent() == getLatch())
13554 Value *NewIV = Updater(OldIV);
13557 for (Use *U : ReplacableUses)
13571 bool IsVirtual = VirtualCollapse.has_value();
13577 IndVarEntry = Guard->getSuccessor(0);
13580 assert(Guard->getSuccessor(1) == Exit);
13581 assert(VirtualCollapse->Begin->getParent() ==
Init);
13583 {VirtualCollapse->Begin, VirtualCollapse->Count}) {
13585 assert(Copy->getOpcode() == Instruction::Add &&
Zero &&
Zero->isZero() &&
13586 "Virtual range copies must add zero");
13590 NonEmpty->getOperand(0) == VirtualCollapse->Count &&
13592 "Collapsed guard must skip empty ranges with zero count");
13604 "Preheader must terminate with unconditional branch");
13607 "Preheader must jump to collapsed initialization");
13610 "Preheader must jump to header");
13614 "Header must terminate with unconditional branch");
13615 assert(Header->getSingleSuccessor() == Cond &&
13616 "Header must jump to exiting block");
13619 assert(Cond->getSinglePredecessor() == Header &&
13620 "Exiting block only reachable from header");
13623 "Exiting block must terminate with conditional branch");
13625 "Exiting block's first successor jump to the body");
13627 "Exiting block's second successor must exit the loop");
13631 "Body only reachable from exiting block");
13636 "Latch must terminate with unconditional branch");
13637 assert(Latch->getSingleSuccessor() == Header &&
"Latch must jump to header");
13640 assert(Latch->getSinglePredecessor() !=
nullptr);
13645 "Exit block must terminate with unconditional branch");
13646 assert(Exit->getSingleSuccessor() == After &&
13647 "Exit block must jump to after block");
13651 "After block only reachable from exit block");
13655 assert(IndVar &&
"Canonical induction variable not found?");
13657 "Induction variable must be an integer");
13659 "Induction variable must be a PHI in the loop header");
13666 auto *NextIndVar =
cast<PHINode>(IndVar)->getIncomingValue(1);
13675 assert(TripCount &&
"Loop trip count not found?");
13677 "Trip count and induction variable must have the same type");
13681 "Exit condition must be a signed less-than comparison");
13683 "Exit condition must compare the induction variable");
13685 "Exit condition must compare with the trip count");
13694 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 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 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.
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 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 void emitFlush(const LocationDescription &Loc)
Generate a flush runtime call.
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 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 void createFlush(const LocationDescription &Loc)
Generator for 'omp flush'.
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.
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.
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.
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.
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),...