LLVM 24.0.0git
OMPIRBuilder.h
Go to the documentation of this file.
1//===- IR/OpenMPIRBuilder.h - OpenMP encoding builder for LLVM IR - C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the OpenMPIRBuilder class and helpers used as a convenient
10// way to create LLVM instructions for OpenMP directives.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
15#define LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
16
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/SetVector.h"
22#include "llvm/IR/CallingConv.h"
23#include "llvm/IR/DebugLoc.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/ValueMap.h"
29#include "llvm/Support/Error.h"
33#include <forward_list>
34#include <functional>
35#include <map>
36#include <optional>
37
38namespace llvm {
40class CodeExtractor;
41class ScanInfo;
44class OpenMPIRBuilder;
45class Loop;
46class LoopAnalysis;
47class LoopInfo;
48
49/// Move the instruction after an InsertPoint to the beginning of another
50/// BasicBlock.
51///
52/// The instructions after \p IP are moved to the beginning of \p New which must
53/// not have any PHINodes. If \p CreateBranch is true, a branch instruction to
54/// \p New will be added such that there is no semantic change. Otherwise, the
55/// \p IP insert block remains degenerate and it is up to the caller to insert a
56/// terminator. \p DL is used as the debug location for the branch instruction
57/// if one is created.
59 bool CreateBranch, DebugLoc DL);
60
61/// Splice a BasicBlock at an IRBuilder's current insertion point. Its new
62/// insert location will stick to after the instruction before the insertion
63/// point (instead of moving with the instruction the InsertPoint stores
64/// internally).
65LLVM_ABI void spliceBB(IRBuilder<> &Builder, BasicBlock *New,
66 bool CreateBranch);
67
68/// Split a BasicBlock at an InsertPoint, even if the block is degenerate
69/// (missing the terminator).
70///
71/// llvm::SplitBasicBlock and BasicBlock::splitBasicBlock require a well-formed
72/// BasicBlock. \p Name is used for the new successor block. If \p CreateBranch
73/// is true, a branch to the new successor will new created such that
74/// semantically there is no change; otherwise the block of the insertion point
75/// remains degenerate and it is the caller's responsibility to insert a
76/// terminator. \p DL is used as the debug location for the branch instruction
77/// if one is created. Returns the new successor block.
79 DebugLoc DL, llvm::Twine Name = {});
80
81/// Split a BasicBlock at \p Builder's insertion point, even if the block is
82/// degenerate (missing the terminator). Its new insert location will stick to
83/// after the instruction before the insertion point (instead of moving with the
84/// instruction the InsertPoint stores internally).
85LLVM_ABI BasicBlock *splitBB(IRBuilderBase &Builder, bool CreateBranch,
86 llvm::Twine Name = {});
87
88/// Split a BasicBlock at \p Builder's insertion point, even if the block is
89/// degenerate (missing the terminator). Its new insert location will stick to
90/// after the instruction before the insertion point (instead of moving with the
91/// instruction the InsertPoint stores internally).
92LLVM_ABI BasicBlock *splitBB(IRBuilder<> &Builder, bool CreateBranch,
93 llvm::Twine Name);
94
95/// Like splitBB, but reuses the current block's name for the new name.
97 bool CreateBranch,
98 llvm::Twine Suffix = ".split");
99
100/// Captures attributes that affect generating LLVM-IR using the
101/// OpenMPIRBuilder and related classes. Note that not all attributes are
102/// required for all classes or functions. In some use cases the configuration
103/// is not necessary at all, because because the only functions that are called
104/// are ones that are not dependent on the configuration.
106public:
107 /// Representation of a collapsed iteration space.
108 enum class CollapseIVMapping {
109 /// Decode source indices from the logical index using division and
110 /// remainder in each iteration.
112 /// Retain the physical nest and decode each assigned range once.
114 };
115
116 /// Mapping used for collapsed loops.
118
119 /// Flag to define whether to generate code for the role of the OpenMP host
120 /// (if set to false) or device (if set to true) in an offloading context. It
121 /// is set when the -fopenmp-is-target-device compiler frontend option is
122 /// specified.
123 std::optional<bool> IsTargetDevice;
124
125 /// Flag for specifying if the compilation is done for an accelerator. It is
126 /// set according to the architecture of the target triple and currently only
127 /// true when targeting AMDGPU or NVPTX. Today, these targets can only perform
128 /// the role of an OpenMP target device, so `IsTargetDevice` must also be true
129 /// if `IsGPU` is true. This restriction might be lifted if an accelerator-
130 /// like target with the ability to work as the OpenMP host is added, or if
131 /// the capabilities of the currently supported GPU architectures are
132 /// expanded.
133 std::optional<bool> IsGPU;
134
135 /// Flag for specifying if LLVMUsed information should be emitted.
136 std::optional<bool> EmitLLVMUsedMetaInfo;
137
138 /// Flag for specifying if offloading is mandatory.
139 std::optional<bool> OpenMPOffloadMandatory;
140
141 /// First separator used between the initial two parts of a name.
142 std::optional<StringRef> FirstSeparator;
143 /// Separator used between all of the rest consecutive parts of s name.
144 std::optional<StringRef> Separator;
145
146 /// Flag for specifying whether the no-signed-wrap (nsw) flag should be added
147 /// to loop induction variable arithmetic. Set when the frontend guarantees
148 /// that signed integer overflow is undefined (with -fno-wrapv).
149 std::optional<bool> NoSignedWrap;
150
151 // Grid Value for the GPU target.
152 std::optional<omp::GV> GridValue;
153
154 /// When compilation is being done for the OpenMP host (i.e. `IsTargetDevice =
155 /// false`), this contains the list of offloading triples associated, if any.
157
158 // Default address space for the target.
159 unsigned DefaultTargetAS = 0;
160
162
166 bool HasRequiresReverseOffload,
167 bool HasRequiresUnifiedAddress,
168 bool HasRequiresUnifiedSharedMemory,
169 bool HasRequiresDynamicAllocators);
170
171 // Getters functions that assert if the required values are not present.
172 bool isTargetDevice() const {
173 assert(IsTargetDevice.has_value() && "IsTargetDevice is not set");
174 return *IsTargetDevice;
175 }
176
177 bool isGPU() const {
178 assert(IsGPU.has_value() && "IsGPU is not set");
179 return *IsGPU;
180 }
181
183 assert(OpenMPOffloadMandatory.has_value() &&
184 "OpenMPOffloadMandatory is not set");
186 }
187
189 assert(GridValue.has_value() && "GridValue is not set");
190 return *GridValue;
191 }
192
193 unsigned getDefaultTargetAS() const { return DefaultTargetAS; }
194
195 bool hasNoSignedWrap() const { return NoSignedWrap.value_or(false); }
197
199
200 bool hasRequiresFlags() const { return RequiresFlags; }
205
206 /// Returns requires directive clauses as flags compatible with those expected
207 /// by libomptarget.
208 LLVM_ABI int64_t getRequiresFlags() const;
209
210 // Returns the FirstSeparator if set, otherwise use the default separator
211 // depending on isGPU
213 if (FirstSeparator.has_value())
214 return *FirstSeparator;
215 if (isGPU())
216 return "_";
217 return ".";
218 }
219
220 // Returns the Separator if set, otherwise use the default separator depending
221 // on isGPU
223 if (Separator.has_value())
224 return *Separator;
225 if (isGPU())
226 return "$";
227 return ".";
228 }
229
231 void setIsGPU(bool Value) { IsGPU = Value; }
237 void setDefaultTargetAS(unsigned AS) { DefaultTargetAS = AS; }
239
244
245private:
246 /// Flags for specifying which requires directive clauses are present.
247 int64_t RequiresFlags;
248};
249
250/// Data structure to contain the information needed to uniquely identify
251/// a target entry.
253 /// The prefix used for kernel names.
254 static constexpr const char *KernelNamePrefix = "__omp_offloading_";
255
256 std::string ParentName;
257 unsigned DeviceID;
258 unsigned FileID;
259 unsigned Line;
260 unsigned Count;
261
264 unsigned FileID, unsigned Line, unsigned Count = 0)
266 Count(Count) {}
267
268 LLVM_ABI static void
270 unsigned DeviceID, unsigned FileID, unsigned Line,
271 unsigned Count);
272
274 return std::make_tuple(ParentName, DeviceID, FileID, Line, Count) <
275 std::make_tuple(RHS.ParentName, RHS.DeviceID, RHS.FileID, RHS.Line,
276 RHS.Count);
277 }
278};
279
280/// Class that manages information about offload code regions and data
282 /// Number of entries registered so far.
283 OpenMPIRBuilder *OMPBuilder;
284 unsigned OffloadingEntriesNum = 0;
285
286public:
287 /// Base class of the entries info.
289 public:
290 /// Kind of a given entry.
291 enum OffloadingEntryInfoKinds : unsigned {
292 /// Entry is a target region.
294 /// Entry is a declare target variable.
296 /// Invalid entry info.
298 };
299
300 protected:
302 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {}
303 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order,
304 uint32_t Flags)
305 : Flags(Flags), Order(Order), Kind(Kind) {}
306 ~OffloadEntryInfo() = default;
307
308 public:
309 bool isValid() const { return Order != ~0u; }
310 unsigned getOrder() const { return Order; }
311 OffloadingEntryInfoKinds getKind() const { return Kind; }
312 uint32_t getFlags() const { return Flags; }
313 void setFlags(uint32_t NewFlags) { Flags = NewFlags; }
314 Constant *getAddress() const { return cast_or_null<Constant>(Addr); }
316 assert(!Addr.pointsToAliveValue() && "Address has been set before!");
317 Addr = V;
318 }
319 static bool classof(const OffloadEntryInfo *Info) { return true; }
320
321 private:
322 /// Address of the entity that has to be mapped for offloading.
323 WeakTrackingVH Addr;
324
325 /// Flags associated with the device global.
326 uint32_t Flags = 0u;
327
328 /// Order this entry was emitted.
329 unsigned Order = ~0u;
330
331 OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid;
332 };
333
334 /// Return true if a there are no entries defined.
335 LLVM_ABI bool empty() const;
336 /// Return number of entries defined so far.
337 unsigned size() const { return OffloadingEntriesNum; }
338
339 OffloadEntriesInfoManager(OpenMPIRBuilder *builder) : OMPBuilder(builder) {}
340
341 //
342 // Target region entries related.
343 //
344
345 /// Kind of the target registry entry.
347 /// Mark the entry as target region.
349 };
350
351 /// Target region entries info.
353 /// Address that can be used as the ID of the entry.
354 Constant *ID = nullptr;
355
356 public:
359 explicit OffloadEntryInfoTargetRegion(unsigned Order, Constant *Addr,
360 Constant *ID,
363 ID(ID) {
364 setAddress(Addr);
365 }
366
367 Constant *getID() const { return ID; }
368 void setID(Constant *V) {
369 assert(!ID && "ID has been set before!");
370 ID = V;
371 }
372 static bool classof(const OffloadEntryInfo *Info) {
373 return Info->getKind() == OffloadingEntryInfoTargetRegion;
374 }
375 };
376
377 /// Initialize target region entry.
378 /// This is ONLY needed for DEVICE compilation.
379 LLVM_ABI void
381 unsigned Order);
382 /// Register target region entry.
384 Constant *Addr, Constant *ID,
386 /// Return true if a target region entry with the provided information
387 /// exists.
389 bool IgnoreAddressId = false) const;
390
391 // Return the Name based on \a EntryInfo using the next available Count.
392 LLVM_ABI void
394 const TargetRegionEntryInfo &EntryInfo);
395
396 /// brief Applies action \a Action on all registered entries.
397 typedef function_ref<void(const TargetRegionEntryInfo &EntryInfo,
398 const OffloadEntryInfoTargetRegion &)>
400 LLVM_ABI void
402
403 //
404 // Device global variable entries related.
405 //
406
407 /// Kind of the global variable entry..
409 /// Mark the entry as a to declare target.
411 /// Mark the entry as a to declare target link.
413 /// Mark the entry as a declare target enter.
415 /// Mark the entry as having no declare target entry kind.
417 /// Mark the entry as a declare target indirect global.
419 /// Mark the entry as a register requires global.
421 /// Mark the entry as a declare target indirect vtable.
423 };
424
425 /// Kind of device clause for declare target variables
426 /// and functions
427 /// NOTE: Currently not used as a part of a variable entry
428 /// used for Flang and Clang to interface with the variable
429 /// related registration functions
431 /// The target is marked for all devices
433 /// The target is marked for non-host devices
435 /// The target is marked for host devices
437 /// The target is marked as having no clause
439 };
440
441 /// Device global variable entries info.
443 /// Type of the global variable.
444 int64_t VarSize;
446 const std::string VarName;
447
448 public:
454 explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, Constant *Addr,
455 int64_t VarSize,
458 const std::string &VarName)
460 VarSize(VarSize), Linkage(Linkage), VarName(VarName) {
461 setAddress(Addr);
462 }
463
464 int64_t getVarSize() const { return VarSize; }
465 StringRef getVarName() const { return VarName; }
466 void setVarSize(int64_t Size) { VarSize = Size; }
467 GlobalValue::LinkageTypes getLinkage() const { return Linkage; }
468 void setLinkage(GlobalValue::LinkageTypes LT) { Linkage = LT; }
469 static bool classof(const OffloadEntryInfo *Info) {
470 return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar;
471 }
472 };
473
474 /// Initialize device global variable entry.
475 /// This is ONLY used for DEVICE compilation.
477 StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order);
478
479 /// Register device global variable entry.
481 StringRef VarName, Constant *Addr, int64_t VarSize,
483 /// Checks if the variable with the given name has been registered already.
485 return OffloadEntriesDeviceGlobalVar.count(VarName) > 0;
486 }
487 /// Applies action \a Action on all registered entries.
488 typedef function_ref<void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)>
492
493private:
494 /// Return the count of entries at a particular source location.
495 unsigned
496 getTargetRegionEntryInfoCount(const TargetRegionEntryInfo &EntryInfo) const;
497
498 /// Update the count of entries at a particular source location.
499 void
500 incrementTargetRegionEntryInfoCount(const TargetRegionEntryInfo &EntryInfo);
501
503 getTargetRegionEntryCountKey(const TargetRegionEntryInfo &EntryInfo) {
504 return TargetRegionEntryInfo(EntryInfo.ParentName, EntryInfo.DeviceID,
505 EntryInfo.FileID, EntryInfo.Line, 0);
506 }
507
508 // Count of entries at a location.
509 std::map<TargetRegionEntryInfo, unsigned> OffloadEntriesTargetRegionCount;
510
511 // Storage for target region entries kind.
512 typedef std::map<TargetRegionEntryInfo, OffloadEntryInfoTargetRegion>
513 OffloadEntriesTargetRegionTy;
514 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
515 /// Storage for device global variable entries kind. The storage is to be
516 /// indexed by mangled name.
518 OffloadEntriesDeviceGlobalVarTy;
519 OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar;
520};
521
522/// An interface to create LLVM-IR for OpenMP directives.
523///
524/// Each OpenMP directive has a corresponding public generator method.
526public:
527 /// Create a new OpenMPIRBuilder operating on the given module \p M. This will
528 /// not have an effect on \p M (see initialize)
530 : M(M), Builder(M), OffloadInfoManager(this), T(M.getTargetTriple()),
531 IsFinalized(false) {
532 Builder.disableGEPCanonicalization();
533 }
535
537 llvm::Value *AtomicVar;
538
539 public:
547
548 llvm::Value *getAtomicPointer() const override { return AtomicVar; }
551 const llvm::Twine &Name) const override {
552 llvm::AllocaInst *allocaInst = Builder->CreateAlloca(Ty);
553 allocaInst->setName(Name);
554 return allocaInst;
555 }
556 };
557 /// Initialize the internal state, this will put structures types and
558 /// potentially other helpers into the underlying module. Must be called
559 /// before any other method and only once! This internal state includes types
560 /// used in the OpenMPIRBuilder generated from OMPKinds.def.
561 LLVM_ABI void initialize();
562
564
565 /// Finalize the underlying module, e.g., by outlining regions.
566 /// \param Fn The function to be finalized. If not used,
567 /// all functions are finalized.
568 LLVM_ABI void finalize(Function *Fn = nullptr);
569
570 /// Check whether the finalize function has already run
571 /// \return true if the finalize function has already run
572 LLVM_ABI bool isFinalized();
573
574 /// Add attributes known for \p FnID to \p Fn.
576
577 /// Type used throughout for insertion points.
579
580 /// Type used to represent an insertion point or an error value.
582
583 /// Get the create a name using the platform specific separators.
584 /// \param Parts parts of the final name that needs separation
585 /// The created name has a first separator between the first and second part
586 /// and a second separator between all other parts.
587 /// E.g. with FirstSeparator "$" and Separator "." and
588 /// parts: "p1", "p2", "p3", "p4"
589 /// The resulting name is "p1$p2.p3.p4"
590 /// The separators are retrieved from the OpenMPIRBuilderConfig.
591 LLVM_ABI std::string
593
594 /// Callback type for variable finalization (think destructors).
595 ///
596 /// \param CodeGenIP is the insertion point at which the finalization code
597 /// should be placed.
598 ///
599 /// A finalize callback knows about all objects that need finalization, e.g.
600 /// destruction, when the scope of the currently generated construct is left
601 /// at the time, and location, the callback is invoked.
602 using FinalizeCallbackTy = std::function<Error(InsertPointTy CodeGenIP)>;
603
605 FinalizationInfo(FinalizeCallbackTy FiniCB, omp::Directive DK,
606 bool IsCancellable)
607 : DK(DK), IsCancellable(IsCancellable), FiniCB(std::move(FiniCB)) {}
608 /// The directive kind of the innermost directive that has an associated
609 /// region which might require finalization when it is left.
610 const omp::Directive DK;
611
612 /// Flag to indicate if the directive is cancellable.
613 const bool IsCancellable;
614
615 /// The basic block to which control should be transferred to
616 /// implement the FiniCB. Memoized to avoid generating finalization
617 /// multiple times.
619
620 /// For cases where there is an unavoidable existing finalization block
621 /// (e.g. loop finialization after omp sections). The existing finalization
622 /// block must not contain any non-finalization code.
624 BasicBlock *ExistingFiniBB);
625
626 private:
627 /// Access via getFiniBB.
628 BasicBlock *FiniBB = nullptr;
629
630 /// The finalization callback provided by the last in-flight invocation of
631 /// createXXXX for the directive of kind DK.
632 FinalizeCallbackTy FiniCB;
633 };
634
635 /// Push a finalization callback on the finalization stack.
636 ///
637 /// NOTE: Temporary solution until Clang CG is gone.
639 FinalizationStack.push_back(FI);
640 }
641
642 /// Pop the last finalization callback from the finalization stack.
643 ///
644 /// NOTE: Temporary solution until Clang CG is gone.
646
647 /// Callback type for body (=inner region) code generation
648 ///
649 /// The callback takes code locations as arguments, each describing a
650 /// location where additional instructions can be inserted.
651 ///
652 /// The CodeGenIP may be in the middle of a basic block or point to the end of
653 /// it. The basic block may have a terminator or be degenerate. The callback
654 /// function may just insert instructions at that position, but also split the
655 /// block (without the Before argument of BasicBlock::splitBasicBlock such
656 /// that the identify of the split predecessor block is preserved) and insert
657 /// additional control flow, including branches that do not lead back to what
658 /// follows the CodeGenIP. Note that since the callback is allowed to split
659 /// the block, callers must assume that InsertPoints to positions in the
660 /// BasicBlock after CodeGenIP including CodeGenIP itself are invalidated. If
661 /// such InsertPoints need to be preserved, it can split the block itself
662 /// before calling the callback.
663 ///
664 /// AllocaIP and CodeGenIP must not point to the same position.
665 ///
666 /// \param AllocaIP is the insertion point at which new allocations should
667 /// be placed. The BasicBlock it is pointing to must not be
668 /// split.
669 /// \param CodeGenIP is the insertion point at which the body code should be
670 /// placed.
671 /// \param DeallocBlocks is the list of insertion blocks where explicit
672 /// deallocations, if needed, should be placed.
673 /// \return an error, if any were triggered during execution.
675 function_ref<Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
676 ArrayRef<BasicBlock *> DeallocBlocks)>;
677
678 /// Callback type for task duplication function code generation. This is the
679 /// task duplication function passed to __kmpc_taskloop. It is expected that
680 /// this function will set up (first)private variables in the duplicated task
681 /// which have non-trivial (copy-)constructors. Insertion points are handled
682 /// the same way as for BodyGenCallbackTy.
683 ///
684 /// \ref createTaskloop lays out the task's auxiliary data structure as:
685 /// `{ lower bound, upper bound, step, data... }`. DestPtr and SrcPtr point
686 /// to this data.
687 ///
688 /// It is acceptable for the callback to be set to nullptr. In that case no
689 /// function will be generated and nullptr will be passed as the task
690 /// duplication function to __kmpc_taskloop.
691 ///
692 /// \param AllocaIP is the insertion point at which new alloca instructions
693 /// should be placed. The BasicBlock it is pointing to must
694 /// not be split.
695 /// \param CodeGenIP is the insertion point at which the body code should be
696 /// placed.
697 /// \param DestPtr This is a pointer to data inside the newly duplicated
698 /// task's auxiliary data structure (allocated after the task
699 /// descriptor.)
700 /// \param SrcPtr This is a pointer to data inside the original task's
701 /// auxiliary data structure (allocated after the task
702 /// descriptor.)
703 ///
704 /// \return The insertion point immediately after the generated code, or an
705 /// error if any occured.
707 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value *DestPtr,
708 Value *SrcPtr)>;
709
710 // This is created primarily for sections construct as llvm::function_ref
711 // (BodyGenCallbackTy) is not storable (as described in the comments of
712 // function_ref class - function_ref contains non-ownable reference
713 // to the callable.
714 ///
715 /// \return an error, if any were triggered during execution.
717 std::function<Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
718 ArrayRef<BasicBlock *> DeallocBlocks)>;
719
720 /// Callback type for loop body code generation.
721 ///
722 /// \param CodeGenIP is the insertion point where the loop's body code must be
723 /// placed. This will be a dedicated BasicBlock with a
724 /// conditional branch from the loop condition check and
725 /// terminated with an unconditional branch to the loop
726 /// latch.
727 /// \param IndVar is the induction variable usable at the insertion point.
728 ///
729 /// \return an error, if any were triggered during execution.
731 function_ref<Error(InsertPointTy CodeGenIP, Value *IndVar)>;
732
733 /// Callback type for variable privatization (think copy & default
734 /// constructor).
735 ///
736 /// \param AllocaIP is the insertion point at which new alloca instructions
737 /// should be placed.
738 /// \param CodeGenIP is the insertion point at which the privatization code
739 /// should be placed.
740 /// \param Original The value being copied/created, should not be used in the
741 /// generated IR.
742 /// \param Inner The equivalent of \p Original that should be used in the
743 /// generated IR; this is equal to \p Original if the value is
744 /// a pointer and can thus be passed directly, otherwise it is
745 /// an equivalent but different value.
746 /// \param ReplVal The replacement value, thus a copy or new created version
747 /// of \p Inner.
748 ///
749 /// \returns The new insertion point where code generation continues and
750 /// \p ReplVal the replacement value.
752 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original,
753 Value &Inner, Value *&ReplVal)>;
754
755 /// Description of a LLVM-IR insertion point (IP) and a debug/source location
756 /// (filename, line, column, ...).
759 : IP(IRB.saveIP()), DL(IRB.getCurrentDebugLocation()) {}
761 : IP(IP), DL(DL) {}
764 };
765
766 /// Emitter methods for OpenMP directives.
767 ///
768 ///{
769
770 /// Generator for '#omp barrier'
771 ///
772 /// \param Loc The location where the barrier directive was encountered.
773 /// \param Kind The kind of directive that caused the barrier.
774 /// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
775 /// \param CheckCancelFlag Flag to indicate a cancel barrier return value
776 /// should be checked and acted upon.
777 /// \param ThreadID Optional parameter to pass in any existing ThreadID value.
778 ///
779 /// \returns The insertion point after the barrier.
781 omp::Directive Kind,
782 bool ForceSimpleCall = false,
783 bool CheckCancelFlag = true);
784
785 /// Generator for '#omp cancel'
786 ///
787 /// \param Loc The location where the directive was encountered.
788 /// \param IfCondition The evaluated 'if' clause expression, if any.
789 /// \param CanceledDirective The kind of directive that is cancled.
790 ///
791 /// \returns The insertion point after the barrier.
793 Value *IfCondition,
794 omp::Directive CanceledDirective);
795
796 /// Generator for '#omp cancellation point'
797 ///
798 /// \param Loc The location where the directive was encountered.
799 /// \param CanceledDirective The kind of directive that is cancled.
800 ///
801 /// \returns The insertion point after the barrier.
803 const LocationDescription &Loc, omp::Directive CanceledDirective);
804
805 /// Creates a ScanInfo object, allocates and returns the pointer.
807
808 /// Generator for '#omp parallel'
809 ///
810 /// \param Loc The insert and source location description.
811 /// \param AllocaIP The insertion point to be used for allocations.
812 /// \param DeallocBlocks The insertion blocks to be used for explicit
813 /// deallocations, if needed.
814 /// \param BodyGenCB Callback that will generate the region code.
815 /// \param PrivCB Callback to copy a given variable (think copy constructor).
816 /// \param FiniCB Callback to finalize variable copies.
817 /// \param IfCondition The evaluated 'if' clause expression, if any.
818 /// \param NumThreads The evaluated 'num_threads' clause expression, if any.
819 /// \param ProcBind The value of the 'proc_bind' clause (see ProcBindKind).
820 /// \param IsCancellable Flag to indicate a cancellable parallel region.
821 ///
822 /// \returns The insertion position *after* the parallel.
824 const LocationDescription &Loc, InsertPointTy AllocaIP,
825 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
826 PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition,
827 Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable);
828
829 /// Generator for the control flow structure of an OpenMP canonical loop.
830 ///
831 /// This generator operates on the logical iteration space of the loop, i.e.
832 /// the caller only has to provide a loop trip count of the loop as defined by
833 /// base language semantics. The trip count is interpreted as an unsigned
834 /// integer. The induction variable passed to \p BodyGenCB will be of the same
835 /// type and run from 0 to \p TripCount - 1. It is up to the callback to
836 /// convert the logical iteration variable to the loop counter variable in the
837 /// loop body.
838 ///
839 /// \param Loc The insert and source location description. The insert
840 /// location can be between two instructions or the end of a
841 /// degenerate block (e.g. a BB under construction).
842 /// \param BodyGenCB Callback that will generate the loop body code.
843 /// \param TripCount Number of iterations the loop body is executed.
844 /// \param Name Base name used to derive BB and instruction names.
845 ///
846 /// \returns An object representing the created control flow structure which
847 /// can be used for loop-associated directives.
850 LoopBodyGenCallbackTy BodyGenCB, Value *TripCount,
851 const Twine &Name = "loop");
852
853 /// Generator for the control flow structure of an OpenMP canonical loops if
854 /// the parent directive has an `inscan` modifier specified.
855 /// If the `inscan` modifier is specified, the region of the parent is
856 /// expected to have a `scan` directive. Based on the clauses in
857 /// scan directive, the body of the loop is split into two loops: Input loop
858 /// and Scan Loop. Input loop contains the code generated for input phase of
859 /// scan and Scan loop contains the code generated for scan phase of scan.
860 /// From the bodyGen callback of these loops, `createScan` would be called
861 /// when a scan directive is encountered from the loop body. `createScan`
862 /// based on whether 1. inclusive or exclusive scan is specified and, 2. input
863 /// loop or scan loop is generated, lowers the body of the for loop
864 /// accordingly.
865 ///
866 /// \param Loc The insert and source location description.
867 /// \param BodyGenCB Callback that will generate the loop body code.
868 /// \param Start Value of the loop counter for the first iterations.
869 /// \param Stop Loop counter values past this will stop the loop.
870 /// \param Step Loop counter increment after each iteration; negative
871 /// means counting down.
872 /// \param IsSigned Whether Start, Stop and Step are signed integers.
873 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
874 /// counter.
875 /// \param ComputeIP Insertion point for instructions computing the trip
876 /// count. Can be used to ensure the trip count is available
877 /// at the outermost loop of a loop nest. If not set,
878 /// defaults to the preheader of the generated loop.
879 /// \param Name Base name used to derive BB and instruction names.
880 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
881 /// `ScanInfoInitialize`.
882 ///
883 /// \returns A vector containing Loop Info of Input Loop and Scan Loop.
886 LoopBodyGenCallbackTy BodyGenCB, Value *Start,
887 Value *Stop, Value *Step, bool IsSigned,
888 bool InclusiveStop, InsertPointTy ComputeIP,
889 const Twine &Name, ScanInfo *ScanRedInfo);
890
891 /// Calculate the trip count of a canonical loop.
892 ///
893 /// This allows specifying user-defined loop counter values using increment,
894 /// upper- and lower bounds. To disambiguate the terminology when counting
895 /// downwards, instead of lower bounds we use \p Start for the loop counter
896 /// value in the first body iteration.
897 ///
898 /// Consider the following limitations:
899 ///
900 /// * A loop counter space over all integer values of its bit-width cannot be
901 /// represented. E.g using uint8_t, its loop trip count of 256 cannot be
902 /// stored into an 8 bit integer):
903 ///
904 /// DO I = 0, 255, 1
905 ///
906 /// * Unsigned wrapping is only supported when wrapping only "once"; E.g.
907 /// effectively counting downwards:
908 ///
909 /// for (uint8_t i = 100u; i > 0; i += 127u)
910 ///
911 ///
912 /// TODO: May need to add additional parameters to represent:
913 ///
914 /// * Allow representing downcounting with unsigned integers.
915 ///
916 /// * Sign of the step and the comparison operator might disagree:
917 ///
918 /// for (int i = 0; i < 42; i -= 1u)
919 ///
920 /// \param Loc The insert and source location description.
921 /// \param Start Value of the loop counter for the first iterations.
922 /// \param Stop Loop counter values past this will stop the loop.
923 /// \param Step Loop counter increment after each iteration; negative
924 /// means counting down.
925 /// \param IsSigned Whether Start, Stop and Step are signed integers.
926 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
927 /// counter.
928 /// \param Name Base name used to derive instruction names.
929 ///
930 /// \returns The value holding the calculated trip count.
932 const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step,
933 bool IsSigned, bool InclusiveStop, const Twine &Name = "loop");
934
935 /// Generator for the control flow structure of an OpenMP canonical loop.
936 ///
937 /// Instead of a logical iteration space, this allows specifying user-defined
938 /// loop counter values using increment, upper- and lower bounds. To
939 /// disambiguate the terminology when counting downwards, instead of lower
940 /// bounds we use \p Start for the loop counter value in the first body
941 ///
942 /// It calls \see calculateCanonicalLoopTripCount for trip count calculations,
943 /// so limitations of that method apply here as well.
944 ///
945 /// \param Loc The insert and source location description.
946 /// \param BodyGenCB Callback that will generate the loop body code.
947 /// \param Start Value of the loop counter for the first iterations.
948 /// \param Stop Loop counter values past this will stop the loop.
949 /// \param Step Loop counter increment after each iteration; negative
950 /// means counting down.
951 /// \param IsSigned Whether Start, Stop and Step are signed integers.
952 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
953 /// counter.
954 /// \param ComputeIP Insertion point for instructions computing the trip
955 /// count. Can be used to ensure the trip count is available
956 /// at the outermost loop of a loop nest. If not set,
957 /// defaults to the preheader of the generated loop.
958 /// \param Name Base name used to derive BB and instruction names.
959 /// \param InScan Whether loop has a scan reduction specified.
960 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
961 /// `ScanInfoInitialize`.
962 ///
963 /// \returns An object representing the created control flow structure which
964 /// can be used for loop-associated directives.
967 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
968 InsertPointTy ComputeIP = {}, const Twine &Name = "loop",
969 bool InScan = false, ScanInfo *ScanRedInfo = nullptr);
970
971 /// Strategy used to derive the original induction variables after collapse.
973
974 /// Collapse a loop nest using Config.CollapseMapping.
975 /// Two mappings are supported: DivMod and Virtual.
976 ///
977 /// The DivMod mapping works as follows.
978 ///
979 /// Merges loops of a loop nest into a single CanonicalLoopNest representation
980 /// that has the same number of innermost loop iterations as the origin loop
981 /// nest. The induction variables of the input loops are derived from the
982 /// collapsed loop's induction variable. This is intended to be used to
983 /// implement OpenMP's collapse clause. Before applying a directive,
984 /// collapseLoops normalizes a loop nest to contain only a single loop and the
985 /// directive's implementation does not need to handle multiple loops itself.
986 /// This does not remove the need to handle all loop nest handling by
987 /// directives, such as the ordered(<n>) clause or the simd schedule-clause
988 /// modifier of the worksharing-loop directive.
989 ///
990 /// Example:
991 /// \code
992 /// for (int i = 0; i < 7; ++i) // Canonical loop "i"
993 /// for (int j = 0; j < 9; ++j) // Canonical loop "j"
994 /// body(i, j);
995 /// \endcode
996 ///
997 /// After collapsing with Loops={i,j}, the loop is changed to
998 /// \code
999 /// for (int ij = 0; ij < 63; ++ij) {
1000 /// int i = ij / 9;
1001 /// int j = ij % 9;
1002 /// body(i, j);
1003 /// }
1004 /// \endcode
1005 ///
1006 /// In the current implementation, the following limitations apply:
1007 ///
1008 /// * All input loops have an induction variable of the same type.
1009 ///
1010 /// * The collapsed loop will have the same trip count integer type as the
1011 /// input loops. Therefore it is possible that the collapsed loop cannot
1012 /// represent all iterations of the input loops. For instance, assuming a
1013 /// 32 bit integer type, and two input loops both iterating 2^16 times, the
1014 /// theoretical trip count of the collapsed loop would be 2^32 iteration,
1015 /// which cannot be represented in an 32-bit integer. Behavior is undefined
1016 /// in this case.
1017 ///
1018 /// * The trip counts of every input loop must be available at \p ComputeIP.
1019 /// Non-rectangular loops are not yet supported.
1020 ///
1021 /// * At each nest level, code between a surrounding loop and its nested loop
1022 /// is hoisted into the loop body, and such code will be executed more
1023 /// often than before collapsing (or not at all if any inner loop iteration
1024 /// has a trip count of 0). This is permitted by the OpenMP specification.
1025 ///
1026 /// The Virtual mapping retains the nest. Threads receive ranges of one
1027 /// unsigned logical index spanning inner-loop invocations. For [b,b+n),
1028 /// decode the start once and use a remaining-iteration budget:
1029 ///
1030 /// if (n != 0) {
1031 /// unsigned remaining = n + b % 9;
1032 /// for (unsigned i = b / 9, start = b % 9; i < 7; ++i, start = 0) {
1033 /// for (unsigned j = start; j < min(remaining, 9u); ++j)
1034 /// body(i, j);
1035 /// if (remaining <= 9) break;
1036 /// remaining -= 9;
1037 /// }
1038 /// }
1039 ///
1040 /// Virtual shares DivMod's type and trip-count limits. Intervening code stays
1041 /// at its level, once per range touching that row; empty ranges skip it.
1042 /// Two loops and direct body-to-preheader/after-to-latch edges
1043 /// are required. Controls must retain form and be unobserved after the nest.
1044 /// Only host static worksharing without chunk or ordered is supported.
1045 /// SIMD, transforms of the result and logical body/IV access are unsupported.
1046 /// MLIR falls back to DivMod; API callers must choose a supported mapping.
1047 ///
1048 /// \param DL Debug location for instructions added for collapsing,
1049 /// such as instructions to compute/derive the input loop's
1050 /// induction variables.
1051 /// \param Loops Loops in the loop nest to collapse. Loops are specified
1052 /// from outermost-to-innermost and every control flow of a
1053 /// loop's body must pass through its directly nested loop.
1054 /// \param ComputeIP Where additional instruction that compute the collapsed
1055 /// trip count. If not set, defaults to before the generated
1056 /// loop.
1057 ///
1058 /// \returns The CanonicalLoopInfo object representing the collapsed loop.
1061 InsertPointTy ComputeIP);
1062
1063 /// Get the default alignment value for given target
1064 ///
1065 /// \param TargetTriple Target triple
1066 /// \param Features StringMap which describes extra CPU features
1067 LLVM_ABI static unsigned
1068 getOpenMPDefaultSimdAlign(const Triple &TargetTriple,
1069 const StringMap<bool> &Features);
1070
1071 /// Retrieve (or create if non-existent) the address of a declare
1072 /// target variable, used in conjunction with registerTargetGlobalVariable
1073 /// to create declare target global variables.
1074 ///
1075 /// \param CaptureClause - enumerator corresponding to the OpenMP capture
1076 /// clause used in conjunction with the variable being registered (link,
1077 /// to, enter).
1078 /// \param DeviceClause - enumerator corresponding to the OpenMP capture
1079 /// clause used in conjunction with the variable being registered (nohost,
1080 /// host, any)
1081 /// \param IsDeclaration - boolean stating if the variable being registered
1082 /// is a declaration-only and not a definition
1083 /// \param IsExternallyVisible - boolean stating if the variable is externally
1084 /// visible
1085 /// \param EntryInfo - Unique entry information for the value generated
1086 /// using getTargetEntryUniqueInfo, used to name generated pointer references
1087 /// to the declare target variable
1088 /// \param MangledName - the mangled name of the variable being registered
1089 /// \param GeneratedRefs - references generated by invocations of
1090 /// registerTargetGlobalVariable invoked from getAddrOfDeclareTargetVar,
1091 /// these are required by Clang for book keeping.
1092 /// \param OpenMPSIMD - if OpenMP SIMD mode is currently enabled
1093 /// \param TargetTriple - The OpenMP device target triple we are compiling
1094 /// for
1095 /// \param LlvmPtrTy - The type of the variable we are generating or
1096 /// retrieving an address for
1097 /// \param GlobalInitializer - a lambda function which creates a constant
1098 /// used for initializing a pointer reference to the variable in certain
1099 /// cases. If a nullptr is passed, it will default to utilising the original
1100 /// variable to initialize the pointer reference.
1101 /// \param VariableLinkage - a lambda function which returns the variables
1102 /// linkage type, if unspecified and a nullptr is given, it will instead
1103 /// utilise the linkage stored on the existing global variable in the
1104 /// LLVMModule.
1108 bool IsDeclaration, bool IsExternallyVisible,
1109 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
1110 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
1111 std::vector<Triple> TargetTriple, Type *LlvmPtrTy,
1112 std::function<Constant *()> GlobalInitializer,
1113 std::function<GlobalValue::LinkageTypes()> VariableLinkage);
1114
1115 /// Registers a target variable for device or host.
1116 ///
1117 /// \param CaptureClause - enumerator corresponding to the OpenMP capture
1118 /// clause used in conjunction with the variable being registered (link,
1119 /// to, enter).
1120 /// \param DeviceClause - enumerator corresponding to the OpenMP capture
1121 /// clause used in conjunction with the variable being registered (nohost,
1122 /// host, any)
1123 /// \param IsDeclaration - boolean stating if the variable being registered
1124 /// is a declaration-only and not a definition
1125 /// \param IsExternallyVisible - boolean stating if the variable is externally
1126 /// visible
1127 /// \param EntryInfo - Unique entry information for the value generated
1128 /// using getTargetEntryUniqueInfo, used to name generated pointer references
1129 /// to the declare target variable
1130 /// \param MangledName - the mangled name of the variable being registered
1131 /// \param GeneratedRefs - references generated by invocations of
1132 /// registerTargetGlobalVariable these are required by Clang for book
1133 /// keeping.
1134 /// \param OpenMPSIMD - if OpenMP SIMD mode is currently enabled
1135 /// \param TargetTriple - The OpenMP device target triple we are compiling
1136 /// for
1137 /// \param GlobalInitializer - a lambda function which creates a constant
1138 /// used for initializing a pointer reference to the variable in certain
1139 /// cases. If a nullptr is passed, it will default to utilising the original
1140 /// variable to initialize the pointer reference.
1141 /// \param VariableLinkage - a lambda function which returns the variables
1142 /// linkage type, if unspecified and a nullptr is given, it will instead
1143 /// utilise the linkage stored on the existing global variable in the
1144 /// LLVMModule.
1145 /// \param LlvmPtrTy - The type of the variable we are generating or
1146 /// retrieving an address for
1147 /// \param Addr - the original llvm value (addr) of the variable to be
1148 /// registered
1152 bool IsDeclaration, bool IsExternallyVisible,
1153 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
1154 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
1155 std::vector<Triple> TargetTriple,
1156 std::function<Constant *()> GlobalInitializer,
1157 std::function<GlobalValue::LinkageTypes()> VariableLinkage,
1158 Type *LlvmPtrTy, Constant *Addr);
1159
1160 /// Register a module-scope replacement of a declare target global variable.
1161 /// During lowering new globals are generated for certain combinations of
1162 /// declare target input, and these new globals require substitution with
1163 /// the originals. This replacement occurs during finalization where uses
1164 /// of \p Original are rewritten to reference \p Replacement. This is
1165 /// predominantly required for lowering through the LLVM-IR + OpenMP
1166 /// dialect infrastructure where the lowering pattern to LLVM-IR prevents
1167 /// immediate use rewrites.
1168 ///
1169 /// This infrastructure is utilised for the device pass only currently,
1170 /// and host passes will skip the finalization process even if replacements
1171 /// are registered.
1172 ///
1173 /// \param Original - The original global variable that will be replaced.
1174 /// \param Replacement - The replacement reference pointer generated by the
1175 /// declare target infrastructure (declare target link or unified shared
1176 /// memory globals).
1177 LLVM_ABI void
1179 GlobalValue *Replacement);
1180
1181 /// Get the offset of the OMP_MAP_MEMBER_OF field.
1182 LLVM_ABI unsigned getFlagMemberOffset();
1183
1184 /// Get OMP_MAP_MEMBER_OF flag with extra bits reserved based on
1185 /// the position given.
1186 /// \param Position - A value indicating the position of the parent
1187 /// of the member in the kernel argument structure, often retrieved
1188 /// by the parents position in the combined information vectors used
1189 /// to generate the structure itself. Multiple children (member's of)
1190 /// with the same parent will use the same returned member flag.
1192
1193 /// Given an initial flag set, this function modifies it to contain
1194 /// the passed in MemberOfFlag generated from the getMemberOfFlag
1195 /// function. The results are dependent on the existing flag bits
1196 /// set in the original flag set.
1197 /// \param Flags - The original set of flags to be modified with the
1198 /// passed in MemberOfFlag.
1199 /// \param MemberOfFlag - A modified OMP_MAP_MEMBER_OF flag, adjusted
1200 /// slightly based on the getMemberOfFlag which adjusts the flag bits
1201 /// based on the members position in its parent.
1202 LLVM_ABI void
1204 omp::OpenMPOffloadMappingFlags MemberOfFlag);
1205
1206private:
1207 /// Attach unroll metadata only to supported logical iteration loops.
1208 void addUnrollMetadata(CanonicalLoopInfo *Loop,
1209 ArrayRef<Metadata *> Properties);
1210 /// Input loop blocks, induction variables, and inner comparison used to
1211 /// build the Virtual row executor. Collected before modifying the CFG.
1212 struct VirtualRowPlan;
1213 /// Collect the input loop blocks, induction variables, and inner comparison.
1214 /// Require direct nesting; reject an indirectbr terminator in the innermost
1215 /// after block. Report a fatal error before changing IR.
1217 /// Generate IR for Count logical iterations starting at Begin, keeping the
1218 /// original loops. Decode Begin once in Entry, limit the final inner-loop
1219 /// execution, and exit the nest when the assigned range is complete.
1220 void createVirtualRowExecutor(CanonicalLoopInfo *Result,
1221 const VirtualRowPlan &Plan,
1222 ArrayRef<Value *> TripCounts, Value *Begin,
1223 Value *Count, BasicBlock *Entry);
1224 /// Create a Virtual CanonicalLoopInfo using the outer loop's control blocks.
1225 /// Initialize Begin/Count for the full nest and skip empty ranges. Build the
1226 /// executor, then invalidate the input CanonicalLoopInfo objects.
1228 createVirtualCollapsedLoop(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
1229 const VirtualRowPlan &Plan,
1230 ArrayRef<Value *> TripCounts,
1231 Value *CollapsedTripCount);
1232 /// Update the Begin and Count copies with the scheduler's range.
1233 /// Use the scheduler's values unchanged, without validation or clipping.
1234 void bindCollapsedRange(CanonicalLoopInfo *Loop, Value *Begin, Value *Count);
1235
1236 /// Modifies the canonical loop to be a statically-scheduled workshare loop
1237 /// which is executed on the device
1238 ///
1239 /// This takes a \p CLI representing a canonical loop, such as the one
1240 /// created by \see createCanonicalLoop and emits additional instructions to
1241 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1242 /// runtime function in the preheader to call OpenMP device rtl function
1243 /// which handles worksharing of loop body interations.
1244 ///
1245 /// \param DL Debug location for instructions added for the
1246 /// workshare-loop construct itself.
1247 /// \param CLI A descriptor of the canonical loop to workshare.
1248 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1249 /// preheader of the loop.
1250 /// \param LoopType Information about type of loop worksharing.
1251 /// It corresponds to type of loop workshare OpenMP pragma.
1252 /// \param NeedsBarrier Indicates whether a barrier must be inserted after
1253 /// the loop.
1254 /// \param NoLoop If true, no-loop code is generated.
1255 /// \param NeedsLastIter If true, the last iteration variable is emitted.
1256 ///
1257 /// \returns Point where to insert code after the workshare construct.
1259 applyWorkshareLoopTarget(DebugLoc DL, CanonicalLoopInfo *CLI,
1260 InsertPointTy AllocaIP,
1261 omp::WorksharingLoopType LoopType, bool NeedsBarrier,
1262 bool NoLoop, bool NeedsLastIter);
1263
1264 /// Modifies the canonical loop to be a statically-scheduled workshare loop.
1265 ///
1266 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1267 /// created by \p createCanonicalLoop and emits additional instructions to
1268 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1269 /// runtime function in the preheader to obtain the loop bounds to be used in
1270 /// the current thread, updates the relevant instructions in the canonical
1271 /// loop and calls to an OpenMP runtime finalization function after the loop.
1272 ///
1273 /// \param DL Debug location for instructions added for the
1274 /// workshare-loop construct itself.
1275 /// \param CLI A descriptor of the canonical loop to workshare.
1276 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1277 /// preheader of the loop.
1278 /// \param NeedsBarrier Indicates whether a barrier must be inserted after
1279 /// the loop.
1280 /// \param LoopType Type of workshare loop.
1281 /// \param HasDistSchedule Defines if the clause being lowered is
1282 /// dist_schedule as this is handled slightly differently
1283 /// \param DistScheduleSchedType Defines the Schedule Type for the Distribute
1284 /// loop. Defaults to None if no Distribute loop is present.
1285 ///
1286 /// \returns Point where to insert code after the workshare construct.
1287 InsertPointOrErrorTy applyStaticWorkshareLoop(
1289 omp::WorksharingLoopType LoopType, bool NeedsBarrier,
1290 bool HasDistSchedule = false,
1291 omp::OMPScheduleType DistScheduleSchedType = omp::OMPScheduleType::None);
1292
1293 /// Modifies the canonical loop a statically-scheduled workshare loop with a
1294 /// user-specified chunk size.
1295 ///
1296 /// \param DL Debug location for instructions added for the
1297 /// workshare-loop construct itself.
1298 /// \param CLI A descriptor of the canonical loop to workshare.
1299 /// \param AllocaIP An insertion point for Alloca instructions usable in
1300 /// the preheader of the loop.
1301 /// \param NeedsBarrier Indicates whether a barrier must be inserted after the
1302 /// loop.
1303 /// \param ChunkSize The user-specified chunk size.
1304 /// \param SchedType Optional type of scheduling to be passed to the init
1305 /// function.
1306 /// \param DistScheduleChunkSize The size of dist_shcedule chunk considered
1307 /// as a unit when
1308 /// scheduling. If \p nullptr, defaults to 1.
1309 /// \param DistScheduleSchedType Defines the Schedule Type for the Distribute
1310 /// loop. Defaults to None if no Distribute loop is present.
1311 ///
1312 /// \returns Point where to insert code after the workshare construct.
1313 InsertPointOrErrorTy applyStaticChunkedWorkshareLoop(
1315 bool NeedsBarrier, Value *ChunkSize,
1316 omp::OMPScheduleType SchedType =
1318 Value *DistScheduleChunkSize = nullptr,
1319 omp::OMPScheduleType DistScheduleSchedType = omp::OMPScheduleType::None);
1320
1321 /// Modifies the canonical loop to be a dynamically-scheduled workshare loop.
1322 ///
1323 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1324 /// created by \p createCanonicalLoop and emits additional instructions to
1325 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1326 /// runtime function in the preheader to obtain, and then in each iteration
1327 /// to update the loop counter.
1328 ///
1329 /// \param DL Debug location for instructions added for the
1330 /// workshare-loop construct itself.
1331 /// \param CLI A descriptor of the canonical loop to workshare.
1332 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1333 /// preheader of the loop.
1334 /// \param SchedType Type of scheduling to be passed to the init function.
1335 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
1336 /// the loop.
1337 /// \param Chunk The size of loop chunk considered as a unit when
1338 /// scheduling. If \p nullptr, defaults to 1.
1339 ///
1340 /// \returns Point where to insert code after the workshare construct.
1341 InsertPointOrErrorTy applyDynamicWorkshareLoop(DebugLoc DL,
1342 CanonicalLoopInfo *CLI,
1343 InsertPointTy AllocaIP,
1344 omp::OMPScheduleType SchedType,
1345 bool NeedsBarrier,
1346 Value *Chunk = nullptr);
1347
1348 /// Create alternative version of the loop to support if clause
1349 ///
1350 /// OpenMP if clause can require to generate second loop. This loop
1351 /// will be executed when if clause condition is not met. createIfVersion
1352 /// adds branch instruction to the copied loop if \p ifCond is not met.
1353 ///
1354 /// \param Loop Original loop which should be versioned.
1355 /// \param IfCond Value which corresponds to if clause condition
1356 /// \param VMap Value to value map to define relation between
1357 /// original and copied loop values and loop blocks.
1358 /// \param NamePrefix Optional name prefix for if.then if.else blocks.
1359 void createIfVersion(CanonicalLoopInfo *Loop, Value *IfCond,
1361 LoopAnalysis &LIA, LoopInfo &LI, llvm::Loop *L,
1362 const Twine &NamePrefix = "");
1363
1364 /// Creates a task duplication function to be passed to kmpc_taskloop.
1365 ///
1366 /// The OpenMP runtime defines this function as taking the destination
1367 /// kmp_task_t, source kmp_task_t, and a lastprivate flag. This function is
1368 /// called on the source and destination tasks after the source task has been
1369 /// duplicated to create the destination task. At this point the destination
1370 /// task has been otherwise set up from the runtime's perspective, but this
1371 /// function is needed to fix up any data for the duplicated task e.g. private
1372 /// variables with non-trivial constructors.
1373 ///
1374 /// \param PrivatesTy The type of the privates structure for the task.
1375 /// \param PrivatesIndex The index inside the privates structure containing
1376 /// the data for the callback.
1377 /// \param DupCB The callback to generate the duplication code. See
1378 /// documentation for \ref TaskDupCallbackTy. This can be
1379 /// nullptr.
1380 Expected<Value *> createTaskDuplicationFunction(Type *PrivatesTy,
1381 int32_t PrivatesIndex,
1382 TaskDupCallbackTy DupCB);
1383
1384public:
1385 /// Modifies the canonical loop to be a workshare loop.
1386 ///
1387 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1388 /// created by \p createCanonicalLoop and emits additional instructions to
1389 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1390 /// runtime function in the preheader to obtain the loop bounds to be used in
1391 /// the current thread, updates the relevant instructions in the canonical
1392 /// loop and calls to an OpenMP runtime finalization function after the loop.
1393 ///
1394 /// The concrete transformation is done by applyStaticWorkshareLoop,
1395 /// applyStaticChunkedWorkshareLoop, or applyDynamicWorkshareLoop, depending
1396 /// on the value of \p SchedKind and \p ChunkSize.
1397 ///
1398 /// \param DL Debug location for instructions added for the
1399 /// workshare-loop construct itself.
1400 /// \param CLI A descriptor of the canonical loop to workshare.
1401 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1402 /// preheader of the loop.
1403 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
1404 /// the loop.
1405 /// \param SchedKind Scheduling algorithm to use.
1406 /// \param ChunkSize The chunk size for the inner loop.
1407 /// \param HasSimdModifier Whether the simd modifier is present in the
1408 /// schedule clause.
1409 /// \param HasMonotonicModifier Whether the monotonic modifier is present in
1410 /// the schedule clause.
1411 /// \param HasNonmonotonicModifier Whether the nonmonotonic modifier is
1412 /// present in the schedule clause.
1413 /// \param HasOrderedClause Whether the (parameterless) ordered clause is
1414 /// present.
1415 /// \param LoopType Information about type of loop worksharing.
1416 /// It corresponds to type of loop workshare OpenMP pragma.
1417 /// \param NoLoop If true, no-loop code is generated.
1418 /// \param HasDistSchedule Defines if the clause being lowered is
1419 /// dist_schedule as this is handled slightly differently
1420 /// \param DistScheduleChunkSize The chunk size for dist_schedule loop
1421 /// \param NeedsLastIter If true, the last iteration variable is emitted.
1422 ///
1423 /// \returns Point where to insert code after the workshare construct.
1426 bool NeedsBarrier,
1427 llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default,
1428 Value *ChunkSize = nullptr, bool HasSimdModifier = false,
1429 bool HasMonotonicModifier = false, bool HasNonmonotonicModifier = false,
1430 bool HasOrderedClause = false,
1431 omp::WorksharingLoopType LoopType =
1433 bool NoLoop = false, bool HasDistSchedule = false,
1434 Value *DistScheduleChunkSize = nullptr, bool NeedsLastIter = false);
1435
1436 /// Tile a loop nest.
1437 ///
1438 /// Tiles the loops of \p Loops by the tile sizes in \p TileSizes. Loops in
1439 /// \p/ Loops must be perfectly nested, from outermost to innermost loop
1440 /// (i.e. Loops.front() is the outermost loop). The trip count llvm::Value
1441 /// of every loop and every tile sizes must be usable in the outermost
1442 /// loop's preheader. This implies that the loop nest is rectangular.
1443 ///
1444 /// Example:
1445 /// \code
1446 /// for (int i = 0; i < 15; ++i) // Canonical loop "i"
1447 /// for (int j = 0; j < 14; ++j) // Canonical loop "j"
1448 /// body(i, j);
1449 /// \endcode
1450 ///
1451 /// After tiling with Loops={i,j} and TileSizes={5,7}, the loop is changed to
1452 /// \code
1453 /// for (int i1 = 0; i1 < 3; ++i1)
1454 /// for (int j1 = 0; j1 < 2; ++j1)
1455 /// for (int i2 = 0; i2 < 5; ++i2)
1456 /// for (int j2 = 0; j2 < 7; ++j2)
1457 /// body(i1*3+i2, j1*3+j2);
1458 /// \endcode
1459 ///
1460 /// The returned vector are the loops {i1,j1,i2,j2}. The loops i1 and j1 are
1461 /// referred to the floor, and the loops i2 and j2 are the tiles. Tiling also
1462 /// handles non-constant trip counts, non-constant tile sizes and trip counts
1463 /// that are not multiples of the tile size. In the latter case the tile loop
1464 /// of the last floor-loop iteration will have fewer iterations than specified
1465 /// as its tile size.
1466 ///
1467 ///
1468 /// @param DL Debug location for instructions added by tiling, for
1469 /// instance the floor- and tile trip count computation.
1470 /// @param Loops Loops to tile. The CanonicalLoopInfo objects are
1471 /// invalidated by this method, i.e. should not used after
1472 /// tiling.
1473 /// @param TileSizes For each loop in \p Loops, the tile size for that
1474 /// dimensions.
1475 ///
1476 /// \returns A list of generated loops. Contains twice as many loops as the
1477 /// input loop nest; the first half are the floor loops and the
1478 /// second half are the tile loops.
1479 LLVM_ABI std::vector<CanonicalLoopInfo *>
1481 ArrayRef<Value *> TileSizes);
1482
1483 /// Fuse a sequence of loops.
1484 ///
1485 /// Fuses the loops of \p Loops.
1486 /// The merging of the loops is done in the following structure:
1487 ///
1488 /// Example:
1489 /// \code
1490 /// for (int i = lb0; i < ub0; i += st0) // trip count is calculated as:
1491 /// body(i) // tc0 = (ub0 - lb0 + st0) / st0
1492 /// for (int j = lb1; j < ub1; j += st1)
1493 /// body(j);
1494 ///
1495 /// ...
1496 ///
1497 /// for (int k = lbk; j < ubk; j += stk)
1498 /// body(k);
1499 /// \endcode
1500 ///
1501 /// After fusing the loops a single loop is left:
1502 /// \code
1503 /// for (fuse.index = 0; fuse.index < max(tc0, tc1, ... tck); ++fuse.index) {
1504 /// if (fuse.index < tc0){
1505 /// iv0 = lb0 + st0 * fuse.index;
1506 /// original.index0 = iv0
1507 /// body(0);
1508 /// }
1509 /// if (fuse.index < tc1){
1510 /// iv1 = lb1 + st1 * fuse.index;
1511 /// original.index1 = iv1
1512 /// body(1);
1513 /// }
1514 ///
1515 /// ...
1516 ///
1517 /// if (fuse.index < tck){
1518 /// ivk = lbk + stk * fuse.index;
1519 /// original.indexk = ivk
1520 /// body(k);
1521 /// }
1522 /// }
1523 /// \endcode
1524 ///
1525 ///
1526 /// @param DL Debug location for instructions added by fusion.
1527 ///
1528 /// @param Loops Loops to fuse. The CanonicalLoopInfo objects are
1529 /// invalidated by this method, i.e. should not used after
1530 /// fusion.
1531 ///
1532 /// \returns A single loop generated by the loop fusion
1535
1536 /// Fully unroll a loop.
1537 ///
1538 /// Instead of unrolling the loop immediately (and duplicating its body
1539 /// instructions), it is deferred to LLVM's LoopUnrollPass by adding loop
1540 /// metadata.
1541 ///
1542 /// \param DL Debug location for instructions added by unrolling.
1543 /// \param Loop The loop to unroll. The loop will be invalidated.
1545
1546 /// Fully or partially unroll a loop. How the loop is unrolled is determined
1547 /// using LLVM's LoopUnrollPass.
1548 ///
1549 /// \param DL Debug location for instructions added by unrolling.
1550 /// \param Loop The loop to unroll. The loop will be invalidated.
1552
1553 /// Partially unroll a loop.
1554 ///
1555 /// The CanonicalLoopInfo of the unrolled loop for use with chained
1556 /// loop-associated directive can be requested using \p UnrolledCLI. Not
1557 /// needing the CanonicalLoopInfo allows more efficient code generation by
1558 /// deferring the actual unrolling to the LoopUnrollPass using loop metadata.
1559 /// A loop-associated directive applied to the unrolled loop needs to know the
1560 /// new trip count, so if the CanonicalLoopInfo is requested with \p Factor ==
1561 /// 0, omp::DefaultPartialUnrollFactor is used.
1562 ///
1563 /// \param DL Debug location for instructions added by unrolling.
1564 /// \param Loop The loop to unroll. The loop will be invalidated.
1565 /// \param Factor The factor to unroll the loop by. A factor of 0
1566 /// leaves the choice of unroll-factor to the
1567 /// implementation.
1568 /// \param UnrolledCLI If non-null, receives the CanonicalLoopInfo of the
1569 /// partially unrolled loop. Otherwise, uses loop metadata
1570 /// to defer unrolling to the LoopUnrollPass.
1572 int32_t Factor,
1573 CanonicalLoopInfo **UnrolledCLI);
1574
1575 /// Add metadata to simd-ize a loop. If IfCond is not nullptr, the loop
1576 /// is cloned. The metadata which prevents vectorization is added to
1577 /// to the cloned loop. The cloned loop is executed when ifCond is evaluated
1578 /// to false.
1579 ///
1580 /// \param Loop The loop to simd-ize.
1581 /// \param AlignedVars The map which containts pairs of the pointer
1582 /// and its corresponding alignment.
1583 /// \param IfCond The value which corresponds to the if clause
1584 /// condition.
1585 /// \param Order The enum to map order clause.
1586 /// \param Simdlen The Simdlen length to apply to the simd loop.
1587 /// \param Safelen The Safelen length to apply to the simd loop.
1589 MapVector<Value *, Value *> AlignedVars,
1590 Value *IfCond, omp::OrderKind Order,
1591 ConstantInt *Simdlen, ConstantInt *Safelen);
1592
1593 /// Generator for '#omp flush'
1594 ///
1595 /// \param Loc The location where the flush directive was encountered
1596 /// \param AO The memory ordering of the flush. NotAtomic is a flush with a
1597 /// list, which is treated as seq_cst.
1598 /// \param Scope The memory scope of the flush.
1599 LLVM_ABI void
1603
1604 /// Generate a call to the runtime to emit the diagnostic of an OpenMP
1605 /// `error` directive with `at(execution)`.
1606 ///
1607 /// \param Loc The location where the error directive was encountered; it is
1608 /// used to build the `ident_t` passed to the runtime.
1609 /// \param IsFatal Selects `severity(fatal)` (true) or `severity(warning)`
1610 /// (false).
1611 /// \param Message The message string (an `i8*`) to display, or null when no
1612 /// `message` clause is present.
1613 LLVM_ABI void createError(const LocationDescription &Loc, bool IsFatal,
1614 Value *Message);
1615
1616 /// Generator for '#omp taskyield'
1617 ///
1618 /// \param Loc The location where the taskyield directive was encountered.
1620
1621 /// A struct to pack the relevant information for an OpenMP depend clause.
1631
1632 /// A struct to pack static and dynamic dependency information for a task.
1633 ///
1634 /// For fixed-count (non-iterator) dependencies, callers populate \p Deps
1635 /// and the builder allocates and fills the kmp_depend_info array internally.
1636 /// For iterator-based dependencies, the caller pre-builds the array and
1637 /// sets \p NumDeps and \p DepArray directly.
1639 SmallVector<DependData> Deps; // vector of dependencies
1640 Value *NumDeps; // number of kmp_depend_info entries (used by iterator path)
1641 Value *DepArray; // kmp_depend_info array (used by iterator path)
1642
1643 DependenciesInfo() : Deps(), NumDeps(nullptr), DepArray(nullptr) {}
1646
1647 bool empty() const { return Deps.empty() && DepArray == nullptr; }
1648 };
1649
1650 /// Store one kmp_depend_info entry at the given \p Entry pointer.
1651 LLVM_ABI void emitTaskDependency(IRBuilderBase &Builder, Value *Entry,
1652 const DependData &Dep);
1653
1654 /// Generator for '#omp taskwait'
1655 ///
1656 /// \param Loc The location where the taskwait directive was encountered.
1657 /// \param Dependencies dependencies as specified by the 'depend' clause.
1658 /// \param IsNowait True when a 'nowait' clause is present
1659 LLVM_ABI void createTaskwait(const LocationDescription &Loc,
1660 DependenciesInfo Dependencies = {},
1661 bool IsNowait = false);
1662
1663 /// Return the LLVM struct type matching runtime `kmp_task_affinity_info_t`.
1664 /// `{ kmp_intptr_t base_addr; size_t len; flags (bitfield storage as i32) }`
1666
1667 /// A struct to pack the relevant information for an OpenMP affinity clause.
1669 Value *Count; // number of kmp_task_affinity_info_t entries
1670 Value *Info; // kmp_task_affinity_info_t
1671 };
1672
1673 /// Generator for `#omp taskloop`
1674 ///
1675 /// \param Loc The location where the taskloop construct was encountered.
1676 /// \param AllocaIP The insertion point to be used for alloca instructions.
1677 /// \param DeallocBlocks The list of insertion blocks where explicit
1678 /// deallocations, if needed, should be placed.
1679 /// \param BodyGenCB Callback that will generate the region code.
1680 /// \param LoopInfo Callback that return the CLI
1681 /// \param LBVal Lowerbound value of loop
1682 /// \param UBVal Upperbound value of loop
1683 /// \param StepVal Step value of loop
1684 /// \param Untied True if the task is untied, false if the task is tied.
1685 /// \param IfCond i1 value. If it evaluates to `false`, an undeferred
1686 /// task is generated, and the encountering thread must
1687 /// suspend the current task region, for which execution
1688 /// cannot be resumed until execution of the structured
1689 /// block that is associated with the generated task is
1690 /// completed.
1691 /// \param GrainSize Value of the GrainSize/Num of Tasks if present
1692 /// \param NoGroup False if NoGroup is defined, true if not
1693 /// \param Sched If Grainsize is defined, Sched is 1. Num Tasks, Shed is 2.
1694 /// Otherwise Sched is 0
1695 /// \param Final i1 value which is `true` if the task is final, `false` if the
1696 /// task is not final.
1697 /// \param Mergeable If the given task is `mergeable`
1698 /// \param Priority `priority-value' specifies the execution order of the
1699 /// tasks that is generated by the construct
1700 /// \param NumOfCollapseLoops Defines the number of loops that are being
1701 /// collapsed. The default value is 1, as thats the value when collapse is not
1702 /// used.
1703 /// \param DupCB The callback to generate the duplication code. See
1704 /// documentation for \ref TaskDupCallbackTy. This can be nullptr.
1705 /// \param TaskContextStructPtrVal If non-null, a pointer to to be placed
1706 /// immediately after the {lower bound, upper
1707 /// bound, step} values in the task data.
1708 /// \param FreeAgent If `true`, the generated tasks are eligible to be
1709 /// executed by a free-agent thread (threadset(omp_pool)).
1710 LLVM_ABI InsertPointOrErrorTy createTaskloop(
1711 const LocationDescription &Loc, InsertPointTy AllocaIP,
1712 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
1714 Value *LBVal, Value *UBVal, Value *StepVal, bool Untied = false,
1715 Value *IfCond = nullptr, Value *GrainSize = nullptr, bool NoGroup = false,
1716 int Sched = 0, Value *Final = nullptr, bool Mergeable = false,
1717 Value *Priority = nullptr, uint64_t NumOfCollapseLoops = 1,
1718 TaskDupCallbackTy DupCB = nullptr,
1719 Value *TaskContextStructPtrVal = nullptr, bool FreeAgent = false);
1720
1721 /// Generator for `#omp task`
1722 ///
1723 /// \param Loc The location where the task construct was encountered.
1724 /// \param AllocaIP The insertion point to be used for allocations.
1725 /// \param DeallocBlocks The insertion blocks to be used for explicit
1726 /// deallocations, if needed.
1727 /// \param BodyGenCB Callback that will generate the region code.
1728 /// \param Tied True if the task is tied, false if the task is untied.
1729 /// \param Final i1 value which is `true` if the task is final, `false` if the
1730 /// task is not final.
1731 /// \param IfCondition i1 value. If it evaluates to `false`, an undeferred
1732 /// task is generated, and the encountering thread must
1733 /// suspend the current task region, for which execution
1734 /// cannot be resumed until execution of the structured
1735 /// block that is associated with the generated task is
1736 /// completed.
1737 /// \param Dependencies Dependencies info holding either a vector of
1738 /// DependData objects or a pre-built dependency array.
1739 /// \param Affinities AffinityData object holding information of accumulated
1740 /// affinities as specified by the 'affinity' clause.
1741 /// \param EventHandle If present, signifies the event handle as part of
1742 /// the detach clause
1743 /// \param Mergeable If the given task is `mergeable`
1744 /// \param priority `priority-value' specifies the execution order of the
1745 /// tasks that is generated by the construct
1746 /// \param FreeAgent If `true`, the task is eligible to be executed by a
1747 /// free-agent thread (threadset(omp_pool)).
1749 const LocationDescription &Loc, InsertPointTy AllocaIP,
1750 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
1751 bool Tied = true, Value *Final = nullptr, Value *IfCondition = nullptr,
1752 const DependenciesInfo &Dependencies = {},
1753 const AffinityData &Affinities = {}, bool Mergeable = false,
1754 Value *EventHandle = nullptr, Value *Priority = nullptr,
1755 bool FreeAgent = false);
1756
1757 /// Generator for the taskgroup construct
1758 ///
1759 /// \param Loc The location where the taskgroup construct was encountered.
1760 /// \param AllocaIP The insertion point to be used for allocations.
1761 /// \param DeallocBlocks The insertion blocks to be used for explicit
1762 /// deallocation instructions, if needed.
1763 /// \param BodyGenCB Callback that will generate the region code.
1765 const LocationDescription &Loc, InsertPointTy AllocaIP,
1766 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB);
1767
1769 std::function<std::tuple<std::string, uint64_t>()>;
1770
1771 /// Creates a unique info for a target entry when provided a filename and
1772 /// line number from.
1773 ///
1774 /// \param CallBack A callback function which should return filename the entry
1775 /// resides in as well as the line number for the target entry
1776 /// \param ParentName The name of the parent the target entry resides in, if
1777 /// any.
1780 vfs::FileSystem &VFS, StringRef ParentName = "");
1781
1782 /// Enum class for the RedctionGen CallBack type to be used.
1784
1785 /// ReductionGen CallBack for Clang
1786 ///
1787 /// \param CodeGenIP InsertPoint for CodeGen.
1788 /// \param Index Index of the ReductionInfo to generate code for.
1789 /// \param LHSPtr Optionally used by Clang to return the LHSPtr it used for
1790 /// codegen, used for fixup later.
1791 /// \param RHSPtr Optionally used by Clang to
1792 /// return the RHSPtr it used for codegen, used for fixup later.
1793 /// \param CurFn Optionally used by Clang to pass in the Current Function as
1794 /// Clang context may be old.
1796 std::function<InsertPointTy(InsertPointTy CodeGenIP, unsigned Index,
1797 Value **LHS, Value **RHS, Function *CurFn)>;
1798
1799 /// ReductionGen CallBack for MLIR
1800 ///
1801 /// \param CodeGenIP InsertPoint for CodeGen.
1802 /// \param LHS Pass in the LHS Value to be used for CodeGen.
1803 /// \param RHS Pass in the RHS Value to be used for CodeGen.
1805 InsertPointTy CodeGenIP, Value *LHS, Value *RHS, Value *&Res)>;
1806
1807 /// Functions used to generate atomic reductions. Such functions take two
1808 /// Values representing pointers to LHS and RHS of the reduction, as well as
1809 /// the element type of these pointers. They are expected to atomically
1810 /// update the LHS to the reduced value.
1812 InsertPointTy, Type *, Value *, Value *)>;
1813
1815 InsertPointTy, Value *ByRefVal, Value *&Res)>;
1816
1817 /// Enum class for reduction evaluation types scalar, complex and aggregate.
1819
1820 /// Information about an OpenMP reduction.
1835
1841
1842 /// Reduction element type, must match pointee type of variable. For by-ref
1843 /// reductions, this would be just an opaque `ptr`.
1845
1846 /// Reduction variable of pointer type.
1848
1849 /// Thread-private partial reduction variable.
1851
1852 /// Reduction evaluation kind - scalar, complex or aggregate.
1854
1855 /// Callback for generating the reduction body. The IR produced by this will
1856 /// be used to combine two values in a thread-safe context, e.g., under
1857 /// lock or within the same thread, and therefore need not be atomic.
1859
1860 /// Clang callback for generating the reduction body. The IR produced by
1861 /// this will be used to combine two values in a thread-safe context, e.g.,
1862 /// under lock or within the same thread, and therefore need not be atomic.
1864
1865 /// Callback for generating the atomic reduction body, may be null. The IR
1866 /// produced by this will be used to atomically combine two values during
1867 /// reduction. If null, the implementation will use the non-atomic version
1868 /// along with the appropriate synchronization mechanisms.
1870
1872
1873 /// For by-ref reductions, we need to keep track of 2 extra types that are
1874 /// potentially different:
1875 /// * The allocated type is the type of the storage allocated by the
1876 /// reduction op's `alloc` region. For example, for allocatables and arrays,
1877 /// this type would be the descriptor/box struct.
1879
1880 /// * The by-ref element type is the type of the actual storage needed for
1881 /// the data of the allocatable or array. For example, an float allocatable
1882 /// of would need some float storage to store intermediate reduction
1883 /// results.
1885 };
1886
1887 enum class CopyAction : unsigned {
1888 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1889 // the warp using shuffle instructions.
1891 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1893 };
1894
1900
1901 /// Supporting functions for Reductions CodeGen.
1902private:
1903 /// Get the id of the current thread on the GPU.
1904 Value *getGPUThreadID();
1905
1906 /// Get the GPU warp size.
1907 Value *getGPUWarpSize();
1908
1909 /// Get the id of the warp in the block.
1910 /// We assume that the warp size is 32, which is always the case
1911 /// on the NVPTX device, to generate more efficient code.
1912 Value *getNVPTXWarpID();
1913
1914 /// Get the id of the current lane in the Warp.
1915 /// We assume that the warp size is 32, which is always the case
1916 /// on the NVPTX device, to generate more efficient code.
1917 Value *getNVPTXLaneID();
1918
1919 /// Cast value to the specified type.
1920 Value *castValueToType(InsertPointTy AllocaIP, Value *From, Type *ToType);
1921
1922 /// This function creates calls to one of two shuffle functions to copy
1923 /// variables between lanes in a warp. The returned value has \p ElementType,
1924 /// even though the shuffle runtime functions operate on 32- or 64-bit values.
1925 Value *createRuntimeShuffleFunction(InsertPointTy AllocaIP, Value *Element,
1926 Type *ElementType, Value *Offset);
1927
1928 /// Function to shuffle over the value from the remote lane.
1929 void shuffleAndStore(InsertPointTy AllocaIP, Value *SrcAddr, Value *DstAddr,
1930 Type *ElementType, Value *Offset, Type *ReductionArrayTy,
1931 bool IsByRefElem);
1932
1933 /// Emit instructions to copy a Reduce list, which contains partially
1934 /// aggregated values, in the specified direction.
1935 Error emitReductionListCopy(
1936 InsertPointTy AllocaIP, CopyAction Action, Type *ReductionArrayTy,
1937 ArrayRef<ReductionInfo> ReductionInfos, Value *SrcBase, Value *DestBase,
1938 ArrayRef<bool> IsByRef,
1939 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr});
1940
1941 /// Emit a helper that reduces data across two OpenMP threads (lanes)
1942 /// in the same warp. It uses shuffle instructions to copy over data from
1943 /// a remote lane's stack. The reduction algorithm performed is specified
1944 /// by the fourth parameter.
1945 ///
1946 /// Algorithm Versions.
1947 /// Full Warp Reduce (argument value 0):
1948 /// This algorithm assumes that all 32 lanes are active and gathers
1949 /// data from these 32 lanes, producing a single resultant value.
1950 /// Contiguous Partial Warp Reduce (argument value 1):
1951 /// This algorithm assumes that only a *contiguous* subset of lanes
1952 /// are active. This happens for the last warp in a parallel region
1953 /// when the user specified num_threads is not an integer multiple of
1954 /// 32. This contiguous subset always starts with the zeroth lane.
1955 /// Partial Warp Reduce (argument value 2):
1956 /// This algorithm gathers data from any number of lanes at any position.
1957 /// All reduced values are stored in the lowest possible lane. The set
1958 /// of problems every algorithm addresses is a super set of those
1959 /// addressable by algorithms with a lower version number. Overhead
1960 /// increases as algorithm version increases.
1961 ///
1962 /// Terminology
1963 /// Reduce element:
1964 /// Reduce element refers to the individual data field with primitive
1965 /// data types to be combined and reduced across threads.
1966 /// Reduce list:
1967 /// Reduce list refers to a collection of local, thread-private
1968 /// reduce elements.
1969 /// Remote Reduce list:
1970 /// Remote Reduce list refers to a collection of remote (relative to
1971 /// the current thread) reduce elements.
1972 ///
1973 /// We distinguish between three states of threads that are important to
1974 /// the implementation of this function.
1975 /// Alive threads:
1976 /// Threads in a warp executing the SIMT instruction, as distinguished from
1977 /// threads that are inactive due to divergent control flow.
1978 /// Active threads:
1979 /// The minimal set of threads that has to be alive upon entry to this
1980 /// function. The computation is correct iff active threads are alive.
1981 /// Some threads are alive but they are not active because they do not
1982 /// contribute to the computation in any useful manner. Turning them off
1983 /// may introduce control flow overheads without any tangible benefits.
1984 /// Effective threads:
1985 /// In order to comply with the argument requirements of the shuffle
1986 /// function, we must keep all lanes holding data alive. But at most
1987 /// half of them perform value aggregation; we refer to this half of
1988 /// threads as effective. The other half is simply handing off their
1989 /// data.
1990 ///
1991 /// Procedure
1992 /// Value shuffle:
1993 /// In this step active threads transfer data from higher lane positions
1994 /// in the warp to lower lane positions, creating Remote Reduce list.
1995 /// Value aggregation:
1996 /// In this step, effective threads combine their thread local Reduce list
1997 /// with Remote Reduce list and store the result in the thread local
1998 /// Reduce list.
1999 /// Value copy:
2000 /// In this step, we deal with the assumption made by algorithm 2
2001 /// (i.e. contiguity assumption). When we have an odd number of lanes
2002 /// active, say 2k+1, only k threads will be effective and therefore k
2003 /// new values will be produced. However, the Reduce list owned by the
2004 /// (2k+1)th thread is ignored in the value aggregation. Therefore
2005 /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2006 /// that the contiguity assumption still holds.
2007 ///
2008 /// \param ReductionInfos Array type containing the ReductionOps.
2009 /// \param ReduceFn The reduction function.
2010 /// \param FuncAttrs Optional param to specify any function attributes that
2011 /// need to be copied to the new function.
2012 /// \param IsByRef For each reduction clause, whether the reduction is by-ref
2013 /// or not.
2014 ///
2015 /// \return The ShuffleAndReduce function.
2016 Expected<Function *> emitShuffleAndReduceFunction(
2018 Function *ReduceFn, AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
2019
2020 /// Helper function for CreateCanonicalScanLoops to create InputLoop
2021 /// in the firstGen and Scan Loop in the SecondGen
2022 /// \param InputLoopGen Callback for generating the loop for input phase
2023 /// \param ScanLoopGen Callback for generating the loop for scan phase
2024 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2025 /// `ScanInfoInitialize`.
2026 ///
2027 /// \return error if any produced, else return success.
2028 Error emitScanBasedDirectiveIR(
2029 llvm::function_ref<Error()> InputLoopGen,
2030 llvm::function_ref<Error(LocationDescription Loc)> ScanLoopGen,
2031 ScanInfo *ScanRedInfo);
2032
2033 /// Creates the basic blocks required for scan reduction.
2034 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2035 /// `ScanInfoInitialize`.
2036 void createScanBBs(ScanInfo *ScanRedInfo);
2037
2038 /// Dynamically allocates the buffer needed for scan reduction.
2039 /// \param AllocaIP The IP where possibly-shared pointer of buffer needs to
2040 /// be declared.
2041 /// \param ScanVars Scan Variables.
2042 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2043 /// `ScanInfoInitialize`.
2044 ///
2045 /// \return error if any produced, else return success.
2046 Error emitScanBasedDirectiveDeclsIR(InsertPointTy AllocaIP,
2047 ArrayRef<llvm::Value *> ScanVars,
2048 ArrayRef<llvm::Type *> ScanVarsType,
2049 ScanInfo *ScanRedInfo);
2050
2051 /// Copies the result back to the reduction variable.
2052 /// \param ReductionInfos Array type containing the ReductionOps.
2053 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2054 /// `ScanInfoInitialize`.
2055 ///
2056 /// \return error if any produced, else return success.
2057 Error emitScanBasedDirectiveFinalsIR(
2060
2061 /// This function emits a helper that gathers Reduce lists from the first
2062 /// lane of every active warp to lanes in the first warp.
2063 ///
2064 /// void inter_warp_copy_func(void* reduce_data, num_warps)
2065 /// shared smem[warp_size];
2066 /// For all data entries D in reduce_data:
2067 /// sync
2068 /// If (I am the first lane in each warp)
2069 /// Copy my local D to smem[warp_id]
2070 /// sync
2071 /// if (I am the first warp)
2072 /// Copy smem[thread_id] to my local D
2073 ///
2074 /// \param Loc The insert and source location description.
2075 /// \param ReductionInfos Array type containing the ReductionOps.
2076 /// \param FuncAttrs Optional param to specify any function attributes that
2077 /// need to be copied to the new function.
2078 /// \param IsByRef For each reduction clause, whether the reduction is by-ref
2079 /// or not.
2080 ///
2081 /// \return The InterWarpCopy function.
2083 emitInterWarpCopyFunction(const LocationDescription &Loc,
2084 ArrayRef<ReductionInfo> ReductionInfos,
2085 AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
2086
2087 /// This function emits a helper that copies all the reduction variables from
2088 /// the team into the provided global buffer for the reduction variables.
2089 ///
2090 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
2091 /// For all data entries D in reduce_data:
2092 /// Copy local D to buffer.D[Idx]
2093 ///
2094 /// \param ReductionInfos Array type containing the ReductionOps.
2095 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
2096 /// \param FuncAttrs Optional param to specify any function attributes that
2097 /// need to be copied to the new function.
2098 ///
2099 /// \return The ListToGlobalCopy function.
2101 emitListToGlobalCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
2102 Type *ReductionsBufferTy,
2103 AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
2104
2105 /// This function emits a helper that copies all the reduction variables from
2106 /// the team into the provided global buffer for the reduction variables.
2107 ///
2108 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
2109 /// For all data entries D in reduce_data:
2110 /// Copy buffer.D[Idx] to local D;
2111 ///
2112 /// \param ReductionInfos Array type containing the ReductionOps.
2113 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
2114 /// \param FuncAttrs Optional param to specify any function attributes that
2115 /// need to be copied to the new function.
2116 ///
2117 /// \return The GlobalToList function.
2119 emitGlobalToListCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
2120 Type *ReductionsBufferTy,
2121 AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
2122
2123 /// This function emits a helper that reduces all the reduction variables from
2124 /// the team into the provided global buffer for the reduction variables.
2125 ///
2126 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
2127 /// void *GlobPtrs[];
2128 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
2129 /// ...
2130 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
2131 /// reduce_function(GlobPtrs, reduce_data);
2132 ///
2133 /// \param ReductionInfos Array type containing the ReductionOps.
2134 /// \param ReduceFn The reduction function.
2135 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
2136 /// \param FuncAttrs Optional param to specify any function attributes that
2137 /// need to be copied to the new function.
2138 ///
2139 /// \return The ListToGlobalReduce function.
2141 emitListToGlobalReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
2142 Function *ReduceFn, Type *ReductionsBufferTy,
2143 AttributeList FuncAttrs,
2144 ArrayRef<bool> IsByRef);
2145
2146 /// This function emits a helper that reduces all the reduction variables from
2147 /// the team into the provided global buffer for the reduction variables.
2148 ///
2149 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
2150 /// void *GlobPtrs[];
2151 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
2152 /// ...
2153 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
2154 /// reduce_function(reduce_data, GlobPtrs);
2155 ///
2156 /// \param ReductionInfos Array type containing the ReductionOps.
2157 /// \param ReduceFn The reduction function.
2158 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
2159 /// \param FuncAttrs Optional param to specify any function attributes that
2160 /// need to be copied to the new function.
2161 ///
2162 /// \return The GlobalToListReduce function.
2164 emitGlobalToListReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
2165 Function *ReduceFn, Type *ReductionsBufferTy,
2166 AttributeList FuncAttrs,
2167 ArrayRef<bool> IsByRef);
2168
2169 /// Get the function name of a reduction function.
2170 std::string getReductionFuncName(StringRef Name) const;
2171
2172 /// Generate a Fortran descriptor for array reductions
2173 ///
2174 /// \param DescriptorAddr Address of the descriptor to initialize
2175 /// \param DataPtr Pointer to the actual data the descriptor should reference
2176 /// \param SrcDescriptorAddr Address of the descriptor to copy metadata from
2177 /// \param DescriptorType Type of the descriptor structure
2178 /// \param DataPtrPtrGen Callback to get the base_ptr field in the descriptor
2179 ///
2180 /// \return Error if DataPtrPtrGen fails, otherwise success.
2181 InsertPointOrErrorTy generateReductionDescriptor(
2182 Value *DescriptorAddr, Value *DataPtr, Value *SrcDescriptorAddr,
2183 Type *DescriptorType,
2185 DataPtrPtrGen);
2186
2187 /// Allocate a by-ref reduction descriptor, copy \p SrcDescriptorAddr into it,
2188 /// and update its data pointer to reference \p DataPtr.
2189 ///
2190 /// \param AllocaIP Insertion point for the descriptor allocation.
2191 /// \param RI Reduction info containing descriptor type and access callback.
2192 /// \param DataPtr Pointer to the actual data the descriptor should reference.
2193 /// \param SrcDescriptorAddr Address of the descriptor to copy metadata from.
2194 /// \param DescriptorPtrTy Pointer type expected by the descriptor consumer.
2195 ///
2196 /// \return The new descriptor address, or an Error if descriptor generation
2197 /// fails.
2198 Expected<Value *> createReductionDescriptorCopy(
2199 InsertPointTy AllocaIP, const ReductionInfo &RI, Value *DataPtr,
2200 Value *SrcDescriptorAddr, Type *DescriptorPtrTy,
2201 const Twine &Name = ".omp.reduction.byref_descriptor");
2202
2203 /// Emits reduction function.
2204 /// \param ReducerName Name of the function calling the reduction.
2205 /// \param ReductionInfos Array type containing the ReductionOps.
2206 /// \param ReductionGenCBKind Optional param to specify Clang or MLIR
2207 /// CodeGenCB kind.
2208 /// \param FuncAttrs Optional param to specify any function attributes that
2209 /// need to be copied to the new function.
2210 ///
2211 /// \return The reduction function.
2212 Expected<Function *> createReductionFunction(
2213 StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,
2214 ArrayRef<bool> IsByRef,
2216 AttributeList FuncAttrs = {});
2217
2218 /// Rewrites uses of registered declare target globals to their
2219 /// replacements if we are processing a device module.
2220 void applyDeclareTargetGlobalReplacements();
2221
2222public:
2223 ///
2224 /// Design of OpenMP reductions on the GPU
2225 ///
2226 /// Consider a typical OpenMP program with one or more reduction
2227 /// clauses:
2228 ///
2229 /// float foo;
2230 /// double bar;
2231 /// #pragma omp target teams distribute parallel for \
2232 /// reduction(+:foo) reduction(*:bar)
2233 /// for (int i = 0; i < N; i++) {
2234 /// foo += A[i]; bar *= B[i];
2235 /// }
2236 ///
2237 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
2238 /// all teams. In our OpenMP implementation on the NVPTX device an
2239 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2240 /// within a team are mapped to CUDA threads within a threadblock.
2241 /// Our goal is to efficiently aggregate values across all OpenMP
2242 /// threads such that:
2243 ///
2244 /// - the compiler and runtime are logically concise, and
2245 /// - the reduction is performed efficiently in a hierarchical
2246 /// manner as follows: within OpenMP threads in the same warp,
2247 /// across warps in a threadblock, and finally across teams on
2248 /// the NVPTX device.
2249 ///
2250 /// Introduction to Decoupling
2251 ///
2252 /// We would like to decouple the compiler and the runtime so that the
2253 /// latter is ignorant of the reduction variables (number, data types)
2254 /// and the reduction operators. This allows a simpler interface
2255 /// and implementation while still attaining good performance.
2256 ///
2257 /// Pseudocode for the aforementioned OpenMP program generated by the
2258 /// compiler is as follows:
2259 ///
2260 /// 1. Create private copies of reduction variables on each OpenMP
2261 /// thread: 'foo_private', 'bar_private'
2262 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2263 /// to it and writes the result in 'foo_private' and 'bar_private'
2264 /// respectively.
2265 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
2266 /// and store the result on the team master:
2267 ///
2268 /// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
2269 /// reduceData, shuffleReduceFn, interWarpCpyFn)
2270 ///
2271 /// where:
2272 /// struct ReduceData {
2273 /// double *foo;
2274 /// double *bar;
2275 /// } reduceData
2276 /// reduceData.foo = &foo_private
2277 /// reduceData.bar = &bar_private
2278 ///
2279 /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2280 /// auxiliary functions generated by the compiler that operate on
2281 /// variables of type 'ReduceData'. They aid the runtime perform
2282 /// algorithmic steps in a data agnostic manner.
2283 ///
2284 /// 'shuffleReduceFn' is a pointer to a function that reduces data
2285 /// of type 'ReduceData' across two OpenMP threads (lanes) in the
2286 /// same warp. It takes the following arguments as input:
2287 ///
2288 /// a. variable of type 'ReduceData' on the calling lane,
2289 /// b. its lane_id,
2290 /// c. an offset relative to the current lane_id to generate a
2291 /// remote_lane_id. The remote lane contains the second
2292 /// variable of type 'ReduceData' that is to be reduced.
2293 /// d. an algorithm version parameter determining which reduction
2294 /// algorithm to use.
2295 ///
2296 /// 'shuffleReduceFn' retrieves data from the remote lane using
2297 /// efficient GPU shuffle intrinsics and reduces, using the
2298 /// algorithm specified by the 4th parameter, the two operands
2299 /// element-wise. The result is written to the first operand.
2300 ///
2301 /// Different reduction algorithms are implemented in different
2302 /// runtime functions, all calling 'shuffleReduceFn' to perform
2303 /// the essential reduction step. Therefore, based on the 4th
2304 /// parameter, this function behaves slightly differently to
2305 /// cooperate with the runtime to ensure correctness under
2306 /// different circumstances.
2307 ///
2308 /// 'InterWarpCpyFn' is a pointer to a function that transfers
2309 /// reduced variables across warps. It tunnels, through CUDA
2310 /// shared memory, the thread-private data of type 'ReduceData'
2311 /// from lane 0 of each warp to a lane in the first warp.
2312 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
2313 /// The last team writes the global reduced value to memory.
2314 ///
2315 /// ret = __kmpc_gpu_teams_reduce_nowait(...,
2316 /// reduceData, shuffleReduceFn, interWarpCpyFn,
2317 /// scratchpadCopyFn, loadAndReduceFn)
2318 ///
2319 /// 'scratchpadCopyFn' is a helper that stores reduced
2320 /// data from the team master to a scratchpad array in
2321 /// global memory.
2322 ///
2323 /// 'loadAndReduceFn' is a helper that loads data from
2324 /// the scratchpad array and reduces it with the input
2325 /// operand.
2326 ///
2327 /// These compiler generated functions hide address
2328 /// calculation and alignment information from the runtime.
2329 /// 5. if ret == 1:
2330 /// The team master of the last team stores the reduced
2331 /// result to the globals in memory.
2332 /// foo += reduceData.foo; bar *= reduceData.bar
2333 ///
2334 ///
2335 /// Warp Reduction Algorithms
2336 ///
2337 /// On the warp level, we have three algorithms implemented in the
2338 /// OpenMP runtime depending on the number of active lanes:
2339 ///
2340 /// Full Warp Reduction
2341 ///
2342 /// The reduce algorithm within a warp where all lanes are active
2343 /// is implemented in the runtime as follows:
2344 ///
2345 /// full_warp_reduce(void *reduce_data,
2346 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2347 /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
2348 /// ShuffleReduceFn(reduce_data, 0, offset, 0);
2349 /// }
2350 ///
2351 /// The algorithm completes in log(2, WARPSIZE) steps.
2352 ///
2353 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
2354 /// not used therefore we save instructions by not retrieving lane_id
2355 /// from the corresponding special registers. The 4th parameter, which
2356 /// represents the version of the algorithm being used, is set to 0 to
2357 /// signify full warp reduction.
2358 ///
2359 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2360 ///
2361 /// #reduce_elem refers to an element in the local lane's data structure
2362 /// #remote_elem is retrieved from a remote lane
2363 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2364 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
2365 ///
2366 /// Contiguous Partial Warp Reduction
2367 ///
2368 /// This reduce algorithm is used within a warp where only the first
2369 /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2370 /// number of OpenMP threads in a parallel region is not a multiple of
2371 /// WARPSIZE. The algorithm is implemented in the runtime as follows:
2372 ///
2373 /// void
2374 /// contiguous_partial_reduce(void *reduce_data,
2375 /// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2376 /// int size, int lane_id) {
2377 /// int curr_size;
2378 /// int offset;
2379 /// curr_size = size;
2380 /// mask = curr_size/2;
2381 /// while (offset>0) {
2382 /// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2383 /// curr_size = (curr_size+1)/2;
2384 /// offset = curr_size/2;
2385 /// }
2386 /// }
2387 ///
2388 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2389 ///
2390 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2391 /// if (lane_id < offset)
2392 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
2393 /// else
2394 /// reduce_elem = remote_elem
2395 ///
2396 /// This algorithm assumes that the data to be reduced are located in a
2397 /// contiguous subset of lanes starting from the first. When there is
2398 /// an odd number of active lanes, the data in the last lane is not
2399 /// aggregated with any other lane's dat but is instead copied over.
2400 ///
2401 /// Dispersed Partial Warp Reduction
2402 ///
2403 /// This algorithm is used within a warp when any discontiguous subset of
2404 /// lanes are active. It is used to implement the reduction operation
2405 /// across lanes in an OpenMP simd region or in a nested parallel region.
2406 ///
2407 /// void
2408 /// dispersed_partial_reduce(void *reduce_data,
2409 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2410 /// int size, remote_id;
2411 /// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2412 /// do {
2413 /// remote_id = next_active_lane_id_right_after_me();
2414 /// # the above function returns 0 of no active lane
2415 /// # is present right after the current lane.
2416 /// size = number_of_active_lanes_in_this_warp();
2417 /// logical_lane_id /= 2;
2418 /// ShuffleReduceFn(reduce_data, logical_lane_id,
2419 /// remote_id-1-threadIdx.x, 2);
2420 /// } while (logical_lane_id % 2 == 0 && size > 1);
2421 /// }
2422 ///
2423 /// There is no assumption made about the initial state of the reduction.
2424 /// Any number of lanes (>=1) could be active at any position. The reduction
2425 /// result is returned in the first active lane.
2426 ///
2427 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2428 ///
2429 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2430 /// if (lane_id % 2 == 0 && offset > 0)
2431 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
2432 /// else
2433 /// reduce_elem = remote_elem
2434 ///
2435 ///
2436 /// Intra-Team Reduction
2437 ///
2438 /// This function, as implemented in the runtime call
2439 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
2440 /// threads in a team. It first reduces within a warp using the
2441 /// aforementioned algorithms. We then proceed to gather all such
2442 /// reduced values at the first warp.
2443 ///
2444 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
2445 /// data from each of the "warp master" (zeroth lane of each warp, where
2446 /// warp-reduced data is held) to the zeroth warp. This step reduces (in
2447 /// a mathematical sense) the problem of reduction across warp masters in
2448 /// a block to the problem of warp reduction.
2449 ///
2450 ///
2451 /// Inter-Team Reduction
2452 ///
2453 /// Once a team has reduced its data to a single value, it is stored in
2454 /// a global scratchpad array. Since each team has a distinct slot, this
2455 /// can be done without locking.
2456 ///
2457 /// The last team to write to the scratchpad array proceeds to reduce the
2458 /// scratchpad array. One or more workers in the last team use the helper
2459 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2460 /// the k'th worker reduces every k'th element.
2461 ///
2462 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
2463 /// reduce across workers and compute a globally reduced value.
2464 ///
2465 /// \param Loc The location where the reduction was
2466 /// encountered. Must be within the associate
2467 /// directive and after the last local access to the
2468 /// reduction variables.
2469 /// \param AllocaIP An insertion point suitable for allocas usable
2470 /// in reductions.
2471 /// \param CodeGenIP An insertion point suitable for code
2472 /// generation.
2473 /// \param ReductionInfos A list of info on each reduction
2474 /// variable.
2475 /// \param IsNoWait Optional flag set if the reduction is
2476 /// marked as nowait.
2477 /// \param IsByRef For each reduction clause, whether the reduction is by-ref.
2478 /// \param IsTeamsReduction Optional flag set if it is a teams
2479 /// reduction.
2480 /// \param IsSPMD Optional flag set when the surrounding kernel
2481 /// is compiled in SPMD execution mode (every
2482 /// reduction private is then known to be a
2483 /// per-thread scratch alloca). When false, the
2484 /// teams-reduction call site emits per-thread
2485 /// scratch and copies the team-local value in so
2486 /// the runtime's cross-team work cannot race on
2487 /// team-shared LDS storage produced by Generic
2488 /// globalization (Generic-SPMD case after
2489 /// OpenMPOpt SPMD-ization).
2490 /// \param GridValue Optional GPU grid value.
2491 /// used for teams reduction.
2492 /// \param SrcLocInfo Source location information global.
2494 const LocationDescription &Loc, InsertPointTy AllocaIP,
2495 InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,
2496 ArrayRef<bool> IsByRef, bool IsNoWait = false,
2497 bool IsTeamsReduction = false, bool IsSPMD = false,
2499 std::optional<omp::GV> GridValue = {}, Value *SrcLocInfo = nullptr);
2500
2501 // TODO: provide atomic and non-atomic reduction generators for reduction
2502 // operators defined by the OpenMP specification.
2503
2504 /// Generator for '#omp reduction'.
2505 ///
2506 /// Emits the IR instructing the runtime to perform the specific kind of
2507 /// reductions. Expects reduction variables to have been privatized and
2508 /// initialized to reduction-neutral values separately. Emits the calls to
2509 /// runtime functions as well as the reduction function and the basic blocks
2510 /// performing the reduction atomically and non-atomically.
2511 ///
2512 /// The code emitted for the following:
2513 ///
2514 /// \code
2515 /// type var_1;
2516 /// type var_2;
2517 /// #pragma omp <directive> reduction(reduction-op:var_1,var_2)
2518 /// /* body */;
2519 /// \endcode
2520 ///
2521 /// corresponds to the following sketch.
2522 ///
2523 /// \code
2524 /// void _outlined_par() {
2525 /// // N is the number of different reductions.
2526 /// void *red_array[] = {privatized_var_1, privatized_var_2, ...};
2527 /// switch(__kmpc_reduce(..., N, /*size of data in red array*/, red_array,
2528 /// _omp_reduction_func,
2529 /// _gomp_critical_user.reduction.var)) {
2530 /// case 1: {
2531 /// var_1 = var_1 <reduction-op> privatized_var_1;
2532 /// var_2 = var_2 <reduction-op> privatized_var_2;
2533 /// // ...
2534 /// __kmpc_end_reduce(...);
2535 /// break;
2536 /// }
2537 /// case 2: {
2538 /// _Atomic<ReductionOp>(var_1, privatized_var_1);
2539 /// _Atomic<ReductionOp>(var_2, privatized_var_2);
2540 /// // ...
2541 /// break;
2542 /// }
2543 /// default: break;
2544 /// }
2545 /// }
2546 ///
2547 /// void _omp_reduction_func(void **lhs, void **rhs) {
2548 /// *(type *)lhs[0] = *(type *)lhs[0] <reduction-op> *(type *)rhs[0];
2549 /// *(type *)lhs[1] = *(type *)lhs[1] <reduction-op> *(type *)rhs[1];
2550 /// // ...
2551 /// }
2552 /// \endcode
2553 ///
2554 /// \param Loc The location where the reduction was
2555 /// encountered. Must be within the associate
2556 /// directive and after the last local access to the
2557 /// reduction variables.
2558 /// \param AllocaIP An insertion point suitable for allocas usable
2559 /// in reductions.
2560 /// \param ReductionInfos A list of info on each reduction variable.
2561 /// \param IsNoWait A flag set if the reduction is marked as nowait.
2562 /// \param IsByRef A flag set if the reduction is using reference
2563 /// or direct value.
2564 /// \param IsTeamsReduction Optional flag set if it is a teams
2565 /// reduction.
2567 const LocationDescription &Loc, InsertPointTy AllocaIP,
2568 ArrayRef<ReductionInfo> ReductionInfos, ArrayRef<bool> IsByRef,
2569 bool IsNoWait = false, bool IsTeamsReduction = false);
2570
2571 ///}
2572
2573 /// Emit the host runtime lookups that redirect the `in_reduction`
2574 /// list items of an `omp.target` region to their per-task reduction-private
2575 /// storage.
2576 ///
2577 /// This owns the complete runtime-generation path for target `in_reduction`.
2578 /// It computes the executing thread's gtid once for the whole target body (so
2579 /// a target with several in_reduction items does not emit a redundant
2580 /// `__kmpc_global_thread_num` per item), then for each item emits
2581 /// `__kmpc_task_reduction_get_th_data(gtid, /*descriptor=*/null, origPtr)`
2582 /// with the address-space normalization required by the runtime entry point.
2583 /// The NULL descriptor makes the runtime walk the enclosing taskgroups to
2584 /// find the matching `task_reduction` registration for the item. The lookups
2585 /// are emitted at \p Loc, which must be inside the target task body.
2586 ///
2587 /// The front-end-specific work (matching each `in_reduction` item to its
2588 /// mapped storage and binding the generated private pointer back to the
2589 /// right value) stays with the caller: each generated private pointer is
2590 /// handed back through \p MapPrivateCB.
2591 ///
2592 /// \param Loc Insertion point for the target body.
2593 /// \param OrigPtrs Per item, the mapped original pointer used as the
2594 /// runtime `orig` argument.
2595 /// \param ResultPtrTys Per item, the type the returned private pointer must
2596 /// have (for address-space normalization). Must have the
2597 /// same length as \p OrigPtrs.
2598 /// \param MapPrivateCB Called once per item, in list order, with the item
2599 /// index and the generated per-task private pointer.
2600 /// \returns The insertion point after the emitted lookups.
2601 LLVM_ABI InsertPointTy createTargetInReduction(
2602 const LocationDescription &Loc, ArrayRef<Value *> OrigPtrs,
2603 ArrayRef<Type *> ResultPtrTys,
2604 function_ref<void(unsigned, Value *)> MapPrivateCB);
2605
2606 /// Return the insertion point used by the underlying IRBuilder.
2608
2609 /// Update the internal location to \p Loc.
2611 Builder.restoreIP(Loc.IP);
2612 Builder.SetCurrentDebugLocation(Loc.DL);
2613 return Loc.IP.isValid();
2614 }
2615
2616 /// Return the function declaration for the runtime function with \p FnID.
2619
2621
2623 ArrayRef<Value *> Args,
2624 const Twine &Name = "");
2625
2626 /// Return the (LLVM-IR) string describing the source location \p LocStr.
2628 uint32_t &SrcLocStrSize);
2629
2630 /// Return the (LLVM-IR) string describing the default source location.
2632
2633 /// Return the (LLVM-IR) string describing the source location identified by
2634 /// the arguments.
2636 StringRef FileName, unsigned Line,
2637 unsigned Column,
2638 uint32_t &SrcLocStrSize);
2639
2640 /// Return the (LLVM-IR) string describing the DebugLoc \p DL. Use \p F as
2641 /// fallback if \p DL does not specify the function name.
2643 const Function *F = nullptr);
2644
2645 /// Return the (LLVM-IR) string describing the source location \p Loc.
2646 LLVM_ABI Constant *getOrCreateSrcLocStr(const LocationDescription &Loc,
2647 uint32_t &SrcLocStrSize);
2648
2649 /// Return an ident_t* encoding the source location \p SrcLocStr and \p Flags.
2650 /// TODO: Create a enum class for the Reserve2Flags
2652 uint32_t SrcLocStrSize,
2653 omp::IdentFlag Flags = omp::IdentFlag(0),
2654 unsigned Reserve2Flags = 0);
2655
2656 /// Create a hidden global flag \p Name in the module with initial value \p
2657 /// Value.
2659
2660 /// Emit the llvm.used metadata.
2662
2663 /// Emit the kernel execution mode.
2666
2667 /// Generate control flow and cleanup for cancellation.
2668 ///
2669 /// \param CancelFlag Flag indicating if the cancellation is performed.
2670 /// \param CanceledDirective The kind of directive that is cancled.
2671 /// \param ExitCB Extra code to be generated in the exit block.
2672 ///
2673 /// \return an error, if any were triggered during execution.
2675 omp::Directive CanceledDirective);
2676
2677 /// Generate a target region entry call.
2678 ///
2679 /// \param Loc The location at which the request originated and is fulfilled.
2680 /// \param AllocaIP The insertion point to be used for alloca instructions.
2681 /// \param Return Return value of the created function returned by reference.
2682 /// \param DeviceID Identifier for the device via the 'device' clause.
2683 /// \param NumTeams Numer of teams for the region via the 'num_teams' clause
2684 /// or 0 if unspecified and -1 if there is no 'teams' clause.
2685 /// \param NumThreads Number of threads via the 'thread_limit' clause.
2686 /// \param HostPtr Pointer to the host-side pointer of the target kernel.
2687 /// \param KernelArgs Array of arguments to the kernel.
2688 LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc,
2689 InsertPointTy AllocaIP,
2690 Value *&Return, Value *Ident,
2691 Value *DeviceID, Value *NumTeams,
2692 Value *NumThreads, Value *HostPtr,
2693 ArrayRef<Value *> KernelArgs);
2694
2695 /// Generate a flush: a fence on a GPU, and a runtime call otherwise.
2696 ///
2697 /// \param Loc The location at which the request originated and is fulfilled.
2698 /// \param AO The memory ordering of the flush. NotAtomic is a flush with a
2699 /// list, which is treated as seq_cst.
2700 /// \param Scope The memory scope of the flush.
2701 LLVM_ABI void
2702 emitFlush(const LocationDescription &Loc,
2705
2706 /// The finalization stack made up of finalize callbacks currently in-flight,
2707 /// wrapped into FinalizationInfo objects that reference also the finalization
2708 /// target block and the kind of cancellable directive.
2710
2711 /// Return true if the last entry in the finalization stack is of kind \p DK
2712 /// and cancellable.
2713 bool isLastFinalizationInfoCancellable(omp::Directive DK) {
2714 return !FinalizationStack.empty() &&
2715 FinalizationStack.back().IsCancellable &&
2716 FinalizationStack.back().DK == DK;
2717 }
2718
2719 /// Generate a taskwait runtime call.
2720 ///
2721 /// \param Loc The location at which the request originated and is fulfilled.
2722 LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc);
2723
2724 /// Generate a taskyield runtime call.
2725 ///
2726 /// \param Loc The location at which the request originated and is fulfilled.
2727 LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc);
2728
2729 /// Return the current thread ID.
2730 ///
2731 /// \param Ident The ident (ident_t*) describing the query origin.
2733
2734 /// The OpenMPIRBuilder Configuration
2736
2737 /// The underlying LLVM-IR module
2739
2740 /// The LLVM-IR Builder used to create IR.
2742
2743 /// Map to remember source location strings
2745
2746 /// Map to remember existing ident_t*.
2748
2749 /// Info manager to keep track of target regions.
2751
2752 /// The target triple of the underlying module.
2753 const Triple T;
2754
2755 /// Helper that contains information about regions we need to outline
2756 /// during finalization.
2758 using PostOutlineCBTy = std::function<void(Function &)>;
2764 // TODO: this should be safe to enable by default
2766
2767 virtual ~OutlineInfo() = default;
2768
2769 /// Collect all blocks in between EntryBB and ExitBB in both the given
2770 /// vector and set.
2772 SmallVectorImpl<BasicBlock *> &BlockVector);
2773
2774 /// Create a CodeExtractor instance based on the information stored in this
2775 /// structure, the list of collected blocks from a previous call to
2776 /// \c collectBlocks and a flag stating whether arguments must be passed in
2777 /// address space 0.
2778 virtual std::unique_ptr<CodeExtractor>
2780 bool ArgsInZeroAddressSpace, Twine Suffix = Twine(""));
2781
2782 /// Return the function that contains the region to be outlined.
2783 Function *getFunction() const { return EntryBB->getParent(); }
2784 };
2785
2786 /// Collection of regions that need to be outlined during finalization.
2788
2789 /// A collection of candidate target functions that's constant allocas will
2790 /// attempt to be raised on a call of finalize after all currently enqueued
2791 /// outline info's have been processed.
2793
2794 /// Describes a declare target global variable replacement to be applied
2795 /// during finalization.
2800
2801 /// Collection of declare target globals to rewrite uses of during
2802 /// device module finalizaiton.
2805
2806 /// Collection of owned canonical loop objects that eventually need to be
2807 /// free'd.
2808 std::forward_list<CanonicalLoopInfo> LoopInfos;
2809
2810 /// Collection of owned ScanInfo objects that eventually need to be free'd.
2811 std::forward_list<ScanInfo> ScanInfos;
2812
2813 /// Add a new region that will be outlined later.
2814 void addOutlineInfo(std::unique_ptr<OutlineInfo> &&OI) {
2815 OutlineInfos.emplace_back(std::move(OI));
2816 }
2817
2818 /// Return true if \p Fn has a region registered for outlining that has not
2819 /// been processed yet.
2820 bool hasPendingOutlines(const Function *Fn) const {
2821 return any_of(OutlineInfos, [Fn](const std::unique_ptr<OutlineInfo> &OI) {
2822 return OI->getFunction() == Fn;
2823 });
2824 }
2825
2826 /// An ordered map of auto-generated variables to their unique names.
2827 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
2828 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
2829 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
2830 /// variables.
2832
2833 /// Computes the size of type in bytes.
2835
2836 // Emit a branch from the current block to the Target block only if
2837 // the current block has a terminator.
2839
2840 // If BB has no use then delete it and return. Else place BB after the current
2841 // block, if possible, or else at the end of the function. Also add a branch
2842 // from current block to BB if current block does not have a terminator.
2843 LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn,
2844 bool IsFinished = false);
2845
2846 /// Emits code for OpenMP 'if' clause using specified \a BodyGenCallbackTy
2847 /// Here is the logic:
2848 /// if (Cond) {
2849 /// ThenGen();
2850 /// } else {
2851 /// ElseGen();
2852 /// }
2853 ///
2854 /// \return an error, if any were triggered during execution.
2856 BodyGenCallbackTy ElseGen,
2857 InsertPointTy AllocaIP = {},
2858 ArrayRef<BasicBlock *> DeallocBlocks = {});
2859
2860 /// Create the global variable holding the offload mappings information.
2861 LLVM_ABI GlobalVariable *
2862 createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
2863 std::string VarName);
2864
2865 /// Create the global variable holding the offload names information.
2866 LLVM_ABI GlobalVariable *
2867 createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
2868 std::string VarName);
2869
2872 AllocaInst *Args = nullptr;
2874 };
2875
2876 /// Create the allocas instruction used in call to mapper functions.
2878 InsertPointTy AllocaIP,
2879 unsigned NumOperands,
2881
2882 /// Create the call for the target mapper function.
2883 /// \param Loc The source location description.
2884 /// \param MapperFunc Function to be called.
2885 /// \param SrcLocInfo Source location information global.
2886 /// \param MaptypesArg The argument types.
2887 /// \param MapnamesArg The argument names.
2888 /// \param MapperAllocas The AllocaInst used for the call.
2889 /// \param DeviceID Device ID for the call.
2890 /// \param NumOperands Number of operands in the call.
2892 Function *MapperFunc, Value *SrcLocInfo,
2893 Value *MaptypesArg, Value *MapnamesArg,
2895 int64_t DeviceID, unsigned NumOperands);
2896
2897 /// Container for the arguments used to pass data to the runtime library.
2899 /// The array of base pointer passed to the runtime library.
2901 /// The array of section pointers passed to the runtime library.
2903 /// The array of sizes passed to the runtime library.
2904 Value *SizesArray = nullptr;
2905 /// The array of map types passed to the runtime library for the beginning
2906 /// of the region or for the entire region if there are no separate map
2907 /// types for the region end.
2909 /// The array of map types passed to the runtime library for the end of the
2910 /// region, or nullptr if there are no separate map types for the region
2911 /// end.
2913 /// The array of user-defined mappers passed to the runtime library.
2915 /// The array of original declaration names of mapped pointers sent to the
2916 /// runtime library for debugging
2918
2920 /// The entry in PointersArray that refers to this descriptor.
2921 unsigned MapIndex;
2923 };
2924 /// Descriptors referenced by PointersArray need their own task-private
2925 /// copies when the runtime call is deferred.
2927
2928 explicit TargetDataRTArgs() = default;
2937 };
2938
2939 /// Container to pass the default attributes with which a kernel must be
2940 /// launched, used to set kernel attributes and populate associated static
2941 /// structures.
2942 ///
2943 /// For max values, < 0 means unset, == 0 means set but unknown at compile
2944 /// time. The number of max values will be 1 except for the case where
2945 /// ompx_bare is set.
2955
2956 /// Container to pass LLVM IR runtime values or constants related to the
2957 /// number of teams and threads with which the kernel must be launched, as
2958 /// well as the trip count of the loop, if it is an SPMD or Generic-SPMD
2959 /// kernel. These must be defined in the host prior to the call to the kernel
2960 /// launch OpenMP RTL function.
2966
2967 /// 'parallel' construct 'num_threads' clause value, if present and it is an
2968 /// SPMD kernel.
2970
2971 /// Total number of iterations of the SPMD or Generic-SPMD kernel or null if
2972 /// it is a generic kernel.
2974
2975 /// Device ID value used in the kernel launch.
2976 Value *DeviceID = nullptr;
2977 };
2978
2979 /// Data structure that contains the needed information to construct the
2980 /// kernel args vector.
2982 /// Number of arguments passed to the runtime library.
2983 unsigned NumTargetItems = 0;
2984 /// Arguments passed to the runtime library
2986 /// The number of iterations
2988 /// The number of teams.
2990 /// The number of threads.
2992 /// The size of the dynamic shared memory.
2994 /// True if the kernel has 'no wait' clause.
2995 bool HasNoWait = false;
2996 /// True if the kernel strictly requires the number of blocks and threads
2997 /// above to run.
2998 bool StrictBlocks = false;
2999 bool StrictThreads = false;
3000 /// The fallback mechanism for the shared memory.
3003
3004 // Constructors for TargetKernelArgs.
3005 TargetKernelArgs() = default;
3017 };
3018
3019 /// Create the kernel args vector used by emitTargetKernel. This function
3020 /// creates various constant values that are used in the resulting args
3021 /// vector.
3022 LLVM_ABI static void getKernelArgsVector(TargetKernelArgs &KernelArgs,
3023 IRBuilderBase &Builder,
3024 SmallVector<Value *> &ArgsVector);
3025
3026 /// Struct that keeps the information that should be kept throughout
3027 /// a 'target data' region.
3029 /// Set to true if device pointer information have to be obtained.
3030 bool RequiresDevicePointerInfo = false;
3031 /// Set to true if Clang emits separate runtime calls for the beginning and
3032 /// end of the region. These calls might have separate map type arrays.
3033 bool SeparateBeginEndCalls = false;
3034
3035 public:
3037
3040
3041 /// Indicate whether any user-defined mapper exists.
3042 bool HasMapper = false;
3043 /// The total number of pointers passed to the runtime library.
3044 unsigned NumberOfPtrs = 0u;
3045
3046 bool EmitDebug = false;
3047
3048 /// Whether the `target ... data` directive has a `nowait` clause.
3049 bool HasNoWait = false;
3050
3051 explicit TargetDataInfo() = default;
3052 explicit TargetDataInfo(bool RequiresDevicePointerInfo,
3053 bool SeparateBeginEndCalls)
3054 : RequiresDevicePointerInfo(RequiresDevicePointerInfo),
3055 SeparateBeginEndCalls(SeparateBeginEndCalls) {}
3056 /// Clear information about the data arrays.
3059 HasMapper = false;
3060 NumberOfPtrs = 0u;
3061 }
3062 /// Return true if the current target data information has valid arrays.
3063 bool isValid() {
3064 return RTArgs.BasePointersArray && RTArgs.PointersArray &&
3065 RTArgs.SizesArray && RTArgs.MapTypesArray &&
3066 (!HasMapper || RTArgs.MappersArray) && NumberOfPtrs;
3067 }
3068 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
3069 bool separateBeginEndCalls() { return SeparateBeginEndCalls; }
3070 };
3071
3080
3081 /// This structure contains combined information generated for mappable
3082 /// clauses, including base pointers, pointers, sizes, map types, user-defined
3083 /// mappers, and non-contiguous information.
3084 struct MapInfosTy {
3098 /// True for entries that have an attach ptr, and thus an accompanying
3099 /// ATTACH entry linking that ptr to its ptee.
3100 ///
3101 /// This is a property of the storage block an entry describes, not of the
3102 /// map clause list item: it is true iff the entry's storage is the pointee
3103 /// storage reached through some attach ptr. So, for `int *p; map(p[1:10])`,
3104 /// which produces
3105 /// &p[1], &p[1], 10*sizeof(int), TO|FROM <- HasAttachPtr = true
3106 /// &p, &p[1], sizeof(void*), ATTACH <- HasAttachPtr = false
3107 /// it is set on the pointee entry only. It is never set on the ATTACH entry
3108 /// itself, nor on an entry that maps the pointer as an object in its own
3109 /// right (e.g. the `map(p)` entry for the pointer's own storage).
3110 ///
3111 /// It is set on every entry whose storage lies in a pointee block,
3112 /// including a combined struct entry for such a block and the individual
3113 /// member entries that are MEMBER_OF it. e.g. for
3114 /// `map(s2.s1p->x, s2.s1p->y)`:
3115 /// &s2.s1p[0], &s2.s1p->x, sizeof(x..y), ALLOC <- true
3116 /// &s2.s1p[0], &s2.s1p->x, 4, MEMBER_OF(1)|TO|FROM <- true
3117 /// &s2.s1p[0], &s2.s1p->y, 4, MEMBER_OF(1)|TO|FROM <- true
3118 /// &s2.s1p, &s2.s1p->x, sizeof(void*), ATTACH <- false
3119 /// with s2.s1p as the attach ptr for all three.
3122
3123 /// Represents a group of mapper sub-components produced by an `iterator`
3124 /// modifier on a `declare mapper`'s map clause: the component count is
3125 /// only known at runtime, so these are pushed one at a time via
3126 /// __tgt_push_mapper_component from inside a generated loop, rather than
3127 /// being added to the arrays above. Only consumed by
3128 /// emitUserDefinedMapper; emitOffloadingArrays ignores this field.
3130 /// Runtime (i64) trip count for this segment.
3131 Value *Count = nullptr;
3132 /// Emits the code computing one iteration's (BasePointer, Pointer,
3133 /// Size) triple, given the loop's linear induction variable (0-based,
3134 /// i64). Owning (not function_ref): the callable is typically a
3135 /// lambda temporary assigned in after construction, which would
3136 /// otherwise dangle by the time this is invoked. Returns an Error if the
3137 /// entry could not be computed, e.g. on region conversion failure.
3138 std::function<Expected<SmallVector<Value *, 3>>(IRBuilderBase &, Value *)>
3140 /// Map type/HasAttachPtr, constant across the segment.
3143 bool HasAttachPtr = false;
3144 /// User-defined mapper to invoke for this segment's component, if the
3145 /// underlying map clause carries one (mirrors CustomMapperCB for the
3146 /// statically-known components above).
3148 };
3150
3151 /// When set, the first statically-known component is a parent synthesized
3152 /// only to group the DynamicSegments' components (via MEMBER_OF): it
3153 /// spans the range those components cover and is pushed only if this i1
3154 /// condition holds at runtime, typically "some segment has a non-zero
3155 /// trip count". Skipping it when no component would be grouped under it
3156 /// keeps the mapped variable from becoming device-present for an iterator
3157 /// that expands to nothing. Consumed by emitUserDefinedMapper only; not
3158 /// merged by append().
3160
3161 /// Append arrays in \a CurInfo.
3162 void append(MapInfosTy &CurInfo) {
3163 BasePointers.append(CurInfo.BasePointers.begin(),
3164 CurInfo.BasePointers.end());
3165 Pointers.append(CurInfo.Pointers.begin(), CurInfo.Pointers.end());
3166 DevicePointers.append(CurInfo.DevicePointers.begin(),
3167 CurInfo.DevicePointers.end());
3168 Sizes.append(CurInfo.Sizes.begin(), CurInfo.Sizes.end());
3169 Types.append(CurInfo.Types.begin(), CurInfo.Types.end());
3170 Names.append(CurInfo.Names.begin(), CurInfo.Names.end());
3171 HasAttachPtr.append(CurInfo.HasAttachPtr.begin(),
3172 CurInfo.HasAttachPtr.end());
3173 NonContigInfo.Dims.append(CurInfo.NonContigInfo.Dims.begin(),
3174 CurInfo.NonContigInfo.Dims.end());
3175 NonContigInfo.Offsets.append(CurInfo.NonContigInfo.Offsets.begin(),
3176 CurInfo.NonContigInfo.Offsets.end());
3177 NonContigInfo.Counts.append(CurInfo.NonContigInfo.Counts.begin(),
3178 CurInfo.NonContigInfo.Counts.end());
3179 NonContigInfo.Strides.append(CurInfo.NonContigInfo.Strides.begin(),
3180 CurInfo.NonContigInfo.Strides.end());
3181 DynamicSegments.append(CurInfo.DynamicSegments.begin(),
3182 CurInfo.DynamicSegments.end());
3183 }
3184 };
3186
3187 /// Callback function type for functions emitting the host fallback code that
3188 /// is executed when the kernel launch fails. It takes an insertion point as
3189 /// parameter where the code should be emitted. It returns an insertion point
3190 /// that points right after after the emitted code.
3193
3194 // Callback function type for emitting and fetching user defined custom
3195 // mappers.
3197 function_ref<Expected<Function *>(unsigned int)>;
3198
3199 /// Generate a target region entry call and host fallback call.
3200 ///
3201 /// \param Loc The location at which the request originated and is fulfilled.
3202 /// \param OutlinedFnID The ooulined function ID.
3203 /// \param EmitTargetCallFallbackCB Call back function to generate host
3204 /// fallback code.
3205 /// \param Args Data structure holding information about the kernel arguments.
3206 /// \param DeviceID Identifier for the device via the 'device' clause.
3207 /// \param RTLoc Source location identifier
3208 /// \param AllocaIP The insertion point to be used for alloca instructions.
3210 const LocationDescription &Loc, Value *OutlinedFnID,
3211 EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,
3212 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP);
3213
3214 /// Callback type for generating the bodies of device directives that require
3215 /// outer target tasks (e.g. in case of having `nowait` or `depend` clauses).
3216 ///
3217 /// \param DeviceID The ID of the device on which the target region will
3218 /// execute.
3219 /// \param RTLoc Source location identifier
3220 /// \Param TargetTaskAllocaIP Insertion point for the alloca block of the
3221 /// generated task.
3222 ///
3223 /// \return an error, if any were triggered during execution.
3225 function_ref<Error(Value *DeviceID, Value *RTLoc,
3226 IRBuilderBase::InsertPoint TargetTaskAllocaIP)>;
3227
3228 /// Generate a target-task for the target construct
3229 ///
3230 /// \param TaskBodyCB Callback to generate the actual body of the target task.
3231 /// \param DeviceID Identifier for the device via the 'device' clause.
3232 /// \param RTLoc Source location identifier
3233 /// \param AllocaIP The insertion point to be used for alloca instructions.
3234 /// \param Dependencies Dependencies info as specified by the 'depend' clause.
3235 /// \param HasNoWait True if the target construct had 'nowait' on it, false
3236 /// otherwise
3238 emitTargetTask(TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID,
3239 Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP,
3240 const DependenciesInfo &Dependencies,
3241 const TargetDataRTArgs &RTArgs, bool HasNoWait);
3242
3243 /// Emit the arguments to be passed to the runtime library based on the
3244 /// arrays of base pointers, pointers, sizes, map types, and mappers. If
3245 /// ForEndCall, emit map types to be passed for the end of the region instead
3246 /// of the beginning.
3249 OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall = false);
3250
3251 /// Emit an array of struct descriptors to be assigned to the offload args.
3253 InsertPointTy CodeGenIP,
3254 MapInfosTy &CombinedInfo,
3255 TargetDataInfo &Info);
3256
3257 /// Emit the arrays used to pass the captures and map information to the
3258 /// offloading runtime library. If there is no map or capture information,
3259 /// return nullptr by reference. Accepts a reference to a MapInfosTy object
3260 /// that contains information generated for mappable clauses,
3261 /// including base pointers, pointers, sizes, map types, user-defined mappers.
3263 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
3264 TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB,
3265 bool IsNonContiguous = false,
3266 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
3267
3268 /// Allocates memory for and populates the arrays required for offloading
3269 /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
3270 /// emits their base addresses as arguments to be passed to the runtime
3271 /// library. In essence, this function is a combination of
3272 /// emitOffloadingArrays and emitOffloadingArraysArgument and should arguably
3273 /// be preferred by clients of OpenMPIRBuilder.
3275 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
3276 TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
3277 CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous = false,
3278 bool ForEndCall = false,
3279 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
3280
3281 /// Creates offloading entry for the provided entry ID \a ID, address \a
3282 /// Addr, size \a Size, and flags \a Flags.
3284 int32_t Flags, GlobalValue::LinkageTypes,
3285 StringRef Name = "");
3286
3287 /// The kind of errors that can occur when emitting the offload entries and
3288 /// metadata.
3295
3296 /// Callback function type
3298 std::function<void(EmitMetadataErrorKind, TargetRegionEntryInfo)>;
3299
3300 // Emit the offloading entries and metadata so that the device codegen side
3301 // can easily figure out what to emit. The produced metadata looks like
3302 // this:
3303 //
3304 // !omp_offload.info = !{!1, ...}
3305 //
3306 // We only generate metadata for function that contain target regions.
3308 EmitMetadataErrorReportFunctionTy &ErrorReportFunction);
3309
3310public:
3311 /// Generator for __kmpc_copyprivate
3312 ///
3313 /// \param Loc The source location description.
3314 /// \param BufSize Number of elements in the buffer.
3315 /// \param CpyBuf List of pointers to data to be copied.
3316 /// \param CpyFn function to call for copying data.
3317 /// \param DidIt flag variable; 1 for 'single' thread, 0 otherwise.
3318 ///
3319 /// \return The insertion position *after* the CopyPrivate call.
3320
3322 llvm::Value *BufSize,
3323 llvm::Value *CpyBuf,
3324 llvm::Value *CpyFn,
3325 llvm::Value *DidIt);
3326
3327 /// Generator for '#omp single'
3328 ///
3329 /// \param Loc The source location description.
3330 /// \param BodyGenCB Callback that will generate the region code.
3331 /// \param FiniCB Callback to finalize variable copies.
3332 /// \param IsNowait If false, a barrier is emitted.
3333 /// \param CPVars copyprivate variables.
3334 /// \param CPFuncs copy functions to use for each copyprivate variable.
3335 ///
3336 /// \returns The insertion position *after* the single call.
3339 FinalizeCallbackTy FiniCB, bool IsNowait,
3340 ArrayRef<llvm::Value *> CPVars = {},
3341 ArrayRef<llvm::Function *> CPFuncs = {});
3342
3343 /// Generator for '#omp scope'
3344 ///
3345 /// \param Loc The source location description.
3346 /// \param BodyGenCB Callback that will generate the region code.
3347 /// \param FiniCB Callback to finalize variable copies.
3348 /// \param IsNowait If false, a barrier is emitted.
3349 ///
3350 /// \returns The insertion position *after* the scope.
3351 LLVM_ABI InsertPointOrErrorTy createScope(const LocationDescription &Loc,
3352 BodyGenCallbackTy BodyGenCB,
3353 FinalizeCallbackTy FiniCB,
3354 bool IsNowait);
3355
3356 /// Generator for '#omp master'
3357 ///
3358 /// \param Loc The insert and source location description.
3359 /// \param BodyGenCB Callback that will generate the region code.
3360 /// \param FiniCB Callback to finalize variable copies.
3361 ///
3362 /// \returns The insertion position *after* the master.
3363 LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc,
3364 BodyGenCallbackTy BodyGenCB,
3365 FinalizeCallbackTy FiniCB);
3366
3367 /// Generator for '#omp masked'
3368 ///
3369 /// \param Loc The insert and source location description.
3370 /// \param BodyGenCB Callback that will generate the region code.
3371 /// \param FiniCB Callback to finialize variable copies.
3372 ///
3373 /// \returns The insertion position *after* the masked.
3374 LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc,
3375 BodyGenCallbackTy BodyGenCB,
3376 FinalizeCallbackTy FiniCB,
3377 Value *Filter);
3378
3379 /// This function performs the scan reduction of the values updated in
3380 /// the input phase. The reduction logic needs to be emitted between input
3381 /// and scan loop returned by `CreateCanonicalScanLoops`. The following
3382 /// is the code that is generated, `buffer` and `span` are expected to be
3383 /// populated before executing the generated code.
3384 /// \code{c}
3385 /// for (int k = 0; k != ceil(log2(span)); ++k) {
3386 /// i=pow(2,k)
3387 /// for (size cnt = last_iter; cnt >= i; --cnt)
3388 /// buffer[cnt] op= buffer[cnt-i];
3389 /// }
3390 /// \endcode
3391 /// \param Loc The insert and source location description.
3392 /// \param ReductionInfos Array type containing the ReductionOps.
3393 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
3394 /// `ScanInfoInitialize`.
3395 ///
3396 /// \returns The insertion position *after* the masked.
3398 const LocationDescription &Loc,
3400 ScanInfo *ScanRedInfo);
3401
3402 /// This directive split and directs the control flow to input phase
3403 /// blocks or scan phase blocks based on 1. whether input loop or scan loop
3404 /// is executed, 2. whether exclusive or inclusive scan is used.
3405 ///
3406 /// \param Loc The insert and source location description.
3407 /// \param AllocaIP The IP where the temporary buffer for scan reduction
3408 // needs to be allocated.
3409 /// \param ScanVars Scan Variables.
3410 /// \param IsInclusive Whether it is an inclusive or exclusive scan.
3411 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
3412 /// `ScanInfoInitialize`.
3413 ///
3414 /// \returns The insertion position *after* the scan.
3415 LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc,
3416 InsertPointTy AllocaIP,
3417 ArrayRef<llvm::Value *> ScanVars,
3418 ArrayRef<llvm::Type *> ScanVarsType,
3419 bool IsInclusive,
3420 ScanInfo *ScanRedInfo);
3421
3422 /// Generator for '#omp critical'
3423 ///
3424 /// \param Loc The insert and source location description.
3425 /// \param BodyGenCB Callback that will generate the region body code.
3426 /// \param FiniCB Callback to finalize variable copies.
3427 /// \param CriticalName name of the lock used by the critical directive
3428 /// \param HintInst Hint Instruction for hint clause associated with critical
3429 ///
3430 /// \returns The insertion position *after* the critical.
3431 LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc,
3432 BodyGenCallbackTy BodyGenCB,
3433 FinalizeCallbackTy FiniCB,
3434 StringRef CriticalName,
3435 Value *HintInst);
3436
3437 /// Generator for '#omp ordered depend (source | sink)'
3438 ///
3439 /// \param Loc The insert and source location description.
3440 /// \param AllocaIP The insertion point to be used for alloca instructions.
3441 /// \param NumLoops The number of loops in depend clause.
3442 /// \param StoreValues The value will be stored in vector address.
3443 /// \param Name The name of alloca instruction.
3444 /// \param IsDependSource If true, depend source; otherwise, depend sink.
3445 ///
3446 /// \return The insertion position *after* the ordered.
3448 createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP,
3449 unsigned NumLoops, ArrayRef<llvm::Value *> StoreValues,
3450 const Twine &Name, bool IsDependSource);
3451
3452 /// Generator for '#omp ordered [threads | simd]'
3453 ///
3454 /// \param Loc The insert and source location description.
3455 /// \param BodyGenCB Callback that will generate the region code.
3456 /// \param FiniCB Callback to finalize variable copies.
3457 /// \param IsThreads If true, with threads clause or without clause;
3458 /// otherwise, with simd clause;
3459 ///
3460 /// \returns The insertion position *after* the ordered.
3462 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3463 FinalizeCallbackTy FiniCB, bool IsThreads);
3464
3465 /// Generator for '#omp sections'
3466 ///
3467 /// \param Loc The insert and source location description.
3468 /// \param AllocaIP The insertion points to be used for alloca instructions.
3469 /// \param SectionCBs Callbacks that will generate body of each section.
3470 /// \param PrivCB Callback to copy a given variable (think copy constructor).
3471 /// \param FiniCB Callback to finalize variable copies.
3472 /// \param IsCancellable Flag to indicate a cancellable parallel region.
3473 /// \param IsNowait If true, barrier - to ensure all sections are executed
3474 /// before moving forward will not be generated.
3475 /// \returns The insertion position *after* the sections.
3477 createSections(const LocationDescription &Loc, InsertPointTy AllocaIP,
3480 bool IsCancellable, bool IsNowait);
3481
3482 /// Generator for '#omp section'
3483 ///
3484 /// \param Loc The insert and source location description.
3485 /// \param BodyGenCB Callback that will generate the region body code.
3486 /// \param FiniCB Callback to finalize variable copies.
3487 /// \returns The insertion position *after* the section.
3488 LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc,
3489 BodyGenCallbackTy BodyGenCB,
3490 FinalizeCallbackTy FiniCB);
3491
3492 /// Generator for `#omp teams`
3493 ///
3494 /// \param Loc The location where the teams construct was encountered.
3495 /// \param BodyGenCB Callback that will generate the region code.
3496 /// \param NumTeamsLower Lower bound on number of teams. If this is nullptr,
3497 /// it is as if lower bound is specified as equal to upperbound. If
3498 /// this is non-null, then upperbound must also be non-null.
3499 /// \param NumTeamsUpper Upper bound on the number of teams.
3500 /// \param ThreadLimit on the number of threads that may participate in a
3501 /// contention group created by each team.
3502 /// \param IfExpr is the integer argument value of the if condition on the
3503 /// teams clause.
3504 LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc,
3505 BodyGenCallbackTy BodyGenCB,
3506 Value *NumTeamsLower = nullptr,
3507 Value *NumTeamsUpper = nullptr,
3508 Value *ThreadLimit = nullptr,
3509 Value *IfExpr = nullptr);
3510
3511 /// Generator for `#omp distribute`
3512 ///
3513 /// \param Loc The location where the distribute construct was encountered.
3514 /// \param AllocaIP The insertion point to be used for allocations.
3515 /// \param DeallocBlocks The insertion blocks to be used for explicit
3516 /// deallocations, if needed.
3517 /// \param BodyGenCB Callback that will generate the region code.
3519 const LocationDescription &Loc, InsertPointTy AllocaIP,
3520 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB);
3521
3522 /// Generate conditional branch and relevant BasicBlocks through which private
3523 /// threads copy the 'copyin' variables from Master copy to threadprivate
3524 /// copies.
3525 ///
3526 /// \param IP insertion block for copyin conditional
3527 /// \param MasterVarPtr a pointer to the master variable
3528 /// \param PrivateVarPtr a pointer to the threadprivate variable
3529 /// \param IntPtrTy Pointer size type
3530 /// \param BranchtoEnd Create a branch between the copyin.not.master blocks
3531 // and copy.in.end block
3532 ///
3533 /// \returns The insertion point where copying operation to be emitted.
3535 Value *MasterAddr,
3536 Value *PrivateAddr,
3538 bool BranchtoEnd = true);
3539
3540 /// Create a runtime call for kmpc_alloc
3541 ///
3542 /// \param Loc The insert and source location description.
3543 /// \param Size Size of allocated memory space
3544 /// \param Allocator Allocator information instruction
3545 /// \param Name Name of call Instruction for OMP_alloc
3546 ///
3547 /// \returns CallInst to the OMP_Alloc call
3548 LLVM_ABI CallInst *createOMPAlloc(const LocationDescription &Loc, Value *Size,
3549 Value *Allocator, std::string Name = "");
3550
3551 /// Create a runtime call for kmpc_align_alloc
3552 ///
3553 /// \param Loc The insert and source location description.
3554 /// \param Align Align value
3555 /// \param Size Size of allocated memory space
3556 /// \param Allocator Allocator information instruction
3557 /// \param Name Name of call Instruction for OMP_Align_Alloc
3558 ///
3559 /// \returns CallInst to the OMP_Align_Alloc call
3560 LLVM_ABI CallInst *createOMPAlignedAlloc(const LocationDescription &Loc,
3561 Value *Align, Value *Size,
3562 Value *Allocator,
3563 std::string Name = "");
3564
3565 /// Create a runtime call for kmpc_free
3566 ///
3567 /// \param Loc The insert and source location description.
3568 /// \param Addr Address of memory space to be freed
3569 /// \param Allocator Allocator information instruction
3570 /// \param Name Name of call Instruction for OMP_Free
3571 ///
3572 /// \returns CallInst to the OMP_Free call
3573 LLVM_ABI CallInst *createOMPFree(const LocationDescription &Loc, Value *Addr,
3574 Value *Allocator, std::string Name = "");
3575
3576 /// Create a runtime call for kmpc_alloc_shared.
3577 ///
3578 /// \param Loc The insert and source location description.
3579 /// \param Size Size of allocated memory space.
3580 /// \param Name Name of call Instruction.
3581 ///
3582 /// \returns CallInst to the kmpc_alloc_shared call.
3583 LLVM_ABI CallInst *createOMPAllocShared(const LocationDescription &Loc,
3584 Value *Size,
3585 const Twine &Name = Twine(""));
3586
3587 /// Create a runtime call for kmpc_alloc_shared.
3588 ///
3589 /// \param Loc The insert and source location description.
3590 /// \param VarType Type of variable to be allocated.
3591 /// \param Name Name of call Instruction.
3592 ///
3593 /// \returns CallInst to the kmpc_alloc_shared call.
3594 LLVM_ABI CallInst *createOMPAllocShared(const LocationDescription &Loc,
3595 Type *VarType,
3596 const Twine &Name = Twine(""));
3597
3598 /// Create a runtime call for kmpc_free_shared.
3599 ///
3600 /// \param Loc The insert and source location description.
3601 /// \param Addr Value obtained from the corresponding kmpc_alloc_shared call.
3602 /// \param Size Size of allocated memory space.
3603 /// \param Name Name of call Instruction.
3604 ///
3605 /// \returns CallInst to the kmpc_free_shared call.
3606 LLVM_ABI CallInst *createOMPFreeShared(const LocationDescription &Loc,
3607 Value *Addr, Value *Size,
3608 const Twine &Name = Twine(""));
3609
3610 /// Create a runtime call for kmpc_free_shared.
3611 ///
3612 /// \param Loc The insert and source location description.
3613 /// \param Addr Value obtained from the corresponding kmpc_alloc_shared call.
3614 /// \param VarType Type of variable to be freed.
3615 /// \param Name Name of call Instruction.
3616 ///
3617 /// \returns CallInst to the kmpc_free_shared call.
3618 LLVM_ABI CallInst *createOMPFreeShared(const LocationDescription &Loc,
3619 Value *Addr, Type *VarType,
3620 const Twine &Name = Twine(""));
3621
3622 /// Create a runtime call for kmpc_threadprivate_cached
3623 ///
3624 /// \param Loc The insert and source location description.
3625 /// \param Pointer pointer to data to be cached
3626 /// \param Size size of data to be cached
3627 /// \param Name Name of call Instruction for callinst
3628 ///
3629 /// \returns CallInst to the thread private cache call.
3630 LLVM_ABI CallInst *
3631 createCachedThreadPrivate(const LocationDescription &Loc,
3633 const llvm::Twine &Name = Twine(""));
3634
3635 /// Create a runtime call for __tgt_interop_init
3636 ///
3637 /// \param Loc The insert and source location description.
3638 /// \param InteropVar variable to be allocated
3639 /// \param InteropType type of interop operation
3640 /// \param Device devide to which offloading will occur
3641 /// \param NumDependences number of dependence variables
3642 /// \param DependenceAddress pointer to dependence variables
3643 /// \param HaveNowaitClause does nowait clause exist
3644 ///
3645 /// \returns CallInst to the __tgt_interop_init call
3646 LLVM_ABI CallInst *createOMPInteropInit(const LocationDescription &Loc,
3647 Value *InteropVar,
3648 omp::OMPInteropType InteropType,
3649 Value *Device, Value *NumDependences,
3650 Value *DependenceAddress,
3651 bool HaveNowaitClause);
3652
3653 /// Create a runtime call for __tgt_interop_destroy
3654 ///
3655 /// \param Loc The insert and source location description.
3656 /// \param InteropVar variable to be allocated
3657 /// \param Device devide to which offloading will occur
3658 /// \param NumDependences number of dependence variables
3659 /// \param DependenceAddress pointer to dependence variables
3660 /// \param HaveNowaitClause does nowait clause exist
3661 ///
3662 /// \returns CallInst to the __tgt_interop_destroy call
3663 LLVM_ABI CallInst *createOMPInteropDestroy(const LocationDescription &Loc,
3664 Value *InteropVar, Value *Device,
3665 Value *NumDependences,
3666 Value *DependenceAddress,
3667 bool HaveNowaitClause);
3668
3669 /// Create a runtime call for __tgt_interop_use
3670 ///
3671 /// \param Loc The insert and source location description.
3672 /// \param InteropVar variable to be allocated
3673 /// \param Device devide to which offloading will occur
3674 /// \param NumDependences number of dependence variables
3675 /// \param DependenceAddress pointer to dependence variables
3676 /// \param HaveNowaitClause does nowait clause exist
3677 ///
3678 /// \returns CallInst to the __tgt_interop_use call
3679 LLVM_ABI CallInst *createOMPInteropUse(const LocationDescription &Loc,
3680 Value *InteropVar, Value *Device,
3681 Value *NumDependences,
3682 Value *DependenceAddress,
3683 bool HaveNowaitClause);
3684
3685 /// The `omp target` interface
3686 ///
3687 /// For more information about the usage of this interface,
3688 /// \see openmp/device/include/Interface.h
3689 ///
3690 ///{
3691
3692 /// Create (or update) the '<kernel>_kernel_environment' global describing
3693 /// the launch configuration of the kernel at the current insertion point,
3694 ///
3695 /// \param Loc The insert and source location description.
3696 /// \param Attrs Structure containing the default attributes, including
3697 /// numbers of threads and teams to launch the kernel with.
3698 ///
3699 /// \returns the (possibly address-space-cast) kernel environment constant,
3700 /// or nullptr if \p Loc has no valid insertion point.
3702 const LocationDescription &Loc,
3704
3705 /// Create a runtime call for kmpc_target_init
3706 ///
3707 /// \param Loc The insert and source location description.
3708 /// \param Attrs Structure containing the default attributes, including
3709 /// numbers of threads and teams to launch the kernel with.
3711 const LocationDescription &Loc,
3713
3714 /// Create a runtime call for kmpc_target_deinit
3715 ///
3716 /// \param Loc The insert and source location description.
3717 /// \param TeamsReductionDataSize The maximal size of all the reduction data
3718 /// for teams reduction.
3719 LLVM_ABI void createTargetDeinit(const LocationDescription &Loc,
3720 int32_t TeamsReductionDataSize = 0);
3721
3722 ///}
3723
3724 /// Helpers to read/write kernel annotations from the IR.
3725 ///
3726 ///{
3727
3728 /// Read/write a bounds on threads for \p Kernel. Read will return 0 if none
3729 /// is set.
3730 LLVM_ABI static std::pair<int32_t, int32_t>
3731 readThreadBoundsForKernel(const Triple &T, Function &Kernel);
3732 LLVM_ABI static void writeThreadBoundsForKernel(const Triple &T,
3733 Function &Kernel, int32_t LB,
3734 int32_t UB);
3735
3736 /// Read/write a bounds on teams for \p Kernel. Read will return 0 if none
3737 /// is set.
3738 LLVM_ABI static std::pair<int32_t, int32_t>
3739 readTeamBoundsForKernel(const Triple &T, Function &Kernel);
3740 LLVM_ABI static void writeTeamsForKernel(const Triple &T, Function &Kernel,
3741 int32_t LB, int32_t UB);
3742 ///}
3743
3744private:
3745 // Sets the function attributes expected for the outlined function
3746 void setOutlinedTargetRegionFunctionAttributes(Function *OutlinedFn);
3747
3748 // Creates the function ID/Address for the given outlined function.
3749 // In the case of an embedded device function the address of the function is
3750 // used, in the case of a non-offload function a constant is created.
3751 Constant *createOutlinedFunctionID(Function *OutlinedFn,
3752 StringRef EntryFnIDName);
3753
3754 // Creates the region entry address for the outlined function
3755 Constant *createTargetRegionEntryAddr(Function *OutlinedFunction,
3756 StringRef EntryFnName);
3757
3758public:
3759 /// Functions used to generate a function with the given name.
3761 std::function<Expected<Function *>(StringRef FunctionName)>;
3762
3763 /// Create a unique name for the entry function using the source location
3764 /// information of the current target region. The name will be something like:
3765 ///
3766 /// __omp_offloading_DD_FFFF_PP_lBB[_CC]
3767 ///
3768 /// where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
3769 /// mangled name of the function that encloses the target region and BB is the
3770 /// line number of the target region. CC is a count added when more than one
3771 /// region is located at the same location.
3772 ///
3773 /// If this target outline function is not an offload entry, we don't need to
3774 /// register it. This may happen if it is guarded by an if clause that is
3775 /// false at compile time, or no target archs have been specified.
3776 ///
3777 /// The created target region ID is used by the runtime library to identify
3778 /// the current target region, so it only has to be unique and not
3779 /// necessarily point to anything. It could be the pointer to the outlined
3780 /// function that implements the target region, but we aren't using that so
3781 /// that the compiler doesn't need to keep that, and could therefore inline
3782 /// the host function if proven worthwhile during optimization. In the other
3783 /// hand, if emitting code for the device, the ID has to be the function
3784 /// address so that it can retrieved from the offloading entry and launched
3785 /// by the runtime library. We also mark the outlined function to have
3786 /// external linkage in case we are emitting code for the device, because
3787 /// these functions will be entry points to the device.
3788 ///
3789 /// \param InfoManager The info manager keeping track of the offload entries
3790 /// \param EntryInfo The entry information about the function
3791 /// \param GenerateFunctionCallback The callback function to generate the code
3792 /// \param OutlinedFunction Pointer to the outlined function
3793 /// \param EntryFnIDName Name of the ID o be created
3795 TargetRegionEntryInfo &EntryInfo,
3796 FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,
3797 Function *&OutlinedFn, Constant *&OutlinedFnID);
3798
3799 /// Registers the given function and sets up the attribtues of the function
3800 /// Returns the FunctionID.
3801 ///
3802 /// \param InfoManager The info manager keeping track of the offload entries
3803 /// \param EntryInfo The entry information about the function
3804 /// \param OutlinedFunction Pointer to the outlined function
3805 /// \param EntryFnName Name of the outlined function
3806 /// \param EntryFnIDName Name of the ID o be created
3809 Function *OutlinedFunction,
3810 StringRef EntryFnName, StringRef EntryFnIDName);
3811
3812 /// Type of BodyGen to use for region codegen
3813 ///
3814 /// Priv: If device pointer privatization is required, emit the body of the
3815 /// region here. It will have to be duplicated: with and without
3816 /// privatization.
3817 /// DupNoPriv: If we need device pointer privatization, we need
3818 /// to emit the body of the region with no privatization in the 'else' branch
3819 /// of the conditional.
3820 /// NoPriv: If we don't require privatization of device
3821 /// pointers, we emit the body in between the runtime calls. This avoids
3822 /// duplicating the body code.
3824
3825 /// Callback type for creating the map infos for the kernel parameters.
3826 /// \param CodeGenIP is the insertion point where code should be generated,
3827 /// if any.
3830
3831private:
3832 /// Emit the array initialization or deletion portion for user-defined mapper
3833 /// code generation. First, it evaluates whether an array section is mapped
3834 /// and whether the \a MapType instructs to delete this section. If \a IsInit
3835 /// is true, and \a MapType indicates to not delete this array, array
3836 /// initialization code is generated. If \a IsInit is false, and \a MapType
3837 /// indicates to delete this array, array deletion code is generated.
3838 void emitUDMapperArrayInitOrDel(Function *MapperFn, llvm::Value *MapperHandle,
3839 llvm::Value *Base, llvm::Value *Begin,
3840 llvm::Value *Size, llvm::Value *MapType,
3841 llvm::Value *MapName, TypeSize ElementSize,
3842 llvm::BasicBlock *ExitBB, bool IsInit);
3843
3844public:
3845 /// Emit the user-defined mapper function. The code generation follows the
3846 /// pattern in the example below.
3847 /// \code
3848 /// void .omp_mapper.<type_name>.<mapper_id>.(void *rt_mapper_handle,
3849 /// void *base, void *begin,
3850 /// int64_t size, int64_t type,
3851 /// void *name = nullptr) {
3852 /// // Allocate space for an array section first or add a base/begin for
3853 /// // pointer dereference.
3854 /// if ((size > 1 || (base != begin && maptype.IsPtrAndObj)) &&
3855 /// !maptype.IsDelete)
3856 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3857 /// size*sizeof(Ty), clearToFromMember(type));
3858 /// // Map members.
3859 /// for (unsigned i = 0; i < size; i++) {
3860 /// // For each component specified by this mapper:
3861 /// for (auto c : begin[i]->all_components) {
3862 /// // Map-type-modifying bits (ALWAYS, DELETE, CLOSE) from the outer
3863 /// // map clause are propagated to each component, except ATTACH
3864 /// // entries (ATTACH|ALWAYS is reserved for attach(always), and other
3865 /// // modifier bits have no meaning for ATTACH). PRESENT propagation is
3866 /// // controlled independently for pointee and non-pointee storage.
3867 /// present_bit = (!(c.isAttach() || c.isPtrAndObj()) &&
3868 /// (c.hasAttachPtr() ? PropagatePresentToPointeeStorage
3869 /// :
3870 /// PropagatePresentToNonPointeeStorage))
3871 /// ? PRESENT : 0;
3872 /// imported_modifier_bits = type & (ALWAYS | DELETE | CLOSE |
3873 /// present_bit);
3874 /// effective_type = c.isAttach() ? c.arg_type
3875 /// : c.arg_type | imported_modifier_bits;
3876 /// if (c.hasMapper())
3877 /// (*c.Mapper())(rt_mapper_handle, c.arg_base, c.arg_begin,
3878 /// c.arg_size, effective_type, c.arg_name);
3879 /// else
3880 /// __tgt_push_mapper_component(rt_mapper_handle, c.arg_base,
3881 /// c.arg_begin, c.arg_size,
3882 /// effective_type, c.arg_name);
3883 /// }
3884 /// }
3885 /// // Delete the array section.
3886 /// if (size > 1 && maptype.IsDelete)
3887 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3888 /// size*sizeof(Ty), clearToFromMember(type));
3889 /// }
3890 /// \endcode
3891 ///
3892 /// \param PrivAndGenMapInfoCB Callback that privatizes code and populates the
3893 /// MapInfos and returns.
3894 /// \param ElemTy DeclareMapper element type.
3895 /// \param FuncName Optional param to specify mapper function name.
3896 /// \param CustomMapperCB Optional callback to generate code related to
3897 /// custom mappers.
3898 /// \param PropagatePresentToPointeeStorage If true, the PRESENT map-type
3899 /// modifier from the outer clause is propagated to the pointee entries the
3900 /// mapper inserts, i.e. those with HasAttachPtr. Callers set this only for
3901 /// OpenMP >= 6.0; at earlier versions the present modifier is treated as not
3902 /// applying to the pointee.
3903 /// \param PropagatePresentToNonPointeeStorage If true, the PRESENT map-type
3904 /// modifier from the outer clause is propagated to eligible mapper entries
3905 /// describing non-pointee storage, i.e. those without HasAttachPtr.
3906 /// ATTACH and PTR_AND_OBJ entries are not eligible for PRESENT propagation.
3909 InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)>
3910 PrivAndGenMapInfoCB,
3911 llvm::Type *ElemTy, StringRef FuncName,
3912 CustomMapperCallbackTy CustomMapperCB, bool PreserveMemberOfFlags = false,
3913 bool PropagatePresentToPointeeStorage = false,
3914 bool PropagatePresentToNonPointeeStorage = false);
3915
3916 /// Generator for '#omp target data'
3917 ///
3918 /// \param Loc The location where the target data construct was encountered.
3919 /// \param AllocaIP The insertion points to be used for allocations.
3920 /// \param CodeGenIP The insertion point at which the target directive code
3921 /// should be placed.
3922 /// \param DeallocBlocks The insertion blocks at which explicit deallocations
3923 /// should be placed, if needed.
3924 /// \param IsBegin If true then emits begin mapper call otherwise emits
3925 /// end mapper call.
3926 /// \param DeviceID Stores the DeviceID from the device clause.
3927 /// \param IfCond Value which corresponds to the if clause condition.
3928 /// \param Info Stores all information realted to the Target Data directive.
3929 /// \param GenMapInfoCB Callback that populates the MapInfos and returns.
3930 /// \param CustomMapperCB Callback to generate code related to
3931 /// custom mappers.
3932 /// \param BodyGenCB Optional Callback to generate the region code.
3933 /// \param DeviceAddrCB Optional callback to generate code related to
3934 /// use_device_ptr and use_device_addr.
3936 const LocationDescription &Loc, InsertPointTy AllocaIP,
3937 InsertPointTy CodeGenIP, ArrayRef<BasicBlock *> DeallocBlocks,
3938 Value *DeviceID, Value *IfCond, TargetDataInfo &Info,
3939 GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB,
3940 omp::RuntimeFunction *MapperFunc = nullptr,
3942 BodyGenTy BodyGenType)>
3943 BodyGenCB = nullptr,
3944 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr,
3945 Value *SrcLocInfo = nullptr);
3946
3948 InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
3949 ArrayRef<BasicBlock *> DeallocBlocks)>;
3950
3952 Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP,
3953 InsertPointTy CodeGenIP, ArrayRef<InsertPointTy> DeallocIPs)>;
3954
3955 /// Generator for '#omp target'
3956 ///
3957 /// \param Loc where the target data construct was encountered.
3958 /// \param IsOffloadEntry whether it is an offload entry.
3959 /// \param CodeGenIP The insertion point where the call to the outlined
3960 /// function should be emitted.
3961 /// \param DeallocBlocks The insertion points at which explicit deallocations
3962 /// should be placed, if needed.
3963 /// \param Info Stores all information realted to the Target directive.
3964 /// \param EntryInfo The entry information about the function.
3965 /// \param DefaultAttrs Structure containing the default attributes, including
3966 /// numbers of threads and teams to launch the kernel with.
3967 /// \param RuntimeAttrs Structure containing the runtime numbers of threads
3968 /// and teams to launch the kernel with.
3969 /// \param IfCond value of the `if` clause.
3970 /// \param Inputs The input values to the region that will be passed.
3971 /// as arguments to the outlined function.
3972 /// \param BodyGenCB Callback that will generate the region code.
3973 /// \param ArgAccessorFuncCB Callback that will generate accessors
3974 /// instructions for passed in target arguments where neccessary
3975 /// \param CustomMapperCB Callback to generate code related to
3976 /// custom mappers.
3977 /// \param Dependencies A vector of DependData objects that carry
3978 /// dependency information as passed in the depend clause
3979 /// \param HasNowait Whether the target construct has a `nowait` clause or
3980 /// not.
3981 /// \param DynCGroupMem The size of the dynamic groupprivate memory for each
3982 /// cgroup.
3983 /// \param DynCGroupMem The fallback mechanism to execute if the requested
3984 /// cgroup memory cannot be provided.
3985 /// \param OutlinedFnLoc Location scoped to the DISubprogram that the caller
3986 /// will attach to the outlined function. \p Loc is scoped to the
3987 /// parent function, so it cannot be used for code emitted inside the
3988 /// outlined function. If this is empty, such code is emitted without a
3989 /// debug location.
3990 /// \param RTLocOverride Optional runtime source-location identifier to report
3991 /// to the offload runtime for the kernel launch. When null, a default
3992 /// source-location identifier is used.
3994 const LocationDescription &Loc, bool IsOffloadEntry,
3997 ArrayRef<BasicBlock *> DeallocBlocks, TargetDataInfo &Info,
3998 TargetRegionEntryInfo &EntryInfo,
3999 const TargetKernelDefaultAttrs &DefaultAttrs,
4000 const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond,
4001 SmallVectorImpl<Value *> &Inputs, GenMapInfoCallbackTy GenMapInfoCB,
4002 TargetBodyGenCallbackTy BodyGenCB,
4003 TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB,
4004 CustomMapperCallbackTy CustomMapperCB,
4005 const DependenciesInfo &Dependencies = {}, bool HasNowait = false,
4006 Value *DynCGroupMem = nullptr,
4007 omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback =
4009 DebugLoc OutlinedFnLoc = {}, Value *RTLocOverride = nullptr);
4010
4011 /// Returns __kmpc_for_static_init_* runtime function for the specified
4012 /// size \a IVSize and sign \a IVSigned. Will create a distribute call
4013 /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
4014 LLVM_ABI FunctionCallee createForStaticInitFunction(unsigned IVSize,
4015 bool IVSigned,
4016 bool IsGPUDistribute);
4017
4018 /// Returns __kmpc_dispatch_init_* runtime function for the specified
4019 /// size \a IVSize and sign \a IVSigned.
4020 LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize,
4021 bool IVSigned);
4022
4023 /// Returns __kmpc_dispatch_next_* runtime function for the specified
4024 /// size \a IVSize and sign \a IVSigned.
4025 LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize,
4026 bool IVSigned);
4027
4028 /// Returns __kmpc_dispatch_fini_* runtime function for the specified
4029 /// size \a IVSize and sign \a IVSigned.
4030 LLVM_ABI FunctionCallee createDispatchFiniFunction(unsigned IVSize,
4031 bool IVSigned);
4032
4033 /// Returns __kmpc_dispatch_deinit runtime function.
4034 LLVM_ABI FunctionCallee createDispatchDeinitFunction();
4035
4036 /// Declarations for LLVM-IR types (simple, array, function and structure) are
4037 /// generated below. Their names are defined and used in OpenMPKinds.def. Here
4038 /// we provide the declarations, the initializeTypes function will provide the
4039 /// values.
4040 ///
4041 ///{
4042#define OMP_TYPE(VarName, InitValue) Type *VarName = nullptr;
4043#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
4044 ArrayType *VarName##Ty = nullptr; \
4045 PointerType *VarName##PtrTy = nullptr;
4046#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
4047 FunctionType *VarName = nullptr; \
4048 PointerType *VarName##Ptr = nullptr;
4049#define OMP_STRUCT_TYPE(VarName, StrName, ...) \
4050 StructType *VarName = nullptr; \
4051 PointerType *VarName##Ptr = nullptr;
4052#include "llvm/Frontend/OpenMP/OMPKinds.def"
4053
4054 ///}
4055
4056private:
4057 /// Create all simple and struct types exposed by the runtime and remember
4058 /// the llvm::PointerTypes of them for easy access later.
4059 void initializeTypes(Module &M);
4060
4061 /// Common interface for generating entry calls for OMP Directives.
4062 /// if the directive has a region/body, It will set the insertion
4063 /// point to the body
4064 ///
4065 /// \param OMPD Directive to generate entry blocks for
4066 /// \param EntryCall Call to the entry OMP Runtime Function
4067 /// \param ExitBB block where the region ends.
4068 /// \param Conditional indicate if the entry call result will be used
4069 /// to evaluate a conditional of whether a thread will execute
4070 /// body code or not.
4071 ///
4072 /// \return The insertion position in exit block
4073 InsertPointTy emitCommonDirectiveEntry(omp::Directive OMPD, Value *EntryCall,
4074 BasicBlock *ExitBB,
4075 bool Conditional = false);
4076
4077 /// Common interface to finalize the region
4078 ///
4079 /// \param OMPD Directive to generate exiting code for
4080 /// \param FinIP Insertion point for emitting Finalization code and exit call.
4081 /// This block must not contain any non-finalization code.
4082 /// \param ExitCall Call to the ending OMP Runtime Function
4083 /// \param HasFinalize indicate if the directive will require finalization
4084 /// and has a finalization callback in the stack that
4085 /// should be called.
4086 ///
4087 /// \return The insertion position in exit block
4088 InsertPointOrErrorTy emitCommonDirectiveExit(omp::Directive OMPD,
4089 InsertPointTy FinIP,
4090 Instruction *ExitCall,
4091 bool HasFinalize = true);
4092
4093 /// Common Interface to generate OMP inlined regions
4094 ///
4095 /// \param OMPD Directive to generate inlined region for
4096 /// \param EntryCall Call to the entry OMP Runtime Function
4097 /// \param ExitCall Call to the ending OMP Runtime Function
4098 /// \param BodyGenCB Body code generation callback.
4099 /// \param FiniCB Finalization Callback. Will be called when finalizing region
4100 /// \param Conditional indicate if the entry call result will be used
4101 /// to evaluate a conditional of whether a thread will execute
4102 /// body code or not.
4103 /// \param HasFinalize indicate if the directive will require finalization
4104 /// and has a finalization callback in the stack that
4105 /// should be called.
4106 /// \param IsCancellable if HasFinalize is set to true, indicate if the
4107 /// the directive should be cancellable.
4108 /// \return The insertion point after the region
4110 EmitOMPInlinedRegion(omp::Directive OMPD, Instruction *EntryCall,
4111 Instruction *ExitCall, BodyGenCallbackTy BodyGenCB,
4112 FinalizeCallbackTy FiniCB, bool Conditional = false,
4113 bool HasFinalize = true, bool IsCancellable = false);
4114
4115 /// Get the platform-specific name separator.
4116 /// \param Parts different parts of the final name that needs separation
4117 /// \param FirstSeparator First separator used between the initial two
4118 /// parts of the name.
4119 /// \param Separator separator used between all of the rest consecutive
4120 /// parts of the name
4121 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
4122 StringRef FirstSeparator,
4123 StringRef Separator);
4124
4125 /// Returns corresponding lock object for the specified critical region
4126 /// name. If the lock object does not exist it is created, otherwise the
4127 /// reference to the existing copy is returned.
4128 /// \param CriticalName Name of the critical region.
4129 ///
4130 Value *getOMPCriticalRegionLock(StringRef CriticalName);
4131
4132 /// Callback type for Atomic Expression update
4133 /// ex:
4134 /// \code{.cpp}
4135 /// unsigned x = 0;
4136 /// #pragma omp atomic update
4137 /// x = Expr(x_old); //Expr() is any legal operation
4138 /// \endcode
4139 ///
4140 /// \param XOld the value of the atomic memory address to use for update
4141 /// \param IRB reference to the IRBuilder to use
4142 ///
4143 /// \returns Value to update X to.
4144 using AtomicUpdateCallbackTy =
4145 const function_ref<Expected<Value *>(Value *XOld, IRBuilder<> &IRB)>;
4146
4147private:
4148 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
4149 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
4150 /// Only Scalar data types.
4151 ///
4152 /// \param AllocaIP The insertion point to be used for alloca
4153 /// instructions.
4154 /// \param X The target atomic pointer to be updated
4155 /// \param XElemTy The element type of the atomic pointer.
4156 /// \param Expr The value to update X with.
4157 /// \param AO Atomic ordering of the generated atomic
4158 /// instructions.
4159 /// \param RMWOp The binary operation used for update. If
4160 /// operation is not supported by atomicRMW,
4161 /// or belong to {FMaximumNum, FMinimumNum, UDecWrap,
4162 /// UIncWrap, USubCond, USubSat, BAD_BINOP}.
4163 /// Then a `cmpExch` based atomic will be generated.
4164 /// \param UpdateOp Code generator for complex expressions that cannot be
4165 /// expressed through atomicrmw instruction.
4166 /// \param VolatileX true if \a X volatile?
4167 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
4168 /// update expression, false otherwise.
4169 /// (e.g. true for X = X BinOp Expr)
4170 ///
4171 /// \returns A pair of the old value of X before the update, and the value
4172 /// used for the update.
4173 Expected<std::pair<Value *, Value *>>
4174 emitAtomicUpdate(InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
4175 AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
4176 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX,
4177 bool IsXBinopExpr, bool IsIgnoreDenormalMode,
4178 bool IsFineGrainedMemory, bool IsRemoteMemory);
4179
4180 /// Emit the binary op. described by \p RMWOp, using \p Src1 and \p Src2 .
4181 ///
4182 /// \Return The instruction
4183 Value *emitRMWOpAsInstruction(Value *Src1, Value *Src2,
4184 AtomicRMWInst::BinOp RMWOp);
4185
4186 bool IsFinalized;
4187
4188public:
4189 /// a struct to pack relevant information while generating atomic Ops
4191 Value *Var = nullptr;
4192 Type *ElemTy = nullptr;
4193 bool IsSigned = false;
4194 bool IsVolatile = false;
4195 };
4196
4197 /// Emit atomic Read for : V = X --- Only Scalar data types.
4198 ///
4199 /// \param Loc The insert and source location description.
4200 /// \param X The target pointer to be atomically read
4201 /// \param V Memory address where to store atomically read
4202 /// value
4203 /// \param AO Atomic ordering of the generated atomic
4204 /// instructions.
4205 /// \param AllocaIP Insert point for allocas
4206 //
4207 /// \return Insertion point after generated atomic read IR.
4210 AtomicOrdering AO,
4211 InsertPointTy AllocaIP);
4212
4213 /// Emit atomic write for : X = Expr --- Only Scalar data types.
4214 ///
4215 /// \param Loc The insert and source location description.
4216 /// \param X The target pointer to be atomically written to
4217 /// \param Expr The value to store.
4218 /// \param AO Atomic ordering of the generated atomic
4219 /// instructions.
4220 /// \param AllocaIP Insert point for allocas
4221 ///
4222 /// \return Insertion point after generated atomic Write IR.
4224 AtomicOpValue &X, Value *Expr,
4225 AtomicOrdering AO,
4226 InsertPointTy AllocaIP);
4227
4228 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
4229 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
4230 /// Only Scalar data types.
4231 ///
4232 /// \param Loc The insert and source location description.
4233 /// \param AllocaIP The insertion point to be used for alloca instructions.
4234 /// \param X The target atomic pointer to be updated
4235 /// \param Expr The value to update X with.
4236 /// \param AO Atomic ordering of the generated atomic instructions.
4237 /// \param RMWOp The binary operation used for update. If operation
4238 /// is not supported by atomicRMW, or belong to
4239 /// {FMaximumNum, FMinimumNum, UDecWrap, UIncWrap,
4240 /// USubCond, USubSat, BAD_BINOP}. Then a
4241 /// `cmpExch` based atomic will be generated.
4242 /// \param UpdateOp Code generator for complex expressions that cannot be
4243 /// expressed through atomicrmw instruction.
4244 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
4245 /// update expression, false otherwise.
4246 /// (e.g. true for X = X BinOp Expr)
4247 ///
4248 /// \return Insertion point after generated atomic update IR.
4251 Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
4252 AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr,
4253 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
4254 bool IsRemoteMemory = false);
4255
4256 /// Emit atomic update for constructs: --- Only Scalar data types
4257 /// V = X; X = X BinOp Expr ,
4258 /// X = X BinOp Expr; V = X,
4259 /// V = X; X = Expr BinOp X,
4260 /// X = Expr BinOp X; V = X,
4261 /// V = X; X = UpdateOp(X),
4262 /// X = UpdateOp(X); V = X,
4263 ///
4264 /// \param Loc The insert and source location description.
4265 /// \param AllocaIP The insertion point to be used for alloca instructions.
4266 /// \param X The target atomic pointer to be updated
4267 /// \param V Memory address where to store captured value
4268 /// \param Expr The value to update X with.
4269 /// \param AO Atomic ordering of the generated atomic instructions
4270 /// \param RMWOp The binary operation used for update. If
4271 /// operation is not supported by atomicRMW, or belong to
4272 /// {FMaximumNum, FMinimumNum, UDecWrap, UIncWrap,
4273 /// USubCond, USubSat, BAD_BINOP}. Then a
4274 /// `cmpExch` based atomic will be generated.
4275 /// \param UpdateOp Code generator for complex expressions that cannot be
4276 /// expressed through atomicrmw instruction.
4277 /// \param UpdateExpr true if X is an in place update of the form
4278 /// X = X BinOp Expr or X = Expr BinOp X
4279 /// \param IsXBinopExpr true if X is Left H.S. in Right H.S. part of the
4280 /// update expression, false otherwise.
4281 /// (e.g. true for X = X BinOp Expr)
4282 /// \param IsPostfixUpdate true if original value of 'x' must be stored in
4283 /// 'v', not an updated one.
4284 ///
4285 /// \return Insertion point after generated atomic capture IR.
4288 AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
4289 AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
4290 bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr,
4291 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
4292 bool IsRemoteMemory = false);
4293
4294 /// Emit atomic compare for constructs: --- Only scalar data types
4295 /// cond-expr-stmt:
4296 /// x = x ordop expr ? expr : x;
4297 /// x = expr ordop x ? expr : x;
4298 /// x = x == e ? d : x;
4299 /// x = e == x ? d : x; (this one is not in the spec)
4300 /// cond-update-stmt:
4301 /// if (x ordop expr) { x = expr; }
4302 /// if (expr ordop x) { x = expr; }
4303 /// if (x == e) { x = d; }
4304 /// if (e == x) { x = d; } (this one is not in the spec)
4305 /// conditional-update-capture-atomic:
4306 /// v = x; cond-update-stmt; (IsPostfixUpdate=true, IsFailOnly=false)
4307 /// cond-update-stmt; v = x; (IsPostfixUpdate=false, IsFailOnly=false)
4308 /// if (x == e) { x = d; } else { v = x; } (IsPostfixUpdate=false,
4309 /// IsFailOnly=true)
4310 /// r = x == e; if (r) { x = d; } (IsPostfixUpdate=false, IsFailOnly=false)
4311 /// r = x == e; if (r) { x = d; } else { v = x; } (IsPostfixUpdate=false,
4312 /// IsFailOnly=true)
4313 ///
4314 /// \param Loc The insert and source location description.
4315 /// \param X The target atomic pointer to be updated.
4316 /// \param V Memory address where to store captured value (for
4317 /// compare capture only).
4318 /// \param R Memory address where to store comparison result
4319 /// (for compare capture with '==' only).
4320 /// \param E The expected value ('e') for forms that use an
4321 /// equality comparison or an expression ('expr') for
4322 /// forms that use 'ordop' (logically an atomic maximum or
4323 /// minimum).
4324 /// \param D The desired value for forms that use an equality
4325 /// comparison. If forms that use 'ordop', it should be
4326 /// \p nullptr.
4327 /// \param AO Atomic ordering of the generated atomic instructions.
4328 /// \param Op Atomic compare operation. It can only be ==, <, or >.
4329 /// \param IsXBinopExpr True if the conditional statement is in the form where
4330 /// x is on LHS. It only matters for < or >.
4331 /// \param IsPostfixUpdate True if original value of 'x' must be stored in
4332 /// 'v', not an updated one (for compare capture
4333 /// only).
4334 /// \param IsFailOnly True if the original value of 'x' is stored to 'v'
4335 /// only when the comparison fails. This is only valid for
4336 /// the case the comparison is '=='.
4337 ///
4338 /// \return Insertion point after generated atomic capture IR.
4339 /// Whether to emit special handling for IEEE 754 -0.0 == +0.0 in
4340 /// atomic compare operations on floating-point types.
4341 bool HandleFPNegZero = false;
4342
4343 /// Set whether atomic compare should handle -0.0/+0.0 equivalence.
4344 /// Returns the previous value so callers can save and restore it.
4345 bool setHandleFPNegZero(bool FPNegZero) {
4346 bool Old = HandleFPNegZero;
4347 HandleFPNegZero = FPNegZero;
4348 return Old;
4349 }
4350
4352 const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
4353 AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
4354 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
4355 bool IsFailOnly, bool IsWeak = false);
4357 const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
4358 AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
4359 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
4360 bool IsFailOnly, AtomicOrdering Failure, bool IsWeak = false);
4361
4362 /// Create the control flow structure of a canonical OpenMP loop.
4363 ///
4364 /// The emitted loop will be disconnected, i.e. no edge to the loop's
4365 /// preheader and no terminator in the AfterBB. The OpenMPIRBuilder's
4366 /// IRBuilder location is not preserved.
4367 ///
4368 /// \param DL DebugLoc used for the instructions in the skeleton.
4369 /// \param TripCount Value to be used for the trip count.
4370 /// \param F Function in which to insert the BasicBlocks.
4371 /// \param PreInsertBefore Where to insert BBs that execute before the body,
4372 /// typically the body itself.
4373 /// \param PostInsertBefore Where to insert BBs that execute after the body.
4374 /// \param Name Base name used to derive BB
4375 /// and instruction names.
4376 /// \param IsCollapsed Whether this is a collapsed loop.
4377 ///
4378 /// \returns The CanonicalLoopInfo that represents the emitted loop.
4381 BasicBlock *PreInsertBefore, BasicBlock *PostInsertBefore,
4382 const Twine &Name = {}, bool IsCollapsed = false);
4383 /// OMP Offload Info Metadata name string
4384 const std::string ompOffloadInfoName = "omp_offload.info";
4385
4386 /// Loads all the offload entries information from the host IR
4387 /// metadata. This function is only meant to be used with device code
4388 /// generation.
4389 ///
4390 /// \param M Module to load Metadata info from. Module passed maybe
4391 /// loaded from bitcode file, i.e, different from OpenMPIRBuilder::M module.
4393
4394 /// Loads all the offload entries information from the host IR
4395 /// metadata read from the file passed in as the HostFilePath argument. This
4396 /// function is only meant to be used with device code generation.
4397 ///
4398 /// \param HostFilePath The path to the host IR file,
4399 /// used to load in offload metadata for the device, allowing host and device
4400 /// to maintain the same metadata mapping.
4402 StringRef HostFilePath);
4403
4404 /// Gets (if variable with the given name already exist) or creates
4405 /// internal global variable with the specified Name. The created variable has
4406 /// linkage CommonLinkage by default and is initialized by null value.
4407 /// \param Ty Type of the global variable. If it is exist already the type
4408 /// must be the same.
4409 /// \param Name Name of the variable.
4412 std::optional<unsigned> AddressSpace = {});
4413
4415 InsertPointTy BodyIP, llvm::Value *LinearIV)>;
4416
4417 /// Create a canonical iterator loop at the current insertion point.
4418 ///
4419 /// This helper splits the current block and builds a canonical loop
4420 /// using createLoopSkeleton(). The resulting control flow looks like:
4421 ///
4422 /// CurBB -> Preheader -> Header -> Body -> Latch -> After -> ContBB
4423 ///
4424 /// The body of the loop is produced by calling \p BodyGen with the insertion
4425 /// point for the loop body and the induction variable.
4426 /// Unlike createCanonicalLoop(), this function is intended for \p BodyGen
4427 /// that may perform region lowering (e.g., translating MLIR regions) and are
4428 /// not guaranteed to preserve the canonical skeleton's body terminator. In
4429 /// particular:
4430 ///
4431 /// - The skeleton’s unconditional branch from the loop body is removed
4432 /// before invoking \p BodyGen.
4433 /// - \p BodyGen may freely emit instructions and introduce control flow
4434 /// within the loop body.
4435 /// - If the body leaves exactly one block without a terminator after
4436 /// \p BodyGen returns, a branch to the latch is inserted there. Otherwise,
4437 /// some block of the body must already branch to the latch.
4438 /// - The body must not branch to blocks that existed before \p BodyGen ran,
4439 /// other than the body block and the latch.
4440 ///
4441 /// \param Loc The location where the iterator modifier was encountered.
4442 /// \param TripCount Number of loop iterations.
4443 /// \param BodyGen Callback to generate the loop body.
4444 /// \param Name Base name used for creating the loop
4445 /// \returns The insertion position *after* the iterator loop
4448 IteratorBodyGenTy BodyGen, llvm::StringRef Name = "iterator");
4449
4450 /// Kind of parameter in a function with 'declare simd' directive.
4459
4460 /// Attribute set of the `declare simd` parameter.
4467
4473
4474 /// Emit x86 vector-function ABI attributes for a `declare simd` function.
4475 ///
4476 /// Generates and attaches `_ZGV*` vector function ABI attributes to \p Fn
4477 /// following the x86 vector ABI used by OpenMP `declare simd`. For each
4478 /// supported ISA (SSE, AVX, AVX2, AVX512) and masking variant, this
4479 /// constructs the appropriate mangled vector-function name and adds it as a
4480 /// function attribute.
4481 ///
4482 /// \param Fn The scalar function to which vector-function attributes
4483 /// are attached.
4484 /// \param NumElements Number of elements used to derive the vector length
4485 /// when
4486 /// \p VLENVal is not specified.
4487 /// \param VLENVal User provided vector length.
4488 /// \param ParamAttrs Array of attribute set of the `declare simd` parameter.
4489 /// \param Branch `undefined`, `inbranch` or `notinbranch` clause.
4491 llvm::Function *Fn, unsigned NumElements, const llvm::APSInt &VLENVal,
4493
4494 /// Emit AArch64 vector-function ABI attributes for a `declare simd` function.
4495 ///
4496 /// Generates and attaches `_ZGV*` vector function ABI attributes to \p Fn
4497 /// following the AArch64 vector-function ABI. The emitted names depend on the
4498 /// selected ISA, user-specified vector length, parameter attribute mangling,
4499 /// and the declare simd branch clause.
4500 ///
4501 /// \param Fn The scalar function to which vector-function
4502 /// attributes are attached.
4503 /// \param VLENVal User provided vector length.
4504 /// \param ParamAttrs Array of attribute set of the `declare simd`
4505 /// parameter.
4506 /// \param Branch `undefined`, `inbranch` or `notinbranch`
4507 /// clause.
4508 /// \param ISA `'n'` for Advanced SIMD or `'s'` for SVE.
4509 /// \param NarrowestDataSize Narrowest data size in bits used to infer the
4510 /// default vector length when \p VLENVal is
4511 /// absent.
4512 /// \param OutputBecomesInput Whether result values are represented as input
4513 /// parameters in the emitted vector-function ABI
4514 /// name.
4516 llvm::Function *Fn, unsigned VLENVal,
4518 char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput);
4519};
4520
4521/// Class to represented the control flow structure of an OpenMP canonical loop.
4522///
4523/// The control-flow structure is standardized for easy consumption by
4524/// directives associated with loops. For instance, the worksharing-loop
4525/// construct may change this control flow such that each loop iteration is
4526/// executed on only one thread. The constraints of a canonical loop in brief
4527/// are:
4528///
4529/// * The number of loop iterations must have been computed before entering the
4530/// loop.
4531///
4532/// * Has an (unsigned) logical induction variable that starts at zero and
4533/// increments by one.
4534///
4535/// * The loop's CFG itself has no side-effects. The OpenMP specification
4536/// itself allows side-effects, but the order in which they happen, including
4537/// how often or whether at all, is unspecified. We expect that the frontend
4538/// will emit those side-effect instructions somewhere (e.g. before the loop)
4539/// such that the CanonicalLoopInfo itself can be side-effect free.
4540///
4541/// Keep in mind that CanonicalLoopInfo is meant to only describe a repeated
4542/// execution of a loop body that satifies these constraints. It does NOT
4543/// represent arbitrary SESE regions that happen to contain a loop. Do not use
4544/// CanonicalLoopInfo for such purposes.
4545///
4546/// The control flow can be described as follows:
4547///
4548/// Preheader
4549/// |
4550/// /-> Header
4551/// | |
4552/// | Cond---\
4553/// | | |
4554/// | Body |
4555/// | | | |
4556/// | <...> |
4557/// | | | |
4558/// \--Latch |
4559/// |
4560/// Exit
4561/// |
4562/// After
4563///
4564/// The loop is thought to start at PreheaderIP (at the Preheader's terminator,
4565/// including) and end at AfterIP (at the After's first instruction, excluding).
4566/// That is, instructions in the Preheader and After blocks (except the
4567/// Preheader's terminator) are out of CanonicalLoopInfo's control and may have
4568/// side-effects. Typically, the Preheader is used to compute the loop's trip
4569/// count. The instructions from BodyIP (at the Body block's first instruction,
4570/// excluding) until the Latch are also considered outside CanonicalLoopInfo's
4571/// control and thus can have side-effects. The body block is the single entry
4572/// point into the loop body, which may contain arbitrary control flow as long
4573/// as all control paths eventually branch to the Latch block.
4574///
4575/// TODO: Consider adding another standardized BasicBlock between Body CFG and
4576/// Latch to guarantee that there is only a single edge to the latch. It would
4577/// make loop transformations easier to not needing to consider multiple
4578/// predecessors of the latch (See redirectAllPredecessorsTo) and would give us
4579/// an equivalant to PreheaderIP, AfterIP and BodyIP for inserting code that
4580/// executes after each body iteration.
4581///
4582/// There must be no loop-carried dependencies through llvm::Values. This is
4583/// equivalant to that the Latch has no PHINode and the Header's only PHINode is
4584/// for the induction variable.
4585///
4586/// All code in Header, Cond, Latch and Exit (plus the terminator of the
4587/// Preheader) are CanonicalLoopInfo's responsibility and their build-up checked
4588/// by assertOK(). They are expected to not be modified unless explicitly
4589/// modifying the CanonicalLoopInfo through a methods that applies a OpenMP
4590/// loop-associated construct such as applyWorkshareLoop, tileLoops, unrollLoop,
4591/// etc. These methods usually invalidate the CanonicalLoopInfo and re-use its
4592/// basic blocks. After invalidation, the CanonicalLoopInfo must not be used
4593/// anymore as its underlying control flow may not exist anymore.
4594/// Loop-transformation methods such as tileLoops, collapseLoops and unrollLoop
4595/// may also return a new CanonicalLoopInfo that can be passed to other
4596/// loop-associated construct implementing methods. These loop-transforming
4597/// methods may either create a new CanonicalLoopInfo usually using
4598/// createLoopSkeleton and invalidate the input CanonicalLoopInfo, or reuse and
4599/// modify one of the input CanonicalLoopInfo and return it as representing the
4600/// modified loop. What is done is an implementation detail of
4601/// transformation-implementing method and callers should always assume that the
4602/// CanonicalLoopInfo passed to it is invalidated and a new object is returned.
4603/// Without Virtual collapse, results have the same guarantees as the one
4604/// created by createCanonicalLoop, such that transforming methods do not have
4605/// to special case where the CanonicalLoopInfo originated from.
4606///
4607/// Generally, methods consuming CanonicalLoopInfo do not need an
4608/// OpenMPIRBuilder::InsertPointTy as argument, but use the locations of the
4609/// CanonicalLoopInfo to insert new or modify existing instructions. Unless
4610/// documented otherwise, methods consuming CanonicalLoopInfo do not invalidate
4611/// any InsertPoint that is outside CanonicalLoopInfo's control. Specifically,
4612/// any InsertPoint in the Preheader, After or Block can still be used after
4613/// calling such a method.
4614///
4615/// TODO: Provide mechanisms for exception handling and cancellation points.
4616///
4617/// Defined outside OpenMPIRBuilder because nested classes cannot be
4618/// forward-declared, e.g. to avoid having to include the entire OMPIRBuilder.h.
4620 friend class OpenMPIRBuilder;
4621
4622private:
4623 /// State retained after Virtual collapse of a loop nest.
4624 struct VirtualCollapseInfo {
4625 /// Copy of the first normalized iteration; scheduling replaces operand
4626 /// zero.
4627 BinaryOperator *Begin = nullptr;
4628 /// Copy of the full count; scheduling replaces operand zero with its count.
4629 /// May wrap for idle scheduler assignments.
4630 BinaryOperator *Count = nullptr;
4631 };
4632 std::optional<VirtualCollapseInfo> VirtualCollapse;
4633
4634 /// Report a fatal error for an unsupported operation on Virtual collapse.
4635 /// Must only be called for a loop with Virtual collapse state.
4636 [[noreturn]] LLVM_ABI void reportUnsupportedVirtualCollapse() const;
4637 /// Return the Virtual range initialization block containing the Begin and
4638 /// Count copies, or nullptr for ordinary canonical loops.
4639 BasicBlock *getVirtualCollapseInit() const;
4640
4641 BasicBlock *Header = nullptr;
4642 BasicBlock *Cond = nullptr;
4643 BasicBlock *Latch = nullptr;
4644 BasicBlock *Exit = nullptr;
4645
4646 // Hold the MLIR value for the `lastiter` of the canonical loop.
4647 Value *LastIter = nullptr;
4648
4649 /// Add the control blocks of this loop to \p BBs.
4650 ///
4651 /// This does not include any block from the body, including the one returned
4652 /// by getBody().
4653 ///
4654 /// FIXME: This currently includes the Preheader and After blocks even though
4655 /// their content is (mostly) not under CanonicalLoopInfo's control.
4656 /// Re-evaluated whether this makes sense.
4657 void collectControlBlocks(SmallVectorImpl<BasicBlock *> &BBs);
4658
4659 /// Sets the number of loop iterations to the given value. This value must be
4660 /// valid in the condition block (i.e., defined in the preheader) and is
4661 /// interpreted as an unsigned integer.
4662 void setTripCount(Value *TripCount);
4663
4664 /// Replace all uses of the canonical induction variable in the loop body with
4665 /// a new one.
4666 ///
4667 /// The intended use case is to update the induction variable for an updated
4668 /// iteration space such that it can stay normalized in the 0...tripcount-1
4669 /// range.
4670 ///
4671 /// The \p Updater is called with the (presumable updated) current normalized
4672 /// induction variable and is expected to return the value that uses of the
4673 /// pre-updated induction values should use instead, typically dependent on
4674 /// the new induction variable. This is a lambda (instead of e.g. just passing
4675 /// the new value) to be able to distinguish the uses of the pre-updated
4676 /// induction variable and uses of the induction varible to compute the
4677 /// updated induction variable value.
4678 void mapIndVar(llvm::function_ref<Value *(Instruction *)> Updater);
4679
4680public:
4681 /// Sets the last iteration variable for this loop.
4682 void setLastIter(Value *IterVar) { LastIter = std::move(IterVar); }
4683
4684 /// Returns the last iteration variable for this loop.
4685 /// Certain use-cases (like translation of linear clause) may access
4686 /// this variable even after a loop transformation. Hence, do not guard
4687 /// this getter function by `isValid`. It is the responsibility of the
4688 /// callee to ensure this functionality is not invoked by a non-outlined
4689 /// CanonicalLoopInfo object (in which case, `setLastIter` will never be
4690 /// invoked and `LastIter` will be by default `nullptr`).
4691 Value *getLastIter() { return LastIter; }
4692
4693 /// Returns whether this object currently represents the IR of a loop. If
4694 /// returning false, it may have been consumed by a loop transformation or not
4695 /// been initialized. Do not use in this case;
4696 bool isValid() const { return Header; }
4697
4698 /// The preheader ensures that there is only a single edge entering the loop.
4699 /// Code that must be execute before any loop iteration can be emitted here,
4700 /// such as computing the loop trip count and begin lifetime markers. Code in
4701 /// the preheader is not considered part of the canonical loop.
4703
4704 /// The header is the entry for each iteration. In the canonical control flow,
4705 /// it only contains the PHINode for the induction variable.
4707 assert(isValid() && "Requires a valid canonical loop");
4708 return Header;
4709 }
4710
4711 /// The condition block computes whether there is another loop iteration. If
4712 /// yes, branches to the body; otherwise to the exit block.
4714 assert(isValid() && "Requires a valid canonical loop");
4715 return Cond;
4716 }
4717
4718 /// The body block is the single entry for a loop iteration and not controlled
4719 /// by CanonicalLoopInfo. It can contain arbitrary control flow but must
4720 /// eventually branch to the \p Latch block.
4721 /// Virtual does not expose a logical loop body.
4723 assert(isValid() && "Requires a valid canonical loop");
4724 if (VirtualCollapse)
4725 reportUnsupportedVirtualCollapse();
4726 return cast<CondBrInst>(Cond->getTerminator())->getSuccessor(0);
4727 }
4728
4729 /// Reaching the latch indicates the end of the loop body code. In the
4730 /// canonical control flow, it only contains the increment of the induction
4731 /// variable.
4733 assert(isValid() && "Requires a valid canonical loop");
4734 return Latch;
4735 }
4736
4737 /// Reaching the exit indicates no more iterations are being executed.
4739 assert(isValid() && "Requires a valid canonical loop");
4740 return Exit;
4741 }
4742
4743 /// The after block is intended for clean-up code such as lifetime end
4744 /// markers. It is separate from the exit block to ensure, analogous to the
4745 /// preheader, it having just a single entry edge and being free from PHI
4746 /// nodes should there be multiple loop exits (such as from break
4747 /// statements/cancellations).
4749 assert(isValid() && "Requires a valid canonical loop");
4750 return Exit->getSingleSuccessor();
4751 }
4752
4753 /// Returns the llvm::Value containing the number of loop iterations. It must
4754 /// be valid in the preheader and always interpreted as an unsigned integer of
4755 /// any bit-width.
4757 assert(isValid() && "Requires a valid canonical loop");
4758 if (VirtualCollapse)
4759 return VirtualCollapse->Count->getOperand(0);
4760 Instruction *CmpI = &Cond->front();
4761 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
4762 return CmpI->getOperand(1);
4763 }
4764
4765 /// Returns the instruction representing the current logical induction
4766 /// variable. Always unsigned, always starting at 0 with an increment of one.
4767 /// Virtual does not expose a logical induction variable.
4769 assert(isValid() && "Requires a valid canonical loop");
4770 if (VirtualCollapse)
4771 reportUnsupportedVirtualCollapse();
4772 Instruction *IndVarPHI = &Header->front();
4773 assert(isa<PHINode>(IndVarPHI) && "First inst must be the IV PHI");
4774 return IndVarPHI;
4775 }
4776
4777 /// Return the type of the induction variable (and the trip count).
4779 assert(isValid() && "Requires a valid canonical loop");
4780 return getTripCount()->getType();
4781 }
4782
4783 /// Return the insertion point for user code before the loop.
4785 assert(isValid() && "Requires a valid canonical loop");
4786 BasicBlock *Preheader = getPreheader();
4787 return std::prev(Preheader->end());
4788 };
4789
4790 /// Return the insertion point for user code in the body.
4792 assert(isValid() && "Requires a valid canonical loop");
4793 BasicBlock *Body = getBody();
4794 return Body->begin();
4795 };
4796
4797 /// Return the insertion point for user code after the loop.
4799 assert(isValid() && "Requires a valid canonical loop");
4800 BasicBlock *After = getAfter();
4801 return After->begin();
4802 };
4803
4805 assert(isValid() && "Requires a valid canonical loop");
4806 return Header->getParent();
4807 }
4808
4809 /// Consistency self-check.
4810 LLVM_ABI void assertOK() const;
4811
4812 /// Invalidate this loop. That is, the underlying IR does not fulfill the
4813 /// requirements of an OpenMP canonical loop anymore.
4814 LLVM_ABI void invalidate();
4815};
4816
4817/// ScanInfo holds the information to assist in lowering of Scan reduction.
4818/// Before lowering, the body of the for loop specifying scan reduction is
4819/// expected to have the following structure
4820///
4821/// Loop Body Entry
4822/// |
4823/// Code before the scan directive
4824/// |
4825/// Scan Directive
4826/// |
4827/// Code after the scan directive
4828/// |
4829/// Loop Body Exit
4830/// When `createCanonicalScanLoops` is executed, the bodyGen callback of it
4831/// transforms the body to:
4832///
4833/// Loop Body Entry
4834/// |
4835/// OMPScanDispatch
4836///
4837/// OMPBeforeScanBlock
4838/// |
4839/// OMPScanLoopExit
4840/// |
4841/// Loop Body Exit
4842///
4843/// The insert point is updated to the first insert point of OMPBeforeScanBlock.
4844/// It dominates the control flow of code generated until
4845/// scan directive is encountered and OMPAfterScanBlock dominates the
4846/// control flow of code generated after scan is encountered. The successor
4847/// of OMPScanDispatch can be OMPBeforeScanBlock or OMPAfterScanBlock based
4848/// on 1.whether it is in Input phase or Scan Phase , 2. whether it is an
4849/// exclusive or inclusive scan. This jump is added when `createScan` is
4850/// executed. If input loop is being generated, if it is inclusive scan,
4851/// `OMPAfterScanBlock` succeeds `OMPScanDispatch` , if exclusive,
4852/// `OMPBeforeScanBlock` succeeds `OMPDispatch` and vice versa for scan loop. At
4853/// the end of the input loop, temporary buffer is populated and at the
4854/// beginning of the scan loop, temporary buffer is read. After scan directive
4855/// is encountered, insertion point is updated to `OMPAfterScanBlock` as it is
4856/// expected to dominate the code after the scan directive. Both Before and
4857/// After scan blocks are succeeded by `OMPScanLoopExit`.
4858/// Temporary buffer allocations are done in `ScanLoopInit` block before the
4859/// lowering of for-loop. The results are copied back to reduction variable in
4860/// `ScanLoopFinish` block.
4862public:
4863 /// Dominates the body of the loop before scan directive
4865
4866 /// Dominates the body of the loop before scan directive
4868
4869 /// Controls the flow to before or after scan blocks
4871
4872 /// Exit block of loop body
4874
4875 /// Block before loop body where scan initializations are done
4877
4878 /// Block after loop body where scan finalizations are done
4880
4881 /// If true, it indicates Input phase is lowered; else it indicates
4882 /// ScanPhase is lowered
4883 bool OMPFirstScanLoop = false;
4884
4885 /// Maps the private reduction variable to the pointer of the temporary
4886 /// buffer
4888
4889 /// Keeps track of value of iteration variable for input/scan loop to be
4890 /// used for Scan directive lowering
4891 llvm::Value *IV = nullptr;
4892
4893 /// Stores the span of canonical loop being lowered to be used for temporary
4894 /// buffer allocation or Finalization.
4895 llvm::Value *Span = nullptr;
4896
4900 ScanInfo(ScanInfo &) = delete;
4901 ScanInfo &operator=(const ScanInfo &) = delete;
4902
4903 ~ScanInfo() { delete (ScanBuffPtrs); }
4904};
4905
4906} // end namespace llvm
4907
4908#endif // LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
arc branch finalize
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
DXIL Finalize Linkage
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
#define T
This file defines constans and helpers used when dealing with OpenMP.
Provides definitions for Target specific Grid Values.
RISCVCC::CondCode CC
Basic Register Allocator
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file implements a set that has insertion order iteration characteristics.
Contains the forward declaration for vfs::FileSystem, as well as the IntrusiveRefCntPtrInfo specializ...
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Align AtomicAlign
Definition Atomic.h:23
bool UseLibcall
Definition Atomic.h:25
IRBuilderBase * Builder
Definition Atomic.h:19
uint64_t AtomicSizeInBits
Definition Atomic.h:21
uint64_t ValueSizeInBits
Definition Atomic.h:22
IRBuilderBase::InsertPoint AllocaIP
Definition Atomic.h:26
Align ValueAlign
Definition Atomic.h:24
BinOp
This enumeration lists the possible modifications atomicrmw can make.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
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.
Value * getLastIter()
Returns the last iteration variable for this 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.
Utility class for extracting code into a new function.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
A debug info location.
Definition DebugLoc.h:126
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
BasicBlock::iterator InsertPoint
InsertPoint - A saved insertion point.
Definition IRBuilder.h:254
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Class to represent integer types.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
OffloadEntryInfoDeviceGlobalVar(unsigned Order, OMPTargetGlobalVarEntryKind Flags)
OffloadEntryInfoDeviceGlobalVar(unsigned Order, Constant *Addr, int64_t VarSize, OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage, const std::string &VarName)
static bool classof(const OffloadEntryInfo *Info)
OffloadEntryInfoTargetRegion(unsigned Order, Constant *Addr, Constant *ID, OMPTargetRegionEntryKind Flags)
@ OffloadingEntryInfoTargetRegion
Entry is a target region.
@ OffloadingEntryInfoDeviceGlobalVar
Entry is a declare target variable.
OffloadingEntryInfoKinds getKind() const
OffloadEntryInfo(OffloadingEntryInfoKinds Kind)
static bool classof(const OffloadEntryInfo *Info)
OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, uint32_t Flags)
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...
@ OMPTargetDeviceClauseNoHost
The target is marked for non-host devices.
@ OMPTargetDeviceClauseAny
The target is marked for all devices.
@ OMPTargetDeviceClauseNone
The target is marked as having no clause.
@ OMPTargetDeviceClauseHost
The target is marked for host 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.
OffloadEntriesInfoManager(OpenMPIRBuilder *builder)
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)
unsigned size() const
Return number of entries defined so far.
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.
@ OMPTargetGlobalVarEntryNone
Mark the entry as having no declare target entry kind.
@ 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.
Captures attributes that affect generating LLVM-IR using the OpenMPIRBuilder and related classes.
std::optional< bool > NoSignedWrap
Flag for specifying whether the no-signed-wrap (nsw) flag should be added to loop induction variable ...
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.
std::optional< StringRef > FirstSeparator
First separator used between the initial two parts of a name.
StringRef separator() const
LLVM_ABI int64_t getRequiresFlags() const
Returns requires directive clauses as flags compatible with those expected by libomptarget.
void setFirstSeparator(StringRef FS)
CollapseIVMapping
Representation of a collapsed iteration space.
@ Virtual
Retain the physical nest and decode each assigned range once.
@ DivMod
Decode source indices from the logical index using division and remainder in each iteration.
void setDefaultTargetAS(unsigned AS)
StringRef firstSeparator() const
std::optional< bool > OpenMPOffloadMandatory
Flag for specifying if offloading is mandatory.
std::optional< bool > EmitLLVMUsedMetaInfo
Flag for specifying if LLVMUsed information should be emitted.
SmallVector< Triple > TargetTriples
When compilation is being done for the OpenMP host (i.e.
LLVM_ABI void setHasRequiresReverseOffload(bool Value)
void setNoSignedWrap(bool Value)
LLVM_ABI bool hasRequiresUnifiedSharedMemory() const
LLVM_ABI void setHasRequiresUnifiedSharedMemory(bool Value)
unsigned getDefaultTargetAS() const
std::optional< StringRef > Separator
Separator used between all of the rest consecutive parts of s name.
LLVM_ABI bool hasRequiresDynamicAllocators() const
bool openMPOffloadMandatory() const
CallingConv::ID getRuntimeCC() const
CollapseIVMapping CollapseMapping
Mapping used for collapsed loops.
LLVM_ABI void setHasRequiresUnifiedAddress(bool Value)
void setOpenMPOffloadMandatory(bool Value)
void setIsTargetDevice(bool Value)
void setSeparator(StringRef S)
void setRuntimeCC(CallingConv::ID CC)
LLVM_ABI void setHasRequiresDynamicAllocators(bool Value)
void setEmitLLVMUsed(bool Value=true)
std::optional< omp::GV > GridValue
LLVM_ABI bool hasRequiresReverseOffload() const
LLVM_ABI bool hasRequiresUnifiedAddress() const
llvm::AllocaInst * CreateAlloca(llvm::Type *Ty, const llvm::Twine &Name) const override
void decorateWithTBAA(llvm::Instruction *I) override
AtomicInfo(IRBuilder<> *Builder, llvm::Type *Ty, uint64_t AtomicSizeInBits, uint64_t ValueSizeInBits, llvm::Align AtomicAlign, llvm::Align ValueAlign, bool UseLibcall, IRBuilderBase::InsertPoint AllocaIP, llvm::Value *AtomicVar)
llvm::Value * getAtomicPointer() const override
Struct that keeps the information that should be kept throughout a 'target data' region.
TargetDataInfo(bool RequiresDevicePointerInfo, bool SeparateBeginEndCalls)
SmallMapVector< const Value *, std::pair< Value *, Value * >, 4 > DevicePtrInfoMap
void clearArrayInfo()
Clear information about the data arrays.
unsigned NumberOfPtrs
The total number of pointers passed to the runtime library.
bool HasNoWait
Whether the target ... data directive has a nowait clause.
bool isValid()
Return true if the current target data information has valid arrays.
bool HasMapper
Indicate whether any user-defined mapper exists.
An interface to create LLVM-IR for OpenMP directives.
LLVM_ABI InsertPointOrErrorTy createOrderedThreadsSimd(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsThreads)
Generator for 'omp ordered [threads | simd]'.
LLVM_ABI void emitAArch64DeclareSimdFunction(llvm::Function *Fn, unsigned VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch, char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput)
Emit AArch64 vector-function ABI attributes for a declare simd function.
LLVM_ABI Constant * getOrCreateIdent(Constant *SrcLocStr, uint32_t SrcLocStrSize, omp::IdentFlag Flags=omp::IdentFlag(0), unsigned Reserve2Flags=0)
Return an ident_t* encoding the source location SrcLocStr and Flags.
LLVM_ABI void emitFlush(const LocationDescription &Loc, AtomicOrdering AO=AtomicOrdering::SequentiallyConsistent, AtomicScope Scope=AtomicScope::Device)
Generate a flush: a fence on a GPU, and a runtime call otherwise.
LLVM_ABI void registerDeclareTargetGlobalReplacement(GlobalValue *Original, GlobalValue *Replacement)
Register a module-scope replacement of a declare target global variable.
LLVM_ABI FunctionCallee getOrCreateRuntimeFunction(Module &M, omp::RuntimeFunction FnID)
Return the function declaration for the runtime function with FnID.
LLVM_ABI InsertPointOrErrorTy createCancel(const LocationDescription &Loc, Value *IfCondition, omp::Directive CanceledDirective)
Generator for 'omp cancel'.
std::function< Expected< Function * >(StringRef FunctionName)> FunctionGenCallback
Functions used to generate a function with the given name.
LLVM_ABI CallInst * createOMPAllocShared(const LocationDescription &Loc, Value *Size, const Twine &Name=Twine(""))
Create a runtime call for kmpc_alloc_shared.
ReductionGenCBKind
Enum class for the RedctionGen CallBack type to be used.
LLVM_ABI CanonicalLoopInfo * collapseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, InsertPointTy ComputeIP)
Collapse a loop nest using Config.CollapseMapping.
LLVM_ABI void createTaskyield(const LocationDescription &Loc)
Generator for 'omp taskyield'.
std::function< Error(InsertPointTy CodeGenIP)> FinalizeCallbackTy
Callback type for variable finalization (think destructors).
LLVM_ABI void emitBranch(BasicBlock *Target)
LLVM_ABI Error emitCancelationCheckImpl(Value *CancelFlag, omp::Directive CanceledDirective)
Generate control flow and cleanup for cancellation.
static LLVM_ABI void writeThreadBoundsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
EvalKind
Enum class for reduction evaluation types scalar, complex and aggregate.
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)
std::function< InsertPointTy(InsertPointTy CodeGenIP, unsigned Index, Value **LHS, Value **RHS, Function *CurFn)> ReductionGenClangCBTy
ReductionGen CallBack for Clang.
LLVM_ABI InsertPointTy createAtomicWrite(const LocationDescription &Loc, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic write for : X = Expr — Only Scalar data types.
LLVM_ABI void loadOffloadInfoMetadata(Module &M)
Loads all the offload entries information from the host IR metadata.
function_ref< MapInfosTy &(InsertPointTy CodeGenIP)> GenMapInfoCallbackTy
Callback type for creating the map infos for the kernel parameters.
LLVM_ABI Error emitOffloadingArrays(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Emit the arrays used to pass the captures and map information to the offloading runtime library.
LLVM_ABI void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully unroll a loop.
function_ref< Error(InsertPointTy CodeGenIP, Value *IndVar)> LoopBodyGenCallbackTy
Callback type for loop body code generation.
LLVM_ABI InsertPointOrErrorTy emitScanReduction(const LocationDescription &Loc, ArrayRef< llvm::OpenMPIRBuilder::ReductionInfo > ReductionInfos, ScanInfo *ScanRedInfo)
This function performs the scan reduction of the values updated in the input phase.
LLVM_ABI InsertPointOrErrorTy createScope(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsNowait)
Generator for 'omp scope'.
static LLVM_ABI std::pair< int32_t, int32_t > readThreadBoundsForKernel(const Triple &T, Function &Kernel)
}
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 which must be inside the target task body **The front end specific work(matching each `in_reduction` item to its *mapped storage and binding the generated private pointer back to the *right value) stays with the caller InsertPointT getInsertionPoint)()
Return the insertion point used by the underlying IRBuilder.
SmallVector< bool, 4 > MapHasAttachPtrArrayTy
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.
std::function< InsertPointOrErrorTy( InsertPointTy CodeGenIP, Value *LHS, Value *RHS, Value *&Res)> ReductionGenCBTy
ReductionGen CallBack for MLIR.
LLVM_ABI void emitUsed(StringRef Name, ArrayRef< llvm::WeakTrackingVH > List)
Emit the llvm.used metadata.
void setConfig(OpenMPIRBuilderConfig C)
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.
bool setHandleFPNegZero(bool FPNegZero)
Set whether atomic compare should handle -0.0/+0.0 equivalence.
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.
SmallVector< uint64_t, 4 > MapDimArrayTy
std::function< Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks)> StorableBodyGenCallbackTy
LLVM_ABI std::string createPlatformSpecificName(ArrayRef< StringRef > Parts) const
Get the create a name using the platform specific separators.
LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_next_* runtime function for the specified size IVSize and sign IVSigned.
static LLVM_ABI void getKernelArgsVector(TargetKernelArgs &KernelArgs, IRBuilderBase &Builder, SmallVector< Value * > &ArgsVector)
Create the kernel args vector used by emitTargetKernel.
LLVM_ABI void createFlush(const LocationDescription &Loc, AtomicOrdering AO=AtomicOrdering::SequentiallyConsistent, AtomicScope Scope=AtomicScope::Device)
Generator for 'omp flush'.
SmallVector< Constant *, 4 > MapNamesArrayTy
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.
OpenMPIRBuilderConfig::CollapseIVMapping CollapseIVMapping
Strategy used to derive the original induction variables after collapse.
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 ?
SmallVector< omp::OpenMPOffloadMappingFlags, 4 > MapFlagsArrayTy
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' ...
SmallVector< MapValuesArrayTy, 4 > MapNonContiguousArrayTy
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< DeviceInfoTy, 4 > MapDeviceInfoArrayTy
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 Function * getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID)
std::function< InsertPointOrErrorTy( InsertPointTy, Value *ByRefVal, Value *&Res)> ReductionGenDataPtrPtrCBTy
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.
SmallVector< Value *, 4 > MapValuesArrayTy
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'.
void pushFinalizationCB(const FinalizationInfo &FI)
Push a finalization callback on the finalization stack.
LLVM_ABI InsertPointOrErrorTy createTargetData(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks, Value *DeviceID, Value *IfCond, TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB, omp::RuntimeFunction *MapperFunc=nullptr, function_ref< InsertPointOrErrorTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)> BodyGenCB=nullptr, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr, Value *SrcLocInfo=nullptr)
Generator for 'omp target data'.
LLVM_ABI InsertPointOrErrorTy emitKernelLaunch(const LocationDescription &Loc, Value *OutlinedFnID, EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args, Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP)
Generate a target region entry call and host fallback call.
StringMap< GlobalVariable *, BumpPtrAllocator > InternalVars
An ordered map of auto-generated variables to their unique names.
LLVM_ABI InsertPointOrErrorTy createCancellationPoint(const LocationDescription &Loc, omp::Directive CanceledDirective)
Generator for 'omp cancellation point'.
LLVM_ABI CallInst * createOMPAlignedAlloc(const LocationDescription &Loc, Value *Align, Value *Size, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_align_alloc.
LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< llvm::Value * > ScanVars, ArrayRef< llvm::Type * > ScanVarsType, bool IsInclusive, ScanInfo *ScanRedInfo)
This directive split and directs the control flow to input phase blocks or scan phase blocks based on...
LLVM_ABI CallInst * createOMPFreeShared(const LocationDescription &Loc, Value *Addr, Value *Size, const Twine &Name=Twine(""))
Create a runtime call for kmpc_free_shared.
LLVM_ABI CallInst * createOMPInteropUse(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_use.
IRBuilder<>::InsertPoint InsertPointTy
Type used throughout for insertion points.
LLVM_ABI GlobalVariable * getOrCreateInternalVariable(Type *Ty, const StringRef &Name, std::optional< unsigned > AddressSpace={})
Gets (if variable with the given name already exist) or creates internal global variable with the spe...
LLVM_ABI GlobalVariable * createOffloadMapnames(SmallVectorImpl< llvm::Constant * > &Names, std::string VarName)
Create the global variable holding the offload names information.
LLVM_ABI InsertPointOrErrorTy createTask(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB, bool Tied=true, Value *Final=nullptr, Value *IfCondition=nullptr, const DependenciesInfo &Dependencies={}, const AffinityData &Affinities={}, bool Mergeable=false, Value *EventHandle=nullptr, Value *Priority=nullptr, bool FreeAgent=false)
Generator for #omp taskloop
std::forward_list< ScanInfo > ScanInfos
Collection of owned ScanInfo objects that eventually need to be free'd.
static LLVM_ABI void writeTeamsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
std::function< InsertPointOrErrorTy( InsertPointTy, Type *, Value *, Value *)> ReductionGenAtomicCBTy
Functions used to generate atomic reductions.
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.
DeclareSimdKindTy
Kind of parameter in a function with 'declare simd' directive.
LLVM_ABI InsertPointOrErrorTy createBarrier(const LocationDescription &Loc, omp::Directive Kind, bool ForceSimpleCall=false, bool CheckCancelFlag=true)
Emitter methods for OpenMP directives.
LLVM_ABI void setCorrectMemberOfFlag(omp::OpenMPOffloadMappingFlags &Flags, omp::OpenMPOffloadMappingFlags MemberOfFlag)
Given an initial flag set, this function modifies it to contain the passed in MemberOfFlag generated ...
LLVM_ABI Error emitOffloadingArraysAndArgs(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info, TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, bool ForEndCall=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Allocates memory for and populates the arrays required for offloading (offload_{baseptrs|ptrs|mappers...
LLVM_ABI Constant * getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the default source location.
LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst)
Generator for 'omp critical'.
LLVM_ABI void createError(const LocationDescription &Loc, bool IsFatal, Value *Message)
Generate a call to the runtime to emit the diagnostic of an OpenMP error directive with at(execution)...
LLVM_ABI void createOffloadEntry(Constant *ID, Constant *Addr, uint64_t Size, int32_t Flags, GlobalValue::LinkageTypes, StringRef Name="")
Creates offloading entry for the provided entry ID ID, address Addr, size Size, and flags Flags.
static LLVM_ABI unsigned getOpenMPDefaultSimdAlign(const Triple &TargetTriple, const StringMap< bool > &Features)
Get the default alignment value for given target.
LLVM_ABI unsigned getFlagMemberOffset()
Get the offset of the OMP_MAP_MEMBER_OF field.
LLVM_ABI InsertPointOrErrorTy createAtomicCapture(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, AtomicOpValue &V, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: — Only Scalar data types V = X; X = X BinOp Expr ,...
LLVM_ABI CanonicalLoopInfo * createLoopSkeleton(DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore, BasicBlock *PostInsertBefore, const Twine &Name={}, bool IsCollapsed=false)
Create the control flow structure of a canonical OpenMP loop.
LLVM_ABI void createOffloadEntriesAndInfoMetadata(EmitMetadataErrorReportFunctionTy &ErrorReportFunction)
LLVM_ABI void applySimd(CanonicalLoopInfo *Loop, MapVector< Value *, Value * > AlignedVars, Value *IfCond, omp::OrderKind Order, ConstantInt *Simdlen, ConstantInt *Safelen)
Add metadata to simd-ize a loop.
SmallVector< std::unique_ptr< OutlineInfo >, 16 > OutlineInfos
Collection of regions that need to be outlined during finalization.
LLVM_ABI InsertPointOrErrorTy createAtomicUpdate(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X For complex Operations: X = ...
std::function< std::tuple< std::string, uint64_t >()> FileIdentifierInfoCallbackTy
bool isLastFinalizationInfoCancellable(omp::Directive DK)
Return true if the last entry in the finalization stack is of kind DK and cancellable.
LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return, Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads, Value *HostPtr, ArrayRef< Value * > KernelArgs)
Generate a target region entry call.
LLVM_ABI GlobalVariable * createOffloadMaptypes(SmallVectorImpl< uint64_t > &Mappings, std::string VarName)
Create the global variable holding the offload mappings information.
LLVM_ABI CallInst * createCachedThreadPrivate(const LocationDescription &Loc, llvm::Value *Pointer, llvm::ConstantInt *Size, const llvm::Twine &Name=Twine(""))
Create a runtime call for kmpc_threadprivate_cached.
IRBuilder Builder
The LLVM-IR Builder used to create IR.
bool hasPendingOutlines(const Function *Fn) const
Return true if Fn has a region registered for outlining that has not been processed yet.
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
OpenMPIRBuilder(Module &M)
Create a new OpenMPIRBuilder operating on the given module M.
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.
void popFinalizationCB()
Pop the last finalization callback from the finalization stack.
LLVM_ABI InsertPointOrErrorTy createSections(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< StorableBodyGenCallbackTy > SectionCBs, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait)
Generator for 'omp sections'.
std::function< void(EmitMetadataErrorKind, TargetRegionEntryInfo)> EmitMetadataErrorReportFunctionTy
Callback function type.
function_ref< InsertPointOrErrorTy( Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< InsertPointTy > DeallocIPs)> TargetGenArgAccessorsCallbackTy
LLVM_ABI Expected< ScanInfo * > scanInfoInitialize()
Creates a ScanInfo object, allocates and returns the pointer.
LLVM_ABI InsertPointOrErrorTy emitTargetTask(TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP, const DependenciesInfo &Dependencies, const TargetDataRTArgs &RTArgs, bool HasNoWait)
Generate a target-task for the target construct.
LLVM_ABI InsertPointTy createAtomicRead(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic Read for : V = X — Only Scalar data types.
LLVM_ABI CallInst * createRuntimeFunctionCall(FunctionCallee Callee, ArrayRef< Value * > Args, const Twine &Name="")
function_ref< Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks)> BodyGenCallbackTy
Callback type for body (=inner region) code generation.
bool updateToLocation(const LocationDescription &Loc)
Update the internal location to Loc.
LLVM_ABI Constant * getAddrOfDeclareTargetVar(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, Type *LlvmPtrTy, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage)
Retrieve (or create if non-existent) the address of a declare target variable, used in conjunction wi...
LLVM_ABI void createTaskwait(const LocationDescription &Loc, DependenciesInfo Dependencies={}, bool IsNowait=false)
Generator for 'omp taskwait'.
origPtr *with the address space normalization required by the runtime entry point *The NULL descriptor makes the runtime walk the enclosing taskgroups to *find the matching task_reduction registration for the item The lookups *are emitted at p Loc
EmitMetadataErrorKind
The kind of errors that can occur when emitting the offload entries and metadata.
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.
ScanInfo & operator=(const ScanInfo &)=delete
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.
ScanInfo(ScanInfo &)=delete
llvm::BasicBlock * OMPScanDispatch
Controls the flow to before or after scan blocks.
A vector that has set insertion semantics.
Definition SetVector.h:57
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Class to represent struct types.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Value * getOperand(unsigned i) const
Definition User.h:207
See the file comment.
Definition ValueMap.h:84
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
Value handle that is nullable, but tries to track the Value.
An efficient, type-erasing, non-owning reference to a callable.
The virtual file system interface.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
OpenMPOffloadMappingFlags
Values for bit flags used to specify the mapping type for offloading.
IdentFlag
IDs for all omp runtime library ident_t flag encodings (see their defintion in openmp/runtime/src/kmp...
RTLDependenceKindTy
Dependence kind for RTL.
RuntimeFunction
IDs for all omp runtime library (RTL) functions.
OMPDynGroupprivateFallbackType
The fallback types for the dyn_groupprivate clause.
WorksharingLoopType
A type of worksharing loop construct.
OMPAtomicCompareOp
Atomic compare operations. Currently OpenMP only supports ==, >, and <.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI BasicBlock * splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch, llvm::Twine Suffix=".split")
Like splitBB, but reuses the current block's name for the new name.
@ Offset
Definition DWP.cpp:577
AtomicScope
Target-neutral memory synchronization scopes.
Definition AtomicScope.h:23
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).
auto cast_or_null(const Y &Val)
Definition Casting.h:714
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI void spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New, bool CreateBranch, DebugLoc DL)
Move the instruction after an InsertPoint to the beginning of another BasicBlock.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
Physical handles captured before the source descriptors are invalidated.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A struct to pack the relevant information for an OpenMP affinity clause.
a struct to pack relevant information while generating atomic Ops
Attribute set of the declare simd parameter.
Describes a declare target global variable replacement to be applied during finalization.
DependData(omp::RTLDependenceKindTy DepKind, Type *DepValueType, Value *DepVal)
omp::RTLDependenceKindTy DepKind
A struct to pack static and dynamic dependency information for a task.
DependenciesInfo(SmallVector< DependData > D)
const omp::Directive DK
The directive kind of the innermost directive that has an associated region which might require final...
const bool IsCancellable
Flag to indicate if the directive is cancellable.
LLVM_ABI Error mergeFiniBB(IRBuilderBase &Builder, BasicBlock *ExistingFiniBB)
For cases where there is an unavoidable existing finalization block (e.g.
FinalizationInfo(FinalizeCallbackTy FiniCB, omp::Directive DK, bool IsCancellable)
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,...
LocationDescription(const InsertPointTy &IP, const DebugLoc &DL)
LocationDescription(const IRBuilderBase &IRB)
Represents a group of mapper sub-components produced by an iterator modifier on a declare mapper's ma...
omp::OpenMPOffloadMappingFlags Type
Map type/HasAttachPtr, constant across the segment.
Value * Count
Runtime (i64) trip count for this segment.
Function * ChildMapperFn
User-defined mapper to invoke for this segment's component, if the underlying map clause carries one ...
std::function< Expected< SmallVector< Value *, 3 > >(IRBuilderBase &, Value *)> GenEntry
Emits the code computing one iteration's (BasePointer, Pointer, Size) triple, given the loop's linear...
This structure contains combined information generated for mappable clauses, including base pointers,...
Value * LeadingParentCond
When set, the first statically-known component is a parent synthesized only to group the DynamicSegme...
void append(MapInfosTy &CurInfo)
Append arrays in CurInfo.
MapDeviceInfoArrayTy DevicePointers
SmallVector< DynamicSegment, 0 > DynamicSegments
MapHasAttachPtrArrayTy HasAttachPtr
True for entries that have an attach ptr, and thus an accompanying ATTACH entry linking that ptr to i...
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.
Function * getFunction() const
Return the function that contains the region to be outlined.
SmallVector< Value *, 2 > ExcludeArgsFromAggregate
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,...
std::function< void(Function &)> PostOutlineCBTy
SmallVector< BasicBlock * > OuterDeallocBBs
EvalKind EvaluationKind
Reduction evaluation kind - scalar, complex or aggregate.
ReductionInfo(Type *ElementType, Value *Variable, Value *PrivateVariable, EvalKind EvaluationKind, ReductionGenCBTy ReductionGen, ReductionGenClangCBTy ReductionGenClang, ReductionGenAtomicCBTy AtomicReductionGen, ReductionGenDataPtrPtrCBTy DataPtrPtrGen, Type *ByRefAllocatedType=nullptr, Type *ByRefElementType=nullptr)
ReductionGenAtomicCBTy AtomicReductionGen
Callback for generating the atomic reduction body, may be null.
ReductionGenCBTy ReductionGen
Callback for generating the reduction body.
ReductionInfo(Value *PrivateVariable)
Type * ByRefAllocatedType
For by-ref reductions, we need to keep track of 2 extra types that are potentially different:
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
unsigned MapIndex
The entry in PointersArray that refers to this descriptor.
Container for the arguments used to pass data to the runtime library.
Value * SizesArray
The array of sizes passed to the runtime library.
TargetDataRTArgs(Value *BasePointersArray, Value *PointersArray, Value *SizesArray, Value *MapTypesArray, Value *MapTypesArrayEnd, Value *MappersArray, Value *MapNamesArray)
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.
TargetKernelArgs(unsigned NumTargetItems, TargetDataRTArgs RTArgs, Value *NumIterations, ArrayRef< Value * > NumTeams, ArrayRef< Value * > NumThreads, Value *DynCGroupMem, bool HasNoWait, bool StrictBlocks, bool StrictThreads, omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback)
Value * NumIterations
The number of iterations.
Value * DynCGroupMem
The size of the dynamic shared memory.
unsigned NumTargetItems
Number of arguments passed to the runtime library.
bool HasNoWait
True if the kernel has 'no wait' clause.
ArrayRef< Value * > NumTeams
The number of teams.
omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback
The fallback mechanism for the shared memory.
Container to pass the default attributes with which a kernel must be launched, used to set kernel att...
Container to pass LLVM IR runtime values or constants related to the number of teams and threads with...
Value * DeviceID
Device ID value used in the kernel launch.
Value * LoopTripCount
Total number of iterations of the SPMD or Generic-SPMD kernel or null if it is a generic kernel.
SmallVector< Value * > MaxThreads
'parallel' construct 'num_threads' clause value, if present and it is an SPMD kernel.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
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.
bool operator<(const TargetRegionEntryInfo &RHS) const
TargetRegionEntryInfo(StringRef ParentName, unsigned DeviceID, unsigned FileID, unsigned Line, unsigned Count=0)
Defines various target-specific GPU grid values that must be consistent between host RTL (plugin),...