| 1 | //===- LLVMModuleOps.cpp - LLVM dialect module-level ops ------------------===// |
| 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 ops of op partition `Module` of the LLVM dialect. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "mlir/Dialect/LLVMIR/LLVMModuleOps.h" |
| 14 | |
| 15 | #include "IR/LLVMOps.h" |
| 16 | #include "mlir/Dialect/LLVMIR/LLVMCallOps.h" |
| 17 | #include "mlir/Dialect/LLVMIR/LLVMConstantOps.h" |
| 18 | #include "mlir/Dialect/LLVMIR/LLVMMemoryOps.h" |
| 19 | #include "mlir/Dialect/LLVMIR/LLVMTerminatorOps.h" |
| 20 | #include "mlir/IR/Builders.h" |
| 21 | #include "mlir/IR/BuiltinOps.h" |
| 22 | #include "mlir/IR/DialectImplementation.h" |
| 23 | #include "mlir/Interfaces/FunctionImplementation.h" |
| 24 | #include "llvm/ADT/DenseSet.h" |
| 25 | #include "llvm/ADT/STLExtras.h" |
| 26 | #include "llvm/ADT/TypeSwitch.h" |
| 27 | |
| 28 | #include <optional> |
| 29 | |
| 30 | using namespace mlir; |
| 31 | using namespace mlir::LLVM; |
| 32 | |
| 33 | NamedAttrList mlir::LLVM::getAttrsForPrinting(Operation *op) { |
| 34 | NamedAttrList attrs(op->getRawDictionaryAttrs()); |
| 35 | op->getName().walkInherentAttrs( |
| 36 | op, visitor: [&](StringRef name, Attribute &attr) { attrs.set(name, value: attr); }); |
| 37 | return attrs; |
| 38 | } |
| 39 | |
| 40 | // TODO: Split inherent attributes from discardable attributes in the assembly |
| 41 | // syntax of GlobalOp and AliasOp. For now, print the selected inherent |
| 42 | // attributes in the regular attribute dictionary. |
| 43 | NamedAttrList |
| 44 | mlir::LLVM::getAttrsForPrinting(Operation *op, |
| 45 | ArrayRef<StringAttr> inherentAttrNames) { |
| 46 | NamedAttrList attrs(op->getRawDictionaryAttrs()); |
| 47 | for (StringAttr name : inherentAttrNames) |
| 48 | if (std::optional<Attribute> attr = op->getInherentAttr(name); |
| 49 | attr && *attr) |
| 50 | attrs.set(name, value: *attr); |
| 51 | return attrs; |
| 52 | } |
| 53 | |
| 54 | /// Verifies `symbol`'s use in `op` to ensure the symbol is a valid and |
| 55 | /// fully defined llvm.func. |
| 56 | static LogicalResult verifySymbolAttrUse(FlatSymbolRefAttr symbol, |
| 57 | Operation *op, |
| 58 | SymbolTableCollection &symbolTable) { |
| 59 | StringRef name = symbol.getValue(); |
| 60 | auto func = |
| 61 | symbolTable.lookupNearestSymbolFrom<LLVMFuncOp>(from: op, symbol: symbol.getAttr()); |
| 62 | if (!func) |
| 63 | return op->emitOpError(message: "'" ) |
| 64 | << name << "' does not reference a valid LLVM function" ; |
| 65 | if (func.isExternal()) |
| 66 | return op->emitOpError(message: "'" ) << name << "' does not have a definition" ; |
| 67 | return success(); |
| 68 | } |
| 69 | |
| 70 | // Parses one of the keywords provided in the list `keywords` and returns the |
| 71 | // position of the parsed keyword in the list. If none of the keywords from the |
| 72 | // list is parsed, returns -1. |
| 73 | int mlir::LLVM::parseOptionalKeywordAlternative(OpAsmParser &parser, |
| 74 | ArrayRef<StringRef> keywords) { |
| 75 | for (const auto &en : llvm::enumerate(First&: keywords)) { |
| 76 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: en.value()))) |
| 77 | return en.index(); |
| 78 | } |
| 79 | return -1; |
| 80 | } |
| 81 | |
| 82 | void mlir::LLVM::printLLVMLinkage(OpAsmPrinter &p, Operation *, |
| 83 | LinkageAttr val) { |
| 84 | p << stringifyLinkage(val.getLinkage()); |
| 85 | } |
| 86 | |
| 87 | ParseResult mlir::LLVM::parseLLVMLinkage(OpAsmParser &p, LinkageAttr &val) { |
| 88 | val = LinkageAttr::get( |
| 89 | context: p.getContext(), |
| 90 | linkage: parseOptionalLLVMKeyword<LLVM::Linkage>(parser&: p, defaultValue: LLVM::Linkage::External)); |
| 91 | return success(); |
| 92 | } |
| 93 | |
| 94 | //===----------------------------------------------------------------------===// |
| 95 | // Verifier for LLVM::ComdatOp. |
| 96 | //===----------------------------------------------------------------------===// |
| 97 | |
| 98 | void ComdatOp::build(OpBuilder &builder, OperationState &result, |
| 99 | StringRef symName) { |
| 100 | result.addAttribute(name: getSymNameAttrName(name: result.name), |
| 101 | attr: builder.getStringAttr(bytes: symName)); |
| 102 | Region *body = result.addRegion(); |
| 103 | body->emplaceBlock(); |
| 104 | } |
| 105 | |
| 106 | LogicalResult ComdatOp::verifyRegions() { |
| 107 | Region &body = getBody(); |
| 108 | for (Operation &op : body.getOps()) |
| 109 | if (!isa<ComdatSelectorOp>(Val: op)) |
| 110 | return op.emitError( |
| 111 | message: "only comdat selector symbols can appear in a comdat region" ); |
| 112 | |
| 113 | return success(); |
| 114 | } |
| 115 | |
| 116 | //===----------------------------------------------------------------------===// |
| 117 | // Builder, printer and verifier for LLVM::GlobalOp. |
| 118 | //===----------------------------------------------------------------------===// |
| 119 | |
| 120 | void GlobalOp::build(OpBuilder &builder, OperationState &result, Type type, |
| 121 | bool isConstant, Linkage linkage, StringRef name, |
| 122 | Attribute value, uint64_t alignment, unsigned addrSpace, |
| 123 | bool dsoLocal, ThreadLocalMode threadModel, |
| 124 | SymbolRefAttr comdat, ArrayRef<NamedAttribute> attrs, |
| 125 | ArrayRef<Attribute> dbgExprs) { |
| 126 | result.getOrAddProperties<Properties>().sym_name = |
| 127 | builder.getStringAttr(bytes: name); |
| 128 | result.addAttribute(name: getGlobalTypeAttrName(name: result.name), attr: TypeAttr::get(type)); |
| 129 | result.addAttribute( |
| 130 | name: getTlsModeAttrName(name: result.name), |
| 131 | attr: ThreadLocalModeAttr::get(context: builder.getContext(), val: threadModel)); |
| 132 | if (isConstant) |
| 133 | result.addAttribute(name: getConstantAttrName(name: result.name), |
| 134 | attr: builder.getUnitAttr()); |
| 135 | if (value) |
| 136 | result.addAttribute(name: getValueAttrName(name: result.name), attr: value); |
| 137 | if (dsoLocal) |
| 138 | result.addAttribute(name: getDsoLocalAttrName(name: result.name), |
| 139 | attr: builder.getUnitAttr()); |
| 140 | if (comdat) |
| 141 | result.addAttribute(name: getComdatAttrName(name: result.name), attr: comdat); |
| 142 | |
| 143 | // Only add an alignment attribute if the "alignment" input |
| 144 | // is different from 0. The value must also be a power of two, but |
| 145 | // this is tested in GlobalOp::verify, not here. |
| 146 | if (alignment != 0) |
| 147 | result.addAttribute(name: getAlignmentAttrName(name: result.name), |
| 148 | attr: builder.getI64IntegerAttr(value: alignment)); |
| 149 | |
| 150 | result.addAttribute(name: getLinkageAttrName(name: result.name), |
| 151 | attr: LinkageAttr::get(context: builder.getContext(), linkage)); |
| 152 | if (addrSpace != 0) |
| 153 | result.addAttribute(name: getAddrSpaceAttrName(name: result.name), |
| 154 | attr: builder.getI32IntegerAttr(value: addrSpace)); |
| 155 | result.attributes.append(inStart: attrs.begin(), inEnd: attrs.end()); |
| 156 | |
| 157 | if (!dbgExprs.empty()) |
| 158 | result.addAttribute(name: getDbgExprsAttrName(name: result.name), |
| 159 | attr: ArrayAttr::get(context: builder.getContext(), value: dbgExprs)); |
| 160 | |
| 161 | result.addRegion(); |
| 162 | } |
| 163 | |
| 164 | template <typename OpType> |
| 165 | static void printCommonGlobalAndAlias(OpAsmPrinter &p, OpType op) { |
| 166 | p << ' ' << stringifyLinkage(op.getLinkage()) << ' '; |
| 167 | StringRef visibility = stringifyVisibility(op.getVisibility_()); |
| 168 | if (!visibility.empty()) |
| 169 | p << visibility << ' '; |
| 170 | |
| 171 | if (ThreadLocalMode mode = op.getTlsMode(); |
| 172 | mode != ThreadLocalMode::NotThreadLocal) { |
| 173 | p << "thread_local" ; |
| 174 | if (mode != ThreadLocalMode::GeneralDynamic) |
| 175 | p << '(' << mode << ')'; |
| 176 | p << ' '; |
| 177 | } |
| 178 | |
| 179 | if (auto unnamedAddr = op.getUnnamedAddr()) { |
| 180 | StringRef str = stringifyUnnamedAddr(*unnamedAddr); |
| 181 | if (!str.empty()) |
| 182 | p << str << ' '; |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | void GlobalOp::print(OpAsmPrinter &p) { |
| 187 | printCommonGlobalAndAlias<GlobalOp>(p, op: *this); |
| 188 | if (getConstant()) |
| 189 | p << "constant " ; |
| 190 | p.printSymbolName(symbolRef: getSymName()); |
| 191 | p << '('; |
| 192 | if (auto value = getValueOrNull()) |
| 193 | p.printAttribute(attr: value); |
| 194 | p << ')'; |
| 195 | if (auto comdat = getComdat()) |
| 196 | p << " comdat(" << *comdat << ')'; |
| 197 | |
| 198 | // Note that the alignment attribute is printed using the |
| 199 | // default syntax here, even though it is an inherent attribute |
| 200 | // (as defined in https://mlir.llvm.org/docs/LangRef/#attributes) |
| 201 | p.printOptionalAttrDict( |
| 202 | attrs: getAttrsForPrinting( |
| 203 | op: *this, inherentAttrNames: {getDsoLocalAttrName(), getExternallyInitializedAttrName(), |
| 204 | getAlignmentAttrName(), getAddrSpaceAttrName(), |
| 205 | getSectionAttrName(), getAssociatedAttrName(), |
| 206 | getAbsoluteSymbolAttrName(), getDbgExprsAttrName(), |
| 207 | getTargetSpecificAttrsAttrName(), getSymVisibilityAttrName()}) |
| 208 | .getAttrs(), |
| 209 | elidedAttrs: {getSymNameAttrName(), getGlobalTypeAttrName(), getConstantAttrName(), |
| 210 | getValueAttrName(), getLinkageAttrName(), getUnnamedAddrAttrName(), |
| 211 | getTlsModeAttrName(), getVisibility_AttrName(), getComdatAttrName()}); |
| 212 | |
| 213 | // Print the trailing type unless it's a string global. |
| 214 | if (llvm::dyn_cast_or_null<StringAttr>(Val: getValueOrNull())) |
| 215 | return; |
| 216 | p << " : " << getType(); |
| 217 | |
| 218 | Region &initializer = getInitializerRegion(); |
| 219 | if (!initializer.empty()) { |
| 220 | p << ' '; |
| 221 | p.printRegion(blocks&: initializer, /*printEntryBlockArgs=*/false); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | static LogicalResult verifyComdat(Operation *op, |
| 226 | std::optional<SymbolRefAttr> attr, |
| 227 | SymbolTableCollection &symbolTable) { |
| 228 | if (!attr) |
| 229 | return success(); |
| 230 | |
| 231 | auto *comdatSelector = symbolTable.lookupNearestSymbolFrom(from: op, symbol: *attr); |
| 232 | if (!isa_and_nonnull<ComdatSelectorOp>(Val: comdatSelector)) |
| 233 | return op->emitError() << "expected comdat symbol" ; |
| 234 | |
| 235 | return success(); |
| 236 | } |
| 237 | |
| 238 | static LogicalResult verifyBlockTags(LLVMFuncOp funcOp) { |
| 239 | llvm::DenseSet<BlockTagAttr> blockTags; |
| 240 | // Note that presence of `BlockTagOp`s currently can't prevent an unrecheable |
| 241 | // block to be removed by canonicalizer's region simplify pass, which needs to |
| 242 | // be dialect aware to allow extra constraints to be described. |
| 243 | WalkResult res = funcOp.walk(callback: [&](BlockTagOp blockTagOp) { |
| 244 | if (blockTags.contains(V: blockTagOp.getTag())) { |
| 245 | blockTagOp.emitError() |
| 246 | << "duplicate block tag '" << blockTagOp.getTag().getId() |
| 247 | << "' in the same function: " ; |
| 248 | return WalkResult::interrupt(); |
| 249 | } |
| 250 | blockTags.insert(V: blockTagOp.getTag()); |
| 251 | return WalkResult::advance(); |
| 252 | }); |
| 253 | |
| 254 | return failure(IsFailure: res.wasInterrupted()); |
| 255 | } |
| 256 | |
| 257 | /// Parse common attributes that might show up in the same order in both |
| 258 | /// GlobalOp and AliasOp. |
| 259 | template <typename OpType> |
| 260 | static ParseResult parseCommonGlobalAndAlias(OpAsmParser &parser, |
| 261 | OperationState &result) { |
| 262 | MLIRContext *ctx = parser.getContext(); |
| 263 | |
| 264 | // Parse optional linkage, default to External. |
| 265 | result.addAttribute( |
| 266 | OpType::getLinkageAttrName(result.name), |
| 267 | LLVM::LinkageAttr::get(context: ctx, linkage: parseOptionalLLVMKeyword<Linkage>( |
| 268 | parser, defaultValue: LLVM::Linkage::External))); |
| 269 | |
| 270 | // Parse optional visibility, default to Default. |
| 271 | result.addAttribute(OpType::getVisibility_AttrName(result.name), |
| 272 | parser.getBuilder().getI64IntegerAttr( |
| 273 | value: parseOptionalLLVMKeyword<LLVM::Visibility, int64_t>( |
| 274 | parser, defaultValue: LLVM::Visibility::Default))); |
| 275 | |
| 276 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "thread_local" ))) { |
| 277 | ThreadLocalMode threadModel = ThreadLocalMode::GeneralDynamic; |
| 278 | |
| 279 | if (succeeded(Result: parser.parseOptionalLParen())) { |
| 280 | SMLoc kwLoc; |
| 281 | if (parser.getCurrentLocation(loc: &kwLoc)) |
| 282 | return failure(); |
| 283 | threadModel = parseOptionalLLVMKeyword<ThreadLocalMode>( |
| 284 | parser, defaultValue: ThreadLocalMode::NotThreadLocal); |
| 285 | if (threadModel == ThreadLocalMode::NotThreadLocal) { |
| 286 | parser.emitError(loc: kwLoc, message: "invalid value for thread_local" ); |
| 287 | return failure(); |
| 288 | } |
| 289 | if (parser.parseRParen()) |
| 290 | return failure(); |
| 291 | } |
| 292 | result.addAttribute(OpType::getTlsModeAttrName(result.name), |
| 293 | ThreadLocalModeAttr::get(context: ctx, val: threadModel)); |
| 294 | } |
| 295 | |
| 296 | // Parse optional UnnamedAddr, default to None. |
| 297 | result.addAttribute(OpType::getUnnamedAddrAttrName(result.name), |
| 298 | parser.getBuilder().getI64IntegerAttr( |
| 299 | value: parseOptionalLLVMKeyword<UnnamedAddr, int64_t>( |
| 300 | parser, defaultValue: LLVM::UnnamedAddr::None))); |
| 301 | |
| 302 | return success(); |
| 303 | } |
| 304 | |
| 305 | // operation ::= `llvm.mlir.global` linkage? visibility? |
| 306 | // (`unnamed_addr` | `local_unnamed_addr`)? |
| 307 | // (`thread_local` (`(` tls-mode `)`)? )? |
| 308 | // `constant`? `@` identifier |
| 309 | // `(` attribute? `)` (`comdat(` symbol-ref-id `)`)? |
| 310 | // attribute-list? (`:` type)? region? |
| 311 | // |
| 312 | // The type can be omitted for string attributes, in which case it will be |
| 313 | // inferred from the value of the string as [strlen(value) x i8]. |
| 314 | ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) { |
| 315 | // Call into common parsing between GlobalOp and AliasOp. |
| 316 | if (parseCommonGlobalAndAlias<GlobalOp>(parser, result).failed()) |
| 317 | return failure(); |
| 318 | |
| 319 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "constant" ))) |
| 320 | result.addAttribute(name: getConstantAttrName(name: result.name), |
| 321 | attr: parser.getBuilder().getUnitAttr()); |
| 322 | |
| 323 | StringAttr name; |
| 324 | if (parser.parseSymbolName(result&: name, attrName: getSymNameAttrName(name: result.name), |
| 325 | attrs&: result.attributes) || |
| 326 | parser.parseLParen()) |
| 327 | return failure(); |
| 328 | |
| 329 | Attribute value; |
| 330 | if (parser.parseOptionalRParen()) { |
| 331 | if (parser.parseAttribute(result&: value, attrName: getValueAttrName(name: result.name), |
| 332 | attrs&: result.attributes) || |
| 333 | parser.parseRParen()) |
| 334 | return failure(); |
| 335 | } |
| 336 | |
| 337 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "comdat" ))) { |
| 338 | SymbolRefAttr comdat; |
| 339 | if (parser.parseLParen() || parser.parseAttribute(result&: comdat) || |
| 340 | parser.parseRParen()) |
| 341 | return failure(); |
| 342 | |
| 343 | result.addAttribute(name: getComdatAttrName(name: result.name), attr: comdat); |
| 344 | } |
| 345 | |
| 346 | SmallVector<Type, 1> types; |
| 347 | if (parser.parseOptionalAttrDict(result&: result.attributes) || |
| 348 | parser.parseOptionalColonTypeList(result&: types)) |
| 349 | return failure(); |
| 350 | |
| 351 | if (types.size() > 1) |
| 352 | return parser.emitError(loc: parser.getNameLoc(), message: "expected zero or one type" ); |
| 353 | |
| 354 | Region &initRegion = *result.addRegion(); |
| 355 | if (types.empty()) { |
| 356 | if (auto strAttr = llvm::dyn_cast_or_null<StringAttr>(Val&: value)) { |
| 357 | MLIRContext *context = parser.getContext(); |
| 358 | auto arrayType = LLVM::LLVMArrayType::get(elementType: IntegerType::get(context, width: 8), |
| 359 | numElements: strAttr.getValue().size()); |
| 360 | types.push_back(Elt: arrayType); |
| 361 | } else { |
| 362 | return parser.emitError(loc: parser.getNameLoc(), |
| 363 | message: "type can only be omitted for string globals" ); |
| 364 | } |
| 365 | } else { |
| 366 | OptionalParseResult parseResult = |
| 367 | parser.parseOptionalRegion(region&: initRegion, /*arguments=*/{}, |
| 368 | /*argTypes=*/enableNameShadowing: {}); |
| 369 | if (parseResult.has_value() && failed(Result: *parseResult)) |
| 370 | return failure(); |
| 371 | } |
| 372 | |
| 373 | result.addAttribute(name: getGlobalTypeAttrName(name: result.name), |
| 374 | attr: TypeAttr::get(type: types[0])); |
| 375 | return success(); |
| 376 | } |
| 377 | |
| 378 | static bool isZeroAttribute(Attribute value) { |
| 379 | if (auto intValue = llvm::dyn_cast<IntegerAttr>(Val&: value)) |
| 380 | return intValue.getValue().isZero(); |
| 381 | if (auto fpValue = llvm::dyn_cast<FloatAttr>(Val&: value)) |
| 382 | return fpValue.getValue().isZero(); |
| 383 | if (auto splatValue = llvm::dyn_cast<SplatElementsAttr>(Val&: value)) |
| 384 | return isZeroAttribute(value: splatValue.getSplatValue<Attribute>()); |
| 385 | if (auto elementsValue = llvm::dyn_cast<ElementsAttr>(Val&: value)) |
| 386 | return llvm::all_of(Range: elementsValue.getValues<Attribute>(), P: isZeroAttribute); |
| 387 | if (auto arrayValue = llvm::dyn_cast<ArrayAttr>(Val&: value)) |
| 388 | return llvm::all_of(Range: arrayValue.getValue(), P: isZeroAttribute); |
| 389 | return false; |
| 390 | } |
| 391 | |
| 392 | LogicalResult GlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) { |
| 393 | return verifyComdat(op: *this, attr: getComdat(), symbolTable); |
| 394 | } |
| 395 | |
| 396 | LogicalResult GlobalOp::verify() { |
| 397 | bool validType = isCompatibleOuterType(type: getType()) |
| 398 | ? !llvm::isa<LLVMVoidType, TokenType, LLVMMetadataType, |
| 399 | LLVMLabelType>(Val: getType()) |
| 400 | : llvm::isa<PointerElementTypeInterface>(Val: getType()); |
| 401 | if (!validType) |
| 402 | return emitOpError( |
| 403 | message: "expects type to be a valid element type for an LLVM global" ); |
| 404 | if ((*this)->getParentOp() && !satisfiesLLVMModule(op: (*this)->getParentOp())) |
| 405 | return emitOpError(message: "must appear at the module level" ); |
| 406 | |
| 407 | if (auto strAttr = llvm::dyn_cast_or_null<StringAttr>(Val: getValueOrNull())) { |
| 408 | auto type = llvm::dyn_cast<LLVMArrayType>(Val: getType()); |
| 409 | IntegerType elementType = |
| 410 | type ? llvm::dyn_cast<IntegerType>(Val: type.getElementType()) : nullptr; |
| 411 | if (!elementType || elementType.getWidth() != 8 || |
| 412 | type.getNumElements() != strAttr.getValue().size()) |
| 413 | return emitOpError( |
| 414 | message: "requires an i8 array type of the length equal to that of the string " |
| 415 | "attribute" ); |
| 416 | } |
| 417 | |
| 418 | if (auto targetExtType = dyn_cast<LLVMTargetExtType>(Val: getType())) { |
| 419 | if (!targetExtType.hasProperty(Prop: LLVMTargetExtType::CanBeGlobal)) |
| 420 | return emitOpError() |
| 421 | << "this target extension type cannot be used in a global" ; |
| 422 | |
| 423 | if (Attribute value = getValueOrNull()) |
| 424 | return emitOpError() << "global with target extension type can only be " |
| 425 | "initialized with zero-initializer" ; |
| 426 | } |
| 427 | |
| 428 | if (getLinkage() == Linkage::Common) { |
| 429 | if (Attribute value = getValueOrNull()) { |
| 430 | if (!isZeroAttribute(value)) { |
| 431 | return emitOpError() |
| 432 | << "expected zero value for '" |
| 433 | << stringifyLinkage(Linkage::Common) << "' linkage" ; |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | if (getLinkage() == Linkage::Appending) { |
| 439 | if (!llvm::isa<LLVMArrayType>(Val: getType())) { |
| 440 | return emitOpError() << "expected array type for '" |
| 441 | << stringifyLinkage(Linkage::Appending) |
| 442 | << "' linkage" ; |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | std::optional<uint64_t> alignAttr = getAlignment(); |
| 447 | if (alignAttr.has_value()) { |
| 448 | uint64_t value = alignAttr.value(); |
| 449 | if (!llvm::isPowerOf2_64(Value: value)) |
| 450 | return emitError() << "alignment attribute is not a power of 2" ; |
| 451 | } |
| 452 | |
| 453 | if (FlatSymbolRefAttr associated = getAssociatedAttr()) { |
| 454 | if (associated.getValue() == getSymName()) |
| 455 | return emitOpError(message: "associated cannot refer to the global itself" ); |
| 456 | } |
| 457 | |
| 458 | if (ArrayAttr absSym = getAbsoluteSymbolAttr()) { |
| 459 | if (absSym.empty() || absSym.size() % 2 != 0) |
| 460 | return emitOpError( |
| 461 | message: "absolute_symbol must contain one or more integer range pairs" ); |
| 462 | Type pairType; |
| 463 | for (Attribute attr : absSym) { |
| 464 | auto intAttr = dyn_cast<IntegerAttr>(Val&: attr); |
| 465 | if (!intAttr) |
| 466 | return emitOpError(message: "absolute_symbol operands must be integers" ); |
| 467 | if (!pairType) |
| 468 | pairType = intAttr.getType(); |
| 469 | else if (intAttr.getType() != pairType) |
| 470 | return emitOpError(message: "absolute_symbol range pair types must match" ); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | return success(); |
| 475 | } |
| 476 | |
| 477 | LogicalResult GlobalOp::verifyRegions() { |
| 478 | if (Block *b = getInitializerBlock()) { |
| 479 | ReturnOp ret = cast<ReturnOp>(Val: b->getTerminator()); |
| 480 | if (ret.operand_type_begin() == ret.operand_type_end()) |
| 481 | return emitOpError(message: "initializer region cannot return void" ); |
| 482 | if (*ret.operand_type_begin() != getType()) |
| 483 | return emitOpError(message: "initializer region type " ) |
| 484 | << *ret.operand_type_begin() << " does not match global type " |
| 485 | << getType(); |
| 486 | |
| 487 | for (Operation &op : *b) { |
| 488 | auto iface = dyn_cast<MemoryEffectOpInterface>(Val&: op); |
| 489 | if (!iface || !iface.hasNoEffect()) |
| 490 | return op.emitError() |
| 491 | << "ops with side effects not allowed in global initializers" ; |
| 492 | } |
| 493 | |
| 494 | if (getValueOrNull()) |
| 495 | return emitOpError(message: "cannot have both initializer value and region" ); |
| 496 | } |
| 497 | |
| 498 | return success(); |
| 499 | } |
| 500 | |
| 501 | //===----------------------------------------------------------------------===// |
| 502 | // LLVM::GlobalCtorsOp |
| 503 | //===----------------------------------------------------------------------===// |
| 504 | |
| 505 | static LogicalResult checkGlobalXtorData(Operation *op, ArrayAttr data) { |
| 506 | if (data.empty()) |
| 507 | return success(); |
| 508 | |
| 509 | if (llvm::all_of(Range: data.getAsRange<Attribute>(), P: [](Attribute v) { |
| 510 | return isa<FlatSymbolRefAttr, ZeroAttr>(Val: v); |
| 511 | })) |
| 512 | return success(); |
| 513 | return op->emitError(message: "data element must be symbol or #llvm.zero" ); |
| 514 | } |
| 515 | |
| 516 | LogicalResult |
| 517 | GlobalCtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) { |
| 518 | for (Attribute ctor : getCtors()) { |
| 519 | if (failed(Result: verifySymbolAttrUse(symbol: llvm::cast<FlatSymbolRefAttr>(Val&: ctor), op: *this, |
| 520 | symbolTable))) |
| 521 | return failure(); |
| 522 | } |
| 523 | return success(); |
| 524 | } |
| 525 | |
| 526 | LogicalResult GlobalCtorsOp::verify() { |
| 527 | if (checkGlobalXtorData(op: *this, data: getData()).failed()) |
| 528 | return failure(); |
| 529 | |
| 530 | if (getCtors().size() == getPriorities().size() && |
| 531 | getCtors().size() == getData().size()) |
| 532 | return success(); |
| 533 | return emitError( |
| 534 | message: "ctors, priorities, and data must have the same number of elements" ); |
| 535 | } |
| 536 | |
| 537 | //===----------------------------------------------------------------------===// |
| 538 | // LLVM::GlobalDtorsOp |
| 539 | //===----------------------------------------------------------------------===// |
| 540 | |
| 541 | LogicalResult |
| 542 | GlobalDtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) { |
| 543 | for (Attribute dtor : getDtors()) { |
| 544 | if (failed(Result: verifySymbolAttrUse(symbol: llvm::cast<FlatSymbolRefAttr>(Val&: dtor), op: *this, |
| 545 | symbolTable))) |
| 546 | return failure(); |
| 547 | } |
| 548 | return success(); |
| 549 | } |
| 550 | |
| 551 | LogicalResult GlobalDtorsOp::verify() { |
| 552 | if (checkGlobalXtorData(op: *this, data: getData()).failed()) |
| 553 | return failure(); |
| 554 | |
| 555 | if (getDtors().size() == getPriorities().size() && |
| 556 | getDtors().size() == getData().size()) |
| 557 | return success(); |
| 558 | return emitError( |
| 559 | message: "dtors, priorities, and data must have the same number of elements" ); |
| 560 | } |
| 561 | |
| 562 | //===----------------------------------------------------------------------===// |
| 563 | // Builder, printer and verifier for LLVM::AliasOp. |
| 564 | //===----------------------------------------------------------------------===// |
| 565 | |
| 566 | void AliasOp::build(OpBuilder &builder, OperationState &result, Type type, |
| 567 | Linkage linkage, StringRef name, bool dsoLocal, |
| 568 | ThreadLocalMode threadModel, |
| 569 | ArrayRef<NamedAttribute> attrs) { |
| 570 | result.addAttribute(name: getSymNameAttrName(name: result.name), |
| 571 | attr: builder.getStringAttr(bytes: name)); |
| 572 | result.addAttribute(name: getAliasTypeAttrName(name: result.name), attr: TypeAttr::get(type)); |
| 573 | result.addAttribute( |
| 574 | name: getTlsModeAttrName(name: result.name), |
| 575 | attr: ThreadLocalModeAttr::get(context: builder.getContext(), val: threadModel)); |
| 576 | if (dsoLocal) |
| 577 | result.addAttribute(name: getDsoLocalAttrName(name: result.name), |
| 578 | attr: builder.getUnitAttr()); |
| 579 | |
| 580 | result.addAttribute(name: getLinkageAttrName(name: result.name), |
| 581 | attr: LinkageAttr::get(context: builder.getContext(), linkage)); |
| 582 | result.attributes.append(inStart: attrs.begin(), inEnd: attrs.end()); |
| 583 | |
| 584 | result.addRegion(); |
| 585 | } |
| 586 | |
| 587 | void AliasOp::print(OpAsmPrinter &p) { |
| 588 | printCommonGlobalAndAlias<AliasOp>(p, op: *this); |
| 589 | |
| 590 | p.printSymbolName(symbolRef: getSymName()); |
| 591 | p.printOptionalAttrDict( |
| 592 | attrs: getAttrsForPrinting(op: *this, |
| 593 | inherentAttrNames: {getDsoLocalAttrName(), getSymVisibilityAttrName()}) |
| 594 | .getAttrs(), |
| 595 | elidedAttrs: {getSymNameAttrName(), getAliasTypeAttrName(), getLinkageAttrName(), |
| 596 | getUnnamedAddrAttrName(), getTlsModeAttrName(), |
| 597 | getVisibility_AttrName()}); |
| 598 | |
| 599 | // Print the trailing type. |
| 600 | p << " : " << getType() << ' '; |
| 601 | // Print the initializer region. |
| 602 | p.printRegion(blocks&: getInitializerRegion(), /*printEntryBlockArgs=*/false); |
| 603 | } |
| 604 | |
| 605 | // operation ::= `llvm.mlir.alias` linkage? visibility? |
| 606 | // (`unnamed_addr` | `local_unnamed_addr`)? |
| 607 | // (`thread_local` (`(` tls-mode `)`)? )? |
| 608 | // `@` identifier `(` attribute? `)` |
| 609 | // attribute-list? `:` type region |
| 610 | // |
| 611 | ParseResult AliasOp::parse(OpAsmParser &parser, OperationState &result) { |
| 612 | // Call into common parsing between GlobalOp and AliasOp. |
| 613 | if (parseCommonGlobalAndAlias<AliasOp>(parser, result).failed()) |
| 614 | return failure(); |
| 615 | |
| 616 | StringAttr name; |
| 617 | if (parser.parseSymbolName(result&: name, attrName: getSymNameAttrName(name: result.name), |
| 618 | attrs&: result.attributes)) |
| 619 | return failure(); |
| 620 | |
| 621 | SmallVector<Type, 1> types; |
| 622 | if (parser.parseOptionalAttrDict(result&: result.attributes) || |
| 623 | parser.parseOptionalColonTypeList(result&: types)) |
| 624 | return failure(); |
| 625 | |
| 626 | if (types.size() > 1) |
| 627 | return parser.emitError(loc: parser.getNameLoc(), message: "expected zero or one type" ); |
| 628 | |
| 629 | Region &initRegion = *result.addRegion(); |
| 630 | if (parser.parseRegion(region&: initRegion).failed()) |
| 631 | return failure(); |
| 632 | |
| 633 | result.addAttribute(name: getAliasTypeAttrName(name: result.name), |
| 634 | attr: TypeAttr::get(type: types[0])); |
| 635 | return success(); |
| 636 | } |
| 637 | |
| 638 | LogicalResult AliasOp::verify() { |
| 639 | bool validType = isCompatibleOuterType(type: getType()) |
| 640 | ? !llvm::isa<LLVMVoidType, TokenType, LLVMMetadataType, |
| 641 | LLVMLabelType>(Val: getType()) |
| 642 | : llvm::isa<PointerElementTypeInterface>(Val: getType()); |
| 643 | if (!validType) |
| 644 | return emitOpError( |
| 645 | message: "expects type to be a valid element type for an LLVM global alias" ); |
| 646 | |
| 647 | // This matches LLVM IR verification logic, see llvm/lib/IR/Verifier.cpp |
| 648 | switch (getLinkage()) { |
| 649 | case Linkage::External: |
| 650 | case Linkage::Internal: |
| 651 | case Linkage::Private: |
| 652 | case Linkage::Weak: |
| 653 | case Linkage::WeakODR: |
| 654 | case Linkage::Linkonce: |
| 655 | case Linkage::LinkonceODR: |
| 656 | case Linkage::AvailableExternally: |
| 657 | break; |
| 658 | default: |
| 659 | return emitOpError() |
| 660 | << "'" << stringifyLinkage(getLinkage()) |
| 661 | << "' linkage not supported in aliases, available options: private, " |
| 662 | "internal, linkonce, weak, linkonce_odr, weak_odr, external or " |
| 663 | "available_externally" ; |
| 664 | } |
| 665 | |
| 666 | return success(); |
| 667 | } |
| 668 | |
| 669 | LogicalResult AliasOp::verifyRegions() { |
| 670 | Block &b = getInitializerBlock(); |
| 671 | auto ret = cast<ReturnOp>(Val: b.getTerminator()); |
| 672 | if (ret.getNumOperands() == 0 || |
| 673 | !isa<LLVM::LLVMPointerType>(Val: ret.getOperand(i: 0).getType())) |
| 674 | return emitOpError(message: "initializer region must always return a pointer" ); |
| 675 | |
| 676 | for (Operation &op : b) { |
| 677 | auto iface = dyn_cast<MemoryEffectOpInterface>(Val&: op); |
| 678 | if (!iface || !iface.hasNoEffect()) |
| 679 | return op.emitError() |
| 680 | << "ops with side effects are not allowed in alias initializers" ; |
| 681 | } |
| 682 | |
| 683 | return success(); |
| 684 | } |
| 685 | |
| 686 | unsigned AliasOp::getAddrSpace() { |
| 687 | Block &initializer = getInitializerBlock(); |
| 688 | auto ret = cast<ReturnOp>(Val: initializer.getTerminator()); |
| 689 | auto ptrTy = cast<LLVMPointerType>(Val: ret.getOperand(i: 0).getType()); |
| 690 | return ptrTy.getAddressSpace(); |
| 691 | } |
| 692 | |
| 693 | //===----------------------------------------------------------------------===// |
| 694 | // IFuncOp |
| 695 | //===----------------------------------------------------------------------===// |
| 696 | |
| 697 | void IFuncOp::build(OpBuilder &builder, OperationState &result, StringRef name, |
| 698 | Type iFuncType, StringRef resolverName, Type resolverType, |
| 699 | Linkage linkage, LLVM::Visibility visibility) { |
| 700 | return build(odsBuilder&: builder, odsState&: result, sym_name: name, i_func_type: iFuncType, resolver: resolverName, resolver_type: resolverType, |
| 701 | linkage, /*dso_local=*/false, /*address_space=*/0, |
| 702 | unnamed_addr: UnnamedAddr::None, visibility_: visibility, /*sym_visibility=*/nullptr); |
| 703 | } |
| 704 | |
| 705 | LogicalResult IFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) { |
| 706 | Operation *symbol = |
| 707 | symbolTable.lookupSymbolIn(symbolTableOp: parentLLVMModule(op: *this), name: getResolverAttr()); |
| 708 | // This matches LLVM IR verification logic, see llvm/lib/IR/Verifier.cpp |
| 709 | auto resolver = dyn_cast_if_present<LLVMFuncOp>(Val: symbol); |
| 710 | auto alias = dyn_cast_if_present<AliasOp>(Val: symbol); |
| 711 | while (alias) { |
| 712 | Block &initBlock = alias.getInitializerBlock(); |
| 713 | auto returnOp = cast<ReturnOp>(Val: initBlock.getTerminator()); |
| 714 | auto addrOp = returnOp.getArg().getDefiningOp<AddressOfOp>(); |
| 715 | // FIXME: This is a best effort solution. The AliasOp body might be more |
| 716 | // complex and in that case we bail out with success. To completely match |
| 717 | // the LLVM IR logic it would be necessary to implement proper alias and |
| 718 | // cast stripping. |
| 719 | if (!addrOp) |
| 720 | return success(); |
| 721 | resolver = addrOp.getFunction(symbolTable); |
| 722 | alias = addrOp.getAlias(symbolTable); |
| 723 | } |
| 724 | if (!resolver) |
| 725 | return emitOpError(message: "must have a function resolver" ); |
| 726 | Linkage linkage = resolver.getLinkage(); |
| 727 | if (resolver.isExternal() || linkage == Linkage::AvailableExternally) |
| 728 | return emitOpError(message: "resolver must be a definition" ); |
| 729 | if (!isa<LLVMPointerType>(Val: resolver.getFunctionType().getReturnType())) |
| 730 | return emitOpError(message: "resolver must return a pointer" ); |
| 731 | auto resolverPtr = dyn_cast<LLVMPointerType>(Val: getResolverType()); |
| 732 | if (!resolverPtr || resolverPtr.getAddressSpace() != getAddressSpace()) |
| 733 | return emitOpError(message: "resolver has incorrect type" ); |
| 734 | return success(); |
| 735 | } |
| 736 | |
| 737 | LogicalResult IFuncOp::verify() { |
| 738 | switch (getLinkage()) { |
| 739 | case Linkage::External: |
| 740 | case Linkage::Internal: |
| 741 | case Linkage::Private: |
| 742 | case Linkage::Weak: |
| 743 | case Linkage::WeakODR: |
| 744 | case Linkage::Linkonce: |
| 745 | case Linkage::LinkonceODR: |
| 746 | break; |
| 747 | default: |
| 748 | return emitOpError() << "'" << stringifyLinkage(getLinkage()) |
| 749 | << "' linkage not supported in ifuncs, available " |
| 750 | "options: private, internal, linkonce, weak, " |
| 751 | "linkonce_odr, weak_odr, or external linkage" ; |
| 752 | } |
| 753 | return success(); |
| 754 | } |
| 755 | |
| 756 | //===----------------------------------------------------------------------===// |
| 757 | // Implementations for LLVM::LLVMFuncOp. |
| 758 | //===----------------------------------------------------------------------===// |
| 759 | |
| 760 | // Add the entry block to the function. |
| 761 | Block *LLVMFuncOp::addEntryBlock(OpBuilder &builder) { |
| 762 | assert(empty() && "function already has an entry block" ); |
| 763 | OpBuilder::InsertionGuard g(builder); |
| 764 | Block *entry = builder.createBlock(parent: &getBody()); |
| 765 | |
| 766 | // FIXME: Allow passing in proper locations for the entry arguments. |
| 767 | LLVMFunctionType type = getFunctionType(); |
| 768 | for (unsigned i = 0, e = type.getNumParams(); i < e; ++i) |
| 769 | entry->addArgument(type: type.getParamType(i), loc: getLoc()); |
| 770 | return entry; |
| 771 | } |
| 772 | |
| 773 | void LLVMFuncOp::build(OpBuilder &builder, OperationState &result, |
| 774 | StringRef name, Type type, LLVM::Linkage linkage, |
| 775 | bool dsoLocal, CConv cconv, SymbolRefAttr comdat, |
| 776 | ArrayRef<NamedAttribute> attrs, |
| 777 | ArrayRef<DictionaryAttr> argAttrs, |
| 778 | std::optional<uint64_t> functionEntryCount) { |
| 779 | result.addRegion(); |
| 780 | result.addAttribute(name: getSymNameAttrName(name: result.name), |
| 781 | attr: builder.getStringAttr(bytes: name)); |
| 782 | result.addAttribute(name: getFunctionTypeAttrName(name: result.name), |
| 783 | attr: TypeAttr::get(type)); |
| 784 | result.addAttribute(name: getLinkageAttrName(name: result.name), |
| 785 | attr: LinkageAttr::get(context: builder.getContext(), linkage)); |
| 786 | result.addAttribute(name: getCConvAttrName(name: result.name), |
| 787 | attr: CConvAttr::get(context: builder.getContext(), CallingConv: cconv)); |
| 788 | result.attributes.append(inStart: attrs.begin(), inEnd: attrs.end()); |
| 789 | if (dsoLocal) |
| 790 | result.addAttribute(name: getDsoLocalAttrName(name: result.name), |
| 791 | attr: builder.getUnitAttr()); |
| 792 | if (comdat) |
| 793 | result.addAttribute(name: getComdatAttrName(name: result.name), attr: comdat); |
| 794 | if (functionEntryCount) |
| 795 | result.addAttribute(name: getFunctionEntryCountAttrName(name: result.name), |
| 796 | attr: FunctionEntryCountAttr::get(context: builder.getContext(), |
| 797 | entry_count: *functionEntryCount, |
| 798 | imports: ArrayRef<uint64_t>{})); |
| 799 | #ifndef NDEBUG |
| 800 | std::optional<NamedAttribute> duplicate = result.attributes.findDuplicate(); |
| 801 | if (duplicate.has_value()) { |
| 802 | llvm::report_fatal_error( |
| 803 | Twine("LLVMFuncOp propagated an attribute that is meant " |
| 804 | "to be constructed by the builder: " ) + |
| 805 | duplicate->getName().str()); |
| 806 | } |
| 807 | #endif |
| 808 | if (argAttrs.empty()) |
| 809 | return; |
| 810 | |
| 811 | assert(llvm::cast<LLVMFunctionType>(type).getNumParams() == argAttrs.size() && |
| 812 | "expected as many argument attribute lists as arguments" ); |
| 813 | call_interface_impl::addArgAndResultAttrs( |
| 814 | builder, result, argAttrs, /*resultAttrs=*/{}, |
| 815 | argAttrsName: getArgAttrsAttrName(name: result.name), resAttrsName: getResAttrsAttrName(name: result.name)); |
| 816 | } |
| 817 | |
| 818 | // Builds an LLVM function type from the given lists of input and output types. |
| 819 | // Returns a null type if any of the types provided are non-LLVM types, or if |
| 820 | // there is more than one output type. |
| 821 | static Type |
| 822 | buildLLVMFunctionType(OpAsmParser &parser, SMLoc loc, ArrayRef<Type> inputs, |
| 823 | ArrayRef<Type> outputs, |
| 824 | function_interface_impl::VariadicFlag variadicFlag) { |
| 825 | Builder &b = parser.getBuilder(); |
| 826 | if (outputs.size() > 1) { |
| 827 | parser.emitError(loc, message: "failed to construct function type: expected zero or " |
| 828 | "one function result" ); |
| 829 | return {}; |
| 830 | } |
| 831 | |
| 832 | // Convert inputs to LLVM types, exit early on error. |
| 833 | SmallVector<Type, 4> llvmInputs; |
| 834 | for (auto t : inputs) { |
| 835 | if (!isCompatibleType(type: t)) { |
| 836 | parser.emitError(loc, message: "failed to construct function type: expected LLVM " |
| 837 | "type for function arguments" ); |
| 838 | return {}; |
| 839 | } |
| 840 | llvmInputs.push_back(Elt: t); |
| 841 | } |
| 842 | |
| 843 | // No output is denoted as "void" in LLVM type system. |
| 844 | Type llvmOutput = |
| 845 | outputs.empty() ? LLVMVoidType::get(ctx: b.getContext()) : outputs.front(); |
| 846 | if (!isCompatibleType(type: llvmOutput)) { |
| 847 | parser.emitError(loc, message: "failed to construct function type: expected LLVM " |
| 848 | "type for function results" ) |
| 849 | << llvmOutput; |
| 850 | return {}; |
| 851 | } |
| 852 | return LLVMFunctionType::get(result: llvmOutput, arguments: llvmInputs, |
| 853 | isVarArg: variadicFlag.isVariadic()); |
| 854 | } |
| 855 | |
| 856 | // Parses an LLVM function. |
| 857 | // |
| 858 | // operation ::= `llvm.func` linkage? cconv? function-signature |
| 859 | // (`comdat(` symbol-ref-id `)`)? |
| 860 | // function-attributes? |
| 861 | // function-body |
| 862 | // |
| 863 | ParseResult LLVMFuncOp::parse(OpAsmParser &parser, OperationState &result) { |
| 864 | // Default to external linkage if no keyword is provided. |
| 865 | result.addAttribute(name: getLinkageAttrName(name: result.name), |
| 866 | attr: LinkageAttr::get(context: parser.getContext(), |
| 867 | linkage: parseOptionalLLVMKeyword<Linkage>( |
| 868 | parser, defaultValue: LLVM::Linkage::External))); |
| 869 | |
| 870 | // Parse optional visibility, default to Default. |
| 871 | result.addAttribute(name: getVisibility_AttrName(name: result.name), |
| 872 | attr: parser.getBuilder().getI64IntegerAttr( |
| 873 | value: parseOptionalLLVMKeyword<LLVM::Visibility, int64_t>( |
| 874 | parser, defaultValue: LLVM::Visibility::Default))); |
| 875 | |
| 876 | // Parse optional UnnamedAddr, default to None. |
| 877 | result.addAttribute(name: getUnnamedAddrAttrName(name: result.name), |
| 878 | attr: parser.getBuilder().getI64IntegerAttr( |
| 879 | value: parseOptionalLLVMKeyword<UnnamedAddr, int64_t>( |
| 880 | parser, defaultValue: LLVM::UnnamedAddr::None))); |
| 881 | |
| 882 | // Default to C Calling Convention if no keyword is provided. |
| 883 | result.addAttribute( |
| 884 | name: getCConvAttrName(name: result.name), |
| 885 | attr: CConvAttr::get(context: parser.getContext(), |
| 886 | CallingConv: parseOptionalLLVMKeyword<CConv>(parser, defaultValue: LLVM::CConv::C))); |
| 887 | |
| 888 | StringAttr nameAttr; |
| 889 | SmallVector<OpAsmParser::Argument> entryArgs; |
| 890 | SmallVector<DictionaryAttr> resultAttrs; |
| 891 | SmallVector<Type> resultTypes; |
| 892 | bool isVariadic; |
| 893 | |
| 894 | auto signatureLocation = parser.getCurrentLocation(); |
| 895 | if (parser.parseSymbolName(result&: nameAttr, attrName: getSymNameAttrName(name: result.name), |
| 896 | attrs&: result.attributes) || |
| 897 | function_interface_impl::parseFunctionSignatureWithArguments( |
| 898 | parser, /*allowVariadic=*/true, arguments&: entryArgs, isVariadic, resultTypes, |
| 899 | resultAttrs)) |
| 900 | return failure(); |
| 901 | |
| 902 | SmallVector<Type> argTypes; |
| 903 | for (auto &arg : entryArgs) |
| 904 | argTypes.push_back(Elt: arg.type); |
| 905 | auto type = |
| 906 | buildLLVMFunctionType(parser, loc: signatureLocation, inputs: argTypes, outputs: resultTypes, |
| 907 | variadicFlag: function_interface_impl::VariadicFlag(isVariadic)); |
| 908 | if (!type) |
| 909 | return failure(); |
| 910 | result.addAttribute(name: getFunctionTypeAttrName(name: result.name), |
| 911 | attr: TypeAttr::get(type)); |
| 912 | |
| 913 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "vscale_range" ))) { |
| 914 | int64_t minRange, maxRange; |
| 915 | if (parser.parseLParen() || parser.parseInteger(result&: minRange) || |
| 916 | parser.parseComma() || parser.parseInteger(result&: maxRange) || |
| 917 | parser.parseRParen()) |
| 918 | return failure(); |
| 919 | auto intTy = IntegerType::get(context: parser.getContext(), width: 32); |
| 920 | result.addAttribute( |
| 921 | name: getVscaleRangeAttrName(name: result.name), |
| 922 | attr: LLVM::VScaleRangeAttr::get(context: parser.getContext(), |
| 923 | minRange: IntegerAttr::get(type: intTy, value: minRange), |
| 924 | maxRange: IntegerAttr::get(type: intTy, value: maxRange))); |
| 925 | } |
| 926 | // Parse the optional comdat selector. |
| 927 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "comdat" ))) { |
| 928 | SymbolRefAttr comdat; |
| 929 | if (parser.parseLParen() || parser.parseAttribute(result&: comdat) || |
| 930 | parser.parseRParen()) |
| 931 | return failure(); |
| 932 | |
| 933 | result.addAttribute(name: getComdatAttrName(name: result.name), attr: comdat); |
| 934 | } |
| 935 | |
| 936 | if (failed(Result: parser.parseOptionalAttrDictWithKeyword(result&: result.attributes))) |
| 937 | return failure(); |
| 938 | call_interface_impl::addArgAndResultAttrs( |
| 939 | builder&: parser.getBuilder(), result, args: entryArgs, resultAttrs, |
| 940 | argAttrsName: getArgAttrsAttrName(name: result.name), resAttrsName: getResAttrsAttrName(name: result.name)); |
| 941 | |
| 942 | auto *body = result.addRegion(); |
| 943 | OptionalParseResult parseResult = |
| 944 | parser.parseOptionalRegion(region&: *body, arguments: entryArgs); |
| 945 | return failure(IsFailure: parseResult.has_value() && failed(Result: *parseResult)); |
| 946 | } |
| 947 | |
| 948 | // Print the LLVMFuncOp. Collects argument and result types and passes them to |
| 949 | // helper functions. Drops "void" result since it cannot be parsed back. Skips |
| 950 | // the external linkage since it is the default value. |
| 951 | void LLVMFuncOp::print(OpAsmPrinter &p) { |
| 952 | p << ' '; |
| 953 | if (getLinkage() != LLVM::Linkage::External) |
| 954 | p << stringifyLinkage(getLinkage()) << ' '; |
| 955 | StringRef visibility = stringifyVisibility(getVisibility_()); |
| 956 | if (!visibility.empty()) |
| 957 | p << visibility << ' '; |
| 958 | if (auto unnamedAddr = getUnnamedAddr()) { |
| 959 | StringRef str = stringifyUnnamedAddr(*unnamedAddr); |
| 960 | if (!str.empty()) |
| 961 | p << str << ' '; |
| 962 | } |
| 963 | if (getCConv() != LLVM::CConv::C) |
| 964 | p << stringifyCConv(getCConv()) << ' '; |
| 965 | |
| 966 | p.printSymbolName(symbolRef: getName()); |
| 967 | |
| 968 | LLVMFunctionType fnType = getFunctionType(); |
| 969 | SmallVector<Type, 8> argTypes; |
| 970 | SmallVector<Type, 1> resTypes; |
| 971 | argTypes.reserve(N: fnType.getNumParams()); |
| 972 | for (unsigned i = 0, e = fnType.getNumParams(); i < e; ++i) |
| 973 | argTypes.push_back(Elt: fnType.getParamType(i)); |
| 974 | |
| 975 | Type returnType = fnType.getReturnType(); |
| 976 | if (!llvm::isa<LLVMVoidType>(Val: returnType)) |
| 977 | resTypes.push_back(Elt: returnType); |
| 978 | |
| 979 | function_interface_impl::printFunctionSignature(p, op: *this, argTypes, |
| 980 | isVariadic: isVarArg(), resultTypes: resTypes); |
| 981 | |
| 982 | // Print vscale range if present |
| 983 | if (std::optional<VScaleRangeAttr> vscale = getVscaleRange()) |
| 984 | p << " vscale_range(" << vscale->getMinRange().getInt() << ", " |
| 985 | << vscale->getMaxRange().getInt() << ')'; |
| 986 | |
| 987 | // Print the optional comdat selector. |
| 988 | if (auto comdat = getComdat()) |
| 989 | p << " comdat(" << *comdat << ')'; |
| 990 | |
| 991 | function_interface_impl::printFunctionAttributes( |
| 992 | p, op: *this, |
| 993 | elided: {getFunctionTypeAttrName(), getArgAttrsAttrName(), getResAttrsAttrName(), |
| 994 | getLinkageAttrName(), getCConvAttrName(), getVisibility_AttrName(), |
| 995 | getComdatAttrName(), getUnnamedAddrAttrName(), |
| 996 | getVscaleRangeAttrName()}); |
| 997 | |
| 998 | // Print the body if this is not an external function. |
| 999 | Region &body = getBody(); |
| 1000 | if (!body.empty()) { |
| 1001 | p << ' '; |
| 1002 | p.printRegion(blocks&: body, /*printEntryBlockArgs=*/false, |
| 1003 | /*printBlockTerminators=*/true); |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | LogicalResult LLVMFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) { |
| 1008 | return verifyComdat(op: *this, attr: getComdat(), symbolTable); |
| 1009 | } |
| 1010 | |
| 1011 | // Verifies LLVM- and implementation-specific properties of the LLVM func Op: |
| 1012 | // - functions don't have 'common' linkage |
| 1013 | // - external functions have 'external' or 'extern_weak' linkage; |
| 1014 | // - vararg is (currently) only supported for external functions; |
| 1015 | LogicalResult LLVMFuncOp::verify() { |
| 1016 | if (getLinkage() == LLVM::Linkage::Common) |
| 1017 | return emitOpError() << "functions cannot have '" |
| 1018 | << stringifyLinkage(LLVM::Linkage::Common) |
| 1019 | << "' linkage" ; |
| 1020 | |
| 1021 | if (isExternal()) { |
| 1022 | if (getFunctionEntryCountAttr()) |
| 1023 | return emitOpError() << "external functions cannot have " |
| 1024 | << getFunctionEntryCountAttrName() << " attribute" ; |
| 1025 | |
| 1026 | if (getLinkage() != LLVM::Linkage::External && |
| 1027 | getLinkage() != LLVM::Linkage::ExternWeak) |
| 1028 | return emitOpError() << "external functions must have '" |
| 1029 | << stringifyLinkage(LLVM::Linkage::External) |
| 1030 | << "' or '" |
| 1031 | << stringifyLinkage(LLVM::Linkage::ExternWeak) |
| 1032 | << "' linkage" ; |
| 1033 | return success(); |
| 1034 | } |
| 1035 | |
| 1036 | // In LLVM IR, these attributes are composed by convention, not by design. |
| 1037 | if (isNoInline() && isAlwaysInline()) |
| 1038 | return emitError(message: "no_inline and always_inline attributes are incompatible" ); |
| 1039 | |
| 1040 | if (isOptimizeNone() && !isNoInline()) |
| 1041 | return emitOpError(message: "with optimize_none must also be no_inline" ); |
| 1042 | |
| 1043 | Type landingpadResultTy; |
| 1044 | StringRef diagnosticMessage; |
| 1045 | bool isLandingpadTypeConsistent = |
| 1046 | !walk(callback: [&](Operation *op) { |
| 1047 | const auto checkType = [&](Type type, StringRef errorMessage) { |
| 1048 | if (!landingpadResultTy) { |
| 1049 | landingpadResultTy = type; |
| 1050 | return WalkResult::advance(); |
| 1051 | } |
| 1052 | if (landingpadResultTy != type) { |
| 1053 | diagnosticMessage = errorMessage; |
| 1054 | return WalkResult::interrupt(); |
| 1055 | } |
| 1056 | return WalkResult::advance(); |
| 1057 | }; |
| 1058 | return TypeSwitch<Operation *, WalkResult>(op) |
| 1059 | .Case(caseFn: [&](LandingpadOp landingpad) { |
| 1060 | constexpr StringLiteral errorMessage = |
| 1061 | "'llvm.landingpad' should have a consistent result type " |
| 1062 | "inside a function" ; |
| 1063 | return checkType(landingpad.getType(), errorMessage); |
| 1064 | }) |
| 1065 | .Case(caseFn: [&](ResumeOp resume) { |
| 1066 | constexpr StringLiteral errorMessage = |
| 1067 | "'llvm.resume' should have a consistent input type inside a " |
| 1068 | "function" ; |
| 1069 | return checkType(resume.getValue().getType(), errorMessage); |
| 1070 | }) |
| 1071 | .Default(defaultFn: [](auto) { return WalkResult::skip(); }); |
| 1072 | }).wasInterrupted(); |
| 1073 | if (!isLandingpadTypeConsistent) { |
| 1074 | assert(!diagnosticMessage.empty() && |
| 1075 | "Expecting a non-empty diagnostic message" ); |
| 1076 | return emitError(message: diagnosticMessage); |
| 1077 | } |
| 1078 | |
| 1079 | if (failed(Result: verifyBlockTags(funcOp: *this))) |
| 1080 | return failure(); |
| 1081 | |
| 1082 | return success(); |
| 1083 | } |
| 1084 | |
| 1085 | /// Verifies LLVM- and implementation-specific properties of the LLVM func Op: |
| 1086 | /// - entry block arguments are of LLVM types. |
| 1087 | LogicalResult LLVMFuncOp::verifyRegions() { |
| 1088 | if (isExternal()) |
| 1089 | return success(); |
| 1090 | |
| 1091 | unsigned numArguments = getFunctionType().getNumParams(); |
| 1092 | Block &entryBlock = front(); |
| 1093 | for (unsigned i = 0; i < numArguments; ++i) { |
| 1094 | Type argType = entryBlock.getArgument(i).getType(); |
| 1095 | if (!isCompatibleType(type: argType)) |
| 1096 | return emitOpError(message: "entry block argument #" ) |
| 1097 | << i << " is not of LLVM type" ; |
| 1098 | } |
| 1099 | |
| 1100 | return success(); |
| 1101 | } |
| 1102 | |
| 1103 | Region *LLVMFuncOp::getCallableRegion() { |
| 1104 | if (isExternal()) |
| 1105 | return nullptr; |
| 1106 | return &getBody(); |
| 1107 | } |
| 1108 | |
| 1109 | //===----------------------------------------------------------------------===// |
| 1110 | // LinkerOptionsOp |
| 1111 | //===----------------------------------------------------------------------===// |
| 1112 | |
| 1113 | LogicalResult LinkerOptionsOp::verify() { |
| 1114 | if (mlir::Operation *parentOp = (*this)->getParentOp(); |
| 1115 | parentOp && !satisfiesLLVMModule(op: parentOp)) |
| 1116 | return emitOpError(message: "must appear at the module level" ); |
| 1117 | return success(); |
| 1118 | } |
| 1119 | |
| 1120 | //===----------------------------------------------------------------------===// |
| 1121 | // ModuleFlagsOp |
| 1122 | //===----------------------------------------------------------------------===// |
| 1123 | |
| 1124 | LogicalResult ModuleFlagsOp::verify() { |
| 1125 | if (Operation *parentOp = (*this)->getParentOp(); |
| 1126 | parentOp && !satisfiesLLVMModule(op: parentOp)) |
| 1127 | return emitOpError(message: "must appear at the module level" ); |
| 1128 | |
| 1129 | llvm::DenseSet<StringAttr> seenNonRequireKeys; |
| 1130 | for (Attribute flag : getFlags()) { |
| 1131 | auto moduleFlag = dyn_cast<ModuleFlagAttrInterface>(Val&: flag); |
| 1132 | if (!moduleFlag) |
| 1133 | return emitOpError(message: "expected a module flag attribute" ); |
| 1134 | if (failed(Result: LLVM::detail::verifyModuleFlagValue( |
| 1135 | key: moduleFlag.getModuleFlagKey(), value: moduleFlag.getModuleFlagValue(), |
| 1136 | emitError: [&] { return emitOpError(); }))) |
| 1137 | return failure(); |
| 1138 | if (moduleFlag.getModuleFlagBehavior() == ModFlagBehavior::Require) |
| 1139 | continue; |
| 1140 | StringAttr key = moduleFlag.getModuleFlagKey(); |
| 1141 | if (!seenNonRequireKeys.insert(V: key).second) |
| 1142 | return emitOpError(message: "expected module flag key '" ) |
| 1143 | << key.getValue() << "' to be unique for non-require flags" ; |
| 1144 | } |
| 1145 | return success(); |
| 1146 | } |
| 1147 | |
| 1148 | //===----------------------------------------------------------------------===// |
| 1149 | // Utility functions. |
| 1150 | //===----------------------------------------------------------------------===// |
| 1151 | |
| 1152 | Value mlir::LLVM::createGlobalString(Location loc, OpBuilder &builder, |
| 1153 | StringRef name, StringRef value, |
| 1154 | LLVM::Linkage linkage) { |
| 1155 | assert(builder.getInsertionBlock() && |
| 1156 | builder.getInsertionBlock()->getParentOp() && |
| 1157 | "expected builder to point to a block constrained in an op" ); |
| 1158 | auto module = |
| 1159 | builder.getInsertionBlock()->getParentOp()->getParentOfType<ModuleOp>(); |
| 1160 | assert(module && "builder points to an op outside of a module" ); |
| 1161 | |
| 1162 | // Create the global at the entry of the module. |
| 1163 | OpBuilder moduleBuilder(module.getBodyRegion(), builder.getListener()); |
| 1164 | MLIRContext *ctx = builder.getContext(); |
| 1165 | auto type = LLVM::LLVMArrayType::get(elementType: IntegerType::get(context: ctx, width: 8), numElements: value.size()); |
| 1166 | auto global = LLVM::GlobalOp::create( |
| 1167 | builder&: moduleBuilder, location: loc, type, /*isConstant=*/true, linkage, name, |
| 1168 | value: builder.getStringAttr(bytes: value), /*alignment=*/0); |
| 1169 | |
| 1170 | LLVMPointerType ptrType = LLVMPointerType::get(context: ctx); |
| 1171 | // Get the pointer to the first character in the global string. |
| 1172 | Value globalPtr = |
| 1173 | LLVM::AddressOfOp::create(builder, location: loc, res: ptrType, global_name: global.getSymNameAttr()); |
| 1174 | return LLVM::GEPOp::create(builder, location: loc, resultType: ptrType, elementType: type, basePtr: globalPtr, |
| 1175 | indices: ArrayRef<GEPArg>{0, 0}); |
| 1176 | } |
| 1177 | |
| 1178 | bool mlir::LLVM::satisfiesLLVMModule(Operation *op) { |
| 1179 | return op->hasTrait<OpTrait::SymbolTable>() && |
| 1180 | op->hasTrait<OpTrait::IsIsolatedFromAbove>(); |
| 1181 | } |
| 1182 | |
| 1183 | Operation *mlir::LLVM::parentLLVMModule(Operation *op) { |
| 1184 | Operation *module = op->getParentOp(); |
| 1185 | while (module && !satisfiesLLVMModule(op: module)) |
| 1186 | module = module->getParentOp(); |
| 1187 | assert(module && "unexpected operation outside of a module" ); |
| 1188 | return module; |
| 1189 | } |
| 1190 | |
| 1191 | #define GET_OP_CLASSES |
| 1192 | #include "mlir/Dialect/LLVMIR/LLVMModuleOps.cpp.inc" |
| 1193 | |