18#include "llvm/ADT/STLExtras.h"
19#include "llvm/BinaryFormat/Dwarf.h"
20#include "llvm/IR/DebugInfoMetadata.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/Support/ErrorHandling.h"
41 DISourceLanguageNameAttr &language);
47 DISourceLanguageNameAttr language);
49#include "mlir/Dialect/LLVMIR/LLVMAttrInterfaces.cpp.inc"
50#include "mlir/Dialect/LLVMIR/LLVMOpsEnums.cpp.inc"
51#define GET_ATTRDEF_CLASSES
52#include "mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.cpp.inc"
60 Type type, ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
61 const ::mlir::DataLayout *dataLayout,
65 emitError() <<
"type must be LLVM type with size, but got " << type;
68 if (ordering == ptr::AtomicOrdering::not_atomic)
74 emitError() <<
"expected a valid data layout";
79 emitError() <<
"unsupported type " << type <<
" for atomic access";
85bool AddressSpaceAttr::isValidLoad(
86 Type type, ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
87 const ::mlir::DataLayout *dataLayout,
93bool AddressSpaceAttr::isValidStore(
94 Type type, ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
95 const ::mlir::DataLayout *dataLayout,
101bool AddressSpaceAttr::isValidAtomicOp(
102 ptr::AtomicBinOp op,
Type type, ptr::AtomicOrdering ordering,
103 std::optional<int64_t> alignment, const ::mlir::DataLayout *dataLayout,
106 assert(
false &&
"unimplemented, see TODO in the source.");
110bool AddressSpaceAttr::isValidAtomicXchg(
111 Type type, ptr::AtomicOrdering successOrdering,
112 ptr::AtomicOrdering failureOrdering, std::optional<int64_t> alignment,
113 const ::mlir::DataLayout *dataLayout,
116 assert(
false &&
"unimplemented, see TODO in the source.");
120bool AddressSpaceAttr::isValidAddrSpaceCast(
124 assert(
false &&
"unimplemented, see TODO in the source.");
128bool AddressSpaceAttr::isValidPtrIntCast(
133 assert(
false &&
"unimplemented, see TODO in the source.");
142 llvm::LLVMContext::MD_dbg, llvm::LLVMContext::MD_prof};
146#define LLVM_FIXED_MD_KIND(EnumID, Name, Value) \
147 case llvm::LLVMContext::EnumID: \
149#include "llvm/IR/FixedMetadataKinds.def"
150#undef LLVM_FIXED_MD_KIND
152 llvm_unreachable(
"unknown fixed metadata kind");
157 StringAttr metadataName, MDNodeAttr node) {
159 StringRef name = metadataName.getValue();
161 return emitError() <<
"function_metadata entry name must not be empty";
165 return emitError() <<
"reserved function_metadata entry '" << name
166 <<
"' is not supported by the generic carrier";
177 Attribute id, AliasScopeDomainAttr domain,
178 StringAttr description) {
181 if (!llvm::isa<StringAttr, DistinctAttr>(
id))
183 <<
"id of an alias scope must be a StringAttr or a DistrinctAttr";
193 return llvm::isa<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr,
194 DICompositeTypeAttr, DIDerivedTypeAttr, DIEnumeratorAttr,
195 DIFileAttr, DIGenericSubrangeAttr, DIGlobalVariableAttr,
196 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
197 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
198 DINamespaceAttr, DINullTypeAttr, DIAnnotationAttr,
199 DIStringTypeAttr, DISubprogramAttr, DISubrangeAttr,
200 DISubroutineTypeAttr>(attr);
208 return llvm::isa<DICommonBlockAttr, DICompileUnitAttr, DICompositeTypeAttr,
210 DIModuleAttr, DINamespaceAttr>(attr);
218 return llvm::isa<DILexicalBlockAttr, DILexicalBlockFileAttr,
219 DISubprogramAttr>(attr);
227 return llvm::isa<DILocalVariableAttr, DIGlobalVariableAttr>(attr);
235 return llvm::isa<DINullTypeAttr, DIBasicTypeAttr, DICompositeTypeAttr,
236 DIDerivedTypeAttr, DIStringTypeAttr, DISubroutineTypeAttr>(
244LogicalResult DIDerivedTypeAttr::verify(
247 uint64_t sizeInBits, uint32_t alignInBits, uint64_t offsetInBits,
248 std::optional<unsigned> dwarfAddressSpace, DIFlags flags,
250 if (extraData && !llvm::isa<DINodeAttr, IntegerAttr>(extraData))
251 return emitError() <<
"extraData must be a DINodeAttr or an IntegerAttr";
260 return llvm::isa<TBAATypeDescriptorAttr, TBAARootAttr>(attr);
274 if (callStack.empty())
275 return emitError() <<
"call stack of a memprof MemInfoBlock must not be "
284MemoryEffectsAttr MemoryEffectsAttr::get(
MLIRContext *context,
286 if (memInfoArgs.empty())
287 return MemoryEffectsAttr::get(context, ModRefInfo::ModRef,
293 if (memInfoArgs.size() == 6)
294 return MemoryEffectsAttr::get(context, memInfoArgs[0], memInfoArgs[1],
295 memInfoArgs[2], memInfoArgs[3],
296 memInfoArgs[4], memInfoArgs[5]);
300bool MemoryEffectsAttr::isReadWrite() {
301 if (this->getArgMem() != ModRefInfo::ModRef)
303 if (this->getInaccessibleMem() != ModRefInfo::ModRef)
305 if (this->getOther() != ModRefInfo::ModRef)
307 if (this->getErrnoMem() != ModRefInfo::ModRef)
309 if (this->getTargetMem0() != ModRefInfo::ModRef)
311 if (this->getTargetMem1() != ModRefInfo::ModRef)
320DIExpressionAttr DIExpressionAttr::get(MLIRContext *context) {
321 return get(context, ArrayRef<DIExpressionElemAttr>({}));
326 auto operandParser = [&]() -> LogicalResult {
327 uint64_t operand = 0;
328 if (!args.empty() && opcode == llvm::dwarf::DW_OP_LLVM_convert) {
332 operand = llvm::dwarf::getAttributeEncoding(keyword);
336 <<
"encountered unknown attribute encoding \"" << keyword
348 <<
"expected integer operand";
352 args.push_back(operand);
363 llvm::interleaveComma(args, printer, [&](uint64_t operand) {
364 if (i > 0 && opcode == llvm::dwarf::DW_OP_LLVM_convert) {
365 if (
const StringRef keyword =
366 llvm::dwarf::AttributeEncodingString(operand);
382DIRecursiveTypeAttrInterface
383DICompositeTypeAttr::withRecId(DistinctAttr recId) {
384 return DICompositeTypeAttr::get(
385 getContext(), recId, getIsRecSelf(), getTag(), getName(), getFile(),
386 getLine(), getScope(), getBaseType(),
getFlags(), getSizeInBits(),
387 getAlignInBits(), getDataLocation(), getRank(), getAllocated(),
388 getAssociated(), getIdentifier(), getDiscriminator(), getElements());
391DIRecursiveTypeAttrInterface
392DICompositeTypeAttr::getRecSelf(DistinctAttr recId) {
393 return DICompositeTypeAttr::get(recId.
getContext(), recId,
true,
394 0, {}, {}, 0, {}, {}, DIFlags(), 0, 0, {}, {},
403 DISourceLanguageNameAttr &language) {
404 DISourceLanguageNameAttr nestedLanguage;
408 if (failed(*nestedResult))
410 language = nestedLanguage;
419 if (
unsigned value = llvm::dwarf::getLanguage(spelling)) {
420 language = DISourceLanguageNameAttr::get(
426 <<
"invalid debug info source language: " << spelling;
430 DISourceLanguageNameAttr language) {
432 if (language.getLanguage() && !language.getName() && !language.getVersion() &&
433 !language.getDialect()) {
434 printer << llvm::dwarf::LanguageString(language.getLanguage());
440LogicalResult DISourceLanguageNameAttr::verify(
442 unsigned name, std::optional<uint32_t> version,
unsigned ) {
443 if (
static_cast<bool>(language) ==
static_cast<bool>(name))
444 return emitError() <<
"expected exactly one of language or name";
445 if (name && !version)
446 return emitError() <<
"DW_LNAME requires a version";
447 if (language && version)
448 return emitError() <<
"DW_LANG cannot have a version";
456DIRecursiveTypeAttrInterface DICompileUnitAttr::withRecId(DistinctAttr recId) {
457 return DICompileUnitAttr::get(
459 getFile(), getProducer(), getIsOptimized(), getEmissionKind(),
460 getIsDebugInfoForProfiling(), getNameTableKind(), getSplitDebugFilename(),
461 getImportedEntities());
464DIRecursiveTypeAttrInterface DICompileUnitAttr::getRecSelf(DistinctAttr recId) {
466 return DICompileUnitAttr::get(
469 {}, {},
false, DIEmissionKind::None,
470 false, DINameTableKind::Default,
474LogicalResult DICompileUnitAttr::verify(
476 bool isRecSelf, DistinctAttr
id, DISourceLanguageNameAttr sourceLanguage,
477 DIFileAttr file, StringAttr producer,
bool isOptimized,
478 DIEmissionKind emissionKind,
bool isDebugInfoForProfiling,
479 DINameTableKind nameTableKind, StringAttr splitDebugFilename,
480 ArrayRef<DINodeAttr> importedEntities) {
484 return emitError() <<
"sourceLanguage must be set";
492DIRecursiveTypeAttrInterface DISubprogramAttr::withRecId(DistinctAttr recId) {
493 return DISubprogramAttr::get(
getContext(), recId, getIsRecSelf(), getId(),
494 getCompileUnit(), getScope(), getName(),
495 getLinkageName(), getFile(), getLine(),
496 getScopeLine(), getSubprogramFlags(),
getType(),
497 getRetainedNodes(), getAnnotations());
500DIRecursiveTypeAttrInterface DISubprogramAttr::getRecSelf(DistinctAttr recId) {
501 return DISubprogramAttr::get(recId.
getContext(), recId,
true,
502 {}, {}, {}, {}, {}, {}, 0, 0, {}, {}, {}, {});
509Attribute ConstantRangeAttr::parse(AsmParser &parser, Type odsType) {
511 IntegerType widthType;
516 unsigned bitWidth = widthType.getWidth();
517 APInt lower(bitWidth, 0);
518 APInt upper(bitWidth, 0);
523 lower = lower.sextOrTrunc(bitWidth);
524 upper = upper.sextOrTrunc(bitWidth);
529void ConstantRangeAttr::print(AsmPrinter &printer)
const {
530 printer <<
"<i" << getLower().getBitWidth() <<
", " << getLower() <<
", "
531 << getUpper() <<
">";
535ConstantRangeAttr::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
536 APInt lower, APInt upper) {
537 if (lower.getBitWidth() != upper.getBitWidth())
539 <<
"expected lower and upper to have matching bitwidths but got "
540 << lower.getBitWidth() <<
" vs. " << upper.getBitWidth();
548TargetFeaturesAttr TargetFeaturesAttr::get(MLIRContext *context,
549 llvm::ArrayRef<StringRef> features) {
550 return Base::get(context,
551 llvm::map_to_vector(features, [&](StringRef feature) {
552 return StringAttr::get(context, feature);
558 MLIRContext *context,
559 llvm::ArrayRef<StringRef> features) {
560 return Base::getChecked(
emitError, context,
561 llvm::map_to_vector(features, [&](StringRef feature) {
562 return StringAttr::get(context, feature);
566TargetFeaturesAttr TargetFeaturesAttr::get(MLIRContext *context,
567 StringRef targetFeatures) {
568 SmallVector<StringRef> features;
569 targetFeatures.split(features,
',', -1,
571 return get(context, features);
576 MLIRContext *context, StringRef targetFeatures) {
577 SmallVector<StringRef> features;
578 targetFeatures.split(features,
',', -1,
580 ArrayRef featuresRef(features);
586 llvm::ArrayRef<StringAttr> features) {
587 for (StringAttr featureAttr : features) {
588 if (!featureAttr || featureAttr.empty())
589 return emitError() <<
"target features can not be null or empty";
590 auto feature = featureAttr.strref();
591 if (feature[0] !=
'+' && feature[0] !=
'-')
592 return emitError() <<
"target features must start with '+' or '-'";
593 if (feature.contains(
','))
594 return emitError() <<
"target features can not contain ','";
599bool TargetFeaturesAttr::contains(StringAttr feature)
const {
603 return llvm::is_contained(getFeatures(), feature);
606bool TargetFeaturesAttr::contains(StringRef feature)
const {
609 return llvm::is_contained(getFeatures(), feature);
612std::string TargetFeaturesAttr::getFeaturesString()
const {
613 std::string featuresString;
614 llvm::raw_string_ostream ss(featuresString);
616 getFeatures(), ss, [&](
auto &feature) { ss << feature.strref(); },
",");
617 return featuresString;
620TargetFeaturesAttr TargetFeaturesAttr::featuresAt(Operation *op) {
624 Operation *parentOp = parentFunction.getOperation();
625 if (
auto llvmFunc = dyn_cast<LLVMFuncOp>(parentOp))
626 return llvmFunc.getTargetFeaturesAttr();
630 TargetFeaturesAttr targetFeatures;
632 parentOp, [&](StringRef name, Attribute &attr) {
633 if (name == getAttributeName())
634 targetFeatures = dyn_cast<TargetFeaturesAttr>(attr);
637 return targetFeatures;
643 auto stringKey = dyn_cast<StringAttr>(key);
650 if (
contains((std::string(
"+") + stringKey.strref()).str()))
653 if (
contains((std::string(
"-") + stringKey.strref()).str()))
664 if (
auto stringAttrKey = dyn_cast<StringAttr>(key)) {
665 if (stringAttrKey.getValue() ==
"triple")
667 if (stringAttrKey.getValue() ==
"chip")
669 if (stringAttrKey.getValue() ==
"features" && getFeatures())
670 return getFeatures();
682 if (key == LLVMDialect::getModuleFlagKeyCGProfileName()) {
683 auto arrayAttr = dyn_cast<ArrayAttr>(value);
684 if ((!arrayAttr) || (!llvm::all_of(arrayAttr, [](
Attribute attr) {
685 return isa<ModuleFlagCGProfileEntryAttr>(attr);
688 <<
"'CG Profile' key expects an array of '#llvm.cgprofile_entry'";
692 if (key == LLVMDialect::getModuleFlagKeyProfileSummaryName()) {
693 if (!isa<ModuleFlagProfileSummaryAttr>(value))
694 return emitError() <<
"'ProfileSummary' key expects a "
695 "'#llvm.profile_summary' attribute";
699 if (isa<IntegerAttr, StringAttr, IntrinsicIntegerAttrInterface>(value))
707 if (
auto arrayAttr = dyn_cast<ArrayAttr>(value))
708 if (!arrayAttr.empty() &&
709 llvm::all_of(arrayAttr, [](
Attribute a) { return isa<StringAttr>(a); }))
713 <<
"only integer, integer-like dialect attributes, string, "
714 "and string-array values are currently supported for "
721 LLVM::ModFlagBehavior flagBehavior, StringAttr key,
726ModFlagBehavior ModuleFlagAttr::getModuleFlagBehavior()
const {
727 return getBehavior();
730StringAttr ModuleFlagAttr::getModuleFlagKey()
const {
return getKey(); }
732Attribute ModuleFlagAttr::getModuleFlagValue()
const {
return getValue(); }
740 Attribute arg,
unsigned addressSpace) {
743 if (!isa<MDGlobalValueAttr, MDNullAttr, MDAddrSpaceCastAttr>(arg))
744 return emitError() <<
"expected #llvm.md_global_value, #llvm.md_null, or "
745 "#llvm.md_addrspacecast operand, but got "
756 StringAttr name, IntegerAttr value,
bool isUnsigned) {
757 if (!value.getType().isSignlessInteger())
758 return emitError() <<
"expected signless integer type for 'value'";
static llvm::DISourceLanguageName getSourceLanguage(DICompileUnitAttr attr)
static StringRef getFixedMetadataKindName(unsigned kind)
static void printExpressionArg(AsmPrinter &printer, uint64_t opcode, ArrayRef< uint64_t > args)
Prints DWARF expression arguments with respect to the specific DWARF operation.
static ParseResult parseExpressionArg(AsmParser &parser, uint64_t opcode, SmallVector< uint64_t > &args)
Parses DWARF expression arguments with respect to the DWARF operation opcode.
static ParseResult parseSourceLanguage(AsmParser &parser, DISourceLanguageNameAttr &language)
Parses a source language from either the historical inline DW_LANG_* syntax or a nested DISourceLangu...
static constexpr unsigned kReservedFunctionMetadataKinds[]
static void printSourceLanguage(AsmPrinter &printer, DISourceLanguageNameAttr language)
Prints an unversioned source language without a dialect using the historical inline DW_LANG_* syntax.
static bool contains(SMRange range, SMLoc loc)
Returns true if the given range contains the given source location.
static arith::FastMathFlags getFlags(arith::FastMathFlagsAttr fastmath)
Returns the flags held by fastmath, or none if it is null.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual OptionalParseResult parseOptionalAttribute(Attribute &result, Type type={})=0
Parse an arbitrary optional attribute of a given type and return it in result.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printAttribute(Attribute attr)
Attributes are known-constant values of operations.
MLIRContext * getContext() const
Return the context this attribute belongs to.
static BoolAttr get(MLIRContext *context, bool value)
This class represents a diagnostic that is inflight and set to be reported.
This class represents a LLVM attribute that describes a local debug info scope.
static bool classof(Attribute attr)
Support LLVM type casting.
constexpr Attribute()=default
static bool classof(Attribute attr)
This class represents a LLVM attribute that describes a debug info scope.
static bool classof(Attribute attr)
Support LLVM type casting.
This class represents a LLVM attribute that describes a debug info type.
static bool classof(Attribute attr)
Support LLVM type casting.
static bool classof(Attribute attr)
Support LLVM type casting.
static bool classof(Attribute attr)
Support LLVM type casting.
constexpr Attribute()=default
MLIRContext is the top-level object for a collection of MLIR operations.
void walkInherentAttrs(Operation *op, InherentAttrVisitor visitor) const
Visit the inherent attributes stored in the properties of op.
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
OperationName getName()
The name of an operation is the key identifier for it.
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
LogicalResult verifyModuleFlagValue(StringAttr key, Attribute value, function_ref< InFlightDiagnostic()> emitError)
Verifies that a module flag value can be exported to LLVM IR.
bool isValidLoadStoreImpl(Type type, ptr::AtomicOrdering ordering, std::optional< int64_t > alignment, const ::mlir::DataLayout *dataLayout, function_ref< InFlightDiagnostic()> emitError)
Checks whether the given type is an LLVM type that can be loaded or stored.
bool isLoadableType(Type type)
Returns true if the given type is a loadable type compatible with the LLVM dialect.
bool isTypeCompatibleWithAtomicOp(Type type, const DataLayout &dataLayout)
Returns true if the given type is supported by atomic operations.
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
llvm::PointerUnion< Type, StringAttr > DataLayoutEntryKey
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
auto getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Ts &&...params)
Helper method analogous to get, but uses getChecked when available to allow graceful failure on inval...
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::function_ref< Fn > function_ref