LLVM 22.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
20#include "llvm/IR/DebugLoc.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/ValueMap.h"
26#include "llvm/Support/Error.h"
28#include <forward_list>
29#include <map>
30#include <optional>
31
32namespace llvm {
33class CanonicalLoopInfo;
34class ScanInfo;
35struct TargetRegionEntryInfo;
36class OffloadEntriesInfoManager;
37class OpenMPIRBuilder;
38class Loop;
39class LoopAnalysis;
40class LoopInfo;
41
42namespace vfs {
43class FileSystem;
44} // namespace vfs
45
46/// Move the instruction after an InsertPoint to the beginning of another
47/// BasicBlock.
48///
49/// The instructions after \p IP are moved to the beginning of \p New which must
50/// not have any PHINodes. If \p CreateBranch is true, a branch instruction to
51/// \p New will be added such that there is no semantic change. Otherwise, the
52/// \p IP insert block remains degenerate and it is up to the caller to insert a
53/// terminator. \p DL is used as the debug location for the branch instruction
54/// if one is created.
56 bool CreateBranch, DebugLoc DL);
57
58/// Splice a BasicBlock at an IRBuilder's current insertion point. Its new
59/// insert location will stick to after the instruction before the insertion
60/// point (instead of moving with the instruction the InsertPoint stores
61/// internally).
62LLVM_ABI void spliceBB(IRBuilder<> &Builder, BasicBlock *New,
63 bool CreateBranch);
64
65/// Split a BasicBlock at an InsertPoint, even if the block is degenerate
66/// (missing the terminator).
67///
68/// llvm::SplitBasicBlock and BasicBlock::splitBasicBlock require a well-formed
69/// BasicBlock. \p Name is used for the new successor block. If \p CreateBranch
70/// is true, a branch to the new successor will new created such that
71/// semantically there is no change; otherwise the block of the insertion point
72/// remains degenerate and it is the caller's responsibility to insert a
73/// terminator. \p DL is used as the debug location for the branch instruction
74/// if one is created. Returns the new successor block.
75LLVM_ABI BasicBlock *splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch,
76 DebugLoc DL, llvm::Twine Name = {});
77
78/// Split a BasicBlock at \p Builder's insertion point, even if the block is
79/// degenerate (missing the terminator). Its new insert location will stick to
80/// after the instruction before the insertion point (instead of moving with the
81/// instruction the InsertPoint stores internally).
82LLVM_ABI BasicBlock *splitBB(IRBuilderBase &Builder, bool CreateBranch,
83 llvm::Twine Name = {});
84
85/// Split a BasicBlock at \p Builder's insertion point, even if the block is
86/// degenerate (missing the terminator). Its new insert location will stick to
87/// after the instruction before the insertion point (instead of moving with the
88/// instruction the InsertPoint stores internally).
89LLVM_ABI BasicBlock *splitBB(IRBuilder<> &Builder, bool CreateBranch,
90 llvm::Twine Name);
91
92/// Like splitBB, but reuses the current block's name for the new name.
93LLVM_ABI BasicBlock *splitBBWithSuffix(IRBuilderBase &Builder,
94 bool CreateBranch,
95 llvm::Twine Suffix = ".split");
96
97/// Captures attributes that affect generating LLVM-IR using the
98/// OpenMPIRBuilder and related classes. Note that not all attributes are
99/// required for all classes or functions. In some use cases the configuration
100/// is not necessary at all, because because the only functions that are called
101/// are ones that are not dependent on the configuration.
102class OpenMPIRBuilderConfig {
103public:
104 /// Flag to define whether to generate code for the role of the OpenMP host
105 /// (if set to false) or device (if set to true) in an offloading context. It
106 /// is set when the -fopenmp-is-target-device compiler frontend option is
107 /// specified.
108 std::optional<bool> IsTargetDevice;
109
110 /// Flag for specifying if the compilation is done for an accelerator. It is
111 /// set according to the architecture of the target triple and currently only
112 /// true when targeting AMDGPU or NVPTX. Today, these targets can only perform
113 /// the role of an OpenMP target device, so `IsTargetDevice` must also be true
114 /// if `IsGPU` is true. This restriction might be lifted if an accelerator-
115 /// like target with the ability to work as the OpenMP host is added, or if
116 /// the capabilities of the currently supported GPU architectures are
117 /// expanded.
118 std::optional<bool> IsGPU;
119
120 /// Flag for specifying if LLVMUsed information should be emitted.
121 std::optional<bool> EmitLLVMUsedMetaInfo;
122
123 /// Flag for specifying if offloading is mandatory.
124 std::optional<bool> OpenMPOffloadMandatory;
125
126 /// First separator used between the initial two parts of a name.
127 std::optional<StringRef> FirstSeparator;
128 /// Separator used between all of the rest consecutive parts of s name.
129 std::optional<StringRef> Separator;
130
131 // Grid Value for the GPU target.
132 std::optional<omp::GV> GridValue;
133
134 /// When compilation is being done for the OpenMP host (i.e. `IsTargetDevice =
135 /// false`), this contains the list of offloading triples associated, if any.
136 SmallVector<Triple> TargetTriples;
137
138 // Default address space for the target.
139 unsigned DefaultTargetAS = 0;
140
141 LLVM_ABI OpenMPIRBuilderConfig();
142 LLVM_ABI OpenMPIRBuilderConfig(bool IsTargetDevice, bool IsGPU,
143 bool OpenMPOffloadMandatory,
144 bool HasRequiresReverseOffload,
145 bool HasRequiresUnifiedAddress,
146 bool HasRequiresUnifiedSharedMemory,
147 bool HasRequiresDynamicAllocators);
148
149 // Getters functions that assert if the required values are not present.
150 bool isTargetDevice() const {
151 assert(IsTargetDevice.has_value() && "IsTargetDevice is not set");
152 return *IsTargetDevice;
153 }
154
155 bool isGPU() const {
156 assert(IsGPU.has_value() && "IsGPU is not set");
157 return *IsGPU;
158 }
159
160 bool openMPOffloadMandatory() const {
161 assert(OpenMPOffloadMandatory.has_value() &&
162 "OpenMPOffloadMandatory is not set");
163 return *OpenMPOffloadMandatory;
164 }
165
166 omp::GV getGridValue() const {
167 assert(GridValue.has_value() && "GridValue is not set");
168 return *GridValue;
169 }
170
171 unsigned getDefaultTargetAS() const { return DefaultTargetAS; }
172
173 bool hasRequiresFlags() const { return RequiresFlags; }
174 LLVM_ABI bool hasRequiresReverseOffload() const;
175 LLVM_ABI bool hasRequiresUnifiedAddress() const;
176 LLVM_ABI bool hasRequiresUnifiedSharedMemory() const;
177 LLVM_ABI bool hasRequiresDynamicAllocators() const;
178
179 /// Returns requires directive clauses as flags compatible with those expected
180 /// by libomptarget.
181 LLVM_ABI int64_t getRequiresFlags() const;
182
183 // Returns the FirstSeparator if set, otherwise use the default separator
184 // depending on isGPU
185 StringRef firstSeparator() const {
186 if (FirstSeparator.has_value())
187 return *FirstSeparator;
188 if (isGPU())
189 return "_";
190 return ".";
191 }
192
193 // Returns the Separator if set, otherwise use the default separator depending
194 // on isGPU
195 StringRef separator() const {
196 if (Separator.has_value())
197 return *Separator;
198 if (isGPU())
199 return "$";
200 return ".";
201 }
202
203 void setIsTargetDevice(bool Value) { IsTargetDevice = Value; }
204 void setIsGPU(bool Value) { IsGPU = Value; }
205 void setEmitLLVMUsed(bool Value = true) { EmitLLVMUsedMetaInfo = Value; }
206 void setOpenMPOffloadMandatory(bool Value) { OpenMPOffloadMandatory = Value; }
207 void setFirstSeparator(StringRef FS) { FirstSeparator = FS; }
208 void setSeparator(StringRef S) { Separator = S; }
209 void setGridValue(omp::GV G) { GridValue = G; }
210 void setDefaultTargetAS(unsigned AS) { DefaultTargetAS = AS; }
211
212 LLVM_ABI void setHasRequiresReverseOffload(bool Value);
213 LLVM_ABI void setHasRequiresUnifiedAddress(bool Value);
214 LLVM_ABI void setHasRequiresUnifiedSharedMemory(bool Value);
215 LLVM_ABI void setHasRequiresDynamicAllocators(bool Value);
216
217private:
218 /// Flags for specifying which requires directive clauses are present.
219 int64_t RequiresFlags;
220};
221
222/// Data structure to contain the information needed to uniquely identify
223/// a target entry.
224struct TargetRegionEntryInfo {
225 /// The prefix used for kernel names.
226 static constexpr const char *KernelNamePrefix = "__omp_offloading_";
227
228 std::string ParentName;
229 unsigned DeviceID;
230 unsigned FileID;
231 unsigned Line;
232 unsigned Count;
233
234 TargetRegionEntryInfo() : DeviceID(0), FileID(0), Line(0), Count(0) {}
235 TargetRegionEntryInfo(StringRef ParentName, unsigned DeviceID,
236 unsigned FileID, unsigned Line, unsigned Count = 0)
237 : ParentName(ParentName), DeviceID(DeviceID), FileID(FileID), Line(Line),
238 Count(Count) {}
239
240 LLVM_ABI static void
241 getTargetRegionEntryFnName(SmallVectorImpl<char> &Name, StringRef ParentName,
242 unsigned DeviceID, unsigned FileID, unsigned Line,
243 unsigned Count);
244
245 bool operator<(const TargetRegionEntryInfo &RHS) const {
246 return std::make_tuple(ParentName, DeviceID, FileID, Line, Count) <
247 std::make_tuple(RHS.ParentName, RHS.DeviceID, RHS.FileID, RHS.Line,
248 RHS.Count);
249 }
250};
251
252/// Class that manages information about offload code regions and data
253class OffloadEntriesInfoManager {
254 /// Number of entries registered so far.
255 OpenMPIRBuilder *OMPBuilder;
256 unsigned OffloadingEntriesNum = 0;
257
258public:
259 /// Base class of the entries info.
260 class OffloadEntryInfo {
261 public:
262 /// Kind of a given entry.
263 enum OffloadingEntryInfoKinds : unsigned {
264 /// Entry is a target region.
265 OffloadingEntryInfoTargetRegion = 0,
266 /// Entry is a declare target variable.
267 OffloadingEntryInfoDeviceGlobalVar = 1,
268 /// Invalid entry info.
269 OffloadingEntryInfoInvalid = ~0u
270 };
271
272 protected:
273 OffloadEntryInfo() = delete;
274 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {}
275 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order,
276 uint32_t Flags)
277 : Flags(Flags), Order(Order), Kind(Kind) {}
278 ~OffloadEntryInfo() = default;
279
280 public:
281 bool isValid() const { return Order != ~0u; }
282 unsigned getOrder() const { return Order; }
283 OffloadingEntryInfoKinds getKind() const { return Kind; }
284 uint32_t getFlags() const { return Flags; }
285 void setFlags(uint32_t NewFlags) { Flags = NewFlags; }
286 Constant *getAddress() const { return cast_or_null<Constant>(Addr); }
287 void setAddress(Constant *V) {
288 assert(!Addr.pointsToAliveValue() && "Address has been set before!");
289 Addr = V;
290 }
291 static bool classof(const OffloadEntryInfo *Info) { return true; }
292
293 private:
294 /// Address of the entity that has to be mapped for offloading.
295 WeakTrackingVH Addr;
296
297 /// Flags associated with the device global.
298 uint32_t Flags = 0u;
299
300 /// Order this entry was emitted.
301 unsigned Order = ~0u;
302
303 OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid;
304 };
305
306 /// Return true if a there are no entries defined.
307 LLVM_ABI bool empty() const;
308 /// Return number of entries defined so far.
309 unsigned size() const { return OffloadingEntriesNum; }
310
311 OffloadEntriesInfoManager(OpenMPIRBuilder *builder) : OMPBuilder(builder) {}
312
313 //
314 // Target region entries related.
315 //
316
317 /// Kind of the target registry entry.
318 enum OMPTargetRegionEntryKind : uint32_t {
319 /// Mark the entry as target region.
320 OMPTargetRegionEntryTargetRegion = 0x0,
321 };
322
323 /// Target region entries info.
324 class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo {
325 /// Address that can be used as the ID of the entry.
326 Constant *ID = nullptr;
327
328 public:
329 OffloadEntryInfoTargetRegion()
330 : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {}
331 explicit OffloadEntryInfoTargetRegion(unsigned Order, Constant *Addr,
332 Constant *ID,
333 OMPTargetRegionEntryKind Flags)
334 : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags),
335 ID(ID) {
336 setAddress(Addr);
337 }
338
339 Constant *getID() const { return ID; }
340 void setID(Constant *V) {
341 assert(!ID && "ID has been set before!");
342 ID = V;
343 }
344 static bool classof(const OffloadEntryInfo *Info) {
345 return Info->getKind() == OffloadingEntryInfoTargetRegion;
346 }
347 };
348
349 /// Initialize target region entry.
350 /// This is ONLY needed for DEVICE compilation.
351 LLVM_ABI void
352 initializeTargetRegionEntryInfo(const TargetRegionEntryInfo &EntryInfo,
353 unsigned Order);
354 /// Register target region entry.
355 LLVM_ABI void registerTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo,
356 Constant *Addr, Constant *ID,
357 OMPTargetRegionEntryKind Flags);
358 /// Return true if a target region entry with the provided information
359 /// exists.
360 LLVM_ABI bool hasTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo,
361 bool IgnoreAddressId = false) const;
362
363 // Return the Name based on \a EntryInfo using the next available Count.
364 LLVM_ABI void
365 getTargetRegionEntryFnName(SmallVectorImpl<char> &Name,
366 const TargetRegionEntryInfo &EntryInfo);
367
368 /// brief Applies action \a Action on all registered entries.
369 typedef function_ref<void(const TargetRegionEntryInfo &EntryInfo,
370 const OffloadEntryInfoTargetRegion &)>
371 OffloadTargetRegionEntryInfoActTy;
372 LLVM_ABI void
373 actOnTargetRegionEntriesInfo(const OffloadTargetRegionEntryInfoActTy &Action);
374
375 //
376 // Device global variable entries related.
377 //
378
379 /// Kind of the global variable entry..
380 enum OMPTargetGlobalVarEntryKind : uint32_t {
381 /// Mark the entry as a to declare target.
382 OMPTargetGlobalVarEntryTo = 0x0,
383 /// Mark the entry as a to declare target link.
384 OMPTargetGlobalVarEntryLink = 0x1,
385 /// Mark the entry as a declare target enter.
386 OMPTargetGlobalVarEntryEnter = 0x2,
387 /// Mark the entry as having no declare target entry kind.
388 OMPTargetGlobalVarEntryNone = 0x3,
389 /// Mark the entry as a declare target indirect global.
390 OMPTargetGlobalVarEntryIndirect = 0x8,
391 /// Mark the entry as a register requires global.
392 OMPTargetGlobalRegisterRequires = 0x10,
393 };
394
395 /// Kind of device clause for declare target variables
396 /// and functions
397 /// NOTE: Currently not used as a part of a variable entry
398 /// used for Flang and Clang to interface with the variable
399 /// related registration functions
400 enum OMPTargetDeviceClauseKind : uint32_t {
401 /// The target is marked for all devices
402 OMPTargetDeviceClauseAny = 0x0,
403 /// The target is marked for non-host devices
404 OMPTargetDeviceClauseNoHost = 0x1,
405 /// The target is marked for host devices
406 OMPTargetDeviceClauseHost = 0x2,
407 /// The target is marked as having no clause
408 OMPTargetDeviceClauseNone = 0x3
409 };
410
411 /// Device global variable entries info.
412 class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo {
413 /// Type of the global variable.
414 int64_t VarSize;
415 GlobalValue::LinkageTypes Linkage;
416 const std::string VarName;
417
418 public:
419 OffloadEntryInfoDeviceGlobalVar()
420 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {}
421 explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order,
422 OMPTargetGlobalVarEntryKind Flags)
423 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {}
424 explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, Constant *Addr,
425 int64_t VarSize,
426 OMPTargetGlobalVarEntryKind Flags,
427 GlobalValue::LinkageTypes Linkage,
428 const std::string &VarName)
429 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags),
430 VarSize(VarSize), Linkage(Linkage), VarName(VarName) {
431 setAddress(Addr);
432 }
433
434 int64_t getVarSize() const { return VarSize; }
435 StringRef getVarName() const { return VarName; }
436 void setVarSize(int64_t Size) { VarSize = Size; }
437 GlobalValue::LinkageTypes getLinkage() const { return Linkage; }
438 void setLinkage(GlobalValue::LinkageTypes LT) { Linkage = LT; }
439 static bool classof(const OffloadEntryInfo *Info) {
440 return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar;
441 }
442 };
443
444 /// Initialize device global variable entry.
445 /// This is ONLY used for DEVICE compilation.
446 LLVM_ABI void initializeDeviceGlobalVarEntryInfo(
447 StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order);
448
449 /// Register device global variable entry.
450 LLVM_ABI void registerDeviceGlobalVarEntryInfo(
451 StringRef VarName, Constant *Addr, int64_t VarSize,
452 OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage);
453 /// Checks if the variable with the given name has been registered already.
454 bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const {
455 return OffloadEntriesDeviceGlobalVar.count(VarName) > 0;
456 }
457 /// Applies action \a Action on all registered entries.
458 typedef function_ref<void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)>
459 OffloadDeviceGlobalVarEntryInfoActTy;
460 LLVM_ABI void actOnDeviceGlobalVarEntriesInfo(
461 const OffloadDeviceGlobalVarEntryInfoActTy &Action);
462
463private:
464 /// Return the count of entries at a particular source location.
465 unsigned
466 getTargetRegionEntryInfoCount(const TargetRegionEntryInfo &EntryInfo) const;
467
468 /// Update the count of entries at a particular source location.
469 void
470 incrementTargetRegionEntryInfoCount(const TargetRegionEntryInfo &EntryInfo);
471
472 static TargetRegionEntryInfo
473 getTargetRegionEntryCountKey(const TargetRegionEntryInfo &EntryInfo) {
474 return TargetRegionEntryInfo(EntryInfo.ParentName, EntryInfo.DeviceID,
475 EntryInfo.FileID, EntryInfo.Line, 0);
476 }
477
478 // Count of entries at a location.
479 std::map<TargetRegionEntryInfo, unsigned> OffloadEntriesTargetRegionCount;
480
481 // Storage for target region entries kind.
482 typedef std::map<TargetRegionEntryInfo, OffloadEntryInfoTargetRegion>
483 OffloadEntriesTargetRegionTy;
484 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
485 /// Storage for device global variable entries kind. The storage is to be
486 /// indexed by mangled name.
487 typedef StringMap<OffloadEntryInfoDeviceGlobalVar>
488 OffloadEntriesDeviceGlobalVarTy;
489 OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar;
490};
491
492/// An interface to create LLVM-IR for OpenMP directives.
493///
494/// Each OpenMP directive has a corresponding public generator method.
495class OpenMPIRBuilder {
496public:
497 /// Create a new OpenMPIRBuilder operating on the given module \p M. This will
498 /// not have an effect on \p M (see initialize)
499 OpenMPIRBuilder(Module &M)
500 : M(M), Builder(M.getContext()), OffloadInfoManager(this),
501 T(M.getTargetTriple()), IsFinalized(false) {}
502 LLVM_ABI ~OpenMPIRBuilder();
503
504 class AtomicInfo : public llvm::AtomicInfo {
505 llvm::Value *AtomicVar;
506
507 public:
508 AtomicInfo(IRBuilder<> *Builder, llvm::Type *Ty, uint64_t AtomicSizeInBits,
509 uint64_t ValueSizeInBits, llvm::Align AtomicAlign,
510 llvm::Align ValueAlign, bool UseLibcall,
511 IRBuilderBase::InsertPoint AllocaIP, llvm::Value *AtomicVar)
512 : llvm::AtomicInfo(Builder, Ty, AtomicSizeInBits, ValueSizeInBits,
513 AtomicAlign, ValueAlign, UseLibcall, AllocaIP),
514 AtomicVar(AtomicVar) {}
515
516 llvm::Value *getAtomicPointer() const override { return AtomicVar; }
517 void decorateWithTBAA(llvm::Instruction *I) override {}
518 llvm::AllocaInst *CreateAlloca(llvm::Type *Ty,
519 const llvm::Twine &Name) const override {
520 llvm::AllocaInst *allocaInst = Builder->CreateAlloca(Ty);
521 allocaInst->setName(Name);
522 return allocaInst;
523 }
524 };
525 /// Initialize the internal state, this will put structures types and
526 /// potentially other helpers into the underlying module. Must be called
527 /// before any other method and only once! This internal state includes types
528 /// used in the OpenMPIRBuilder generated from OMPKinds.def.
529 LLVM_ABI void initialize();
530
531 void setConfig(OpenMPIRBuilderConfig C) { Config = C; }
532
533 /// Finalize the underlying module, e.g., by outlining regions.
534 /// \param Fn The function to be finalized. If not used,
535 /// all functions are finalized.
536 LLVM_ABI void finalize(Function *Fn = nullptr);
537
538 /// Check whether the finalize function has already run
539 /// \return true if the finalize function has already run
540 LLVM_ABI bool isFinalized();
541
542 /// Add attributes known for \p FnID to \p Fn.
543 LLVM_ABI void addAttributes(omp::RuntimeFunction FnID, Function &Fn);
544
545 /// Type used throughout for insertion points.
546 using InsertPointTy = IRBuilder<>::InsertPoint;
547
548 /// Type used to represent an insertion point or an error value.
549 using InsertPointOrErrorTy = Expected<InsertPointTy>;
550
551 /// Get the create a name using the platform specific separators.
552 /// \param Parts parts of the final name that needs separation
553 /// The created name has a first separator between the first and second part
554 /// and a second separator between all other parts.
555 /// E.g. with FirstSeparator "$" and Separator "." and
556 /// parts: "p1", "p2", "p3", "p4"
557 /// The resulting name is "p1$p2.p3.p4"
558 /// The separators are retrieved from the OpenMPIRBuilderConfig.
559 LLVM_ABI std::string
560 createPlatformSpecificName(ArrayRef<StringRef> Parts) const;
561
562 /// Callback type for variable finalization (think destructors).
563 ///
564 /// \param CodeGenIP is the insertion point at which the finalization code
565 /// should be placed.
566 ///
567 /// A finalize callback knows about all objects that need finalization, e.g.
568 /// destruction, when the scope of the currently generated construct is left
569 /// at the time, and location, the callback is invoked.
570 using FinalizeCallbackTy = std::function<Error(InsertPointTy CodeGenIP)>;
571
572 struct FinalizationInfo {
573 /// The finalization callback provided by the last in-flight invocation of
574 /// createXXXX for the directive of kind DK.
575 FinalizeCallbackTy FiniCB;
576
577 /// The directive kind of the innermost directive that has an associated
578 /// region which might require finalization when it is left.
579 omp::Directive DK;
580
581 /// Flag to indicate if the directive is cancellable.
582 bool IsCancellable;
583 };
584
585 /// Push a finalization callback on the finalization stack.
586 ///
587 /// NOTE: Temporary solution until Clang CG is gone.
588 void pushFinalizationCB(const FinalizationInfo &FI) {
589 FinalizationStack.push_back(FI);
590 }
591
592 /// Pop the last finalization callback from the finalization stack.
593 ///
594 /// NOTE: Temporary solution until Clang CG is gone.
595 void popFinalizationCB() { FinalizationStack.pop_back(); }
596
597 /// Callback type for body (=inner region) code generation
598 ///
599 /// The callback takes code locations as arguments, each describing a
600 /// location where additional instructions can be inserted.
601 ///
602 /// The CodeGenIP may be in the middle of a basic block or point to the end of
603 /// it. The basic block may have a terminator or be degenerate. The callback
604 /// function may just insert instructions at that position, but also split the
605 /// block (without the Before argument of BasicBlock::splitBasicBlock such
606 /// that the identify of the split predecessor block is preserved) and insert
607 /// additional control flow, including branches that do not lead back to what
608 /// follows the CodeGenIP. Note that since the callback is allowed to split
609 /// the block, callers must assume that InsertPoints to positions in the
610 /// BasicBlock after CodeGenIP including CodeGenIP itself are invalidated. If
611 /// such InsertPoints need to be preserved, it can split the block itself
612 /// before calling the callback.
613 ///
614 /// AllocaIP and CodeGenIP must not point to the same position.
615 ///
616 /// \param AllocaIP is the insertion point at which new alloca instructions
617 /// should be placed. The BasicBlock it is pointing to must
618 /// not be split.
619 /// \param CodeGenIP is the insertion point at which the body code should be
620 /// placed.
621 ///
622 /// \return an error, if any were triggered during execution.
623 using BodyGenCallbackTy =
624 function_ref<Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
625
626 // This is created primarily for sections construct as llvm::function_ref
627 // (BodyGenCallbackTy) is not storable (as described in the comments of
628 // function_ref class - function_ref contains non-ownable reference
629 // to the callable.
630 ///
631 /// \return an error, if any were triggered during execution.
632 using StorableBodyGenCallbackTy =
633 std::function<Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
634
635 /// Callback type for loop body code generation.
636 ///
637 /// \param CodeGenIP is the insertion point where the loop's body code must be
638 /// placed. This will be a dedicated BasicBlock with a
639 /// conditional branch from the loop condition check and
640 /// terminated with an unconditional branch to the loop
641 /// latch.
642 /// \param IndVar is the induction variable usable at the insertion point.
643 ///
644 /// \return an error, if any were triggered during execution.
645 using LoopBodyGenCallbackTy =
646 function_ref<Error(InsertPointTy CodeGenIP, Value *IndVar)>;
647
648 /// Callback type for variable privatization (think copy & default
649 /// constructor).
650 ///
651 /// \param AllocaIP is the insertion point at which new alloca instructions
652 /// should be placed.
653 /// \param CodeGenIP is the insertion point at which the privatization code
654 /// should be placed.
655 /// \param Original The value being copied/created, should not be used in the
656 /// generated IR.
657 /// \param Inner The equivalent of \p Original that should be used in the
658 /// generated IR; this is equal to \p Original if the value is
659 /// a pointer and can thus be passed directly, otherwise it is
660 /// an equivalent but different value.
661 /// \param ReplVal The replacement value, thus a copy or new created version
662 /// of \p Inner.
663 ///
664 /// \returns The new insertion point where code generation continues and
665 /// \p ReplVal the replacement value.
666 using PrivatizeCallbackTy = function_ref<InsertPointOrErrorTy(
667 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original,
668 Value &Inner, Value *&ReplVal)>;
669
670 /// Description of a LLVM-IR insertion point (IP) and a debug/source location
671 /// (filename, line, column, ...).
672 struct LocationDescription {
673 LocationDescription(const IRBuilderBase &IRB)
674 : IP(IRB.saveIP()), DL(IRB.getCurrentDebugLocation()) {}
675 LocationDescription(const InsertPointTy &IP) : IP(IP) {}
676 LocationDescription(const InsertPointTy &IP, const DebugLoc &DL)
677 : IP(IP), DL(DL) {}
678 InsertPointTy IP;
679 DebugLoc DL;
680 };
681
682 /// Emitter methods for OpenMP directives.
683 ///
684 ///{
685
686 /// Generator for '#omp barrier'
687 ///
688 /// \param Loc The location where the barrier directive was encountered.
689 /// \param Kind The kind of directive that caused the barrier.
690 /// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
691 /// \param CheckCancelFlag Flag to indicate a cancel barrier return value
692 /// should be checked and acted upon.
693 /// \param ThreadID Optional parameter to pass in any existing ThreadID value.
694 ///
695 /// \returns The insertion point after the barrier.
696 LLVM_ABI InsertPointOrErrorTy createBarrier(const LocationDescription &Loc,
697 omp::Directive Kind,
698 bool ForceSimpleCall = false,
699 bool CheckCancelFlag = true);
700
701 /// Generator for '#omp cancel'
702 ///
703 /// \param Loc The location where the directive was encountered.
704 /// \param IfCondition The evaluated 'if' clause expression, if any.
705 /// \param CanceledDirective The kind of directive that is cancled.
706 ///
707 /// \returns The insertion point after the barrier.
708 LLVM_ABI InsertPointOrErrorTy createCancel(const LocationDescription &Loc,
709 Value *IfCondition,
710 omp::Directive CanceledDirective);
711
712 /// Generator for '#omp cancellation point'
713 ///
714 /// \param Loc The location where the directive was encountered.
715 /// \param CanceledDirective The kind of directive that is cancled.
716 ///
717 /// \returns The insertion point after the barrier.
718 LLVM_ABI InsertPointOrErrorTy createCancellationPoint(
719 const LocationDescription &Loc, omp::Directive CanceledDirective);
720
721 /// Creates a ScanInfo object, allocates and returns the pointer.
722 LLVM_ABI Expected<ScanInfo *> scanInfoInitialize();
723
724 /// Generator for '#omp parallel'
725 ///
726 /// \param Loc The insert and source location description.
727 /// \param AllocaIP The insertion points to be used for alloca instructions.
728 /// \param BodyGenCB Callback that will generate the region code.
729 /// \param PrivCB Callback to copy a given variable (think copy constructor).
730 /// \param FiniCB Callback to finalize variable copies.
731 /// \param IfCondition The evaluated 'if' clause expression, if any.
732 /// \param NumThreads The evaluated 'num_threads' clause expression, if any.
733 /// \param ProcBind The value of the 'proc_bind' clause (see ProcBindKind).
734 /// \param IsCancellable Flag to indicate a cancellable parallel region.
735 ///
736 /// \returns The insertion position *after* the parallel.
737 LLVM_ABI InsertPointOrErrorTy createParallel(
738 const LocationDescription &Loc, InsertPointTy AllocaIP,
739 BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
740 FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
741 omp::ProcBindKind ProcBind, bool IsCancellable);
742
743 /// Generator for the control flow structure of an OpenMP canonical loop.
744 ///
745 /// This generator operates on the logical iteration space of the loop, i.e.
746 /// the caller only has to provide a loop trip count of the loop as defined by
747 /// base language semantics. The trip count is interpreted as an unsigned
748 /// integer. The induction variable passed to \p BodyGenCB will be of the same
749 /// type and run from 0 to \p TripCount - 1. It is up to the callback to
750 /// convert the logical iteration variable to the loop counter variable in the
751 /// loop body.
752 ///
753 /// \param Loc The insert and source location description. The insert
754 /// location can be between two instructions or the end of a
755 /// degenerate block (e.g. a BB under construction).
756 /// \param BodyGenCB Callback that will generate the loop body code.
757 /// \param TripCount Number of iterations the loop body is executed.
758 /// \param Name Base name used to derive BB and instruction names.
759 ///
760 /// \returns An object representing the created control flow structure which
761 /// can be used for loop-associated directives.
762 LLVM_ABI Expected<CanonicalLoopInfo *>
763 createCanonicalLoop(const LocationDescription &Loc,
764 LoopBodyGenCallbackTy BodyGenCB, Value *TripCount,
765 const Twine &Name = "loop");
766
767 /// Generator for the control flow structure of an OpenMP canonical loops if
768 /// the parent directive has an `inscan` modifier specified.
769 /// If the `inscan` modifier is specified, the region of the parent is
770 /// expected to have a `scan` directive. Based on the clauses in
771 /// scan directive, the body of the loop is split into two loops: Input loop
772 /// and Scan Loop. Input loop contains the code generated for input phase of
773 /// scan and Scan loop contains the code generated for scan phase of scan.
774 /// From the bodyGen callback of these loops, `createScan` would be called
775 /// when a scan directive is encountered from the loop body. `createScan`
776 /// based on whether 1. inclusive or exclusive scan is specified and, 2. input
777 /// loop or scan loop is generated, lowers the body of the for loop
778 /// accordingly.
779 ///
780 /// \param Loc The insert and source location description.
781 /// \param BodyGenCB Callback that will generate the loop body code.
782 /// \param Start Value of the loop counter for the first iterations.
783 /// \param Stop Loop counter values past this will stop the loop.
784 /// \param Step Loop counter increment after each iteration; negative
785 /// means counting down.
786 /// \param IsSigned Whether Start, Stop and Step are signed integers.
787 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
788 /// counter.
789 /// \param ComputeIP Insertion point for instructions computing the trip
790 /// count. Can be used to ensure the trip count is available
791 /// at the outermost loop of a loop nest. If not set,
792 /// defaults to the preheader of the generated loop.
793 /// \param Name Base name used to derive BB and instruction names.
794 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
795 /// `ScanInfoInitialize`.
796 ///
797 /// \returns A vector containing Loop Info of Input Loop and Scan Loop.
798 LLVM_ABI Expected<SmallVector<llvm::CanonicalLoopInfo *>>
799 createCanonicalScanLoops(const LocationDescription &Loc,
800 LoopBodyGenCallbackTy BodyGenCB, Value *Start,
801 Value *Stop, Value *Step, bool IsSigned,
802 bool InclusiveStop, InsertPointTy ComputeIP,
803 const Twine &Name, ScanInfo *ScanRedInfo);
804
805 /// Calculate the trip count of a canonical loop.
806 ///
807 /// This allows specifying user-defined loop counter values using increment,
808 /// upper- and lower bounds. To disambiguate the terminology when counting
809 /// downwards, instead of lower bounds we use \p Start for the loop counter
810 /// value in the first body iteration.
811 ///
812 /// Consider the following limitations:
813 ///
814 /// * A loop counter space over all integer values of its bit-width cannot be
815 /// represented. E.g using uint8_t, its loop trip count of 256 cannot be
816 /// stored into an 8 bit integer):
817 ///
818 /// DO I = 0, 255, 1
819 ///
820 /// * Unsigned wrapping is only supported when wrapping only "once"; E.g.
821 /// effectively counting downwards:
822 ///
823 /// for (uint8_t i = 100u; i > 0; i += 127u)
824 ///
825 ///
826 /// TODO: May need to add additional parameters to represent:
827 ///
828 /// * Allow representing downcounting with unsigned integers.
829 ///
830 /// * Sign of the step and the comparison operator might disagree:
831 ///
832 /// for (int i = 0; i < 42; i -= 1u)
833 ///
834 /// \param Loc The insert and source location description.
835 /// \param Start Value of the loop counter for the first iterations.
836 /// \param Stop Loop counter values past this will stop the loop.
837 /// \param Step Loop counter increment after each iteration; negative
838 /// means counting down.
839 /// \param IsSigned Whether Start, Stop and Step are signed integers.
840 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
841 /// counter.
842 /// \param Name Base name used to derive instruction names.
843 ///
844 /// \returns The value holding the calculated trip count.
845 LLVM_ABI Value *calculateCanonicalLoopTripCount(
846 const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step,
847 bool IsSigned, bool InclusiveStop, const Twine &Name = "loop");
848
849 /// Generator for the control flow structure of an OpenMP canonical loop.
850 ///
851 /// Instead of a logical iteration space, this allows specifying user-defined
852 /// loop counter values using increment, upper- and lower bounds. To
853 /// disambiguate the terminology when counting downwards, instead of lower
854 /// bounds we use \p Start for the loop counter value in the first body
855 ///
856 /// It calls \see calculateCanonicalLoopTripCount for trip count calculations,
857 /// so limitations of that method apply here as well.
858 ///
859 /// \param Loc The insert and source location description.
860 /// \param BodyGenCB Callback that will generate the loop body code.
861 /// \param Start Value of the loop counter for the first iterations.
862 /// \param Stop Loop counter values past this will stop the loop.
863 /// \param Step Loop counter increment after each iteration; negative
864 /// means counting down.
865 /// \param IsSigned Whether Start, Stop and Step are signed integers.
866 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
867 /// counter.
868 /// \param ComputeIP Insertion point for instructions computing the trip
869 /// count. Can be used to ensure the trip count is available
870 /// at the outermost loop of a loop nest. If not set,
871 /// defaults to the preheader of the generated loop.
872 /// \param Name Base name used to derive BB and instruction names.
873 /// \param InScan Whether loop has a scan reduction specified.
874 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
875 /// `ScanInfoInitialize`.
876 ///
877 /// \returns An object representing the created control flow structure which
878 /// can be used for loop-associated directives.
879 LLVM_ABI Expected<CanonicalLoopInfo *> createCanonicalLoop(
880 const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
881 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
882 InsertPointTy ComputeIP = {}, const Twine &Name = "loop",
883 bool InScan = false, ScanInfo *ScanRedInfo = nullptr);
884
885 /// Collapse a loop nest into a single loop.
886 ///
887 /// Merges loops of a loop nest into a single CanonicalLoopNest representation
888 /// that has the same number of innermost loop iterations as the origin loop
889 /// nest. The induction variables of the input loops are derived from the
890 /// collapsed loop's induction variable. This is intended to be used to
891 /// implement OpenMP's collapse clause. Before applying a directive,
892 /// collapseLoops normalizes a loop nest to contain only a single loop and the
893 /// directive's implementation does not need to handle multiple loops itself.
894 /// This does not remove the need to handle all loop nest handling by
895 /// directives, such as the ordered(<n>) clause or the simd schedule-clause
896 /// modifier of the worksharing-loop directive.
897 ///
898 /// Example:
899 /// \code
900 /// for (int i = 0; i < 7; ++i) // Canonical loop "i"
901 /// for (int j = 0; j < 9; ++j) // Canonical loop "j"
902 /// body(i, j);
903 /// \endcode
904 ///
905 /// After collapsing with Loops={i,j}, the loop is changed to
906 /// \code
907 /// for (int ij = 0; ij < 63; ++ij) {
908 /// int i = ij / 9;
909 /// int j = ij % 9;
910 /// body(i, j);
911 /// }
912 /// \endcode
913 ///
914 /// In the current implementation, the following limitations apply:
915 ///
916 /// * All input loops have an induction variable of the same type.
917 ///
918 /// * The collapsed loop will have the same trip count integer type as the
919 /// input loops. Therefore it is possible that the collapsed loop cannot
920 /// represent all iterations of the input loops. For instance, assuming a
921 /// 32 bit integer type, and two input loops both iterating 2^16 times, the
922 /// theoretical trip count of the collapsed loop would be 2^32 iteration,
923 /// which cannot be represented in an 32-bit integer. Behavior is undefined
924 /// in this case.
925 ///
926 /// * The trip counts of every input loop must be available at \p ComputeIP.
927 /// Non-rectangular loops are not yet supported.
928 ///
929 /// * At each nest level, code between a surrounding loop and its nested loop
930 /// is hoisted into the loop body, and such code will be executed more
931 /// often than before collapsing (or not at all if any inner loop iteration
932 /// has a trip count of 0). This is permitted by the OpenMP specification.
933 ///
934 /// \param DL Debug location for instructions added for collapsing,
935 /// such as instructions to compute/derive the input loop's
936 /// induction variables.
937 /// \param Loops Loops in the loop nest to collapse. Loops are specified
938 /// from outermost-to-innermost and every control flow of a
939 /// loop's body must pass through its directly nested loop.
940 /// \param ComputeIP Where additional instruction that compute the collapsed
941 /// trip count. If not set, defaults to before the generated
942 /// loop.
943 ///
944 /// \returns The CanonicalLoopInfo object representing the collapsed loop.
945 LLVM_ABI CanonicalLoopInfo *collapseLoops(DebugLoc DL,
946 ArrayRef<CanonicalLoopInfo *> Loops,
947 InsertPointTy ComputeIP);
948
949 /// Get the default alignment value for given target
950 ///
951 /// \param TargetTriple Target triple
952 /// \param Features StringMap which describes extra CPU features
953 LLVM_ABI static unsigned
954 getOpenMPDefaultSimdAlign(const Triple &TargetTriple,
955 const StringMap<bool> &Features);
956
957 /// Retrieve (or create if non-existent) the address of a declare
958 /// target variable, used in conjunction with registerTargetGlobalVariable
959 /// to create declare target global variables.
960 ///
961 /// \param CaptureClause - enumerator corresponding to the OpenMP capture
962 /// clause used in conjunction with the variable being registered (link,
963 /// to, enter).
964 /// \param DeviceClause - enumerator corresponding to the OpenMP capture
965 /// clause used in conjunction with the variable being registered (nohost,
966 /// host, any)
967 /// \param IsDeclaration - boolean stating if the variable being registered
968 /// is a declaration-only and not a definition
969 /// \param IsExternallyVisible - boolean stating if the variable is externally
970 /// visible
971 /// \param EntryInfo - Unique entry information for the value generated
972 /// using getTargetEntryUniqueInfo, used to name generated pointer references
973 /// to the declare target variable
974 /// \param MangledName - the mangled name of the variable being registered
975 /// \param GeneratedRefs - references generated by invocations of
976 /// registerTargetGlobalVariable invoked from getAddrOfDeclareTargetVar,
977 /// these are required by Clang for book keeping.
978 /// \param OpenMPSIMD - if OpenMP SIMD mode is currently enabled
979 /// \param TargetTriple - The OpenMP device target triple we are compiling
980 /// for
981 /// \param LlvmPtrTy - The type of the variable we are generating or
982 /// retrieving an address for
983 /// \param GlobalInitializer - a lambda function which creates a constant
984 /// used for initializing a pointer reference to the variable in certain
985 /// cases. If a nullptr is passed, it will default to utilising the original
986 /// variable to initialize the pointer reference.
987 /// \param VariableLinkage - a lambda function which returns the variables
988 /// linkage type, if unspecified and a nullptr is given, it will instead
989 /// utilise the linkage stored on the existing global variable in the
990 /// LLVMModule.
991 LLVM_ABI Constant *getAddrOfDeclareTargetVar(
992 OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause,
993 OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause,
994 bool IsDeclaration, bool IsExternallyVisible,
995 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
996 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
997 std::vector<Triple> TargetTriple, Type *LlvmPtrTy,
998 std::function<Constant *()> GlobalInitializer,
999 std::function<GlobalValue::LinkageTypes()> VariableLinkage);
1000
1001 /// Registers a target variable for device or host.
1002 ///
1003 /// \param CaptureClause - enumerator corresponding to the OpenMP capture
1004 /// clause used in conjunction with the variable being registered (link,
1005 /// to, enter).
1006 /// \param DeviceClause - enumerator corresponding to the OpenMP capture
1007 /// clause used in conjunction with the variable being registered (nohost,
1008 /// host, any)
1009 /// \param IsDeclaration - boolean stating if the variable being registered
1010 /// is a declaration-only and not a definition
1011 /// \param IsExternallyVisible - boolean stating if the variable is externally
1012 /// visible
1013 /// \param EntryInfo - Unique entry information for the value generated
1014 /// using getTargetEntryUniqueInfo, used to name generated pointer references
1015 /// to the declare target variable
1016 /// \param MangledName - the mangled name of the variable being registered
1017 /// \param GeneratedRefs - references generated by invocations of
1018 /// registerTargetGlobalVariable these are required by Clang for book
1019 /// keeping.
1020 /// \param OpenMPSIMD - if OpenMP SIMD mode is currently enabled
1021 /// \param TargetTriple - The OpenMP device target triple we are compiling
1022 /// for
1023 /// \param GlobalInitializer - a lambda function which creates a constant
1024 /// used for initializing a pointer reference to the variable in certain
1025 /// cases. If a nullptr is passed, it will default to utilising the original
1026 /// variable to initialize the pointer reference.
1027 /// \param VariableLinkage - a lambda function which returns the variables
1028 /// linkage type, if unspecified and a nullptr is given, it will instead
1029 /// utilise the linkage stored on the existing global variable in the
1030 /// LLVMModule.
1031 /// \param LlvmPtrTy - The type of the variable we are generating or
1032 /// retrieving an address for
1033 /// \param Addr - the original llvm value (addr) of the variable to be
1034 /// registered
1035 LLVM_ABI void registerTargetGlobalVariable(
1036 OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause,
1037 OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause,
1038 bool IsDeclaration, bool IsExternallyVisible,
1039 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
1040 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
1041 std::vector<Triple> TargetTriple,
1042 std::function<Constant *()> GlobalInitializer,
1043 std::function<GlobalValue::LinkageTypes()> VariableLinkage,
1044 Type *LlvmPtrTy, Constant *Addr);
1045
1046 /// Get the offset of the OMP_MAP_MEMBER_OF field.
1047 LLVM_ABI unsigned getFlagMemberOffset();
1048
1049 /// Get OMP_MAP_MEMBER_OF flag with extra bits reserved based on
1050 /// the position given.
1051 /// \param Position - A value indicating the position of the parent
1052 /// of the member in the kernel argument structure, often retrieved
1053 /// by the parents position in the combined information vectors used
1054 /// to generate the structure itself. Multiple children (member's of)
1055 /// with the same parent will use the same returned member flag.
1056 LLVM_ABI omp::OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position);
1057
1058 /// Given an initial flag set, this function modifies it to contain
1059 /// the passed in MemberOfFlag generated from the getMemberOfFlag
1060 /// function. The results are dependent on the existing flag bits
1061 /// set in the original flag set.
1062 /// \param Flags - The original set of flags to be modified with the
1063 /// passed in MemberOfFlag.
1064 /// \param MemberOfFlag - A modified OMP_MAP_MEMBER_OF flag, adjusted
1065 /// slightly based on the getMemberOfFlag which adjusts the flag bits
1066 /// based on the members position in its parent.
1067 LLVM_ABI void
1068 setCorrectMemberOfFlag(omp::OpenMPOffloadMappingFlags &Flags,
1069 omp::OpenMPOffloadMappingFlags MemberOfFlag);
1070
1071private:
1072 /// Modifies the canonical loop to be a statically-scheduled workshare loop
1073 /// which is executed on the device
1074 ///
1075 /// This takes a \p CLI representing a canonical loop, such as the one
1076 /// created by \see createCanonicalLoop and emits additional instructions to
1077 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1078 /// runtime function in the preheader to call OpenMP device rtl function
1079 /// which handles worksharing of loop body interations.
1080 ///
1081 /// \param DL Debug location for instructions added for the
1082 /// workshare-loop construct itself.
1083 /// \param CLI A descriptor of the canonical loop to workshare.
1084 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1085 /// preheader of the loop.
1086 /// \param LoopType Information about type of loop worksharing.
1087 /// It corresponds to type of loop workshare OpenMP pragma.
1088 /// \param NoLoop If true, no-loop code is generated.
1089 ///
1090 /// \returns Point where to insert code after the workshare construct.
1091 InsertPointTy applyWorkshareLoopTarget(DebugLoc DL, CanonicalLoopInfo *CLI,
1092 InsertPointTy AllocaIP,
1093 omp::WorksharingLoopType LoopType,
1094 bool NoLoop);
1095
1096 /// Modifies the canonical loop to be a statically-scheduled workshare loop.
1097 ///
1098 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1099 /// created by \p createCanonicalLoop and emits additional instructions to
1100 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1101 /// runtime function in the preheader to obtain the loop bounds to be used in
1102 /// the current thread, updates the relevant instructions in the canonical
1103 /// loop and calls to an OpenMP runtime finalization function after the loop.
1104 ///
1105 /// \param DL Debug location for instructions added for the
1106 /// workshare-loop construct itself.
1107 /// \param CLI A descriptor of the canonical loop to workshare.
1108 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1109 /// preheader of the loop.
1110 /// \param NeedsBarrier Indicates whether a barrier must be inserted after
1111 /// the loop.
1112 /// \param LoopType Type of workshare loop.
1113 ///
1114 /// \returns Point where to insert code after the workshare construct.
1115 InsertPointOrErrorTy applyStaticWorkshareLoop(
1116 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
1117 omp::WorksharingLoopType LoopType, bool NeedsBarrier);
1118
1119 /// Modifies the canonical loop a statically-scheduled workshare loop with a
1120 /// user-specified chunk size.
1121 ///
1122 /// \param DL Debug location for instructions added for the
1123 /// workshare-loop construct itself.
1124 /// \param CLI A descriptor of the canonical loop to workshare.
1125 /// \param AllocaIP An insertion point for Alloca instructions usable in
1126 /// the preheader of the loop.
1127 /// \param NeedsBarrier Indicates whether a barrier must be inserted after the
1128 /// loop.
1129 /// \param ChunkSize The user-specified chunk size.
1130 ///
1131 /// \returns Point where to insert code after the workshare construct.
1132 InsertPointOrErrorTy applyStaticChunkedWorkshareLoop(DebugLoc DL,
1133 CanonicalLoopInfo *CLI,
1134 InsertPointTy AllocaIP,
1135 bool NeedsBarrier,
1136 Value *ChunkSize);
1137
1138 /// Modifies the canonical loop to be a dynamically-scheduled workshare loop.
1139 ///
1140 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1141 /// created by \p createCanonicalLoop and emits additional instructions to
1142 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1143 /// runtime function in the preheader to obtain, and then in each iteration
1144 /// to update the loop counter.
1145 ///
1146 /// \param DL Debug location for instructions added for the
1147 /// workshare-loop construct itself.
1148 /// \param CLI A descriptor of the canonical loop to workshare.
1149 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1150 /// preheader of the loop.
1151 /// \param SchedType Type of scheduling to be passed to the init function.
1152 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
1153 /// the loop.
1154 /// \param Chunk The size of loop chunk considered as a unit when
1155 /// scheduling. If \p nullptr, defaults to 1.
1156 ///
1157 /// \returns Point where to insert code after the workshare construct.
1158 InsertPointOrErrorTy applyDynamicWorkshareLoop(DebugLoc DL,
1159 CanonicalLoopInfo *CLI,
1160 InsertPointTy AllocaIP,
1161 omp::OMPScheduleType SchedType,
1162 bool NeedsBarrier,
1163 Value *Chunk = nullptr);
1164
1165 /// Create alternative version of the loop to support if clause
1166 ///
1167 /// OpenMP if clause can require to generate second loop. This loop
1168 /// will be executed when if clause condition is not met. createIfVersion
1169 /// adds branch instruction to the copied loop if \p ifCond is not met.
1170 ///
1171 /// \param Loop Original loop which should be versioned.
1172 /// \param IfCond Value which corresponds to if clause condition
1173 /// \param VMap Value to value map to define relation between
1174 /// original and copied loop values and loop blocks.
1175 /// \param NamePrefix Optional name prefix for if.then if.else blocks.
1176 void createIfVersion(CanonicalLoopInfo *Loop, Value *IfCond,
1177 ValueMap<const Value *, WeakTrackingVH> &VMap,
1178 LoopAnalysis &LIA, LoopInfo &LI, llvm::Loop *L,
1179 const Twine &NamePrefix = "");
1180
1181public:
1182 /// Modifies the canonical loop to be a workshare loop.
1183 ///
1184 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1185 /// created by \p createCanonicalLoop and emits additional instructions to
1186 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1187 /// runtime function in the preheader to obtain the loop bounds to be used in
1188 /// the current thread, updates the relevant instructions in the canonical
1189 /// loop and calls to an OpenMP runtime finalization function after the loop.
1190 ///
1191 /// The concrete transformation is done by applyStaticWorkshareLoop,
1192 /// applyStaticChunkedWorkshareLoop, or applyDynamicWorkshareLoop, depending
1193 /// on the value of \p SchedKind and \p ChunkSize.
1194 ///
1195 /// \param DL Debug location for instructions added for the
1196 /// workshare-loop construct itself.
1197 /// \param CLI A descriptor of the canonical loop to workshare.
1198 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1199 /// preheader of the loop.
1200 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
1201 /// the loop.
1202 /// \param SchedKind Scheduling algorithm to use.
1203 /// \param ChunkSize The chunk size for the inner loop.
1204 /// \param HasSimdModifier Whether the simd modifier is present in the
1205 /// schedule clause.
1206 /// \param HasMonotonicModifier Whether the monotonic modifier is present in
1207 /// the schedule clause.
1208 /// \param HasNonmonotonicModifier Whether the nonmonotonic modifier is
1209 /// present in the schedule clause.
1210 /// \param HasOrderedClause Whether the (parameterless) ordered clause is
1211 /// present.
1212 /// \param LoopType Information about type of loop worksharing.
1213 /// It corresponds to type of loop workshare OpenMP pragma.
1214 /// \param NoLoop If true, no-loop code is generated.
1215 ///
1216 /// \returns Point where to insert code after the workshare construct.
1217 LLVM_ABI InsertPointOrErrorTy applyWorkshareLoop(
1218 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
1219 bool NeedsBarrier,
1220 llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default,
1221 Value *ChunkSize = nullptr, bool HasSimdModifier = false,
1222 bool HasMonotonicModifier = false, bool HasNonmonotonicModifier = false,
1223 bool HasOrderedClause = false,
1224 omp::WorksharingLoopType LoopType =
1225 omp::WorksharingLoopType::ForStaticLoop,
1226 bool NoLoop = false);
1227
1228 /// Tile a loop nest.
1229 ///
1230 /// Tiles the loops of \p Loops by the tile sizes in \p TileSizes. Loops in
1231 /// \p/ Loops must be perfectly nested, from outermost to innermost loop
1232 /// (i.e. Loops.front() is the outermost loop). The trip count llvm::Value
1233 /// of every loop and every tile sizes must be usable in the outermost
1234 /// loop's preheader. This implies that the loop nest is rectangular.
1235 ///
1236 /// Example:
1237 /// \code
1238 /// for (int i = 0; i < 15; ++i) // Canonical loop "i"
1239 /// for (int j = 0; j < 14; ++j) // Canonical loop "j"
1240 /// body(i, j);
1241 /// \endcode
1242 ///
1243 /// After tiling with Loops={i,j} and TileSizes={5,7}, the loop is changed to
1244 /// \code
1245 /// for (int i1 = 0; i1 < 3; ++i1)
1246 /// for (int j1 = 0; j1 < 2; ++j1)
1247 /// for (int i2 = 0; i2 < 5; ++i2)
1248 /// for (int j2 = 0; j2 < 7; ++j2)
1249 /// body(i1*3+i2, j1*3+j2);
1250 /// \endcode
1251 ///
1252 /// The returned vector are the loops {i1,j1,i2,j2}. The loops i1 and j1 are
1253 /// referred to the floor, and the loops i2 and j2 are the tiles. Tiling also
1254 /// handles non-constant trip counts, non-constant tile sizes and trip counts
1255 /// that are not multiples of the tile size. In the latter case the tile loop
1256 /// of the last floor-loop iteration will have fewer iterations than specified
1257 /// as its tile size.
1258 ///
1259 ///
1260 /// @param DL Debug location for instructions added by tiling, for
1261 /// instance the floor- and tile trip count computation.
1262 /// @param Loops Loops to tile. The CanonicalLoopInfo objects are
1263 /// invalidated by this method, i.e. should not used after
1264 /// tiling.
1265 /// @param TileSizes For each loop in \p Loops, the tile size for that
1266 /// dimensions.
1267 ///
1268 /// \returns A list of generated loops. Contains twice as many loops as the
1269 /// input loop nest; the first half are the floor loops and the
1270 /// second half are the tile loops.
1271 LLVM_ABI std::vector<CanonicalLoopInfo *>
1272 tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
1273 ArrayRef<Value *> TileSizes);
1274
1275 /// Fully unroll a loop.
1276 ///
1277 /// Instead of unrolling the loop immediately (and duplicating its body
1278 /// instructions), it is deferred to LLVM's LoopUnrollPass by adding loop
1279 /// metadata.
1280 ///
1281 /// \param DL Debug location for instructions added by unrolling.
1282 /// \param Loop The loop to unroll. The loop will be invalidated.
1283 LLVM_ABI void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop);
1284
1285 /// Fully or partially unroll a loop. How the loop is unrolled is determined
1286 /// using LLVM's LoopUnrollPass.
1287 ///
1288 /// \param DL Debug location for instructions added by unrolling.
1289 /// \param Loop The loop to unroll. The loop will be invalidated.
1290 LLVM_ABI void unrollLoopHeuristic(DebugLoc DL, CanonicalLoopInfo *Loop);
1291
1292 /// Partially unroll a loop.
1293 ///
1294 /// The CanonicalLoopInfo of the unrolled loop for use with chained
1295 /// loop-associated directive can be requested using \p UnrolledCLI. Not
1296 /// needing the CanonicalLoopInfo allows more efficient code generation by
1297 /// deferring the actual unrolling to the LoopUnrollPass using loop metadata.
1298 /// A loop-associated directive applied to the unrolled loop needs to know the
1299 /// new trip count which means that if using a heuristically determined unroll
1300 /// factor (\p Factor == 0), that factor must be computed immediately. We are
1301 /// using the same logic as the LoopUnrollPass to derived the unroll factor,
1302 /// but which assumes that some canonicalization has taken place (e.g.
1303 /// Mem2Reg, LICM, GVN, Inlining, etc.). That is, the heuristic will perform
1304 /// better when the unrolled loop's CanonicalLoopInfo is not needed.
1305 ///
1306 /// \param DL Debug location for instructions added by unrolling.
1307 /// \param Loop The loop to unroll. The loop will be invalidated.
1308 /// \param Factor The factor to unroll the loop by. A factor of 0
1309 /// indicates that a heuristic should be used to determine
1310 /// the unroll-factor.
1311 /// \param UnrolledCLI If non-null, receives the CanonicalLoopInfo of the
1312 /// partially unrolled loop. Otherwise, uses loop metadata
1313 /// to defer unrolling to the LoopUnrollPass.
1314 LLVM_ABI void unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,
1315 int32_t Factor,
1316 CanonicalLoopInfo **UnrolledCLI);
1317
1318 /// Add metadata to simd-ize a loop. If IfCond is not nullptr, the loop
1319 /// is cloned. The metadata which prevents vectorization is added to
1320 /// to the cloned loop. The cloned loop is executed when ifCond is evaluated
1321 /// to false.
1322 ///
1323 /// \param Loop The loop to simd-ize.
1324 /// \param AlignedVars The map which containts pairs of the pointer
1325 /// and its corresponding alignment.
1326 /// \param IfCond The value which corresponds to the if clause
1327 /// condition.
1328 /// \param Order The enum to map order clause.
1329 /// \param Simdlen The Simdlen length to apply to the simd loop.
1330 /// \param Safelen The Safelen length to apply to the simd loop.
1331 LLVM_ABI void applySimd(CanonicalLoopInfo *Loop,
1332 MapVector<Value *, Value *> AlignedVars,
1333 Value *IfCond, omp::OrderKind Order,
1334 ConstantInt *Simdlen, ConstantInt *Safelen);
1335
1336 /// Generator for '#omp flush'
1337 ///
1338 /// \param Loc The location where the flush directive was encountered
1339 LLVM_ABI void createFlush(const LocationDescription &Loc);
1340
1341 /// Generator for '#omp taskwait'
1342 ///
1343 /// \param Loc The location where the taskwait directive was encountered.
1344 LLVM_ABI void createTaskwait(const LocationDescription &Loc);
1345
1346 /// Generator for '#omp taskyield'
1347 ///
1348 /// \param Loc The location where the taskyield directive was encountered.
1349 LLVM_ABI void createTaskyield(const LocationDescription &Loc);
1350
1351 /// A struct to pack the relevant information for an OpenMP depend clause.
1352 struct DependData {
1353 omp::RTLDependenceKindTy DepKind = omp::RTLDependenceKindTy::DepUnknown;
1354 Type *DepValueType;
1355 Value *DepVal;
1356 explicit DependData() = default;
1357 DependData(omp::RTLDependenceKindTy DepKind, Type *DepValueType,
1358 Value *DepVal)
1359 : DepKind(DepKind), DepValueType(DepValueType), DepVal(DepVal) {}
1360 };
1361
1362 /// Generator for `#omp task`
1363 ///
1364 /// \param Loc The location where the task construct was encountered.
1365 /// \param AllocaIP The insertion point to be used for alloca instructions.
1366 /// \param BodyGenCB Callback that will generate the region code.
1367 /// \param Tied True if the task is tied, false if the task is untied.
1368 /// \param Final i1 value which is `true` if the task is final, `false` if the
1369 /// task is not final.
1370 /// \param IfCondition i1 value. If it evaluates to `false`, an undeferred
1371 /// task is generated, and the encountering thread must
1372 /// suspend the current task region, for which execution
1373 /// cannot be resumed until execution of the structured
1374 /// block that is associated with the generated task is
1375 /// completed.
1376 /// \param EventHandle If present, signifies the event handle as part of
1377 /// the detach clause
1378 /// \param Mergeable If the given task is `mergeable`
1379 /// \param priority `priority-value' specifies the execution order of the
1380 /// tasks that is generated by the construct
1381 LLVM_ABI InsertPointOrErrorTy
1382 createTask(const LocationDescription &Loc, InsertPointTy AllocaIP,
1383 BodyGenCallbackTy BodyGenCB, bool Tied = true,
1384 Value *Final = nullptr, Value *IfCondition = nullptr,
1385 SmallVector<DependData> Dependencies = {}, bool Mergeable = false,
1386 Value *EventHandle = nullptr, Value *Priority = nullptr);
1387
1388 /// Generator for the taskgroup construct
1389 ///
1390 /// \param Loc The location where the taskgroup construct was encountered.
1391 /// \param AllocaIP The insertion point to be used for alloca instructions.
1392 /// \param BodyGenCB Callback that will generate the region code.
1393 LLVM_ABI InsertPointOrErrorTy createTaskgroup(const LocationDescription &Loc,
1394 InsertPointTy AllocaIP,
1395 BodyGenCallbackTy BodyGenCB);
1396
1397 using FileIdentifierInfoCallbackTy =
1398 std::function<std::tuple<std::string, uint64_t>()>;
1399
1400 /// Creates a unique info for a target entry when provided a filename and
1401 /// line number from.
1402 ///
1403 /// \param CallBack A callback function which should return filename the entry
1404 /// resides in as well as the line number for the target entry
1405 /// \param ParentName The name of the parent the target entry resides in, if
1406 /// any.
1407 LLVM_ABI static TargetRegionEntryInfo
1408 getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack,
1409 StringRef ParentName = "");
1410
1411 /// Enum class for the RedctionGen CallBack type to be used.
1412 enum class ReductionGenCBKind { Clang, MLIR };
1413
1414 /// ReductionGen CallBack for Clang
1415 ///
1416 /// \param CodeGenIP InsertPoint for CodeGen.
1417 /// \param Index Index of the ReductionInfo to generate code for.
1418 /// \param LHSPtr Optionally used by Clang to return the LHSPtr it used for
1419 /// codegen, used for fixup later.
1420 /// \param RHSPtr Optionally used by Clang to
1421 /// return the RHSPtr it used for codegen, used for fixup later.
1422 /// \param CurFn Optionally used by Clang to pass in the Current Function as
1423 /// Clang context may be old.
1424 using ReductionGenClangCBTy =
1425 std::function<InsertPointTy(InsertPointTy CodeGenIP, unsigned Index,
1426 Value **LHS, Value **RHS, Function *CurFn)>;
1427
1428 /// ReductionGen CallBack for MLIR
1429 ///
1430 /// \param CodeGenIP InsertPoint for CodeGen.
1431 /// \param LHS Pass in the LHS Value to be used for CodeGen.
1432 /// \param RHS Pass in the RHS Value to be used for CodeGen.
1433 using ReductionGenCBTy = std::function<InsertPointOrErrorTy(
1434 InsertPointTy CodeGenIP, Value *LHS, Value *RHS, Value *&Res)>;
1435
1436 /// Functions used to generate atomic reductions. Such functions take two
1437 /// Values representing pointers to LHS and RHS of the reduction, as well as
1438 /// the element type of these pointers. They are expected to atomically
1439 /// update the LHS to the reduced value.
1440 using ReductionGenAtomicCBTy = std::function<InsertPointOrErrorTy(
1441 InsertPointTy, Type *, Value *, Value *)>;
1442
1443 /// Enum class for reduction evaluation types scalar, complex and aggregate.
1444 enum class EvalKind { Scalar, Complex, Aggregate };
1445
1446 /// Information about an OpenMP reduction.
1447 struct ReductionInfo {
1448 ReductionInfo(Type *ElementType, Value *Variable, Value *PrivateVariable,
1449 EvalKind EvaluationKind, ReductionGenCBTy ReductionGen,
1450 ReductionGenClangCBTy ReductionGenClang,
1451 ReductionGenAtomicCBTy AtomicReductionGen)
1453 PrivateVariable(PrivateVariable), EvaluationKind(EvaluationKind),
1454 ReductionGen(ReductionGen), ReductionGenClang(ReductionGenClang),
1455 AtomicReductionGen(AtomicReductionGen) {}
1456 ReductionInfo(Value *PrivateVariable)
1457 : ElementType(nullptr), Variable(nullptr),
1458 PrivateVariable(PrivateVariable), EvaluationKind(EvalKind::Scalar),
1459 ReductionGen(), ReductionGenClang(), AtomicReductionGen() {}
1460
1461 /// Reduction element type, must match pointee type of variable.
1463
1464 /// Reduction variable of pointer type.
1465 Value *Variable;
1466
1467 /// Thread-private partial reduction variable.
1468 Value *PrivateVariable;
1469
1470 /// Reduction evaluation kind - scalar, complex or aggregate.
1471 EvalKind EvaluationKind;
1472
1473 /// Callback for generating the reduction body. The IR produced by this will
1474 /// be used to combine two values in a thread-safe context, e.g., under
1475 /// lock or within the same thread, and therefore need not be atomic.
1476 ReductionGenCBTy ReductionGen;
1477
1478 /// Clang callback for generating the reduction body. The IR produced by
1479 /// this will be used to combine two values in a thread-safe context, e.g.,
1480 /// under lock or within the same thread, and therefore need not be atomic.
1481 ReductionGenClangCBTy ReductionGenClang;
1482
1483 /// Callback for generating the atomic reduction body, may be null. The IR
1484 /// produced by this will be used to atomically combine two values during
1485 /// reduction. If null, the implementation will use the non-atomic version
1486 /// along with the appropriate synchronization mechanisms.
1487 ReductionGenAtomicCBTy AtomicReductionGen;
1488 };
1489
1490 enum class CopyAction : unsigned {
1491 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1492 // the warp using shuffle instructions.
1493 RemoteLaneToThread,
1494 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1495 ThreadCopy,
1496 };
1497
1498 struct CopyOptionsTy {
1499 Value *RemoteLaneOffset = nullptr;
1500 Value *ScratchpadIndex = nullptr;
1501 Value *ScratchpadWidth = nullptr;
1502 };
1503
1504 /// Supporting functions for Reductions CodeGen.
1505private:
1506 /// Get the id of the current thread on the GPU.
1507 Value *getGPUThreadID();
1508
1509 /// Get the GPU warp size.
1510 Value *getGPUWarpSize();
1511
1512 /// Get the id of the warp in the block.
1513 /// We assume that the warp size is 32, which is always the case
1514 /// on the NVPTX device, to generate more efficient code.
1515 Value *getNVPTXWarpID();
1516
1517 /// Get the id of the current lane in the Warp.
1518 /// We assume that the warp size is 32, which is always the case
1519 /// on the NVPTX device, to generate more efficient code.
1520 Value *getNVPTXLaneID();
1521
1522 /// Cast value to the specified type.
1523 Value *castValueToType(InsertPointTy AllocaIP, Value *From, Type *ToType);
1524
1525 /// This function creates calls to one of two shuffle functions to copy
1526 /// variables between lanes in a warp.
1527 Value *createRuntimeShuffleFunction(InsertPointTy AllocaIP, Value *Element,
1528 Type *ElementType, Value *Offset);
1529
1530 /// Function to shuffle over the value from the remote lane.
1531 void shuffleAndStore(InsertPointTy AllocaIP, Value *SrcAddr, Value *DstAddr,
1532 Type *ElementType, Value *Offset,
1533 Type *ReductionArrayTy);
1534
1535 /// Emit instructions to copy a Reduce list, which contains partially
1536 /// aggregated values, in the specified direction.
1537 void emitReductionListCopy(
1538 InsertPointTy AllocaIP, CopyAction Action, Type *ReductionArrayTy,
1539 ArrayRef<ReductionInfo> ReductionInfos, Value *SrcBase, Value *DestBase,
1540 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr});
1541
1542 /// Emit a helper that reduces data across two OpenMP threads (lanes)
1543 /// in the same warp. It uses shuffle instructions to copy over data from
1544 /// a remote lane's stack. The reduction algorithm performed is specified
1545 /// by the fourth parameter.
1546 ///
1547 /// Algorithm Versions.
1548 /// Full Warp Reduce (argument value 0):
1549 /// This algorithm assumes that all 32 lanes are active and gathers
1550 /// data from these 32 lanes, producing a single resultant value.
1551 /// Contiguous Partial Warp Reduce (argument value 1):
1552 /// This algorithm assumes that only a *contiguous* subset of lanes
1553 /// are active. This happens for the last warp in a parallel region
1554 /// when the user specified num_threads is not an integer multiple of
1555 /// 32. This contiguous subset always starts with the zeroth lane.
1556 /// Partial Warp Reduce (argument value 2):
1557 /// This algorithm gathers data from any number of lanes at any position.
1558 /// All reduced values are stored in the lowest possible lane. The set
1559 /// of problems every algorithm addresses is a super set of those
1560 /// addressable by algorithms with a lower version number. Overhead
1561 /// increases as algorithm version increases.
1562 ///
1563 /// Terminology
1564 /// Reduce element:
1565 /// Reduce element refers to the individual data field with primitive
1566 /// data types to be combined and reduced across threads.
1567 /// Reduce list:
1568 /// Reduce list refers to a collection of local, thread-private
1569 /// reduce elements.
1570 /// Remote Reduce list:
1571 /// Remote Reduce list refers to a collection of remote (relative to
1572 /// the current thread) reduce elements.
1573 ///
1574 /// We distinguish between three states of threads that are important to
1575 /// the implementation of this function.
1576 /// Alive threads:
1577 /// Threads in a warp executing the SIMT instruction, as distinguished from
1578 /// threads that are inactive due to divergent control flow.
1579 /// Active threads:
1580 /// The minimal set of threads that has to be alive upon entry to this
1581 /// function. The computation is correct iff active threads are alive.
1582 /// Some threads are alive but they are not active because they do not
1583 /// contribute to the computation in any useful manner. Turning them off
1584 /// may introduce control flow overheads without any tangible benefits.
1585 /// Effective threads:
1586 /// In order to comply with the argument requirements of the shuffle
1587 /// function, we must keep all lanes holding data alive. But at most
1588 /// half of them perform value aggregation; we refer to this half of
1589 /// threads as effective. The other half is simply handing off their
1590 /// data.
1591 ///
1592 /// Procedure
1593 /// Value shuffle:
1594 /// In this step active threads transfer data from higher lane positions
1595 /// in the warp to lower lane positions, creating Remote Reduce list.
1596 /// Value aggregation:
1597 /// In this step, effective threads combine their thread local Reduce list
1598 /// with Remote Reduce list and store the result in the thread local
1599 /// Reduce list.
1600 /// Value copy:
1601 /// In this step, we deal with the assumption made by algorithm 2
1602 /// (i.e. contiguity assumption). When we have an odd number of lanes
1603 /// active, say 2k+1, only k threads will be effective and therefore k
1604 /// new values will be produced. However, the Reduce list owned by the
1605 /// (2k+1)th thread is ignored in the value aggregation. Therefore
1606 /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
1607 /// that the contiguity assumption still holds.
1608 ///
1609 /// \param ReductionInfos Array type containing the ReductionOps.
1610 /// \param ReduceFn The reduction function.
1611 /// \param FuncAttrs Optional param to specify any function attributes that
1612 /// need to be copied to the new function.
1613 ///
1614 /// \return The ShuffleAndReduce function.
1615 Function *emitShuffleAndReduceFunction(
1616 ArrayRef<OpenMPIRBuilder::ReductionInfo> ReductionInfos,
1617 Function *ReduceFn, AttributeList FuncAttrs);
1618
1619 /// Helper function for CreateCanonicalScanLoops to create InputLoop
1620 /// in the firstGen and Scan Loop in the SecondGen
1621 /// \param InputLoopGen Callback for generating the loop for input phase
1622 /// \param ScanLoopGen Callback for generating the loop for scan phase
1623 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1624 /// `ScanInfoInitialize`.
1625 ///
1626 /// \return error if any produced, else return success.
1627 Error emitScanBasedDirectiveIR(
1628 llvm::function_ref<Error()> InputLoopGen,
1629 llvm::function_ref<Error(LocationDescription Loc)> ScanLoopGen,
1630 ScanInfo *ScanRedInfo);
1631
1632 /// Creates the basic blocks required for scan reduction.
1633 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1634 /// `ScanInfoInitialize`.
1635 void createScanBBs(ScanInfo *ScanRedInfo);
1636
1637 /// Dynamically allocates the buffer needed for scan reduction.
1638 /// \param AllocaIP The IP where possibly-shared pointer of buffer needs to
1639 /// be declared.
1640 /// \param ScanVars Scan Variables.
1641 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1642 /// `ScanInfoInitialize`.
1643 ///
1644 /// \return error if any produced, else return success.
1645 Error emitScanBasedDirectiveDeclsIR(InsertPointTy AllocaIP,
1646 ArrayRef<llvm::Value *> ScanVars,
1647 ArrayRef<llvm::Type *> ScanVarsType,
1648 ScanInfo *ScanRedInfo);
1649
1650 /// Copies the result back to the reduction variable.
1651 /// \param ReductionInfos Array type containing the ReductionOps.
1652 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1653 /// `ScanInfoInitialize`.
1654 ///
1655 /// \return error if any produced, else return success.
1656 Error emitScanBasedDirectiveFinalsIR(
1657 ArrayRef<llvm::OpenMPIRBuilder::ReductionInfo> ReductionInfos,
1658 ScanInfo *ScanInfo);
1659
1660 /// This function emits a helper that gathers Reduce lists from the first
1661 /// lane of every active warp to lanes in the first warp.
1662 ///
1663 /// void inter_warp_copy_func(void* reduce_data, num_warps)
1664 /// shared smem[warp_size];
1665 /// For all data entries D in reduce_data:
1666 /// sync
1667 /// If (I am the first lane in each warp)
1668 /// Copy my local D to smem[warp_id]
1669 /// sync
1670 /// if (I am the first warp)
1671 /// Copy smem[thread_id] to my local D
1672 ///
1673 /// \param Loc The insert and source location description.
1674 /// \param ReductionInfos Array type containing the ReductionOps.
1675 /// \param FuncAttrs Optional param to specify any function attributes that
1676 /// need to be copied to the new function.
1677 ///
1678 /// \return The InterWarpCopy function.
1679 Expected<Function *>
1680 emitInterWarpCopyFunction(const LocationDescription &Loc,
1681 ArrayRef<ReductionInfo> ReductionInfos,
1682 AttributeList FuncAttrs);
1683
1684 /// This function emits a helper that copies all the reduction variables from
1685 /// the team into the provided global buffer for the reduction variables.
1686 ///
1687 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
1688 /// For all data entries D in reduce_data:
1689 /// Copy local D to buffer.D[Idx]
1690 ///
1691 /// \param ReductionInfos Array type containing the ReductionOps.
1692 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1693 /// \param FuncAttrs Optional param to specify any function attributes that
1694 /// need to be copied to the new function.
1695 ///
1696 /// \return The ListToGlobalCopy function.
1697 Function *emitListToGlobalCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
1698 Type *ReductionsBufferTy,
1699 AttributeList FuncAttrs);
1700
1701 /// This function emits a helper that copies all the reduction variables from
1702 /// the team into the provided global buffer for the reduction variables.
1703 ///
1704 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
1705 /// For all data entries D in reduce_data:
1706 /// Copy buffer.D[Idx] to local D;
1707 ///
1708 /// \param ReductionInfos Array type containing the ReductionOps.
1709 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1710 /// \param FuncAttrs Optional param to specify any function attributes that
1711 /// need to be copied to the new function.
1712 ///
1713 /// \return The GlobalToList function.
1714 Function *emitGlobalToListCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
1715 Type *ReductionsBufferTy,
1716 AttributeList FuncAttrs);
1717
1718 /// This function emits a helper that reduces all the reduction variables from
1719 /// the team into the provided global buffer for the reduction variables.
1720 ///
1721 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
1722 /// void *GlobPtrs[];
1723 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
1724 /// ...
1725 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
1726 /// reduce_function(GlobPtrs, reduce_data);
1727 ///
1728 /// \param ReductionInfos Array type containing the ReductionOps.
1729 /// \param ReduceFn The reduction function.
1730 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1731 /// \param FuncAttrs Optional param to specify any function attributes that
1732 /// need to be copied to the new function.
1733 ///
1734 /// \return The ListToGlobalReduce function.
1735 Function *
1736 emitListToGlobalReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
1737 Function *ReduceFn, Type *ReductionsBufferTy,
1738 AttributeList FuncAttrs);
1739
1740 /// This function emits a helper that reduces all the reduction variables from
1741 /// the team into the provided global buffer for the reduction variables.
1742 ///
1743 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
1744 /// void *GlobPtrs[];
1745 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
1746 /// ...
1747 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
1748 /// reduce_function(reduce_data, GlobPtrs);
1749 ///
1750 /// \param ReductionInfos Array type containing the ReductionOps.
1751 /// \param ReduceFn The reduction function.
1752 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1753 /// \param FuncAttrs Optional param to specify any function attributes that
1754 /// need to be copied to the new function.
1755 ///
1756 /// \return The GlobalToListReduce function.
1757 Function *
1758 emitGlobalToListReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
1759 Function *ReduceFn, Type *ReductionsBufferTy,
1760 AttributeList FuncAttrs);
1761
1762 /// Get the function name of a reduction function.
1763 std::string getReductionFuncName(StringRef Name) const;
1764
1765 /// Emits reduction function.
1766 /// \param ReducerName Name of the function calling the reduction.
1767 /// \param ReductionInfos Array type containing the ReductionOps.
1768 /// \param ReductionGenCBKind Optional param to specify Clang or MLIR
1769 /// CodeGenCB kind.
1770 /// \param FuncAttrs Optional param to specify any function attributes that
1771 /// need to be copied to the new function.
1772 ///
1773 /// \return The reduction function.
1774 Expected<Function *> createReductionFunction(
1775 StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,
1776 ReductionGenCBKind ReductionGenCBKind = ReductionGenCBKind::MLIR,
1777 AttributeList FuncAttrs = {});
1778
1779public:
1780 ///
1781 /// Design of OpenMP reductions on the GPU
1782 ///
1783 /// Consider a typical OpenMP program with one or more reduction
1784 /// clauses:
1785 ///
1786 /// float foo;
1787 /// double bar;
1788 /// #pragma omp target teams distribute parallel for \
1789 /// reduction(+:foo) reduction(*:bar)
1790 /// for (int i = 0; i < N; i++) {
1791 /// foo += A[i]; bar *= B[i];
1792 /// }
1793 ///
1794 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
1795 /// all teams. In our OpenMP implementation on the NVPTX device an
1796 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1797 /// within a team are mapped to CUDA threads within a threadblock.
1798 /// Our goal is to efficiently aggregate values across all OpenMP
1799 /// threads such that:
1800 ///
1801 /// - the compiler and runtime are logically concise, and
1802 /// - the reduction is performed efficiently in a hierarchical
1803 /// manner as follows: within OpenMP threads in the same warp,
1804 /// across warps in a threadblock, and finally across teams on
1805 /// the NVPTX device.
1806 ///
1807 /// Introduction to Decoupling
1808 ///
1809 /// We would like to decouple the compiler and the runtime so that the
1810 /// latter is ignorant of the reduction variables (number, data types)
1811 /// and the reduction operators. This allows a simpler interface
1812 /// and implementation while still attaining good performance.
1813 ///
1814 /// Pseudocode for the aforementioned OpenMP program generated by the
1815 /// compiler is as follows:
1816 ///
1817 /// 1. Create private copies of reduction variables on each OpenMP
1818 /// thread: 'foo_private', 'bar_private'
1819 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1820 /// to it and writes the result in 'foo_private' and 'bar_private'
1821 /// respectively.
1822 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
1823 /// and store the result on the team master:
1824 ///
1825 /// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
1826 /// reduceData, shuffleReduceFn, interWarpCpyFn)
1827 ///
1828 /// where:
1829 /// struct ReduceData {
1830 /// double *foo;
1831 /// double *bar;
1832 /// } reduceData
1833 /// reduceData.foo = &foo_private
1834 /// reduceData.bar = &bar_private
1835 ///
1836 /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
1837 /// auxiliary functions generated by the compiler that operate on
1838 /// variables of type 'ReduceData'. They aid the runtime perform
1839 /// algorithmic steps in a data agnostic manner.
1840 ///
1841 /// 'shuffleReduceFn' is a pointer to a function that reduces data
1842 /// of type 'ReduceData' across two OpenMP threads (lanes) in the
1843 /// same warp. It takes the following arguments as input:
1844 ///
1845 /// a. variable of type 'ReduceData' on the calling lane,
1846 /// b. its lane_id,
1847 /// c. an offset relative to the current lane_id to generate a
1848 /// remote_lane_id. The remote lane contains the second
1849 /// variable of type 'ReduceData' that is to be reduced.
1850 /// d. an algorithm version parameter determining which reduction
1851 /// algorithm to use.
1852 ///
1853 /// 'shuffleReduceFn' retrieves data from the remote lane using
1854 /// efficient GPU shuffle intrinsics and reduces, using the
1855 /// algorithm specified by the 4th parameter, the two operands
1856 /// element-wise. The result is written to the first operand.
1857 ///
1858 /// Different reduction algorithms are implemented in different
1859 /// runtime functions, all calling 'shuffleReduceFn' to perform
1860 /// the essential reduction step. Therefore, based on the 4th
1861 /// parameter, this function behaves slightly differently to
1862 /// cooperate with the runtime to ensure correctness under
1863 /// different circumstances.
1864 ///
1865 /// 'InterWarpCpyFn' is a pointer to a function that transfers
1866 /// reduced variables across warps. It tunnels, through CUDA
1867 /// shared memory, the thread-private data of type 'ReduceData'
1868 /// from lane 0 of each warp to a lane in the first warp.
1869 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
1870 /// The last team writes the global reduced value to memory.
1871 ///
1872 /// ret = __kmpc_nvptx_teams_reduce_nowait(...,
1873 /// reduceData, shuffleReduceFn, interWarpCpyFn,
1874 /// scratchpadCopyFn, loadAndReduceFn)
1875 ///
1876 /// 'scratchpadCopyFn' is a helper that stores reduced
1877 /// data from the team master to a scratchpad array in
1878 /// global memory.
1879 ///
1880 /// 'loadAndReduceFn' is a helper that loads data from
1881 /// the scratchpad array and reduces it with the input
1882 /// operand.
1883 ///
1884 /// These compiler generated functions hide address
1885 /// calculation and alignment information from the runtime.
1886 /// 5. if ret == 1:
1887 /// The team master of the last team stores the reduced
1888 /// result to the globals in memory.
1889 /// foo += reduceData.foo; bar *= reduceData.bar
1890 ///
1891 ///
1892 /// Warp Reduction Algorithms
1893 ///
1894 /// On the warp level, we have three algorithms implemented in the
1895 /// OpenMP runtime depending on the number of active lanes:
1896 ///
1897 /// Full Warp Reduction
1898 ///
1899 /// The reduce algorithm within a warp where all lanes are active
1900 /// is implemented in the runtime as follows:
1901 ///
1902 /// full_warp_reduce(void *reduce_data,
1903 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1904 /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
1905 /// ShuffleReduceFn(reduce_data, 0, offset, 0);
1906 /// }
1907 ///
1908 /// The algorithm completes in log(2, WARPSIZE) steps.
1909 ///
1910 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
1911 /// not used therefore we save instructions by not retrieving lane_id
1912 /// from the corresponding special registers. The 4th parameter, which
1913 /// represents the version of the algorithm being used, is set to 0 to
1914 /// signify full warp reduction.
1915 ///
1916 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1917 ///
1918 /// #reduce_elem refers to an element in the local lane's data structure
1919 /// #remote_elem is retrieved from a remote lane
1920 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1921 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
1922 ///
1923 /// Contiguous Partial Warp Reduction
1924 ///
1925 /// This reduce algorithm is used within a warp where only the first
1926 /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
1927 /// number of OpenMP threads in a parallel region is not a multiple of
1928 /// WARPSIZE. The algorithm is implemented in the runtime as follows:
1929 ///
1930 /// void
1931 /// contiguous_partial_reduce(void *reduce_data,
1932 /// kmp_ShuffleReductFctPtr ShuffleReduceFn,
1933 /// int size, int lane_id) {
1934 /// int curr_size;
1935 /// int offset;
1936 /// curr_size = size;
1937 /// mask = curr_size/2;
1938 /// while (offset>0) {
1939 /// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
1940 /// curr_size = (curr_size+1)/2;
1941 /// offset = curr_size/2;
1942 /// }
1943 /// }
1944 ///
1945 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1946 ///
1947 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1948 /// if (lane_id < offset)
1949 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
1950 /// else
1951 /// reduce_elem = remote_elem
1952 ///
1953 /// This algorithm assumes that the data to be reduced are located in a
1954 /// contiguous subset of lanes starting from the first. When there is
1955 /// an odd number of active lanes, the data in the last lane is not
1956 /// aggregated with any other lane's dat but is instead copied over.
1957 ///
1958 /// Dispersed Partial Warp Reduction
1959 ///
1960 /// This algorithm is used within a warp when any discontiguous subset of
1961 /// lanes are active. It is used to implement the reduction operation
1962 /// across lanes in an OpenMP simd region or in a nested parallel region.
1963 ///
1964 /// void
1965 /// dispersed_partial_reduce(void *reduce_data,
1966 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1967 /// int size, remote_id;
1968 /// int logical_lane_id = number_of_active_lanes_before_me() * 2;
1969 /// do {
1970 /// remote_id = next_active_lane_id_right_after_me();
1971 /// # the above function returns 0 of no active lane
1972 /// # is present right after the current lane.
1973 /// size = number_of_active_lanes_in_this_warp();
1974 /// logical_lane_id /= 2;
1975 /// ShuffleReduceFn(reduce_data, logical_lane_id,
1976 /// remote_id-1-threadIdx.x, 2);
1977 /// } while (logical_lane_id % 2 == 0 && size > 1);
1978 /// }
1979 ///
1980 /// There is no assumption made about the initial state of the reduction.
1981 /// Any number of lanes (>=1) could be active at any position. The reduction
1982 /// result is returned in the first active lane.
1983 ///
1984 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1985 ///
1986 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1987 /// if (lane_id % 2 == 0 && offset > 0)
1988 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
1989 /// else
1990 /// reduce_elem = remote_elem
1991 ///
1992 ///
1993 /// Intra-Team Reduction
1994 ///
1995 /// This function, as implemented in the runtime call
1996 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
1997 /// threads in a team. It first reduces within a warp using the
1998 /// aforementioned algorithms. We then proceed to gather all such
1999 /// reduced values at the first warp.
2000 ///
2001 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
2002 /// data from each of the "warp master" (zeroth lane of each warp, where
2003 /// warp-reduced data is held) to the zeroth warp. This step reduces (in
2004 /// a mathematical sense) the problem of reduction across warp masters in
2005 /// a block to the problem of warp reduction.
2006 ///
2007 ///
2008 /// Inter-Team Reduction
2009 ///
2010 /// Once a team has reduced its data to a single value, it is stored in
2011 /// a global scratchpad array. Since each team has a distinct slot, this
2012 /// can be done without locking.
2013 ///
2014 /// The last team to write to the scratchpad array proceeds to reduce the
2015 /// scratchpad array. One or more workers in the last team use the helper
2016 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2017 /// the k'th worker reduces every k'th element.
2018 ///
2019 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
2020 /// reduce across workers and compute a globally reduced value.
2021 ///
2022 /// \param Loc The location where the reduction was
2023 /// encountered. Must be within the associate
2024 /// directive and after the last local access to the
2025 /// reduction variables.
2026 /// \param AllocaIP An insertion point suitable for allocas usable
2027 /// in reductions.
2028 /// \param CodeGenIP An insertion point suitable for code
2029 /// generation. \param ReductionInfos A list of info on each reduction
2030 /// variable. \param IsNoWait Optional flag set if the reduction is
2031 /// marked as
2032 /// nowait.
2033 /// \param IsTeamsReduction Optional flag set if it is a teams
2034 /// reduction.
2035 /// \param GridValue Optional GPU grid value.
2036 /// \param ReductionBufNum Optional OpenMPCUDAReductionBufNumValue to be
2037 /// used for teams reduction.
2038 /// \param SrcLocInfo Source location information global.
2039 LLVM_ABI InsertPointOrErrorTy createReductionsGPU(
2040 const LocationDescription &Loc, InsertPointTy AllocaIP,
2041 InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,
2042 bool IsNoWait = false, bool IsTeamsReduction = false,
2043 ReductionGenCBKind ReductionGenCBKind = ReductionGenCBKind::MLIR,
2044 std::optional<omp::GV> GridValue = {}, unsigned ReductionBufNum = 1024,
2045 Value *SrcLocInfo = nullptr);
2046
2047 // TODO: provide atomic and non-atomic reduction generators for reduction
2048 // operators defined by the OpenMP specification.
2049
2050 /// Generator for '#omp reduction'.
2051 ///
2052 /// Emits the IR instructing the runtime to perform the specific kind of
2053 /// reductions. Expects reduction variables to have been privatized and
2054 /// initialized to reduction-neutral values separately. Emits the calls to
2055 /// runtime functions as well as the reduction function and the basic blocks
2056 /// performing the reduction atomically and non-atomically.
2057 ///
2058 /// The code emitted for the following:
2059 ///
2060 /// \code
2061 /// type var_1;
2062 /// type var_2;
2063 /// #pragma omp <directive> reduction(reduction-op:var_1,var_2)
2064 /// /* body */;
2065 /// \endcode
2066 ///
2067 /// corresponds to the following sketch.
2068 ///
2069 /// \code
2070 /// void _outlined_par() {
2071 /// // N is the number of different reductions.
2072 /// void *red_array[] = {privatized_var_1, privatized_var_2, ...};
2073 /// switch(__kmpc_reduce(..., N, /*size of data in red array*/, red_array,
2074 /// _omp_reduction_func,
2075 /// _gomp_critical_user.reduction.var)) {
2076 /// case 1: {
2077 /// var_1 = var_1 <reduction-op> privatized_var_1;
2078 /// var_2 = var_2 <reduction-op> privatized_var_2;
2079 /// // ...
2080 /// __kmpc_end_reduce(...);
2081 /// break;
2082 /// }
2083 /// case 2: {
2084 /// _Atomic<ReductionOp>(var_1, privatized_var_1);
2085 /// _Atomic<ReductionOp>(var_2, privatized_var_2);
2086 /// // ...
2087 /// break;
2088 /// }
2089 /// default: break;
2090 /// }
2091 /// }
2092 ///
2093 /// void _omp_reduction_func(void **lhs, void **rhs) {
2094 /// *(type *)lhs[0] = *(type *)lhs[0] <reduction-op> *(type *)rhs[0];
2095 /// *(type *)lhs[1] = *(type *)lhs[1] <reduction-op> *(type *)rhs[1];
2096 /// // ...
2097 /// }
2098 /// \endcode
2099 ///
2100 /// \param Loc The location where the reduction was
2101 /// encountered. Must be within the associate
2102 /// directive and after the last local access to the
2103 /// reduction variables.
2104 /// \param AllocaIP An insertion point suitable for allocas usable
2105 /// in reductions.
2106 /// \param ReductionInfos A list of info on each reduction variable.
2107 /// \param IsNoWait A flag set if the reduction is marked as nowait.
2108 /// \param IsByRef A flag set if the reduction is using reference
2109 /// or direct value.
2110 /// \param IsTeamsReduction Optional flag set if it is a teams
2111 /// reduction.
2112 LLVM_ABI InsertPointOrErrorTy createReductions(
2113 const LocationDescription &Loc, InsertPointTy AllocaIP,
2114 ArrayRef<ReductionInfo> ReductionInfos, ArrayRef<bool> IsByRef,
2115 bool IsNoWait = false, bool IsTeamsReduction = false);
2116
2117 ///}
2118
2119 /// Return the insertion point used by the underlying IRBuilder.
2120 InsertPointTy getInsertionPoint() { return Builder.saveIP(); }
2121
2122 /// Update the internal location to \p Loc.
2123 bool updateToLocation(const LocationDescription &Loc) {
2124 Builder.restoreIP(Loc.IP);
2125 Builder.SetCurrentDebugLocation(Loc.DL);
2126 return Loc.IP.getBlock() != nullptr;
2127 }
2128
2129 /// Return the function declaration for the runtime function with \p FnID.
2130 LLVM_ABI FunctionCallee getOrCreateRuntimeFunction(Module &M,
2131 omp::RuntimeFunction FnID);
2132
2133 LLVM_ABI Function *getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID);
2134
2135 /// Return the (LLVM-IR) string describing the source location \p LocStr.
2136 LLVM_ABI Constant *getOrCreateSrcLocStr(StringRef LocStr,
2137 uint32_t &SrcLocStrSize);
2138
2139 /// Return the (LLVM-IR) string describing the default source location.
2140 LLVM_ABI Constant *getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize);
2141
2142 /// Return the (LLVM-IR) string describing the source location identified by
2143 /// the arguments.
2144 LLVM_ABI Constant *getOrCreateSrcLocStr(StringRef FunctionName,
2145 StringRef FileName, unsigned Line,
2146 unsigned Column,
2147 uint32_t &SrcLocStrSize);
2148
2149 /// Return the (LLVM-IR) string describing the DebugLoc \p DL. Use \p F as
2150 /// fallback if \p DL does not specify the function name.
2151 LLVM_ABI Constant *getOrCreateSrcLocStr(DebugLoc DL, uint32_t &SrcLocStrSize,
2152 Function *F = nullptr);
2153
2154 /// Return the (LLVM-IR) string describing the source location \p Loc.
2155 LLVM_ABI Constant *getOrCreateSrcLocStr(const LocationDescription &Loc,
2156 uint32_t &SrcLocStrSize);
2157
2158 /// Return an ident_t* encoding the source location \p SrcLocStr and \p Flags.
2159 /// TODO: Create a enum class for the Reserve2Flags
2160 LLVM_ABI Constant *getOrCreateIdent(Constant *SrcLocStr,
2161 uint32_t SrcLocStrSize,
2162 omp::IdentFlag Flags = omp::IdentFlag(0),
2163 unsigned Reserve2Flags = 0);
2164
2165 /// Create a hidden global flag \p Name in the module with initial value \p
2166 /// Value.
2167 LLVM_ABI GlobalValue *createGlobalFlag(unsigned Value, StringRef Name);
2168
2169 /// Emit the llvm.used metadata.
2170 LLVM_ABI void emitUsed(StringRef Name, ArrayRef<llvm::WeakTrackingVH> List);
2171
2172 /// Emit the kernel execution mode.
2173 LLVM_ABI GlobalVariable *
2174 emitKernelExecutionMode(StringRef KernelName, omp::OMPTgtExecModeFlags Mode);
2175
2176 /// Generate control flow and cleanup for cancellation.
2177 ///
2178 /// \param CancelFlag Flag indicating if the cancellation is performed.
2179 /// \param CanceledDirective The kind of directive that is cancled.
2180 /// \param ExitCB Extra code to be generated in the exit block.
2181 ///
2182 /// \return an error, if any were triggered during execution.
2183 LLVM_ABI Error emitCancelationCheckImpl(Value *CancelFlag,
2184 omp::Directive CanceledDirective,
2185 FinalizeCallbackTy ExitCB = {});
2186
2187 /// Generate a target region entry call.
2188 ///
2189 /// \param Loc The location at which the request originated and is fulfilled.
2190 /// \param AllocaIP The insertion point to be used for alloca instructions.
2191 /// \param Return Return value of the created function returned by reference.
2192 /// \param DeviceID Identifier for the device via the 'device' clause.
2193 /// \param NumTeams Numer of teams for the region via the 'num_teams' clause
2194 /// or 0 if unspecified and -1 if there is no 'teams' clause.
2195 /// \param NumThreads Number of threads via the 'thread_limit' clause.
2196 /// \param HostPtr Pointer to the host-side pointer of the target kernel.
2197 /// \param KernelArgs Array of arguments to the kernel.
2198 LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc,
2199 InsertPointTy AllocaIP,
2200 Value *&Return, Value *Ident,
2201 Value *DeviceID, Value *NumTeams,
2202 Value *NumThreads, Value *HostPtr,
2203 ArrayRef<Value *> KernelArgs);
2204
2205 /// Generate a flush runtime call.
2206 ///
2207 /// \param Loc The location at which the request originated and is fulfilled.
2208 LLVM_ABI void emitFlush(const LocationDescription &Loc);
2209
2210 /// The finalization stack made up of finalize callbacks currently in-flight,
2211 /// wrapped into FinalizationInfo objects that reference also the finalization
2212 /// target block and the kind of cancellable directive.
2213 SmallVector<FinalizationInfo, 8> FinalizationStack;
2214
2215 /// Return true if the last entry in the finalization stack is of kind \p DK
2216 /// and cancellable.
2217 bool isLastFinalizationInfoCancellable(omp::Directive DK) {
2218 return !FinalizationStack.empty() &&
2219 FinalizationStack.back().IsCancellable &&
2220 FinalizationStack.back().DK == DK;
2221 }
2222
2223 /// Generate a taskwait runtime call.
2224 ///
2225 /// \param Loc The location at which the request originated and is fulfilled.
2226 LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc);
2227
2228 /// Generate a taskyield runtime call.
2229 ///
2230 /// \param Loc The location at which the request originated and is fulfilled.
2231 LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc);
2232
2233 /// Return the current thread ID.
2234 ///
2235 /// \param Ident The ident (ident_t*) describing the query origin.
2236 LLVM_ABI Value *getOrCreateThreadID(Value *Ident);
2237
2238 /// The OpenMPIRBuilder Configuration
2239 OpenMPIRBuilderConfig Config;
2240
2241 /// The underlying LLVM-IR module
2242 Module &M;
2243
2244 /// The LLVM-IR Builder used to create IR.
2245 IRBuilder<> Builder;
2246
2247 /// Map to remember source location strings
2248 StringMap<Constant *> SrcLocStrMap;
2249
2250 /// Map to remember existing ident_t*.
2251 DenseMap<std::pair<Constant *, uint64_t>, Constant *> IdentMap;
2252
2253 /// Info manager to keep track of target regions.
2254 OffloadEntriesInfoManager OffloadInfoManager;
2255
2256 /// The target triple of the underlying module.
2257 const Triple T;
2258
2259 /// Helper that contains information about regions we need to outline
2260 /// during finalization.
2261 struct OutlineInfo {
2262 using PostOutlineCBTy = std::function<void(Function &)>;
2263 PostOutlineCBTy PostOutlineCB;
2264 BasicBlock *EntryBB, *ExitBB, *OuterAllocaBB;
2265 SmallVector<Value *, 2> ExcludeArgsFromAggregate;
2266
2267 /// Collect all blocks in between EntryBB and ExitBB in both the given
2268 /// vector and set.
2269 LLVM_ABI void collectBlocks(SmallPtrSetImpl<BasicBlock *> &BlockSet,
2270 SmallVectorImpl<BasicBlock *> &BlockVector);
2271
2272 /// Return the function that contains the region to be outlined.
2273 Function *getFunction() const { return EntryBB->getParent(); }
2274 };
2275
2276 /// Collection of regions that need to be outlined during finalization.
2277 SmallVector<OutlineInfo, 16> OutlineInfos;
2278
2279 /// A collection of candidate target functions that's constant allocas will
2280 /// attempt to be raised on a call of finalize after all currently enqueued
2281 /// outline info's have been processed.
2282 SmallVector<llvm::Function *, 16> ConstantAllocaRaiseCandidates;
2283
2284 /// Collection of owned canonical loop objects that eventually need to be
2285 /// free'd.
2286 std::forward_list<CanonicalLoopInfo> LoopInfos;
2287
2288 /// Collection of owned ScanInfo objects that eventually need to be free'd.
2289 std::forward_list<ScanInfo> ScanInfos;
2290
2291 /// Add a new region that will be outlined later.
2292 void addOutlineInfo(OutlineInfo &&OI) { OutlineInfos.emplace_back(OI); }
2293
2294 /// An ordered map of auto-generated variables to their unique names.
2295 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
2296 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
2297 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
2298 /// variables.
2299 StringMap<GlobalVariable *, BumpPtrAllocator> InternalVars;
2300
2301 /// Computes the size of type in bytes.
2303
2304 // Emit a branch from the current block to the Target block only if
2305 // the current block has a terminator.
2306 LLVM_ABI void emitBranch(BasicBlock *Target);
2307
2308 // If BB has no use then delete it and return. Else place BB after the current
2309 // block, if possible, or else at the end of the function. Also add a branch
2310 // from current block to BB if current block does not have a terminator.
2311 LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn,
2312 bool IsFinished = false);
2313
2314 /// Emits code for OpenMP 'if' clause using specified \a BodyGenCallbackTy
2315 /// Here is the logic:
2316 /// if (Cond) {
2317 /// ThenGen();
2318 /// } else {
2319 /// ElseGen();
2320 /// }
2321 ///
2322 /// \return an error, if any were triggered during execution.
2323 LLVM_ABI Error emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,
2324 BodyGenCallbackTy ElseGen,
2325 InsertPointTy AllocaIP = {});
2326
2327 /// Create the global variable holding the offload mappings information.
2328 LLVM_ABI GlobalVariable *
2329 createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
2330 std::string VarName);
2331
2332 /// Create the global variable holding the offload names information.
2333 LLVM_ABI GlobalVariable *
2334 createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
2335 std::string VarName);
2336
2337 struct MapperAllocas {
2338 AllocaInst *ArgsBase = nullptr;
2339 AllocaInst *Args = nullptr;
2340 AllocaInst *ArgSizes = nullptr;
2341 };
2342
2343 /// Create the allocas instruction used in call to mapper functions.
2344 LLVM_ABI void createMapperAllocas(const LocationDescription &Loc,
2345 InsertPointTy AllocaIP,
2346 unsigned NumOperands,
2347 struct MapperAllocas &MapperAllocas);
2348
2349 /// Create the call for the target mapper function.
2350 /// \param Loc The source location description.
2351 /// \param MapperFunc Function to be called.
2352 /// \param SrcLocInfo Source location information global.
2353 /// \param MaptypesArg The argument types.
2354 /// \param MapnamesArg The argument names.
2355 /// \param MapperAllocas The AllocaInst used for the call.
2356 /// \param DeviceID Device ID for the call.
2357 /// \param NumOperands Number of operands in the call.
2358 LLVM_ABI void emitMapperCall(const LocationDescription &Loc,
2359 Function *MapperFunc, Value *SrcLocInfo,
2360 Value *MaptypesArg, Value *MapnamesArg,
2361 struct MapperAllocas &MapperAllocas,
2362 int64_t DeviceID, unsigned NumOperands);
2363
2364 /// Container for the arguments used to pass data to the runtime library.
2365 struct TargetDataRTArgs {
2366 /// The array of base pointer passed to the runtime library.
2367 Value *BasePointersArray = nullptr;
2368 /// The array of section pointers passed to the runtime library.
2369 Value *PointersArray = nullptr;
2370 /// The array of sizes passed to the runtime library.
2371 Value *SizesArray = nullptr;
2372 /// The array of map types passed to the runtime library for the beginning
2373 /// of the region or for the entire region if there are no separate map
2374 /// types for the region end.
2375 Value *MapTypesArray = nullptr;
2376 /// The array of map types passed to the runtime library for the end of the
2377 /// region, or nullptr if there are no separate map types for the region
2378 /// end.
2379 Value *MapTypesArrayEnd = nullptr;
2380 /// The array of user-defined mappers passed to the runtime library.
2381 Value *MappersArray = nullptr;
2382 /// The array of original declaration names of mapped pointers sent to the
2383 /// runtime library for debugging
2384 Value *MapNamesArray = nullptr;
2385
2386 explicit TargetDataRTArgs() {}
2387 explicit TargetDataRTArgs(Value *BasePointersArray, Value *PointersArray,
2388 Value *SizesArray, Value *MapTypesArray,
2389 Value *MapTypesArrayEnd, Value *MappersArray,
2390 Value *MapNamesArray)
2391 : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
2392 SizesArray(SizesArray), MapTypesArray(MapTypesArray),
2393 MapTypesArrayEnd(MapTypesArrayEnd), MappersArray(MappersArray),
2394 MapNamesArray(MapNamesArray) {}
2395 };
2396
2397 /// Container to pass the default attributes with which a kernel must be
2398 /// launched, used to set kernel attributes and populate associated static
2399 /// structures.
2400 ///
2401 /// For max values, < 0 means unset, == 0 means set but unknown at compile
2402 /// time. The number of max values will be 1 except for the case where
2403 /// ompx_bare is set.
2404 struct TargetKernelDefaultAttrs {
2405 omp::OMPTgtExecModeFlags ExecFlags =
2406 omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC;
2407 SmallVector<int32_t, 3> MaxTeams = {-1};
2408 int32_t MinTeams = 1;
2409 SmallVector<int32_t, 3> MaxThreads = {-1};
2410 int32_t MinThreads = 1;
2411 int32_t ReductionDataSize = 0;
2412 int32_t ReductionBufferLength = 0;
2413 };
2414
2415 /// Container to pass LLVM IR runtime values or constants related to the
2416 /// number of teams and threads with which the kernel must be launched, as
2417 /// well as the trip count of the loop, if it is an SPMD or Generic-SPMD
2418 /// kernel. These must be defined in the host prior to the call to the kernel
2419 /// launch OpenMP RTL function.
2420 struct TargetKernelRuntimeAttrs {
2421 SmallVector<Value *, 3> MaxTeams = {nullptr};
2422 Value *MinTeams = nullptr;
2423 SmallVector<Value *, 3> TargetThreadLimit = {nullptr};
2424 SmallVector<Value *, 3> TeamsThreadLimit = {nullptr};
2425
2426 /// 'parallel' construct 'num_threads' clause value, if present and it is an
2427 /// SPMD kernel.
2428 Value *MaxThreads = nullptr;
2429
2430 /// Total number of iterations of the SPMD or Generic-SPMD kernel or null if
2431 /// it is a generic kernel.
2432 Value *LoopTripCount = nullptr;
2433 };
2434
2435 /// Data structure that contains the needed information to construct the
2436 /// kernel args vector.
2437 struct TargetKernelArgs {
2438 /// Number of arguments passed to the runtime library.
2439 unsigned NumTargetItems = 0;
2440 /// Arguments passed to the runtime library
2441 TargetDataRTArgs RTArgs;
2442 /// The number of iterations
2443 Value *NumIterations = nullptr;
2444 /// The number of teams.
2445 ArrayRef<Value *> NumTeams;
2446 /// The number of threads.
2447 ArrayRef<Value *> NumThreads;
2448 /// The size of the dynamic shared memory.
2449 Value *DynCGGroupMem = nullptr;
2450 /// True if the kernel has 'no wait' clause.
2451 bool HasNoWait = false;
2452
2453 // Constructors for TargetKernelArgs.
2454 TargetKernelArgs() {}
2455 TargetKernelArgs(unsigned NumTargetItems, TargetDataRTArgs RTArgs,
2456 Value *NumIterations, ArrayRef<Value *> NumTeams,
2457 ArrayRef<Value *> NumThreads, Value *DynCGGroupMem,
2458 bool HasNoWait)
2459 : NumTargetItems(NumTargetItems), RTArgs(RTArgs),
2460 NumIterations(NumIterations), NumTeams(NumTeams),
2461 NumThreads(NumThreads), DynCGGroupMem(DynCGGroupMem),
2462 HasNoWait(HasNoWait) {}
2463 };
2464
2465 /// Create the kernel args vector used by emitTargetKernel. This function
2466 /// creates various constant values that are used in the resulting args
2467 /// vector.
2468 LLVM_ABI static void getKernelArgsVector(TargetKernelArgs &KernelArgs,
2469 IRBuilderBase &Builder,
2470 SmallVector<Value *> &ArgsVector);
2471
2472 /// Struct that keeps the information that should be kept throughout
2473 /// a 'target data' region.
2474 class TargetDataInfo {
2475 /// Set to true if device pointer information have to be obtained.
2476 bool RequiresDevicePointerInfo = false;
2477 /// Set to true if Clang emits separate runtime calls for the beginning and
2478 /// end of the region. These calls might have separate map type arrays.
2479 bool SeparateBeginEndCalls = false;
2480
2481 public:
2482 TargetDataRTArgs RTArgs;
2483
2484 SmallMapVector<const Value *, std::pair<Value *, Value *>, 4>
2485 DevicePtrInfoMap;
2486
2487 /// Indicate whether any user-defined mapper exists.
2488 bool HasMapper = false;
2489 /// The total number of pointers passed to the runtime library.
2490 unsigned NumberOfPtrs = 0u;
2491
2492 bool EmitDebug = false;
2493
2494 /// Whether the `target ... data` directive has a `nowait` clause.
2495 bool HasNoWait = false;
2496
2497 explicit TargetDataInfo() {}
2498 explicit TargetDataInfo(bool RequiresDevicePointerInfo,
2499 bool SeparateBeginEndCalls)
2500 : RequiresDevicePointerInfo(RequiresDevicePointerInfo),
2501 SeparateBeginEndCalls(SeparateBeginEndCalls) {}
2502 /// Clear information about the data arrays.
2503 void clearArrayInfo() {
2504 RTArgs = TargetDataRTArgs();
2505 HasMapper = false;
2506 NumberOfPtrs = 0u;
2507 }
2508 /// Return true if the current target data information has valid arrays.
2509 bool isValid() {
2510 return RTArgs.BasePointersArray && RTArgs.PointersArray &&
2511 RTArgs.SizesArray && RTArgs.MapTypesArray &&
2512 (!HasMapper || RTArgs.MappersArray) && NumberOfPtrs;
2513 }
2514 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
2515 bool separateBeginEndCalls() { return SeparateBeginEndCalls; }
2516 };
2517
2518 enum class DeviceInfoTy { None, Pointer, Address };
2519 using MapValuesArrayTy = SmallVector<Value *, 4>;
2520 using MapDeviceInfoArrayTy = SmallVector<DeviceInfoTy, 4>;
2521 using MapFlagsArrayTy = SmallVector<omp::OpenMPOffloadMappingFlags, 4>;
2522 using MapNamesArrayTy = SmallVector<Constant *, 4>;
2523 using MapDimArrayTy = SmallVector<uint64_t, 4>;
2524 using MapNonContiguousArrayTy = SmallVector<MapValuesArrayTy, 4>;
2525
2526 /// This structure contains combined information generated for mappable
2527 /// clauses, including base pointers, pointers, sizes, map types, user-defined
2528 /// mappers, and non-contiguous information.
2529 struct MapInfosTy {
2530 struct StructNonContiguousInfo {
2531 bool IsNonContiguous = false;
2532 MapDimArrayTy Dims;
2533 MapNonContiguousArrayTy Offsets;
2534 MapNonContiguousArrayTy Counts;
2535 MapNonContiguousArrayTy Strides;
2536 };
2537 MapValuesArrayTy BasePointers;
2538 MapValuesArrayTy Pointers;
2539 MapDeviceInfoArrayTy DevicePointers;
2540 MapValuesArrayTy Sizes;
2541 MapFlagsArrayTy Types;
2542 MapNamesArrayTy Names;
2543 StructNonContiguousInfo NonContigInfo;
2544
2545 /// Append arrays in \a CurInfo.
2546 void append(MapInfosTy &CurInfo) {
2547 BasePointers.append(CurInfo.BasePointers.begin(),
2548 CurInfo.BasePointers.end());
2549 Pointers.append(CurInfo.Pointers.begin(), CurInfo.Pointers.end());
2550 DevicePointers.append(CurInfo.DevicePointers.begin(),
2551 CurInfo.DevicePointers.end());
2552 Sizes.append(CurInfo.Sizes.begin(), CurInfo.Sizes.end());
2553 Types.append(CurInfo.Types.begin(), CurInfo.Types.end());
2554 Names.append(CurInfo.Names.begin(), CurInfo.Names.end());
2555 NonContigInfo.Dims.append(CurInfo.NonContigInfo.Dims.begin(),
2556 CurInfo.NonContigInfo.Dims.end());
2557 NonContigInfo.Offsets.append(CurInfo.NonContigInfo.Offsets.begin(),
2558 CurInfo.NonContigInfo.Offsets.end());
2559 NonContigInfo.Counts.append(CurInfo.NonContigInfo.Counts.begin(),
2560 CurInfo.NonContigInfo.Counts.end());
2561 NonContigInfo.Strides.append(CurInfo.NonContigInfo.Strides.begin(),
2562 CurInfo.NonContigInfo.Strides.end());
2563 }
2564 };
2565 using MapInfosOrErrorTy = Expected<MapInfosTy &>;
2566
2567 /// Callback function type for functions emitting the host fallback code that
2568 /// is executed when the kernel launch fails. It takes an insertion point as
2569 /// parameter where the code should be emitted. It returns an insertion point
2570 /// that points right after after the emitted code.
2571 using EmitFallbackCallbackTy =
2572 function_ref<InsertPointOrErrorTy(InsertPointTy)>;
2573
2574 // Callback function type for emitting and fetching user defined custom
2575 // mappers.
2576 using CustomMapperCallbackTy =
2577 function_ref<Expected<Function *>(unsigned int)>;
2578
2579 /// Generate a target region entry call and host fallback call.
2580 ///
2581 /// \param Loc The location at which the request originated and is fulfilled.
2582 /// \param OutlinedFnID The ooulined function ID.
2583 /// \param EmitTargetCallFallbackCB Call back function to generate host
2584 /// fallback code.
2585 /// \param Args Data structure holding information about the kernel arguments.
2586 /// \param DeviceID Identifier for the device via the 'device' clause.
2587 /// \param RTLoc Source location identifier
2588 /// \param AllocaIP The insertion point to be used for alloca instructions.
2589 LLVM_ABI InsertPointOrErrorTy emitKernelLaunch(
2590 const LocationDescription &Loc, Value *OutlinedFnID,
2591 EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,
2592 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP);
2593
2594 /// Callback type for generating the bodies of device directives that require
2595 /// outer target tasks (e.g. in case of having `nowait` or `depend` clauses).
2596 ///
2597 /// \param DeviceID The ID of the device on which the target region will
2598 /// execute.
2599 /// \param RTLoc Source location identifier
2600 /// \Param TargetTaskAllocaIP Insertion point for the alloca block of the
2601 /// generated task.
2602 ///
2603 /// \return an error, if any were triggered during execution.
2604 using TargetTaskBodyCallbackTy =
2605 function_ref<Error(Value *DeviceID, Value *RTLoc,
2606 IRBuilderBase::InsertPoint TargetTaskAllocaIP)>;
2607
2608 /// Generate a target-task for the target construct
2609 ///
2610 /// \param TaskBodyCB Callback to generate the actual body of the target task.
2611 /// \param DeviceID Identifier for the device via the 'device' clause.
2612 /// \param RTLoc Source location identifier
2613 /// \param AllocaIP The insertion point to be used for alloca instructions.
2614 /// \param Dependencies Vector of DependData objects holding information of
2615 /// dependencies as specified by the 'depend' clause.
2616 /// \param HasNoWait True if the target construct had 'nowait' on it, false
2617 /// otherwise
2618 LLVM_ABI InsertPointOrErrorTy emitTargetTask(
2619 TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc,
2620 OpenMPIRBuilder::InsertPointTy AllocaIP,
2621 const SmallVector<llvm::OpenMPIRBuilder::DependData> &Dependencies,
2622 const TargetDataRTArgs &RTArgs, bool HasNoWait);
2623
2624 /// Emit the arguments to be passed to the runtime library based on the
2625 /// arrays of base pointers, pointers, sizes, map types, and mappers. If
2626 /// ForEndCall, emit map types to be passed for the end of the region instead
2627 /// of the beginning.
2628 LLVM_ABI void emitOffloadingArraysArgument(
2629 IRBuilderBase &Builder, OpenMPIRBuilder::TargetDataRTArgs &RTArgs,
2630 OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall = false);
2631
2632 /// Emit an array of struct descriptors to be assigned to the offload args.
2633 LLVM_ABI void emitNonContiguousDescriptor(InsertPointTy AllocaIP,
2634 InsertPointTy CodeGenIP,
2635 MapInfosTy &CombinedInfo,
2636 TargetDataInfo &Info);
2637
2638 /// Emit the arrays used to pass the captures and map information to the
2639 /// offloading runtime library. If there is no map or capture information,
2640 /// return nullptr by reference. Accepts a reference to a MapInfosTy object
2641 /// that contains information generated for mappable clauses,
2642 /// including base pointers, pointers, sizes, map types, user-defined mappers.
2643 LLVM_ABI Error emitOffloadingArrays(
2644 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
2645 TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB,
2646 bool IsNonContiguous = false,
2647 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
2648
2649 /// Allocates memory for and populates the arrays required for offloading
2650 /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
2651 /// emits their base addresses as arguments to be passed to the runtime
2652 /// library. In essence, this function is a combination of
2653 /// emitOffloadingArrays and emitOffloadingArraysArgument and should arguably
2654 /// be preferred by clients of OpenMPIRBuilder.
2655 LLVM_ABI Error emitOffloadingArraysAndArgs(
2656 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
2657 TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
2658 CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous = false,
2659 bool ForEndCall = false,
2660 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
2661
2662 /// Creates offloading entry for the provided entry ID \a ID, address \a
2663 /// Addr, size \a Size, and flags \a Flags.
2664 LLVM_ABI void createOffloadEntry(Constant *ID, Constant *Addr, uint64_t Size,
2665 int32_t Flags, GlobalValue::LinkageTypes,
2666 StringRef Name = "");
2667
2668 /// The kind of errors that can occur when emitting the offload entries and
2669 /// metadata.
2670 enum EmitMetadataErrorKind {
2671 EMIT_MD_TARGET_REGION_ERROR,
2672 EMIT_MD_DECLARE_TARGET_ERROR,
2673 EMIT_MD_GLOBAL_VAR_LINK_ERROR
2674 };
2675
2676 /// Callback function type
2677 using EmitMetadataErrorReportFunctionTy =
2678 std::function<void(EmitMetadataErrorKind, TargetRegionEntryInfo)>;
2679
2680 // Emit the offloading entries and metadata so that the device codegen side
2681 // can easily figure out what to emit. The produced metadata looks like
2682 // this:
2683 //
2684 // !omp_offload.info = !{!1, ...}
2685 //
2686 // We only generate metadata for function that contain target regions.
2687 LLVM_ABI void createOffloadEntriesAndInfoMetadata(
2688 EmitMetadataErrorReportFunctionTy &ErrorReportFunction);
2689
2690public:
2691 /// Generator for __kmpc_copyprivate
2692 ///
2693 /// \param Loc The source location description.
2694 /// \param BufSize Number of elements in the buffer.
2695 /// \param CpyBuf List of pointers to data to be copied.
2696 /// \param CpyFn function to call for copying data.
2697 /// \param DidIt flag variable; 1 for 'single' thread, 0 otherwise.
2698 ///
2699 /// \return The insertion position *after* the CopyPrivate call.
2700
2701 LLVM_ABI InsertPointTy createCopyPrivate(const LocationDescription &Loc,
2702 llvm::Value *BufSize,
2703 llvm::Value *CpyBuf,
2704 llvm::Value *CpyFn,
2705 llvm::Value *DidIt);
2706
2707 /// Generator for '#omp single'
2708 ///
2709 /// \param Loc The source location description.
2710 /// \param BodyGenCB Callback that will generate the region code.
2711 /// \param FiniCB Callback to finalize variable copies.
2712 /// \param IsNowait If false, a barrier is emitted.
2713 /// \param CPVars copyprivate variables.
2714 /// \param CPFuncs copy functions to use for each copyprivate variable.
2715 ///
2716 /// \returns The insertion position *after* the single call.
2717 LLVM_ABI InsertPointOrErrorTy
2718 createSingle(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2719 FinalizeCallbackTy FiniCB, bool IsNowait,
2720 ArrayRef<llvm::Value *> CPVars = {},
2721 ArrayRef<llvm::Function *> CPFuncs = {});
2722
2723 /// Generator for '#omp master'
2724 ///
2725 /// \param Loc The insert and source location description.
2726 /// \param BodyGenCB Callback that will generate the region code.
2727 /// \param FiniCB Callback to finalize variable copies.
2728 ///
2729 /// \returns The insertion position *after* the master.
2730 LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc,
2731 BodyGenCallbackTy BodyGenCB,
2732 FinalizeCallbackTy FiniCB);
2733
2734 /// Generator for '#omp masked'
2735 ///
2736 /// \param Loc The insert and source location description.
2737 /// \param BodyGenCB Callback that will generate the region code.
2738 /// \param FiniCB Callback to finialize variable copies.
2739 ///
2740 /// \returns The insertion position *after* the masked.
2741 LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc,
2742 BodyGenCallbackTy BodyGenCB,
2743 FinalizeCallbackTy FiniCB,
2744 Value *Filter);
2745
2746 /// This function performs the scan reduction of the values updated in
2747 /// the input phase. The reduction logic needs to be emitted between input
2748 /// and scan loop returned by `CreateCanonicalScanLoops`. The following
2749 /// is the code that is generated, `buffer` and `span` are expected to be
2750 /// populated before executing the generated code.
2751 /// \code{c}
2752 /// for (int k = 0; k != ceil(log2(span)); ++k) {
2753 /// i=pow(2,k)
2754 /// for (size cnt = last_iter; cnt >= i; --cnt)
2755 /// buffer[cnt] op= buffer[cnt-i];
2756 /// }
2757 /// \endcode
2758 /// \param Loc The insert and source location description.
2759 /// \param ReductionInfos Array type containing the ReductionOps.
2760 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2761 /// `ScanInfoInitialize`.
2762 ///
2763 /// \returns The insertion position *after* the masked.
2764 LLVM_ABI InsertPointOrErrorTy emitScanReduction(
2765 const LocationDescription &Loc,
2766 ArrayRef<llvm::OpenMPIRBuilder::ReductionInfo> ReductionInfos,
2767 ScanInfo *ScanRedInfo);
2768
2769 /// This directive split and directs the control flow to input phase
2770 /// blocks or scan phase blocks based on 1. whether input loop or scan loop
2771 /// is executed, 2. whether exclusive or inclusive scan is used.
2772 ///
2773 /// \param Loc The insert and source location description.
2774 /// \param AllocaIP The IP where the temporary buffer for scan reduction
2775 // needs to be allocated.
2776 /// \param ScanVars Scan Variables.
2777 /// \param IsInclusive Whether it is an inclusive or exclusive scan.
2778 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2779 /// `ScanInfoInitialize`.
2780 ///
2781 /// \returns The insertion position *after* the scan.
2782 LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc,
2783 InsertPointTy AllocaIP,
2784 ArrayRef<llvm::Value *> ScanVars,
2785 ArrayRef<llvm::Type *> ScanVarsType,
2786 bool IsInclusive,
2787 ScanInfo *ScanRedInfo);
2788
2789 /// Generator for '#omp critical'
2790 ///
2791 /// \param Loc The insert and source location description.
2792 /// \param BodyGenCB Callback that will generate the region body code.
2793 /// \param FiniCB Callback to finalize variable copies.
2794 /// \param CriticalName name of the lock used by the critical directive
2795 /// \param HintInst Hint Instruction for hint clause associated with critical
2796 ///
2797 /// \returns The insertion position *after* the critical.
2798 LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc,
2799 BodyGenCallbackTy BodyGenCB,
2800 FinalizeCallbackTy FiniCB,
2801 StringRef CriticalName,
2802 Value *HintInst);
2803
2804 /// Generator for '#omp ordered depend (source | sink)'
2805 ///
2806 /// \param Loc The insert and source location description.
2807 /// \param AllocaIP The insertion point to be used for alloca instructions.
2808 /// \param NumLoops The number of loops in depend clause.
2809 /// \param StoreValues The value will be stored in vector address.
2810 /// \param Name The name of alloca instruction.
2811 /// \param IsDependSource If true, depend source; otherwise, depend sink.
2812 ///
2813 /// \return The insertion position *after* the ordered.
2814 LLVM_ABI InsertPointTy
2815 createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP,
2816 unsigned NumLoops, ArrayRef<llvm::Value *> StoreValues,
2817 const Twine &Name, bool IsDependSource);
2818
2819 /// Generator for '#omp ordered [threads | simd]'
2820 ///
2821 /// \param Loc The insert and source location description.
2822 /// \param BodyGenCB Callback that will generate the region code.
2823 /// \param FiniCB Callback to finalize variable copies.
2824 /// \param IsThreads If true, with threads clause or without clause;
2825 /// otherwise, with simd clause;
2826 ///
2827 /// \returns The insertion position *after* the ordered.
2828 LLVM_ABI InsertPointOrErrorTy createOrderedThreadsSimd(
2829 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2830 FinalizeCallbackTy FiniCB, bool IsThreads);
2831
2832 /// Generator for '#omp sections'
2833 ///
2834 /// \param Loc The insert and source location description.
2835 /// \param AllocaIP The insertion points to be used for alloca instructions.
2836 /// \param SectionCBs Callbacks that will generate body of each section.
2837 /// \param PrivCB Callback to copy a given variable (think copy constructor).
2838 /// \param FiniCB Callback to finalize variable copies.
2839 /// \param IsCancellable Flag to indicate a cancellable parallel region.
2840 /// \param IsNowait If true, barrier - to ensure all sections are executed
2841 /// before moving forward will not be generated.
2842 /// \returns The insertion position *after* the sections.
2843 LLVM_ABI InsertPointOrErrorTy
2844 createSections(const LocationDescription &Loc, InsertPointTy AllocaIP,
2845 ArrayRef<StorableBodyGenCallbackTy> SectionCBs,
2846 PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB,
2847 bool IsCancellable, bool IsNowait);
2848
2849 /// Generator for '#omp section'
2850 ///
2851 /// \param Loc The insert and source location description.
2852 /// \param BodyGenCB Callback that will generate the region body code.
2853 /// \param FiniCB Callback to finalize variable copies.
2854 /// \returns The insertion position *after* the section.
2855 LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc,
2856 BodyGenCallbackTy BodyGenCB,
2857 FinalizeCallbackTy FiniCB);
2858
2859 /// Generator for `#omp teams`
2860 ///
2861 /// \param Loc The location where the teams construct was encountered.
2862 /// \param BodyGenCB Callback that will generate the region code.
2863 /// \param NumTeamsLower Lower bound on number of teams. If this is nullptr,
2864 /// it is as if lower bound is specified as equal to upperbound. If
2865 /// this is non-null, then upperbound must also be non-null.
2866 /// \param NumTeamsUpper Upper bound on the number of teams.
2867 /// \param ThreadLimit on the number of threads that may participate in a
2868 /// contention group created by each team.
2869 /// \param IfExpr is the integer argument value of the if condition on the
2870 /// teams clause.
2871 LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc,
2872 BodyGenCallbackTy BodyGenCB,
2873 Value *NumTeamsLower = nullptr,
2874 Value *NumTeamsUpper = nullptr,
2875 Value *ThreadLimit = nullptr,
2876 Value *IfExpr = nullptr);
2877
2878 /// Generator for `#omp distribute`
2879 ///
2880 /// \param Loc The location where the distribute construct was encountered.
2881 /// \param AllocaIP The insertion points to be used for alloca instructions.
2882 /// \param BodyGenCB Callback that will generate the region code.
2883 LLVM_ABI InsertPointOrErrorTy createDistribute(const LocationDescription &Loc,
2884 InsertPointTy AllocaIP,
2885 BodyGenCallbackTy BodyGenCB);
2886
2887 /// Generate conditional branch and relevant BasicBlocks through which private
2888 /// threads copy the 'copyin' variables from Master copy to threadprivate
2889 /// copies.
2890 ///
2891 /// \param IP insertion block for copyin conditional
2892 /// \param MasterVarPtr a pointer to the master variable
2893 /// \param PrivateVarPtr a pointer to the threadprivate variable
2894 /// \param IntPtrTy Pointer size type
2895 /// \param BranchtoEnd Create a branch between the copyin.not.master blocks
2896 // and copy.in.end block
2897 ///
2898 /// \returns The insertion point where copying operation to be emitted.
2899 LLVM_ABI InsertPointTy createCopyinClauseBlocks(InsertPointTy IP,
2900 Value *MasterAddr,
2901 Value *PrivateAddr,
2902 llvm::IntegerType *IntPtrTy,
2903 bool BranchtoEnd = true);
2904
2905 /// Create a runtime call for kmpc_Alloc
2906 ///
2907 /// \param Loc The insert and source location description.
2908 /// \param Size Size of allocated memory space
2909 /// \param Allocator Allocator information instruction
2910 /// \param Name Name of call Instruction for OMP_alloc
2911 ///
2912 /// \returns CallInst to the OMP_Alloc call
2913 LLVM_ABI CallInst *createOMPAlloc(const LocationDescription &Loc, Value *Size,
2914 Value *Allocator, std::string Name = "");
2915
2916 /// Create a runtime call for kmpc_free
2917 ///
2918 /// \param Loc The insert and source location description.
2919 /// \param Addr Address of memory space to be freed
2920 /// \param Allocator Allocator information instruction
2921 /// \param Name Name of call Instruction for OMP_Free
2922 ///
2923 /// \returns CallInst to the OMP_Free call
2924 LLVM_ABI CallInst *createOMPFree(const LocationDescription &Loc, Value *Addr,
2925 Value *Allocator, std::string Name = "");
2926
2927 /// Create a runtime call for kmpc_threadprivate_cached
2928 ///
2929 /// \param Loc The insert and source location description.
2930 /// \param Pointer pointer to data to be cached
2931 /// \param Size size of data to be cached
2932 /// \param Name Name of call Instruction for callinst
2933 ///
2934 /// \returns CallInst to the thread private cache call.
2935 LLVM_ABI CallInst *
2936 createCachedThreadPrivate(const LocationDescription &Loc,
2937 llvm::Value *Pointer, llvm::ConstantInt *Size,
2938 const llvm::Twine &Name = Twine(""));
2939
2940 /// Create a runtime call for __tgt_interop_init
2941 ///
2942 /// \param Loc The insert and source location description.
2943 /// \param InteropVar variable to be allocated
2944 /// \param InteropType type of interop operation
2945 /// \param Device devide to which offloading will occur
2946 /// \param NumDependences number of dependence variables
2947 /// \param DependenceAddress pointer to dependence variables
2948 /// \param HaveNowaitClause does nowait clause exist
2949 ///
2950 /// \returns CallInst to the __tgt_interop_init call
2951 LLVM_ABI CallInst *createOMPInteropInit(const LocationDescription &Loc,
2952 Value *InteropVar,
2953 omp::OMPInteropType InteropType,
2954 Value *Device, Value *NumDependences,
2955 Value *DependenceAddress,
2956 bool HaveNowaitClause);
2957
2958 /// Create a runtime call for __tgt_interop_destroy
2959 ///
2960 /// \param Loc The insert and source location description.
2961 /// \param InteropVar variable to be allocated
2962 /// \param Device devide to which offloading will occur
2963 /// \param NumDependences number of dependence variables
2964 /// \param DependenceAddress pointer to dependence variables
2965 /// \param HaveNowaitClause does nowait clause exist
2966 ///
2967 /// \returns CallInst to the __tgt_interop_destroy call
2968 LLVM_ABI CallInst *createOMPInteropDestroy(const LocationDescription &Loc,
2969 Value *InteropVar, Value *Device,
2970 Value *NumDependences,
2971 Value *DependenceAddress,
2972 bool HaveNowaitClause);
2973
2974 /// Create a runtime call for __tgt_interop_use
2975 ///
2976 /// \param Loc The insert and source location description.
2977 /// \param InteropVar variable to be allocated
2978 /// \param Device devide to which offloading will occur
2979 /// \param NumDependences number of dependence variables
2980 /// \param DependenceAddress pointer to dependence variables
2981 /// \param HaveNowaitClause does nowait clause exist
2982 ///
2983 /// \returns CallInst to the __tgt_interop_use call
2984 LLVM_ABI CallInst *createOMPInteropUse(const LocationDescription &Loc,
2985 Value *InteropVar, Value *Device,
2986 Value *NumDependences,
2987 Value *DependenceAddress,
2988 bool HaveNowaitClause);
2989
2990 /// The `omp target` interface
2991 ///
2992 /// For more information about the usage of this interface,
2993 /// \see openmp/libomptarget/deviceRTLs/common/include/target.h
2994 ///
2995 ///{
2996
2997 /// Create a runtime call for kmpc_target_init
2998 ///
2999 /// \param Loc The insert and source location description.
3000 /// \param Attrs Structure containing the default attributes, including
3001 /// numbers of threads and teams to launch the kernel with.
3002 LLVM_ABI InsertPointTy createTargetInit(
3003 const LocationDescription &Loc,
3004 const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs);
3005
3006 /// Create a runtime call for kmpc_target_deinit
3007 ///
3008 /// \param Loc The insert and source location description.
3009 /// \param TeamsReductionDataSize The maximal size of all the reduction data
3010 /// for teams reduction.
3011 /// \param TeamsReductionBufferLength The number of elements (each of up to
3012 /// \p TeamsReductionDataSize size), in the teams reduction buffer.
3013 LLVM_ABI void createTargetDeinit(const LocationDescription &Loc,
3014 int32_t TeamsReductionDataSize = 0,
3015 int32_t TeamsReductionBufferLength = 1024);
3016
3017 ///}
3018
3019 /// Helpers to read/write kernel annotations from the IR.
3020 ///
3021 ///{
3022
3023 /// Read/write a bounds on threads for \p Kernel. Read will return 0 if none
3024 /// is set.
3025 LLVM_ABI static std::pair<int32_t, int32_t>
3026 readThreadBoundsForKernel(const Triple &T, Function &Kernel);
3027 LLVM_ABI static void writeThreadBoundsForKernel(const Triple &T,
3028 Function &Kernel, int32_t LB,
3029 int32_t UB);
3030
3031 /// Read/write a bounds on teams for \p Kernel. Read will return 0 if none
3032 /// is set.
3033 LLVM_ABI static std::pair<int32_t, int32_t>
3034 readTeamBoundsForKernel(const Triple &T, Function &Kernel);
3035 LLVM_ABI static void writeTeamsForKernel(const Triple &T, Function &Kernel,
3036 int32_t LB, int32_t UB);
3037 ///}
3038
3039private:
3040 // Sets the function attributes expected for the outlined function
3041 void setOutlinedTargetRegionFunctionAttributes(Function *OutlinedFn);
3042
3043 // Creates the function ID/Address for the given outlined function.
3044 // In the case of an embedded device function the address of the function is
3045 // used, in the case of a non-offload function a constant is created.
3046 Constant *createOutlinedFunctionID(Function *OutlinedFn,
3047 StringRef EntryFnIDName);
3048
3049 // Creates the region entry address for the outlined function
3050 Constant *createTargetRegionEntryAddr(Function *OutlinedFunction,
3051 StringRef EntryFnName);
3052
3053public:
3054 /// Functions used to generate a function with the given name.
3055 using FunctionGenCallback =
3056 std::function<Expected<Function *>(StringRef FunctionName)>;
3057
3058 /// Create a unique name for the entry function using the source location
3059 /// information of the current target region. The name will be something like:
3060 ///
3061 /// __omp_offloading_DD_FFFF_PP_lBB[_CC]
3062 ///
3063 /// where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
3064 /// mangled name of the function that encloses the target region and BB is the
3065 /// line number of the target region. CC is a count added when more than one
3066 /// region is located at the same location.
3067 ///
3068 /// If this target outline function is not an offload entry, we don't need to
3069 /// register it. This may happen if it is guarded by an if clause that is
3070 /// false at compile time, or no target archs have been specified.
3071 ///
3072 /// The created target region ID is used by the runtime library to identify
3073 /// the current target region, so it only has to be unique and not
3074 /// necessarily point to anything. It could be the pointer to the outlined
3075 /// function that implements the target region, but we aren't using that so
3076 /// that the compiler doesn't need to keep that, and could therefore inline
3077 /// the host function if proven worthwhile during optimization. In the other
3078 /// hand, if emitting code for the device, the ID has to be the function
3079 /// address so that it can retrieved from the offloading entry and launched
3080 /// by the runtime library. We also mark the outlined function to have
3081 /// external linkage in case we are emitting code for the device, because
3082 /// these functions will be entry points to the device.
3083 ///
3084 /// \param InfoManager The info manager keeping track of the offload entries
3085 /// \param EntryInfo The entry information about the function
3086 /// \param GenerateFunctionCallback The callback function to generate the code
3087 /// \param OutlinedFunction Pointer to the outlined function
3088 /// \param EntryFnIDName Name of the ID o be created
3089 LLVM_ABI Error emitTargetRegionFunction(
3090 TargetRegionEntryInfo &EntryInfo,
3091 FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,
3092 Function *&OutlinedFn, Constant *&OutlinedFnID);
3093
3094 /// Registers the given function and sets up the attribtues of the function
3095 /// Returns the FunctionID.
3096 ///
3097 /// \param InfoManager The info manager keeping track of the offload entries
3098 /// \param EntryInfo The entry information about the function
3099 /// \param OutlinedFunction Pointer to the outlined function
3100 /// \param EntryFnName Name of the outlined function
3101 /// \param EntryFnIDName Name of the ID o be created
3103 registerTargetRegionFunction(TargetRegionEntryInfo &EntryInfo,
3104 Function *OutlinedFunction,
3105 StringRef EntryFnName, StringRef EntryFnIDName);
3106
3107 /// Type of BodyGen to use for region codegen
3108 ///
3109 /// Priv: If device pointer privatization is required, emit the body of the
3110 /// region here. It will have to be duplicated: with and without
3111 /// privatization.
3112 /// DupNoPriv: If we need device pointer privatization, we need
3113 /// to emit the body of the region with no privatization in the 'else' branch
3114 /// of the conditional.
3115 /// NoPriv: If we don't require privatization of device
3116 /// pointers, we emit the body in between the runtime calls. This avoids
3117 /// duplicating the body code.
3118 enum BodyGenTy { Priv, DupNoPriv, NoPriv };
3119
3120 /// Callback type for creating the map infos for the kernel parameters.
3121 /// \param CodeGenIP is the insertion point where code should be generated,
3122 /// if any.
3123 using GenMapInfoCallbackTy =
3124 function_ref<MapInfosTy &(InsertPointTy CodeGenIP)>;
3125
3126private:
3127 /// Emit the array initialization or deletion portion for user-defined mapper
3128 /// code generation. First, it evaluates whether an array section is mapped
3129 /// and whether the \a MapType instructs to delete this section. If \a IsInit
3130 /// is true, and \a MapType indicates to not delete this array, array
3131 /// initialization code is generated. If \a IsInit is false, and \a MapType
3132 /// indicates to delete this array, array deletion code is generated.
3133 void emitUDMapperArrayInitOrDel(Function *MapperFn, llvm::Value *MapperHandle,
3134 llvm::Value *Base, llvm::Value *Begin,
3135 llvm::Value *Size, llvm::Value *MapType,
3136 llvm::Value *MapName, TypeSize ElementSize,
3137 llvm::BasicBlock *ExitBB, bool IsInit);
3138
3139public:
3140 /// Emit the user-defined mapper function. The code generation follows the
3141 /// pattern in the example below.
3142 /// \code
3143 /// void .omp_mapper.<type_name>.<mapper_id>.(void *rt_mapper_handle,
3144 /// void *base, void *begin,
3145 /// int64_t size, int64_t type,
3146 /// void *name = nullptr) {
3147 /// // Allocate space for an array section first or add a base/begin for
3148 /// // pointer dereference.
3149 /// if ((size > 1 || (base != begin && maptype.IsPtrAndObj)) &&
3150 /// !maptype.IsDelete)
3151 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3152 /// size*sizeof(Ty), clearToFromMember(type));
3153 /// // Map members.
3154 /// for (unsigned i = 0; i < size; i++) {
3155 /// // For each component specified by this mapper:
3156 /// for (auto c : begin[i]->all_components) {
3157 /// if (c.hasMapper())
3158 /// (*c.Mapper())(rt_mapper_handle, c.arg_base, c.arg_begin,
3159 /// c.arg_size,
3160 /// c.arg_type, c.arg_name);
3161 /// else
3162 /// __tgt_push_mapper_component(rt_mapper_handle, c.arg_base,
3163 /// c.arg_begin, c.arg_size, c.arg_type,
3164 /// c.arg_name);
3165 /// }
3166 /// }
3167 /// // Delete the array section.
3168 /// if (size > 1 && maptype.IsDelete)
3169 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3170 /// size*sizeof(Ty), clearToFromMember(type));
3171 /// }
3172 /// \endcode
3173 ///
3174 /// \param PrivAndGenMapInfoCB Callback that privatizes code and populates the
3175 /// MapInfos and returns.
3176 /// \param ElemTy DeclareMapper element type.
3177 /// \param FuncName Optional param to specify mapper function name.
3178 /// \param CustomMapperCB Optional callback to generate code related to
3179 /// custom mappers.
3180 LLVM_ABI Expected<Function *> emitUserDefinedMapper(
3181 function_ref<MapInfosOrErrorTy(
3182 InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)>
3183 PrivAndGenMapInfoCB,
3184 llvm::Type *ElemTy, StringRef FuncName,
3185 CustomMapperCallbackTy CustomMapperCB);
3186
3187 /// Generator for '#omp target data'
3188 ///
3189 /// \param Loc The location where the target data construct was encountered.
3190 /// \param AllocaIP The insertion points to be used for alloca instructions.
3191 /// \param CodeGenIP The insertion point at which the target directive code
3192 /// should be placed.
3193 /// \param IsBegin If true then emits begin mapper call otherwise emits
3194 /// end mapper call.
3195 /// \param DeviceID Stores the DeviceID from the device clause.
3196 /// \param IfCond Value which corresponds to the if clause condition.
3197 /// \param Info Stores all information realted to the Target Data directive.
3198 /// \param GenMapInfoCB Callback that populates the MapInfos and returns.
3199 /// \param CustomMapperCB Callback to generate code related to
3200 /// custom mappers.
3201 /// \param BodyGenCB Optional Callback to generate the region code.
3202 /// \param DeviceAddrCB Optional callback to generate code related to
3203 /// use_device_ptr and use_device_addr.
3204 LLVM_ABI InsertPointOrErrorTy createTargetData(
3205 const LocationDescription &Loc, InsertPointTy AllocaIP,
3206 InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond,
3207 TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB,
3208 CustomMapperCallbackTy CustomMapperCB,
3209 omp::RuntimeFunction *MapperFunc = nullptr,
3210 function_ref<InsertPointOrErrorTy(InsertPointTy CodeGenIP,
3211 BodyGenTy BodyGenType)>
3212 BodyGenCB = nullptr,
3213 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr,
3214 Value *SrcLocInfo = nullptr);
3215
3216 using TargetBodyGenCallbackTy = function_ref<InsertPointOrErrorTy(
3217 InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
3218
3219 using TargetGenArgAccessorsCallbackTy = function_ref<InsertPointOrErrorTy(
3220 Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP,
3221 InsertPointTy CodeGenIP)>;
3222
3223 /// Generator for '#omp target'
3224 ///
3225 /// \param Loc where the target data construct was encountered.
3226 /// \param IsOffloadEntry whether it is an offload entry.
3227 /// \param CodeGenIP The insertion point where the call to the outlined
3228 /// function should be emitted.
3229 /// \param Info Stores all information realted to the Target directive.
3230 /// \param EntryInfo The entry information about the function.
3231 /// \param DefaultAttrs Structure containing the default attributes, including
3232 /// numbers of threads and teams to launch the kernel with.
3233 /// \param RuntimeAttrs Structure containing the runtime numbers of threads
3234 /// and teams to launch the kernel with.
3235 /// \param IfCond value of the `if` clause.
3236 /// \param Inputs The input values to the region that will be passed.
3237 /// as arguments to the outlined function.
3238 /// \param BodyGenCB Callback that will generate the region code.
3239 /// \param ArgAccessorFuncCB Callback that will generate accessors
3240 /// instructions for passed in target arguments where neccessary
3241 /// \param CustomMapperCB Callback to generate code related to
3242 /// custom mappers.
3243 /// \param Dependencies A vector of DependData objects that carry
3244 /// dependency information as passed in the depend clause
3245 /// \param HasNowait Whether the target construct has a `nowait` clause or
3246 /// not.
3247 LLVM_ABI InsertPointOrErrorTy createTarget(
3248 const LocationDescription &Loc, bool IsOffloadEntry,
3249 OpenMPIRBuilder::InsertPointTy AllocaIP,
3250 OpenMPIRBuilder::InsertPointTy CodeGenIP, TargetDataInfo &Info,
3251 TargetRegionEntryInfo &EntryInfo,
3252 const TargetKernelDefaultAttrs &DefaultAttrs,
3253 const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond,
3254 SmallVectorImpl<Value *> &Inputs, GenMapInfoCallbackTy GenMapInfoCB,
3255 TargetBodyGenCallbackTy BodyGenCB,
3256 TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB,
3257 CustomMapperCallbackTy CustomMapperCB,
3258 const SmallVector<DependData> &Dependencies, bool HasNowait = false);
3259
3260 /// Returns __kmpc_for_static_init_* runtime function for the specified
3261 /// size \a IVSize and sign \a IVSigned. Will create a distribute call
3262 /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
3263 LLVM_ABI FunctionCallee createForStaticInitFunction(unsigned IVSize,
3264 bool IVSigned,
3265 bool IsGPUDistribute);
3266
3267 /// Returns __kmpc_dispatch_init_* runtime function for the specified
3268 /// size \a IVSize and sign \a IVSigned.
3269 LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize,
3270 bool IVSigned);
3271
3272 /// Returns __kmpc_dispatch_next_* runtime function for the specified
3273 /// size \a IVSize and sign \a IVSigned.
3274 LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize,
3275 bool IVSigned);
3276
3277 /// Returns __kmpc_dispatch_fini_* runtime function for the specified
3278 /// size \a IVSize and sign \a IVSigned.
3279 LLVM_ABI FunctionCallee createDispatchFiniFunction(unsigned IVSize,
3280 bool IVSigned);
3281
3282 /// Returns __kmpc_dispatch_deinit runtime function.
3283 LLVM_ABI FunctionCallee createDispatchDeinitFunction();
3284
3285 /// Declarations for LLVM-IR types (simple, array, function and structure) are
3286 /// generated below. Their names are defined and used in OpenMPKinds.def. Here
3287 /// we provide the declarations, the initializeTypes function will provide the
3288 /// values.
3289 ///
3290 ///{
3291#define OMP_TYPE(VarName, InitValue) Type *VarName = nullptr;
3292#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
3293 ArrayType *VarName##Ty = nullptr; \
3294 PointerType *VarName##PtrTy = nullptr;
3295#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
3296 FunctionType *VarName = nullptr; \
3297 PointerType *VarName##Ptr = nullptr;
3298#define OMP_STRUCT_TYPE(VarName, StrName, ...) \
3299 StructType *VarName = nullptr; \
3300 PointerType *VarName##Ptr = nullptr;
3301#include "llvm/Frontend/OpenMP/OMPKinds.def"
3302
3303 ///}
3304
3305private:
3306 /// Create all simple and struct types exposed by the runtime and remember
3307 /// the llvm::PointerTypes of them for easy access later.
3308 void initializeTypes(Module &M);
3309
3310 /// Common interface for generating entry calls for OMP Directives.
3311 /// if the directive has a region/body, It will set the insertion
3312 /// point to the body
3313 ///
3314 /// \param OMPD Directive to generate entry blocks for
3315 /// \param EntryCall Call to the entry OMP Runtime Function
3316 /// \param ExitBB block where the region ends.
3317 /// \param Conditional indicate if the entry call result will be used
3318 /// to evaluate a conditional of whether a thread will execute
3319 /// body code or not.
3320 ///
3321 /// \return The insertion position in exit block
3322 InsertPointTy emitCommonDirectiveEntry(omp::Directive OMPD, Value *EntryCall,
3323 BasicBlock *ExitBB,
3324 bool Conditional = false);
3325
3326 /// Common interface to finalize the region
3327 ///
3328 /// \param OMPD Directive to generate exiting code for
3329 /// \param FinIP Insertion point for emitting Finalization code and exit call
3330 /// \param ExitCall Call to the ending OMP Runtime Function
3331 /// \param HasFinalize indicate if the directive will require finalization
3332 /// and has a finalization callback in the stack that
3333 /// should be called.
3334 ///
3335 /// \return The insertion position in exit block
3336 InsertPointOrErrorTy emitCommonDirectiveExit(omp::Directive OMPD,
3337 InsertPointTy FinIP,
3338 Instruction *ExitCall,
3339 bool HasFinalize = true);
3340
3341 /// Common Interface to generate OMP inlined regions
3342 ///
3343 /// \param OMPD Directive to generate inlined region for
3344 /// \param EntryCall Call to the entry OMP Runtime Function
3345 /// \param ExitCall Call to the ending OMP Runtime Function
3346 /// \param BodyGenCB Body code generation callback.
3347 /// \param FiniCB Finalization Callback. Will be called when finalizing region
3348 /// \param Conditional indicate if the entry call result will be used
3349 /// to evaluate a conditional of whether a thread will execute
3350 /// body code or not.
3351 /// \param HasFinalize indicate if the directive will require finalization
3352 /// and has a finalization callback in the stack that
3353 /// should be called.
3354 /// \param IsCancellable if HasFinalize is set to true, indicate if the
3355 /// the directive should be cancellable.
3356 /// \return The insertion point after the region
3357 InsertPointOrErrorTy
3358 EmitOMPInlinedRegion(omp::Directive OMPD, Instruction *EntryCall,
3359 Instruction *ExitCall, BodyGenCallbackTy BodyGenCB,
3360 FinalizeCallbackTy FiniCB, bool Conditional = false,
3361 bool HasFinalize = true, bool IsCancellable = false);
3362
3363 /// Get the platform-specific name separator.
3364 /// \param Parts different parts of the final name that needs separation
3365 /// \param FirstSeparator First separator used between the initial two
3366 /// parts of the name.
3367 /// \param Separator separator used between all of the rest consecutive
3368 /// parts of the name
3369 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
3370 StringRef FirstSeparator,
3371 StringRef Separator);
3372
3373 /// Returns corresponding lock object for the specified critical region
3374 /// name. If the lock object does not exist it is created, otherwise the
3375 /// reference to the existing copy is returned.
3376 /// \param CriticalName Name of the critical region.
3377 ///
3378 Value *getOMPCriticalRegionLock(StringRef CriticalName);
3379
3380 /// Callback type for Atomic Expression update
3381 /// ex:
3382 /// \code{.cpp}
3383 /// unsigned x = 0;
3384 /// #pragma omp atomic update
3385 /// x = Expr(x_old); //Expr() is any legal operation
3386 /// \endcode
3387 ///
3388 /// \param XOld the value of the atomic memory address to use for update
3389 /// \param IRB reference to the IRBuilder to use
3390 ///
3391 /// \returns Value to update X to.
3392 using AtomicUpdateCallbackTy =
3393 const function_ref<Expected<Value *>(Value *XOld, IRBuilder<> &IRB)>;
3394
3395private:
3396 enum AtomicKind { Read, Write, Update, Capture, Compare };
3397
3398 /// Determine whether to emit flush or not
3399 ///
3400 /// \param Loc The insert and source location description.
3401 /// \param AO The required atomic ordering
3402 /// \param AK The OpenMP atomic operation kind used.
3403 ///
3404 /// \returns wether a flush was emitted or not
3405 bool checkAndEmitFlushAfterAtomic(const LocationDescription &Loc,
3406 AtomicOrdering AO, AtomicKind AK);
3407
3408 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
3409 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
3410 /// Only Scalar data types.
3411 ///
3412 /// \param AllocaIP The insertion point to be used for alloca
3413 /// instructions.
3414 /// \param X The target atomic pointer to be updated
3415 /// \param XElemTy The element type of the atomic pointer.
3416 /// \param Expr The value to update X with.
3417 /// \param AO Atomic ordering of the generated atomic
3418 /// instructions.
3419 /// \param RMWOp The binary operation used for update. If
3420 /// operation is not supported by atomicRMW,
3421 /// or belong to {FADD, FSUB, BAD_BINOP}.
3422 /// Then a `cmpExch` based atomic will be generated.
3423 /// \param UpdateOp Code generator for complex expressions that cannot be
3424 /// expressed through atomicrmw instruction.
3425 /// \param VolatileX true if \a X volatile?
3426 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
3427 /// update expression, false otherwise.
3428 /// (e.g. true for X = X BinOp Expr)
3429 ///
3430 /// \returns A pair of the old value of X before the update, and the value
3431 /// used for the update.
3432 Expected<std::pair<Value *, Value *>>
3433 emitAtomicUpdate(InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
3434 AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3435 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX,
3436 bool IsXBinopExpr, bool IsIgnoreDenormalMode,
3437 bool IsFineGrainedMemory, bool IsRemoteMemory);
3438
3439 /// Emit the binary op. described by \p RMWOp, using \p Src1 and \p Src2 .
3440 ///
3441 /// \Return The instruction
3442 Value *emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3443 AtomicRMWInst::BinOp RMWOp);
3444
3445 bool IsFinalized;
3446
3447public:
3448 /// a struct to pack relevant information while generating atomic Ops
3449 struct AtomicOpValue {
3450 Value *Var = nullptr;
3451 Type *ElemTy = nullptr;
3452 bool IsSigned = false;
3453 bool IsVolatile = false;
3454 };
3455
3456 /// Emit atomic Read for : V = X --- Only Scalar data types.
3457 ///
3458 /// \param Loc The insert and source location description.
3459 /// \param X The target pointer to be atomically read
3460 /// \param V Memory address where to store atomically read
3461 /// value
3462 /// \param AO Atomic ordering of the generated atomic
3463 /// instructions.
3464 /// \param AllocaIP Insert point for allocas
3465 //
3466 /// \return Insertion point after generated atomic read IR.
3467 LLVM_ABI InsertPointTy createAtomicRead(const LocationDescription &Loc,
3468 AtomicOpValue &X, AtomicOpValue &V,
3469 AtomicOrdering AO,
3470 InsertPointTy AllocaIP);
3471
3472 /// Emit atomic write for : X = Expr --- Only Scalar data types.
3473 ///
3474 /// \param Loc The insert and source location description.
3475 /// \param X The target pointer to be atomically written to
3476 /// \param Expr The value to store.
3477 /// \param AO Atomic ordering of the generated atomic
3478 /// instructions.
3479 /// \param AllocaIP Insert point for allocas
3480 ///
3481 /// \return Insertion point after generated atomic Write IR.
3482 LLVM_ABI InsertPointTy createAtomicWrite(const LocationDescription &Loc,
3483 AtomicOpValue &X, Value *Expr,
3484 AtomicOrdering AO,
3485 InsertPointTy AllocaIP);
3486
3487 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
3488 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
3489 /// Only Scalar data types.
3490 ///
3491 /// \param Loc The insert and source location description.
3492 /// \param AllocaIP The insertion point to be used for alloca instructions.
3493 /// \param X The target atomic pointer to be updated
3494 /// \param Expr The value to update X with.
3495 /// \param AO Atomic ordering of the generated atomic instructions.
3496 /// \param RMWOp The binary operation used for update. If operation
3497 /// is not supported by atomicRMW, or belong to
3498 /// {FADD, FSUB, BAD_BINOP}. Then a `cmpExch` based
3499 /// atomic will be generated.
3500 /// \param UpdateOp Code generator for complex expressions that cannot be
3501 /// expressed through atomicrmw instruction.
3502 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
3503 /// update expression, false otherwise.
3504 /// (e.g. true for X = X BinOp Expr)
3505 ///
3506 /// \return Insertion point after generated atomic update IR.
3507 LLVM_ABI InsertPointOrErrorTy createAtomicUpdate(
3508 const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3509 Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3510 AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr,
3511 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
3512 bool IsRemoteMemory = false);
3513
3514 /// Emit atomic update for constructs: --- Only Scalar data types
3515 /// V = X; X = X BinOp Expr ,
3516 /// X = X BinOp Expr; V = X,
3517 /// V = X; X = Expr BinOp X,
3518 /// X = Expr BinOp X; V = X,
3519 /// V = X; X = UpdateOp(X),
3520 /// X = UpdateOp(X); V = X,
3521 ///
3522 /// \param Loc The insert and source location description.
3523 /// \param AllocaIP The insertion point to be used for alloca instructions.
3524 /// \param X The target atomic pointer to be updated
3525 /// \param V Memory address where to store captured value
3526 /// \param Expr The value to update X with.
3527 /// \param AO Atomic ordering of the generated atomic instructions
3528 /// \param RMWOp The binary operation used for update. If
3529 /// operation is not supported by atomicRMW, or belong to
3530 /// {FADD, FSUB, BAD_BINOP}. Then a cmpExch based
3531 /// atomic will be generated.
3532 /// \param UpdateOp Code generator for complex expressions that cannot be
3533 /// expressed through atomicrmw instruction.
3534 /// \param UpdateExpr true if X is an in place update of the form
3535 /// X = X BinOp Expr or X = Expr BinOp X
3536 /// \param IsXBinopExpr true if X is Left H.S. in Right H.S. part of the
3537 /// update expression, false otherwise.
3538 /// (e.g. true for X = X BinOp Expr)
3539 /// \param IsPostfixUpdate true if original value of 'x' must be stored in
3540 /// 'v', not an updated one.
3541 ///
3542 /// \return Insertion point after generated atomic capture IR.
3543 LLVM_ABI InsertPointOrErrorTy createAtomicCapture(
3544 const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3545 AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
3546 AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
3547 bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr,
3548 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
3549 bool IsRemoteMemory = false);
3550
3551 /// Emit atomic compare for constructs: --- Only scalar data types
3552 /// cond-expr-stmt:
3553 /// x = x ordop expr ? expr : x;
3554 /// x = expr ordop x ? expr : x;
3555 /// x = x == e ? d : x;
3556 /// x = e == x ? d : x; (this one is not in the spec)
3557 /// cond-update-stmt:
3558 /// if (x ordop expr) { x = expr; }
3559 /// if (expr ordop x) { x = expr; }
3560 /// if (x == e) { x = d; }
3561 /// if (e == x) { x = d; } (this one is not in the spec)
3562 /// conditional-update-capture-atomic:
3563 /// v = x; cond-update-stmt; (IsPostfixUpdate=true, IsFailOnly=false)
3564 /// cond-update-stmt; v = x; (IsPostfixUpdate=false, IsFailOnly=false)
3565 /// if (x == e) { x = d; } else { v = x; } (IsPostfixUpdate=false,
3566 /// IsFailOnly=true)
3567 /// r = x == e; if (r) { x = d; } (IsPostfixUpdate=false, IsFailOnly=false)
3568 /// r = x == e; if (r) { x = d; } else { v = x; } (IsPostfixUpdate=false,
3569 /// IsFailOnly=true)
3570 ///
3571 /// \param Loc The insert and source location description.
3572 /// \param X The target atomic pointer to be updated.
3573 /// \param V Memory address where to store captured value (for
3574 /// compare capture only).
3575 /// \param R Memory address where to store comparison result
3576 /// (for compare capture with '==' only).
3577 /// \param E The expected value ('e') for forms that use an
3578 /// equality comparison or an expression ('expr') for
3579 /// forms that use 'ordop' (logically an atomic maximum or
3580 /// minimum).
3581 /// \param D The desired value for forms that use an equality
3582 /// comparison. If forms that use 'ordop', it should be
3583 /// \p nullptr.
3584 /// \param AO Atomic ordering of the generated atomic instructions.
3585 /// \param Op Atomic compare operation. It can only be ==, <, or >.
3586 /// \param IsXBinopExpr True if the conditional statement is in the form where
3587 /// x is on LHS. It only matters for < or >.
3588 /// \param IsPostfixUpdate True if original value of 'x' must be stored in
3589 /// 'v', not an updated one (for compare capture
3590 /// only).
3591 /// \param IsFailOnly True if the original value of 'x' is stored to 'v'
3592 /// only when the comparison fails. This is only valid for
3593 /// the case the comparison is '=='.
3594 ///
3595 /// \return Insertion point after generated atomic capture IR.
3596 LLVM_ABI InsertPointTy
3597 createAtomicCompare(const LocationDescription &Loc, AtomicOpValue &X,
3598 AtomicOpValue &V, AtomicOpValue &R, Value *E, Value *D,
3599 AtomicOrdering AO, omp::OMPAtomicCompareOp Op,
3600 bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly);
3601 LLVM_ABI InsertPointTy createAtomicCompare(
3602 const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
3603 AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
3604 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
3605 bool IsFailOnly, AtomicOrdering Failure);
3606
3607 /// Create the control flow structure of a canonical OpenMP loop.
3608 ///
3609 /// The emitted loop will be disconnected, i.e. no edge to the loop's
3610 /// preheader and no terminator in the AfterBB. The OpenMPIRBuilder's
3611 /// IRBuilder location is not preserved.
3612 ///
3613 /// \param DL DebugLoc used for the instructions in the skeleton.
3614 /// \param TripCount Value to be used for the trip count.
3615 /// \param F Function in which to insert the BasicBlocks.
3616 /// \param PreInsertBefore Where to insert BBs that execute before the body,
3617 /// typically the body itself.
3618 /// \param PostInsertBefore Where to insert BBs that execute after the body.
3619 /// \param Name Base name used to derive BB
3620 /// and instruction names.
3621 ///
3622 /// \returns The CanonicalLoopInfo that represents the emitted loop.
3623 LLVM_ABI CanonicalLoopInfo *createLoopSkeleton(DebugLoc DL, Value *TripCount,
3624 Function *F,
3625 BasicBlock *PreInsertBefore,
3626 BasicBlock *PostInsertBefore,
3627 const Twine &Name = {});
3628 /// OMP Offload Info Metadata name string
3629 const std::string ompOffloadInfoName = "omp_offload.info";
3630
3631 /// Loads all the offload entries information from the host IR
3632 /// metadata. This function is only meant to be used with device code
3633 /// generation.
3634 ///
3635 /// \param M Module to load Metadata info from. Module passed maybe
3636 /// loaded from bitcode file, i.e, different from OpenMPIRBuilder::M module.
3637 LLVM_ABI void loadOffloadInfoMetadata(Module &M);
3638
3639 /// Loads all the offload entries information from the host IR
3640 /// metadata read from the file passed in as the HostFilePath argument. This
3641 /// function is only meant to be used with device code generation.
3642 ///
3643 /// \param HostFilePath The path to the host IR file,
3644 /// used to load in offload metadata for the device, allowing host and device
3645 /// to maintain the same metadata mapping.
3646 LLVM_ABI void loadOffloadInfoMetadata(vfs::FileSystem &VFS,
3647 StringRef HostFilePath);
3648
3649 /// Gets (if variable with the given name already exist) or creates
3650 /// internal global variable with the specified Name. The created variable has
3651 /// linkage CommonLinkage by default and is initialized by null value.
3652 /// \param Ty Type of the global variable. If it is exist already the type
3653 /// must be the same.
3654 /// \param Name Name of the variable.
3655 LLVM_ABI GlobalVariable *
3656 getOrCreateInternalVariable(Type *Ty, const StringRef &Name,
3657 unsigned AddressSpace = 0);
3658};
3659
3660/// Class to represented the control flow structure of an OpenMP canonical loop.
3661///
3662/// The control-flow structure is standardized for easy consumption by
3663/// directives associated with loops. For instance, the worksharing-loop
3664/// construct may change this control flow such that each loop iteration is
3665/// executed on only one thread. The constraints of a canonical loop in brief
3666/// are:
3667///
3668/// * The number of loop iterations must have been computed before entering the
3669/// loop.
3670///
3671/// * Has an (unsigned) logical induction variable that starts at zero and
3672/// increments by one.
3673///
3674/// * The loop's CFG itself has no side-effects. The OpenMP specification
3675/// itself allows side-effects, but the order in which they happen, including
3676/// how often or whether at all, is unspecified. We expect that the frontend
3677/// will emit those side-effect instructions somewhere (e.g. before the loop)
3678/// such that the CanonicalLoopInfo itself can be side-effect free.
3679///
3680/// Keep in mind that CanonicalLoopInfo is meant to only describe a repeated
3681/// execution of a loop body that satifies these constraints. It does NOT
3682/// represent arbitrary SESE regions that happen to contain a loop. Do not use
3683/// CanonicalLoopInfo for such purposes.
3684///
3685/// The control flow can be described as follows:
3686///
3687/// Preheader
3688/// |
3689/// /-> Header
3690/// | |
3691/// | Cond---\
3692/// | | |
3693/// | Body |
3694/// | | | |
3695/// | <...> |
3696/// | | | |
3697/// \--Latch |
3698/// |
3699/// Exit
3700/// |
3701/// After
3702///
3703/// The loop is thought to start at PreheaderIP (at the Preheader's terminator,
3704/// including) and end at AfterIP (at the After's first instruction, excluding).
3705/// That is, instructions in the Preheader and After blocks (except the
3706/// Preheader's terminator) are out of CanonicalLoopInfo's control and may have
3707/// side-effects. Typically, the Preheader is used to compute the loop's trip
3708/// count. The instructions from BodyIP (at the Body block's first instruction,
3709/// excluding) until the Latch are also considered outside CanonicalLoopInfo's
3710/// control and thus can have side-effects. The body block is the single entry
3711/// point into the loop body, which may contain arbitrary control flow as long
3712/// as all control paths eventually branch to the Latch block.
3713///
3714/// TODO: Consider adding another standardized BasicBlock between Body CFG and
3715/// Latch to guarantee that there is only a single edge to the latch. It would
3716/// make loop transformations easier to not needing to consider multiple
3717/// predecessors of the latch (See redirectAllPredecessorsTo) and would give us
3718/// an equivalant to PreheaderIP, AfterIP and BodyIP for inserting code that
3719/// executes after each body iteration.
3720///
3721/// There must be no loop-carried dependencies through llvm::Values. This is
3722/// equivalant to that the Latch has no PHINode and the Header's only PHINode is
3723/// for the induction variable.
3724///
3725/// All code in Header, Cond, Latch and Exit (plus the terminator of the
3726/// Preheader) are CanonicalLoopInfo's responsibility and their build-up checked
3727/// by assertOK(). They are expected to not be modified unless explicitly
3728/// modifying the CanonicalLoopInfo through a methods that applies a OpenMP
3729/// loop-associated construct such as applyWorkshareLoop, tileLoops, unrollLoop,
3730/// etc. These methods usually invalidate the CanonicalLoopInfo and re-use its
3731/// basic blocks. After invalidation, the CanonicalLoopInfo must not be used
3732/// anymore as its underlying control flow may not exist anymore.
3733/// Loop-transformation methods such as tileLoops, collapseLoops and unrollLoop
3734/// may also return a new CanonicalLoopInfo that can be passed to other
3735/// loop-associated construct implementing methods. These loop-transforming
3736/// methods may either create a new CanonicalLoopInfo usually using
3737/// createLoopSkeleton and invalidate the input CanonicalLoopInfo, or reuse and
3738/// modify one of the input CanonicalLoopInfo and return it as representing the
3739/// modified loop. What is done is an implementation detail of
3740/// transformation-implementing method and callers should always assume that the
3741/// CanonicalLoopInfo passed to it is invalidated and a new object is returned.
3742/// Returned CanonicalLoopInfo have the same structure and guarantees as the one
3743/// created by createCanonicalLoop, such that transforming methods do not have
3744/// to special case where the CanonicalLoopInfo originated from.
3745///
3746/// Generally, methods consuming CanonicalLoopInfo do not need an
3747/// OpenMPIRBuilder::InsertPointTy as argument, but use the locations of the
3748/// CanonicalLoopInfo to insert new or modify existing instructions. Unless
3749/// documented otherwise, methods consuming CanonicalLoopInfo do not invalidate
3750/// any InsertPoint that is outside CanonicalLoopInfo's control. Specifically,
3751/// any InsertPoint in the Preheader, After or Block can still be used after
3752/// calling such a method.
3753///
3754/// TODO: Provide mechanisms for exception handling and cancellation points.
3755///
3756/// Defined outside OpenMPIRBuilder because nested classes cannot be
3757/// forward-declared, e.g. to avoid having to include the entire OMPIRBuilder.h.
3758class CanonicalLoopInfo {
3759 friend class OpenMPIRBuilder;
3760
3761private:
3762 BasicBlock *Header = nullptr;
3763 BasicBlock *Cond = nullptr;
3764 BasicBlock *Latch = nullptr;
3765 BasicBlock *Exit = nullptr;
3766
3767 // Hold the MLIR value for the `lastiter` of the canonical loop.
3768 Value *LastIter = nullptr;
3769
3770 /// Add the control blocks of this loop to \p BBs.
3771 ///
3772 /// This does not include any block from the body, including the one returned
3773 /// by getBody().
3774 ///
3775 /// FIXME: This currently includes the Preheader and After blocks even though
3776 /// their content is (mostly) not under CanonicalLoopInfo's control.
3777 /// Re-evaluated whether this makes sense.
3778 void collectControlBlocks(SmallVectorImpl<BasicBlock *> &BBs);
3779
3780 /// Sets the number of loop iterations to the given value. This value must be
3781 /// valid in the condition block (i.e., defined in the preheader) and is
3782 /// interpreted as an unsigned integer.
3783 void setTripCount(Value *TripCount);
3784
3785 /// Replace all uses of the canonical induction variable in the loop body with
3786 /// a new one.
3787 ///
3788 /// The intended use case is to update the induction variable for an updated
3789 /// iteration space such that it can stay normalized in the 0...tripcount-1
3790 /// range.
3791 ///
3792 /// The \p Updater is called with the (presumable updated) current normalized
3793 /// induction variable and is expected to return the value that uses of the
3794 /// pre-updated induction values should use instead, typically dependent on
3795 /// the new induction variable. This is a lambda (instead of e.g. just passing
3796 /// the new value) to be able to distinguish the uses of the pre-updated
3797 /// induction variable and uses of the induction varible to compute the
3798 /// updated induction variable value.
3799 void mapIndVar(llvm::function_ref<Value *(Instruction *)> Updater);
3800
3801public:
3802 /// Sets the last iteration variable for this loop.
3803 void setLastIter(Value *IterVar) { LastIter = std::move(IterVar); }
3804
3805 /// Returns the last iteration variable for this loop.
3806 /// Certain use-cases (like translation of linear clause) may access
3807 /// this variable even after a loop transformation. Hence, do not guard
3808 /// this getter function by `isValid`. It is the responsibility of the
3809 /// callee to ensure this functionality is not invoked by a non-outlined
3810 /// CanonicalLoopInfo object (in which case, `setLastIter` will never be
3811 /// invoked and `LastIter` will be by default `nullptr`).
3812 Value *getLastIter() { return LastIter; }
3813
3814 /// Returns whether this object currently represents the IR of a loop. If
3815 /// returning false, it may have been consumed by a loop transformation or not
3816 /// been intialized. Do not use in this case;
3817 bool isValid() const { return Header; }
3818
3819 /// The preheader ensures that there is only a single edge entering the loop.
3820 /// Code that must be execute before any loop iteration can be emitted here,
3821 /// such as computing the loop trip count and begin lifetime markers. Code in
3822 /// the preheader is not considered part of the canonical loop.
3823 LLVM_ABI BasicBlock *getPreheader() const;
3824
3825 /// The header is the entry for each iteration. In the canonical control flow,
3826 /// it only contains the PHINode for the induction variable.
3827 BasicBlock *getHeader() const {
3828 assert(isValid() && "Requires a valid canonical loop");
3829 return Header;
3830 }
3831
3832 /// The condition block computes whether there is another loop iteration. If
3833 /// yes, branches to the body; otherwise to the exit block.
3834 BasicBlock *getCond() const {
3835 assert(isValid() && "Requires a valid canonical loop");
3836 return Cond;
3837 }
3838
3839 /// The body block is the single entry for a loop iteration and not controlled
3840 /// by CanonicalLoopInfo. It can contain arbitrary control flow but must
3841 /// eventually branch to the \p Latch block.
3842 BasicBlock *getBody() const {
3843 assert(isValid() && "Requires a valid canonical loop");
3844 return cast<BranchInst>(Cond->getTerminator())->getSuccessor(0);
3845 }
3846
3847 /// Reaching the latch indicates the end of the loop body code. In the
3848 /// canonical control flow, it only contains the increment of the induction
3849 /// variable.
3850 BasicBlock *getLatch() const {
3851 assert(isValid() && "Requires a valid canonical loop");
3852 return Latch;
3853 }
3854
3855 /// Reaching the exit indicates no more iterations are being executed.
3856 BasicBlock *getExit() const {
3857 assert(isValid() && "Requires a valid canonical loop");
3858 return Exit;
3859 }
3860
3861 /// The after block is intended for clean-up code such as lifetime end
3862 /// markers. It is separate from the exit block to ensure, analogous to the
3863 /// preheader, it having just a single entry edge and being free from PHI
3864 /// nodes should there be multiple loop exits (such as from break
3865 /// statements/cancellations).
3866 BasicBlock *getAfter() const {
3867 assert(isValid() && "Requires a valid canonical loop");
3868 return Exit->getSingleSuccessor();
3869 }
3870
3871 /// Returns the llvm::Value containing the number of loop iterations. It must
3872 /// be valid in the preheader and always interpreted as an unsigned integer of
3873 /// any bit-width.
3874 Value *getTripCount() const {
3875 assert(isValid() && "Requires a valid canonical loop");
3876 Instruction *CmpI = &Cond->front();
3877 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
3878 return CmpI->getOperand(1);
3879 }
3880
3881 /// Returns the instruction representing the current logical induction
3882 /// variable. Always unsigned, always starting at 0 with an increment of one.
3883 Instruction *getIndVar() const {
3884 assert(isValid() && "Requires a valid canonical loop");
3885 Instruction *IndVarPHI = &Header->front();
3886 assert(isa<PHINode>(IndVarPHI) && "First inst must be the IV PHI");
3887 return IndVarPHI;
3888 }
3889
3890 /// Return the type of the induction variable (and the trip count).
3891 Type *getIndVarType() const {
3892 assert(isValid() && "Requires a valid canonical loop");
3893 return getIndVar()->getType();
3894 }
3895
3896 /// Return the insertion point for user code before the loop.
3897 OpenMPIRBuilder::InsertPointTy getPreheaderIP() const {
3898 assert(isValid() && "Requires a valid canonical loop");
3899 BasicBlock *Preheader = getPreheader();
3900 return {Preheader, std::prev(Preheader->end())};
3901 };
3902
3903 /// Return the insertion point for user code in the body.
3904 OpenMPIRBuilder::InsertPointTy getBodyIP() const {
3905 assert(isValid() && "Requires a valid canonical loop");
3906 BasicBlock *Body = getBody();
3907 return {Body, Body->begin()};
3908 };
3909
3910 /// Return the insertion point for user code after the loop.
3911 OpenMPIRBuilder::InsertPointTy getAfterIP() const {
3912 assert(isValid() && "Requires a valid canonical loop");
3913 BasicBlock *After = getAfter();
3914 return {After, After->begin()};
3915 };
3916
3917 Function *getFunction() const {
3918 assert(isValid() && "Requires a valid canonical loop");
3919 return Header->getParent();
3920 }
3921
3922 /// Consistency self-check.
3923 LLVM_ABI void assertOK() const;
3924
3925 /// Invalidate this loop. That is, the underlying IR does not fulfill the
3926 /// requirements of an OpenMP canonical loop anymore.
3927 LLVM_ABI void invalidate();
3928};
3929
3930/// ScanInfo holds the information to assist in lowering of Scan reduction.
3931/// Before lowering, the body of the for loop specifying scan reduction is
3932/// expected to have the following structure
3933///
3934/// Loop Body Entry
3935/// |
3936/// Code before the scan directive
3937/// |
3938/// Scan Directive
3939/// |
3940/// Code after the scan directive
3941/// |
3942/// Loop Body Exit
3943/// When `createCanonicalScanLoops` is executed, the bodyGen callback of it
3944/// transforms the body to:
3945///
3946/// Loop Body Entry
3947/// |
3948/// OMPScanDispatch
3949///
3950/// OMPBeforeScanBlock
3951/// |
3952/// OMPScanLoopExit
3953/// |
3954/// Loop Body Exit
3955///
3956/// The insert point is updated to the first insert point of OMPBeforeScanBlock.
3957/// It dominates the control flow of code generated until
3958/// scan directive is encountered and OMPAfterScanBlock dominates the
3959/// control flow of code generated after scan is encountered. The successor
3960/// of OMPScanDispatch can be OMPBeforeScanBlock or OMPAfterScanBlock based
3961/// on 1.whether it is in Input phase or Scan Phase , 2. whether it is an
3962/// exclusive or inclusive scan. This jump is added when `createScan` is
3963/// executed. If input loop is being generated, if it is inclusive scan,
3964/// `OMPAfterScanBlock` succeeds `OMPScanDispatch` , if exclusive,
3965/// `OMPBeforeScanBlock` succeeds `OMPDispatch` and vice versa for scan loop. At
3966/// the end of the input loop, temporary buffer is populated and at the
3967/// beginning of the scan loop, temporary buffer is read. After scan directive
3968/// is encountered, insertion point is updated to `OMPAfterScanBlock` as it is
3969/// expected to dominate the code after the scan directive. Both Before and
3970/// After scan blocks are succeeded by `OMPScanLoopExit`.
3971/// Temporary buffer allocations are done in `ScanLoopInit` block before the
3972/// lowering of for-loop. The results are copied back to reduction variable in
3973/// `ScanLoopFinish` block.
3974class ScanInfo {
3975public:
3976 /// Dominates the body of the loop before scan directive
3977 llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
3978
3979 /// Dominates the body of the loop before scan directive
3980 llvm::BasicBlock *OMPAfterScanBlock = nullptr;
3981
3982 /// Controls the flow to before or after scan blocks
3983 llvm::BasicBlock *OMPScanDispatch = nullptr;
3984
3985 /// Exit block of loop body
3986 llvm::BasicBlock *OMPScanLoopExit = nullptr;
3987
3988 /// Block before loop body where scan initializations are done
3989 llvm::BasicBlock *OMPScanInit = nullptr;
3990
3991 /// Block after loop body where scan finalizations are done
3992 llvm::BasicBlock *OMPScanFinish = nullptr;
3993
3994 /// If true, it indicates Input phase is lowered; else it indicates
3995 /// ScanPhase is lowered
3996 bool OMPFirstScanLoop = false;
3997
3998 /// Maps the private reduction variable to the pointer of the temporary
3999 /// buffer
4000 llvm::SmallDenseMap<llvm::Value *, llvm::Value *> *ScanBuffPtrs;
4001
4002 /// Keeps track of value of iteration variable for input/scan loop to be
4003 /// used for Scan directive lowering
4004 llvm::Value *IV;
4005
4006 /// Stores the span of canonical loop being lowered to be used for temporary
4007 /// buffer allocation or Finalization.
4008 llvm::Value *Span;
4009
4010 ScanInfo() {
4011 ScanBuffPtrs = new llvm::SmallDenseMap<llvm::Value *, llvm::Value *>();
4012 }
4013
4014 ~ScanInfo() { delete (ScanBuffPtrs); }
4015};
4016
4017} // end namespace llvm
4018
4019#endif // LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
arc branch finalize
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
This file defines the BumpPtrAllocator interface.
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")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define LLVM_ABI
Definition Compiler.h:213
DXIL Finalize Linkage
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix, bool &Renamed)
Get the name of a profiling variable for a particular function.
bool operator<(const DeltaInfo &LHS, int64_t Delta)
Definition LineTable.cpp:30
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define G(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
static std::optional< uint64_t > getSizeInBytes(std::optional< uint64_t > SizeInBits)
#define T
This file defines constans and helpers used when dealing with OpenMP.
Provides definitions for Target specific Grid Values.
static const omp::GV & getGridValue(const Triple &T, Function *Kernel)
const SmallVectorImpl< MachineOperand > & Cond
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")))
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
std::unordered_set< BasicBlock * > BlockSet
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static uint32_t getFlags(const Symbol *Sym)
Definition TapiFile.cpp:26
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringLiteral > StandardNames)
Initialize the set of available library functions based on the specified target triple.
@ None
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * RHS
Value * LHS
static cl::opt< unsigned > MaxThreads("xcore-max-threads", cl::Optional, cl::desc("Maximum number of threads (for emulation thread-local storage)"), cl::Hidden, cl::value_desc("number"), cl::init(8))
static const uint32_t IV[8]
Definition blake3_impl.h:83
LLVM Basic Block Representation.
Definition BasicBlock.h:62
A debug info location.
Definition DebugLoc.h:124
InsertPoint - A saved insertion point.
Definition IRBuilder.h:291
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2780
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
The virtual file system interface.
LLVM_ABI bool isGPU(const Module &M)
Return true iff M target a GPU (and we can use GPU AS reasoning).
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
Offsets
Offsets in bytes from the start of the input buffer.
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:60
bool empty() const
Definition BasicBlock.h:101
Context & getContext() const
Definition BasicBlock.h:99
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:456
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1657
FunctionAddr VTableAddr Count
Definition InstrProf.h:139