1 //===- LLVMDialect.cpp - LLVM IR Ops and Dialect registration -------------===// 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 types and operation details for the LLVM IR dialect in 10 // MLIR, and the LLVM IR dialect. It also registers the dialect. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 14 #include "TypeDetail.h" 15 #include "mlir/Dialect/LLVMIR/LLVMTypes.h" 16 #include "mlir/IR/Builders.h" 17 #include "mlir/IR/BuiltinOps.h" 18 #include "mlir/IR/BuiltinTypes.h" 19 #include "mlir/IR/DialectImplementation.h" 20 #include "mlir/IR/FunctionImplementation.h" 21 #include "mlir/IR/MLIRContext.h" 22 #include "mlir/IR/Matchers.h" 23 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/ADT/TypeSwitch.h" 26 #include "llvm/AsmParser/Parser.h" 27 #include "llvm/Bitcode/BitcodeReader.h" 28 #include "llvm/Bitcode/BitcodeWriter.h" 29 #include "llvm/IR/Attributes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/Support/Mutex.h" 33 #include "llvm/Support/SourceMgr.h" 34 35 #include <numeric> 36 37 using namespace mlir; 38 using namespace mlir::LLVM; 39 using mlir::LLVM::linkage::getMaxEnumValForLinkage; 40 41 #include "mlir/Dialect/LLVMIR/LLVMOpsDialect.cpp.inc" 42 43 static constexpr const char kVolatileAttrName[] = "volatile_"; 44 static constexpr const char kNonTemporalAttrName[] = "nontemporal"; 45 46 #include "mlir/Dialect/LLVMIR/LLVMOpsEnums.cpp.inc" 47 #include "mlir/Dialect/LLVMIR/LLVMOpsInterfaces.cpp.inc" 48 #define GET_ATTRDEF_CLASSES 49 #include "mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.cpp.inc" 50 51 static auto processFMFAttr(ArrayRef<NamedAttribute> attrs) { 52 SmallVector<NamedAttribute, 8> filteredAttrs( 53 llvm::make_filter_range(attrs, [&](NamedAttribute attr) { 54 if (attr.getName() == "fastmathFlags") { 55 auto defAttr = FMFAttr::get(attr.getValue().getContext(), {}); 56 return defAttr != attr.getValue(); 57 } 58 return true; 59 })); 60 return filteredAttrs; 61 } 62 63 static ParseResult parseLLVMOpAttrs(OpAsmParser &parser, 64 NamedAttrList &result) { 65 return parser.parseOptionalAttrDict(result); 66 } 67 68 static void printLLVMOpAttrs(OpAsmPrinter &printer, Operation *op, 69 DictionaryAttr attrs) { 70 printer.printOptionalAttrDict(processFMFAttr(attrs.getValue())); 71 } 72 73 /// Verifies `symbol`'s use in `op` to ensure the symbol is a valid and 74 /// fully defined llvm.func. 75 static LogicalResult verifySymbolAttrUse(FlatSymbolRefAttr symbol, 76 Operation *op, 77 SymbolTableCollection &symbolTable) { 78 StringRef name = symbol.getValue(); 79 auto func = 80 symbolTable.lookupNearestSymbolFrom<LLVMFuncOp>(op, symbol.getAttr()); 81 if (!func) 82 return op->emitOpError("'") 83 << name << "' does not reference a valid LLVM function"; 84 if (func.isExternal()) 85 return op->emitOpError("'") << name << "' does not have a definition"; 86 return success(); 87 } 88 89 //===----------------------------------------------------------------------===// 90 // Printing/parsing for LLVM::CmpOp. 91 //===----------------------------------------------------------------------===// 92 93 void ICmpOp::print(OpAsmPrinter &p) { 94 p << " \"" << stringifyICmpPredicate(getPredicate()) << "\" " << getOperand(0) 95 << ", " << getOperand(1); 96 p.printOptionalAttrDict((*this)->getAttrs(), {"predicate"}); 97 p << " : " << getLhs().getType(); 98 } 99 100 void FCmpOp::print(OpAsmPrinter &p) { 101 p << " \"" << stringifyFCmpPredicate(getPredicate()) << "\" " << getOperand(0) 102 << ", " << getOperand(1); 103 p.printOptionalAttrDict(processFMFAttr((*this)->getAttrs()), {"predicate"}); 104 p << " : " << getLhs().getType(); 105 } 106 107 // <operation> ::= `llvm.icmp` string-literal ssa-use `,` ssa-use 108 // attribute-dict? `:` type 109 // <operation> ::= `llvm.fcmp` string-literal ssa-use `,` ssa-use 110 // attribute-dict? `:` type 111 template <typename CmpPredicateType> 112 static ParseResult parseCmpOp(OpAsmParser &parser, OperationState &result) { 113 Builder &builder = parser.getBuilder(); 114 115 StringAttr predicateAttr; 116 OpAsmParser::UnresolvedOperand lhs, rhs; 117 Type type; 118 SMLoc predicateLoc, trailingTypeLoc; 119 if (parser.getCurrentLocation(&predicateLoc) || 120 parser.parseAttribute(predicateAttr, "predicate", result.attributes) || 121 parser.parseOperand(lhs) || parser.parseComma() || 122 parser.parseOperand(rhs) || 123 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 124 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type) || 125 parser.resolveOperand(lhs, type, result.operands) || 126 parser.resolveOperand(rhs, type, result.operands)) 127 return failure(); 128 129 // Replace the string attribute `predicate` with an integer attribute. 130 int64_t predicateValue = 0; 131 if (std::is_same<CmpPredicateType, ICmpPredicate>()) { 132 Optional<ICmpPredicate> predicate = 133 symbolizeICmpPredicate(predicateAttr.getValue()); 134 if (!predicate) 135 return parser.emitError(predicateLoc) 136 << "'" << predicateAttr.getValue() 137 << "' is an incorrect value of the 'predicate' attribute"; 138 predicateValue = static_cast<int64_t>(predicate.getValue()); 139 } else { 140 Optional<FCmpPredicate> predicate = 141 symbolizeFCmpPredicate(predicateAttr.getValue()); 142 if (!predicate) 143 return parser.emitError(predicateLoc) 144 << "'" << predicateAttr.getValue() 145 << "' is an incorrect value of the 'predicate' attribute"; 146 predicateValue = static_cast<int64_t>(predicate.getValue()); 147 } 148 149 result.attributes.set("predicate", 150 parser.getBuilder().getI64IntegerAttr(predicateValue)); 151 152 // The result type is either i1 or a vector type <? x i1> if the inputs are 153 // vectors. 154 Type resultType = IntegerType::get(builder.getContext(), 1); 155 if (!isCompatibleType(type)) 156 return parser.emitError(trailingTypeLoc, 157 "expected LLVM dialect-compatible type"); 158 if (LLVM::isCompatibleVectorType(type)) { 159 if (LLVM::isScalableVectorType(type)) { 160 resultType = LLVM::getVectorType( 161 resultType, LLVM::getVectorNumElements(type).getKnownMinValue(), 162 /*isScalable=*/true); 163 } else { 164 resultType = LLVM::getVectorType( 165 resultType, LLVM::getVectorNumElements(type).getFixedValue(), 166 /*isScalable=*/false); 167 } 168 } 169 170 result.addTypes({resultType}); 171 return success(); 172 } 173 174 ParseResult ICmpOp::parse(OpAsmParser &parser, OperationState &result) { 175 return parseCmpOp<ICmpPredicate>(parser, result); 176 } 177 178 ParseResult FCmpOp::parse(OpAsmParser &parser, OperationState &result) { 179 return parseCmpOp<FCmpPredicate>(parser, result); 180 } 181 182 //===----------------------------------------------------------------------===// 183 // Printing/parsing for LLVM::AllocaOp. 184 //===----------------------------------------------------------------------===// 185 186 void AllocaOp::print(OpAsmPrinter &p) { 187 auto elemTy = getType().cast<LLVM::LLVMPointerType>().getElementType(); 188 189 auto funcTy = 190 FunctionType::get(getContext(), {getArraySize().getType()}, {getType()}); 191 192 p << ' ' << getArraySize() << " x " << elemTy; 193 if (getAlignment().hasValue() && *getAlignment() != 0) 194 p.printOptionalAttrDict((*this)->getAttrs()); 195 else 196 p.printOptionalAttrDict((*this)->getAttrs(), {"alignment"}); 197 p << " : " << funcTy; 198 } 199 200 // <operation> ::= `llvm.alloca` ssa-use `x` type attribute-dict? 201 // `:` type `,` type 202 ParseResult AllocaOp::parse(OpAsmParser &parser, OperationState &result) { 203 OpAsmParser::UnresolvedOperand arraySize; 204 Type type, elemType; 205 SMLoc trailingTypeLoc; 206 if (parser.parseOperand(arraySize) || parser.parseKeyword("x") || 207 parser.parseType(elemType) || 208 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 209 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type)) 210 return failure(); 211 212 Optional<NamedAttribute> alignmentAttr = 213 result.attributes.getNamed("alignment"); 214 if (alignmentAttr.hasValue()) { 215 auto alignmentInt = 216 alignmentAttr.getValue().getValue().dyn_cast<IntegerAttr>(); 217 if (!alignmentInt) 218 return parser.emitError(parser.getNameLoc(), 219 "expected integer alignment"); 220 if (alignmentInt.getValue().isNullValue()) 221 result.attributes.erase("alignment"); 222 } 223 224 // Extract the result type from the trailing function type. 225 auto funcType = type.dyn_cast<FunctionType>(); 226 if (!funcType || funcType.getNumInputs() != 1 || 227 funcType.getNumResults() != 1) 228 return parser.emitError( 229 trailingTypeLoc, 230 "expected trailing function type with one argument and one result"); 231 232 if (parser.resolveOperand(arraySize, funcType.getInput(0), result.operands)) 233 return failure(); 234 235 result.addTypes({funcType.getResult(0)}); 236 return success(); 237 } 238 239 //===----------------------------------------------------------------------===// 240 // LLVM::BrOp 241 //===----------------------------------------------------------------------===// 242 243 SuccessorOperands BrOp::getSuccessorOperands(unsigned index) { 244 assert(index == 0 && "invalid successor index"); 245 return SuccessorOperands(getDestOperandsMutable()); 246 } 247 248 //===----------------------------------------------------------------------===// 249 // LLVM::CondBrOp 250 //===----------------------------------------------------------------------===// 251 252 SuccessorOperands CondBrOp::getSuccessorOperands(unsigned index) { 253 assert(index < getNumSuccessors() && "invalid successor index"); 254 return SuccessorOperands(index == 0 ? getTrueDestOperandsMutable() 255 : getFalseDestOperandsMutable()); 256 } 257 258 //===----------------------------------------------------------------------===// 259 // LLVM::SwitchOp 260 //===----------------------------------------------------------------------===// 261 262 void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value, 263 Block *defaultDestination, ValueRange defaultOperands, 264 ArrayRef<int32_t> caseValues, BlockRange caseDestinations, 265 ArrayRef<ValueRange> caseOperands, 266 ArrayRef<int32_t> branchWeights) { 267 ElementsAttr caseValuesAttr; 268 if (!caseValues.empty()) 269 caseValuesAttr = builder.getI32VectorAttr(caseValues); 270 271 ElementsAttr weightsAttr; 272 if (!branchWeights.empty()) 273 weightsAttr = builder.getI32VectorAttr(llvm::to_vector<4>(branchWeights)); 274 275 build(builder, result, value, defaultOperands, caseOperands, caseValuesAttr, 276 weightsAttr, defaultDestination, caseDestinations); 277 } 278 279 /// <cases> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)? 280 /// ( `,` integer `:` bb-id (`(` ssa-use-and-type-list `)`)? )? 281 static ParseResult parseSwitchOpCases( 282 OpAsmParser &parser, Type flagType, ElementsAttr &caseValues, 283 SmallVectorImpl<Block *> &caseDestinations, 284 SmallVectorImpl<SmallVector<OpAsmParser::UnresolvedOperand>> &caseOperands, 285 SmallVectorImpl<SmallVector<Type>> &caseOperandTypes) { 286 SmallVector<APInt> values; 287 unsigned bitWidth = flagType.getIntOrFloatBitWidth(); 288 do { 289 int64_t value = 0; 290 OptionalParseResult integerParseResult = parser.parseOptionalInteger(value); 291 if (values.empty() && !integerParseResult.hasValue()) 292 return success(); 293 294 if (!integerParseResult.hasValue() || integerParseResult.getValue()) 295 return failure(); 296 values.push_back(APInt(bitWidth, value)); 297 298 Block *destination; 299 SmallVector<OpAsmParser::UnresolvedOperand> operands; 300 SmallVector<Type> operandTypes; 301 if (parser.parseColon() || parser.parseSuccessor(destination)) 302 return failure(); 303 if (!parser.parseOptionalLParen()) { 304 if (parser.parseRegionArgumentList(operands) || 305 parser.parseColonTypeList(operandTypes) || parser.parseRParen()) 306 return failure(); 307 } 308 caseDestinations.push_back(destination); 309 caseOperands.emplace_back(operands); 310 caseOperandTypes.emplace_back(operandTypes); 311 } while (!parser.parseOptionalComma()); 312 313 ShapedType caseValueType = 314 VectorType::get(static_cast<int64_t>(values.size()), flagType); 315 caseValues = DenseIntElementsAttr::get(caseValueType, values); 316 return success(); 317 } 318 319 static void printSwitchOpCases(OpAsmPrinter &p, SwitchOp op, Type flagType, 320 ElementsAttr caseValues, 321 SuccessorRange caseDestinations, 322 OperandRangeRange caseOperands, 323 const TypeRangeRange &caseOperandTypes) { 324 if (!caseValues) 325 return; 326 327 size_t index = 0; 328 llvm::interleave( 329 llvm::zip(caseValues.cast<DenseIntElementsAttr>(), caseDestinations), 330 [&](auto i) { 331 p << " "; 332 p << std::get<0>(i).getLimitedValue(); 333 p << ": "; 334 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]); 335 }, 336 [&] { 337 p << ','; 338 p.printNewline(); 339 }); 340 p.printNewline(); 341 } 342 343 LogicalResult SwitchOp::verify() { 344 if ((!getCaseValues() && !getCaseDestinations().empty()) || 345 (getCaseValues() && 346 getCaseValues()->size() != 347 static_cast<int64_t>(getCaseDestinations().size()))) 348 return emitOpError("expects number of case values to match number of " 349 "case destinations"); 350 if (getBranchWeights() && getBranchWeights()->size() != getNumSuccessors()) 351 return emitError("expects number of branch weights to match number of " 352 "successors: ") 353 << getBranchWeights()->size() << " vs " << getNumSuccessors(); 354 return success(); 355 } 356 357 SuccessorOperands SwitchOp::getSuccessorOperands(unsigned index) { 358 assert(index < getNumSuccessors() && "invalid successor index"); 359 return SuccessorOperands(index == 0 ? getDefaultOperandsMutable() 360 : getCaseOperandsMutable(index - 1)); 361 } 362 363 //===----------------------------------------------------------------------===// 364 // Code for LLVM::GEPOp. 365 //===----------------------------------------------------------------------===// 366 367 constexpr int GEPOp::kDynamicIndex; 368 369 /// Populates `indices` with positions of GEP indices that would correspond to 370 /// LLVMStructTypes potentially nested in the given type. The type currently 371 /// visited gets `currentIndex` and LLVM container types are visited 372 /// recursively. The recursion is bounded and takes care of recursive types by 373 /// means of the `visited` set. 374 static void recordStructIndices(Type type, unsigned currentIndex, 375 SmallVectorImpl<unsigned> &indices, 376 SmallVectorImpl<unsigned> *structSizes, 377 SmallPtrSet<Type, 4> &visited) { 378 if (visited.contains(type)) 379 return; 380 381 visited.insert(type); 382 383 llvm::TypeSwitch<Type>(type) 384 .Case<LLVMStructType>([&](LLVMStructType structType) { 385 indices.push_back(currentIndex); 386 if (structSizes) 387 structSizes->push_back(structType.getBody().size()); 388 for (Type elementType : structType.getBody()) 389 recordStructIndices(elementType, currentIndex + 1, indices, 390 structSizes, visited); 391 }) 392 .Case<VectorType, LLVMScalableVectorType, LLVMFixedVectorType, 393 LLVMArrayType>([&](auto containerType) { 394 recordStructIndices(containerType.getElementType(), currentIndex + 1, 395 indices, structSizes, visited); 396 }); 397 } 398 399 /// Populates `indices` with positions of GEP indices that correspond to 400 /// LLVMStructTypes potentially nested in the given `baseGEPType`, which must 401 /// be either an LLVMPointer type or a vector thereof. If `structSizes` is 402 /// provided, it is populated with sizes of the indexed structs for bounds 403 /// verification purposes. 404 static void 405 findKnownStructIndices(Type baseGEPType, SmallVectorImpl<unsigned> &indices, 406 SmallVectorImpl<unsigned> *structSizes = nullptr) { 407 Type type = baseGEPType; 408 if (auto vectorType = type.dyn_cast<VectorType>()) 409 type = vectorType.getElementType(); 410 if (auto scalableVectorType = type.dyn_cast<LLVMScalableVectorType>()) 411 type = scalableVectorType.getElementType(); 412 if (auto fixedVectorType = type.dyn_cast<LLVMFixedVectorType>()) 413 type = fixedVectorType.getElementType(); 414 415 Type pointeeType = type.cast<LLVMPointerType>().getElementType(); 416 SmallPtrSet<Type, 4> visited; 417 recordStructIndices(pointeeType, /*currentIndex=*/1, indices, structSizes, 418 visited); 419 } 420 421 void GEPOp::build(OpBuilder &builder, OperationState &result, Type resultType, 422 Value basePtr, ValueRange operands, 423 ArrayRef<NamedAttribute> attributes) { 424 build(builder, result, resultType, basePtr, operands, 425 SmallVector<int32_t>(operands.size(), LLVM::GEPOp::kDynamicIndex), 426 attributes); 427 } 428 429 void GEPOp::build(OpBuilder &builder, OperationState &result, Type resultType, 430 Value basePtr, ValueRange indices, 431 ArrayRef<int32_t> structIndices, 432 ArrayRef<NamedAttribute> attributes) { 433 SmallVector<Value> remainingIndices; 434 SmallVector<int32_t> updatedStructIndices(structIndices.begin(), 435 structIndices.end()); 436 SmallVector<unsigned> structRelatedPositions; 437 findKnownStructIndices(basePtr.getType(), structRelatedPositions); 438 439 SmallVector<unsigned> operandsToErase; 440 for (unsigned pos : structRelatedPositions) { 441 // GEP may not be indexing as deep as some structs are located. 442 if (pos >= structIndices.size()) 443 continue; 444 445 // If the index is already static, it's fine. 446 if (structIndices[pos] != kDynamicIndex) 447 continue; 448 449 // Find the corresponding operand. 450 unsigned operandPos = 451 std::count(structIndices.begin(), std::next(structIndices.begin(), pos), 452 kDynamicIndex); 453 454 // Extract the constant value from the operand and put it into the attribute 455 // instead. 456 APInt staticIndexValue; 457 bool matched = 458 matchPattern(indices[operandPos], m_ConstantInt(&staticIndexValue)); 459 (void)matched; 460 assert(matched && "index into a struct must be a constant"); 461 assert(staticIndexValue.sge(APInt::getSignedMinValue(/*numBits=*/32)) && 462 "struct index underflows 32-bit integer"); 463 assert(staticIndexValue.sle(APInt::getSignedMaxValue(/*numBits=*/32)) && 464 "struct index overflows 32-bit integer"); 465 auto staticIndex = static_cast<int32_t>(staticIndexValue.getSExtValue()); 466 updatedStructIndices[pos] = staticIndex; 467 operandsToErase.push_back(operandPos); 468 } 469 470 for (unsigned i = 0, e = indices.size(); i < e; ++i) { 471 if (!llvm::is_contained(operandsToErase, i)) 472 remainingIndices.push_back(indices[i]); 473 } 474 475 assert(remainingIndices.size() == static_cast<size_t>(llvm::count( 476 updatedStructIndices, kDynamicIndex)) && 477 "expected as many index operands as dynamic index attr elements"); 478 479 result.addTypes(resultType); 480 result.addAttributes(attributes); 481 result.addAttribute("structIndices", 482 builder.getI32TensorAttr(updatedStructIndices)); 483 result.addOperands(basePtr); 484 result.addOperands(remainingIndices); 485 } 486 487 static ParseResult 488 parseGEPIndices(OpAsmParser &parser, 489 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &indices, 490 DenseIntElementsAttr &structIndices) { 491 SmallVector<int32_t> constantIndices; 492 do { 493 int32_t constantIndex; 494 OptionalParseResult parsedInteger = 495 parser.parseOptionalInteger(constantIndex); 496 if (parsedInteger.hasValue()) { 497 if (failed(parsedInteger.getValue())) 498 return failure(); 499 constantIndices.push_back(constantIndex); 500 continue; 501 } 502 503 constantIndices.push_back(LLVM::GEPOp::kDynamicIndex); 504 if (failed(parser.parseOperand(indices.emplace_back()))) 505 return failure(); 506 } while (succeeded(parser.parseOptionalComma())); 507 508 structIndices = parser.getBuilder().getI32TensorAttr(constantIndices); 509 return success(); 510 } 511 512 static void printGEPIndices(OpAsmPrinter &printer, LLVM::GEPOp gepOp, 513 OperandRange indices, 514 DenseIntElementsAttr structIndices) { 515 unsigned operandIdx = 0; 516 llvm::interleaveComma(structIndices.getValues<int32_t>(), printer, 517 [&](int32_t cst) { 518 if (cst == LLVM::GEPOp::kDynamicIndex) 519 printer.printOperand(indices[operandIdx++]); 520 else 521 printer << cst; 522 }); 523 } 524 525 LogicalResult LLVM::GEPOp::verify() { 526 SmallVector<unsigned> indices; 527 SmallVector<unsigned> structSizes; 528 findKnownStructIndices(getBase().getType(), indices, &structSizes); 529 DenseIntElementsAttr structIndices = getStructIndices(); 530 for (unsigned i : llvm::seq<unsigned>(0, indices.size())) { 531 unsigned index = indices[i]; 532 // GEP may not be indexing as deep as some structs nested in the type. 533 if (index >= structIndices.getNumElements()) 534 continue; 535 536 int32_t staticIndex = structIndices.getValues<int32_t>()[index]; 537 if (staticIndex == LLVM::GEPOp::kDynamicIndex) 538 return emitOpError() << "expected index " << index 539 << " indexing a struct to be constant"; 540 if (staticIndex < 0 || static_cast<unsigned>(staticIndex) >= structSizes[i]) 541 return emitOpError() << "index " << index 542 << " indexing a struct is out of bounds"; 543 } 544 return success(); 545 } 546 547 //===----------------------------------------------------------------------===// 548 // Builder, printer and parser for for LLVM::LoadOp. 549 //===----------------------------------------------------------------------===// 550 551 LogicalResult verifySymbolAttribute( 552 Operation *op, StringRef attributeName, 553 llvm::function_ref<LogicalResult(Operation *, SymbolRefAttr)> 554 verifySymbolType) { 555 if (Attribute attribute = op->getAttr(attributeName)) { 556 // The attribute is already verified to be a symbol ref array attribute via 557 // a constraint in the operation definition. 558 for (SymbolRefAttr symbolRef : 559 attribute.cast<ArrayAttr>().getAsRange<SymbolRefAttr>()) { 560 StringAttr metadataName = symbolRef.getRootReference(); 561 StringAttr symbolName = symbolRef.getLeafReference(); 562 // We want @metadata::@symbol, not just @symbol 563 if (metadataName == symbolName) { 564 return op->emitOpError() << "expected '" << symbolRef 565 << "' to specify a fully qualified reference"; 566 } 567 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 568 op->getParentOp(), metadataName); 569 if (!metadataOp) 570 return op->emitOpError() 571 << "expected '" << symbolRef << "' to reference a metadata op"; 572 Operation *symbolOp = 573 SymbolTable::lookupNearestSymbolFrom(metadataOp, symbolName); 574 if (!symbolOp) 575 return op->emitOpError() 576 << "expected '" << symbolRef << "' to be a valid reference"; 577 if (failed(verifySymbolType(symbolOp, symbolRef))) { 578 return failure(); 579 } 580 } 581 } 582 return success(); 583 } 584 585 // Verifies that metadata ops are wired up properly. 586 template <typename OpTy> 587 static LogicalResult verifyOpMetadata(Operation *op, StringRef attributeName) { 588 auto verifySymbolType = [op](Operation *symbolOp, 589 SymbolRefAttr symbolRef) -> LogicalResult { 590 if (!isa<OpTy>(symbolOp)) { 591 return op->emitOpError() 592 << "expected '" << symbolRef << "' to resolve to a " 593 << OpTy::getOperationName(); 594 } 595 return success(); 596 }; 597 598 return verifySymbolAttribute(op, attributeName, verifySymbolType); 599 } 600 601 static LogicalResult verifyMemoryOpMetadata(Operation *op) { 602 // access_groups 603 if (failed(verifyOpMetadata<LLVM::AccessGroupMetadataOp>( 604 op, LLVMDialect::getAccessGroupsAttrName()))) 605 return failure(); 606 607 // alias_scopes 608 if (failed(verifyOpMetadata<LLVM::AliasScopeMetadataOp>( 609 op, LLVMDialect::getAliasScopesAttrName()))) 610 return failure(); 611 612 // noalias_scopes 613 if (failed(verifyOpMetadata<LLVM::AliasScopeMetadataOp>( 614 op, LLVMDialect::getNoAliasScopesAttrName()))) 615 return failure(); 616 617 return success(); 618 } 619 620 LogicalResult LoadOp::verify() { return verifyMemoryOpMetadata(*this); } 621 622 void LoadOp::build(OpBuilder &builder, OperationState &result, Type t, 623 Value addr, unsigned alignment, bool isVolatile, 624 bool isNonTemporal) { 625 result.addOperands(addr); 626 result.addTypes(t); 627 if (isVolatile) 628 result.addAttribute(kVolatileAttrName, builder.getUnitAttr()); 629 if (isNonTemporal) 630 result.addAttribute(kNonTemporalAttrName, builder.getUnitAttr()); 631 if (alignment != 0) 632 result.addAttribute("alignment", builder.getI64IntegerAttr(alignment)); 633 } 634 635 void LoadOp::print(OpAsmPrinter &p) { 636 p << ' '; 637 if (getVolatile_()) 638 p << "volatile "; 639 p << getAddr(); 640 p.printOptionalAttrDict((*this)->getAttrs(), {kVolatileAttrName}); 641 p << " : " << getAddr().getType(); 642 } 643 644 // Extract the pointee type from the LLVM pointer type wrapped in MLIR. Return 645 // the resulting type wrapped in MLIR, or nullptr on error. 646 static Type getLoadStoreElementType(OpAsmParser &parser, Type type, 647 SMLoc trailingTypeLoc) { 648 auto llvmTy = type.dyn_cast<LLVM::LLVMPointerType>(); 649 if (!llvmTy) 650 return parser.emitError(trailingTypeLoc, "expected LLVM pointer type"), 651 nullptr; 652 return llvmTy.getElementType(); 653 } 654 655 // <operation> ::= `llvm.load` `volatile` ssa-use attribute-dict? `:` type 656 ParseResult LoadOp::parse(OpAsmParser &parser, OperationState &result) { 657 OpAsmParser::UnresolvedOperand addr; 658 Type type; 659 SMLoc trailingTypeLoc; 660 661 if (succeeded(parser.parseOptionalKeyword("volatile"))) 662 result.addAttribute(kVolatileAttrName, parser.getBuilder().getUnitAttr()); 663 664 if (parser.parseOperand(addr) || 665 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 666 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type) || 667 parser.resolveOperand(addr, type, result.operands)) 668 return failure(); 669 670 Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc); 671 672 result.addTypes(elemTy); 673 return success(); 674 } 675 676 //===----------------------------------------------------------------------===// 677 // Builder, printer and parser for LLVM::StoreOp. 678 //===----------------------------------------------------------------------===// 679 680 LogicalResult StoreOp::verify() { return verifyMemoryOpMetadata(*this); } 681 682 void StoreOp::build(OpBuilder &builder, OperationState &result, Value value, 683 Value addr, unsigned alignment, bool isVolatile, 684 bool isNonTemporal) { 685 result.addOperands({value, addr}); 686 result.addTypes({}); 687 if (isVolatile) 688 result.addAttribute(kVolatileAttrName, builder.getUnitAttr()); 689 if (isNonTemporal) 690 result.addAttribute(kNonTemporalAttrName, builder.getUnitAttr()); 691 if (alignment != 0) 692 result.addAttribute("alignment", builder.getI64IntegerAttr(alignment)); 693 } 694 695 void StoreOp::print(OpAsmPrinter &p) { 696 p << ' '; 697 if (getVolatile_()) 698 p << "volatile "; 699 p << getValue() << ", " << getAddr(); 700 p.printOptionalAttrDict((*this)->getAttrs(), {kVolatileAttrName}); 701 p << " : " << getAddr().getType(); 702 } 703 704 // <operation> ::= `llvm.store` `volatile` ssa-use `,` ssa-use 705 // attribute-dict? `:` type 706 ParseResult StoreOp::parse(OpAsmParser &parser, OperationState &result) { 707 OpAsmParser::UnresolvedOperand addr, value; 708 Type type; 709 SMLoc trailingTypeLoc; 710 711 if (succeeded(parser.parseOptionalKeyword("volatile"))) 712 result.addAttribute(kVolatileAttrName, parser.getBuilder().getUnitAttr()); 713 714 if (parser.parseOperand(value) || parser.parseComma() || 715 parser.parseOperand(addr) || 716 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 717 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type)) 718 return failure(); 719 720 Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc); 721 if (!elemTy) 722 return failure(); 723 724 if (parser.resolveOperand(value, elemTy, result.operands) || 725 parser.resolveOperand(addr, type, result.operands)) 726 return failure(); 727 728 return success(); 729 } 730 731 ///===---------------------------------------------------------------------===// 732 /// LLVM::InvokeOp 733 ///===---------------------------------------------------------------------===// 734 735 SuccessorOperands InvokeOp::getSuccessorOperands(unsigned index) { 736 assert(index < getNumSuccessors() && "invalid successor index"); 737 return SuccessorOperands(index == 0 ? getNormalDestOperandsMutable() 738 : getUnwindDestOperandsMutable()); 739 } 740 741 LogicalResult InvokeOp::verify() { 742 if (getNumResults() > 1) 743 return emitOpError("must have 0 or 1 result"); 744 745 Block *unwindDest = getUnwindDest(); 746 if (unwindDest->empty()) 747 return emitError("must have at least one operation in unwind destination"); 748 749 // In unwind destination, first operation must be LandingpadOp 750 if (!isa<LandingpadOp>(unwindDest->front())) 751 return emitError("first operation in unwind destination should be a " 752 "llvm.landingpad operation"); 753 754 return success(); 755 } 756 757 void InvokeOp::print(OpAsmPrinter &p) { 758 auto callee = getCallee(); 759 bool isDirect = callee.hasValue(); 760 761 p << ' '; 762 763 // Either function name or pointer 764 if (isDirect) 765 p.printSymbolName(callee.getValue()); 766 else 767 p << getOperand(0); 768 769 p << '(' << getOperands().drop_front(isDirect ? 0 : 1) << ')'; 770 p << " to "; 771 p.printSuccessorAndUseList(getNormalDest(), getNormalDestOperands()); 772 p << " unwind "; 773 p.printSuccessorAndUseList(getUnwindDest(), getUnwindDestOperands()); 774 775 p.printOptionalAttrDict((*this)->getAttrs(), 776 {InvokeOp::getOperandSegmentSizeAttr(), "callee"}); 777 p << " : "; 778 p.printFunctionalType(llvm::drop_begin(getOperandTypes(), isDirect ? 0 : 1), 779 getResultTypes()); 780 } 781 782 /// <operation> ::= `llvm.invoke` (function-id | ssa-use) `(` ssa-use-list `)` 783 /// `to` bb-id (`[` ssa-use-and-type-list `]`)? 784 /// `unwind` bb-id (`[` ssa-use-and-type-list `]`)? 785 /// attribute-dict? `:` function-type 786 ParseResult InvokeOp::parse(OpAsmParser &parser, OperationState &result) { 787 SmallVector<OpAsmParser::UnresolvedOperand, 8> operands; 788 FunctionType funcType; 789 SymbolRefAttr funcAttr; 790 SMLoc trailingTypeLoc; 791 Block *normalDest, *unwindDest; 792 SmallVector<Value, 4> normalOperands, unwindOperands; 793 Builder &builder = parser.getBuilder(); 794 795 // Parse an operand list that will, in practice, contain 0 or 1 operand. In 796 // case of an indirect call, there will be 1 operand before `(`. In case of a 797 // direct call, there will be no operands and the parser will stop at the 798 // function identifier without complaining. 799 if (parser.parseOperandList(operands)) 800 return failure(); 801 bool isDirect = operands.empty(); 802 803 // Optionally parse a function identifier. 804 if (isDirect && parser.parseAttribute(funcAttr, "callee", result.attributes)) 805 return failure(); 806 807 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) || 808 parser.parseKeyword("to") || 809 parser.parseSuccessorAndUseList(normalDest, normalOperands) || 810 parser.parseKeyword("unwind") || 811 parser.parseSuccessorAndUseList(unwindDest, unwindOperands) || 812 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 813 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(funcType)) 814 return failure(); 815 816 if (isDirect) { 817 // Make sure types match. 818 if (parser.resolveOperands(operands, funcType.getInputs(), 819 parser.getNameLoc(), result.operands)) 820 return failure(); 821 result.addTypes(funcType.getResults()); 822 } else { 823 // Construct the LLVM IR Dialect function type that the first operand 824 // should match. 825 if (funcType.getNumResults() > 1) 826 return parser.emitError(trailingTypeLoc, 827 "expected function with 0 or 1 result"); 828 829 Type llvmResultType; 830 if (funcType.getNumResults() == 0) { 831 llvmResultType = LLVM::LLVMVoidType::get(builder.getContext()); 832 } else { 833 llvmResultType = funcType.getResult(0); 834 if (!isCompatibleType(llvmResultType)) 835 return parser.emitError(trailingTypeLoc, 836 "expected result to have LLVM type"); 837 } 838 839 SmallVector<Type, 8> argTypes; 840 argTypes.reserve(funcType.getNumInputs()); 841 for (Type ty : funcType.getInputs()) { 842 if (isCompatibleType(ty)) 843 argTypes.push_back(ty); 844 else 845 return parser.emitError(trailingTypeLoc, 846 "expected LLVM types as inputs"); 847 } 848 849 auto llvmFuncType = LLVM::LLVMFunctionType::get(llvmResultType, argTypes); 850 auto wrappedFuncType = LLVM::LLVMPointerType::get(llvmFuncType); 851 852 auto funcArguments = llvm::makeArrayRef(operands).drop_front(); 853 854 // Make sure that the first operand (indirect callee) matches the wrapped 855 // LLVM IR function type, and that the types of the other call operands 856 // match the types of the function arguments. 857 if (parser.resolveOperand(operands[0], wrappedFuncType, result.operands) || 858 parser.resolveOperands(funcArguments, funcType.getInputs(), 859 parser.getNameLoc(), result.operands)) 860 return failure(); 861 862 result.addTypes(llvmResultType); 863 } 864 result.addSuccessors({normalDest, unwindDest}); 865 result.addOperands(normalOperands); 866 result.addOperands(unwindOperands); 867 868 result.addAttribute( 869 InvokeOp::getOperandSegmentSizeAttr(), 870 builder.getI32VectorAttr({static_cast<int32_t>(operands.size()), 871 static_cast<int32_t>(normalOperands.size()), 872 static_cast<int32_t>(unwindOperands.size())})); 873 return success(); 874 } 875 876 ///===----------------------------------------------------------------------===// 877 /// Verifying/Printing/Parsing for LLVM::LandingpadOp. 878 ///===----------------------------------------------------------------------===// 879 880 LogicalResult LandingpadOp::verify() { 881 Value value; 882 if (LLVMFuncOp func = (*this)->getParentOfType<LLVMFuncOp>()) { 883 if (!func.getPersonality().hasValue()) 884 return emitError( 885 "llvm.landingpad needs to be in a function with a personality"); 886 } 887 888 if (!getCleanup() && getOperands().empty()) 889 return emitError("landingpad instruction expects at least one clause or " 890 "cleanup attribute"); 891 892 for (unsigned idx = 0, ie = getNumOperands(); idx < ie; idx++) { 893 value = getOperand(idx); 894 bool isFilter = value.getType().isa<LLVMArrayType>(); 895 if (isFilter) { 896 // FIXME: Verify filter clauses when arrays are appropriately handled 897 } else { 898 // catch - global addresses only. 899 // Bitcast ops should have global addresses as their args. 900 if (auto bcOp = value.getDefiningOp<BitcastOp>()) { 901 if (auto addrOp = bcOp.getArg().getDefiningOp<AddressOfOp>()) 902 continue; 903 return emitError("constant clauses expected").attachNote(bcOp.getLoc()) 904 << "global addresses expected as operand to " 905 "bitcast used in clauses for landingpad"; 906 } 907 // NullOp and AddressOfOp allowed 908 if (value.getDefiningOp<NullOp>()) 909 continue; 910 if (value.getDefiningOp<AddressOfOp>()) 911 continue; 912 return emitError("clause #") 913 << idx << " is not a known constant - null, addressof, bitcast"; 914 } 915 } 916 return success(); 917 } 918 919 void LandingpadOp::print(OpAsmPrinter &p) { 920 p << (getCleanup() ? " cleanup " : " "); 921 922 // Clauses 923 for (auto value : getOperands()) { 924 // Similar to llvm - if clause is an array type then it is filter 925 // clause else catch clause 926 bool isArrayTy = value.getType().isa<LLVMArrayType>(); 927 p << '(' << (isArrayTy ? "filter " : "catch ") << value << " : " 928 << value.getType() << ") "; 929 } 930 931 p.printOptionalAttrDict((*this)->getAttrs(), {"cleanup"}); 932 933 p << ": " << getType(); 934 } 935 936 /// <operation> ::= `llvm.landingpad` `cleanup`? 937 /// ((`catch` | `filter`) operand-type ssa-use)* attribute-dict? 938 ParseResult LandingpadOp::parse(OpAsmParser &parser, OperationState &result) { 939 // Check for cleanup 940 if (succeeded(parser.parseOptionalKeyword("cleanup"))) 941 result.addAttribute("cleanup", parser.getBuilder().getUnitAttr()); 942 943 // Parse clauses with types 944 while (succeeded(parser.parseOptionalLParen()) && 945 (succeeded(parser.parseOptionalKeyword("filter")) || 946 succeeded(parser.parseOptionalKeyword("catch")))) { 947 OpAsmParser::UnresolvedOperand operand; 948 Type ty; 949 if (parser.parseOperand(operand) || parser.parseColon() || 950 parser.parseType(ty) || 951 parser.resolveOperand(operand, ty, result.operands) || 952 parser.parseRParen()) 953 return failure(); 954 } 955 956 Type type; 957 if (parser.parseColon() || parser.parseType(type)) 958 return failure(); 959 960 result.addTypes(type); 961 return success(); 962 } 963 964 //===----------------------------------------------------------------------===// 965 // Verifying/Printing/parsing for LLVM::CallOp. 966 //===----------------------------------------------------------------------===// 967 968 LogicalResult CallOp::verify() { 969 if (getNumResults() > 1) 970 return emitOpError("must have 0 or 1 result"); 971 972 // Type for the callee, we'll get it differently depending if it is a direct 973 // or indirect call. 974 Type fnType; 975 976 bool isIndirect = false; 977 978 // If this is an indirect call, the callee attribute is missing. 979 FlatSymbolRefAttr calleeName = getCalleeAttr(); 980 if (!calleeName) { 981 isIndirect = true; 982 if (!getNumOperands()) 983 return emitOpError( 984 "must have either a `callee` attribute or at least an operand"); 985 auto ptrType = getOperand(0).getType().dyn_cast<LLVMPointerType>(); 986 if (!ptrType) 987 return emitOpError("indirect call expects a pointer as callee: ") 988 << ptrType; 989 fnType = ptrType.getElementType(); 990 } else { 991 Operation *callee = 992 SymbolTable::lookupNearestSymbolFrom(*this, calleeName.getAttr()); 993 if (!callee) 994 return emitOpError() 995 << "'" << calleeName.getValue() 996 << "' does not reference a symbol in the current scope"; 997 auto fn = dyn_cast<LLVMFuncOp>(callee); 998 if (!fn) 999 return emitOpError() << "'" << calleeName.getValue() 1000 << "' does not reference a valid LLVM function"; 1001 1002 fnType = fn.getFunctionType(); 1003 } 1004 1005 LLVMFunctionType funcType = fnType.dyn_cast<LLVMFunctionType>(); 1006 if (!funcType) 1007 return emitOpError("callee does not have a functional type: ") << fnType; 1008 1009 // Verify that the operand and result types match the callee. 1010 1011 if (!funcType.isVarArg() && 1012 funcType.getNumParams() != (getNumOperands() - isIndirect)) 1013 return emitOpError() << "incorrect number of operands (" 1014 << (getNumOperands() - isIndirect) 1015 << ") for callee (expecting: " 1016 << funcType.getNumParams() << ")"; 1017 1018 if (funcType.getNumParams() > (getNumOperands() - isIndirect)) 1019 return emitOpError() << "incorrect number of operands (" 1020 << (getNumOperands() - isIndirect) 1021 << ") for varargs callee (expecting at least: " 1022 << funcType.getNumParams() << ")"; 1023 1024 for (unsigned i = 0, e = funcType.getNumParams(); i != e; ++i) 1025 if (getOperand(i + isIndirect).getType() != funcType.getParamType(i)) 1026 return emitOpError() << "operand type mismatch for operand " << i << ": " 1027 << getOperand(i + isIndirect).getType() 1028 << " != " << funcType.getParamType(i); 1029 1030 if (getNumResults() == 0 && 1031 !funcType.getReturnType().isa<LLVM::LLVMVoidType>()) 1032 return emitOpError() << "expected function call to produce a value"; 1033 1034 if (getNumResults() != 0 && 1035 funcType.getReturnType().isa<LLVM::LLVMVoidType>()) 1036 return emitOpError() 1037 << "calling function with void result must not produce values"; 1038 1039 if (getNumResults() > 1) 1040 return emitOpError() 1041 << "expected LLVM function call to produce 0 or 1 result"; 1042 1043 if (getNumResults() && getResult(0).getType() != funcType.getReturnType()) 1044 return emitOpError() << "result type mismatch: " << getResult(0).getType() 1045 << " != " << funcType.getReturnType(); 1046 1047 return success(); 1048 } 1049 1050 void CallOp::print(OpAsmPrinter &p) { 1051 auto callee = getCallee(); 1052 bool isDirect = callee.hasValue(); 1053 1054 // Print the direct callee if present as a function attribute, or an indirect 1055 // callee (first operand) otherwise. 1056 p << ' '; 1057 if (isDirect) 1058 p.printSymbolName(callee.getValue()); 1059 else 1060 p << getOperand(0); 1061 1062 auto args = getOperands().drop_front(isDirect ? 0 : 1); 1063 p << '(' << args << ')'; 1064 p.printOptionalAttrDict(processFMFAttr((*this)->getAttrs()), {"callee"}); 1065 1066 // Reconstruct the function MLIR function type from operand and result types. 1067 p << " : "; 1068 p.printFunctionalType(args.getTypes(), getResultTypes()); 1069 } 1070 1071 // <operation> ::= `llvm.call` (function-id | ssa-use) `(` ssa-use-list `)` 1072 // attribute-dict? `:` function-type 1073 ParseResult CallOp::parse(OpAsmParser &parser, OperationState &result) { 1074 SmallVector<OpAsmParser::UnresolvedOperand, 8> operands; 1075 Type type; 1076 SymbolRefAttr funcAttr; 1077 SMLoc trailingTypeLoc; 1078 1079 // Parse an operand list that will, in practice, contain 0 or 1 operand. In 1080 // case of an indirect call, there will be 1 operand before `(`. In case of a 1081 // direct call, there will be no operands and the parser will stop at the 1082 // function identifier without complaining. 1083 if (parser.parseOperandList(operands)) 1084 return failure(); 1085 bool isDirect = operands.empty(); 1086 1087 // Optionally parse a function identifier. 1088 if (isDirect) 1089 if (parser.parseAttribute(funcAttr, "callee", result.attributes)) 1090 return failure(); 1091 1092 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) || 1093 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 1094 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type)) 1095 return failure(); 1096 1097 auto funcType = type.dyn_cast<FunctionType>(); 1098 if (!funcType) 1099 return parser.emitError(trailingTypeLoc, "expected function type"); 1100 if (funcType.getNumResults() > 1) 1101 return parser.emitError(trailingTypeLoc, 1102 "expected function with 0 or 1 result"); 1103 if (isDirect) { 1104 // Make sure types match. 1105 if (parser.resolveOperands(operands, funcType.getInputs(), 1106 parser.getNameLoc(), result.operands)) 1107 return failure(); 1108 if (funcType.getNumResults() != 0 && 1109 !funcType.getResult(0).isa<LLVM::LLVMVoidType>()) 1110 result.addTypes(funcType.getResults()); 1111 } else { 1112 Builder &builder = parser.getBuilder(); 1113 Type llvmResultType; 1114 if (funcType.getNumResults() == 0) { 1115 llvmResultType = LLVM::LLVMVoidType::get(builder.getContext()); 1116 } else { 1117 llvmResultType = funcType.getResult(0); 1118 if (!isCompatibleType(llvmResultType)) 1119 return parser.emitError(trailingTypeLoc, 1120 "expected result to have LLVM type"); 1121 } 1122 1123 SmallVector<Type, 8> argTypes; 1124 argTypes.reserve(funcType.getNumInputs()); 1125 for (int i = 0, e = funcType.getNumInputs(); i < e; ++i) { 1126 auto argType = funcType.getInput(i); 1127 if (!isCompatibleType(argType)) 1128 return parser.emitError(trailingTypeLoc, 1129 "expected LLVM types as inputs"); 1130 argTypes.push_back(argType); 1131 } 1132 auto llvmFuncType = LLVM::LLVMFunctionType::get(llvmResultType, argTypes); 1133 auto wrappedFuncType = LLVM::LLVMPointerType::get(llvmFuncType); 1134 1135 auto funcArguments = 1136 ArrayRef<OpAsmParser::UnresolvedOperand>(operands).drop_front(); 1137 1138 // Make sure that the first operand (indirect callee) matches the wrapped 1139 // LLVM IR function type, and that the types of the other call operands 1140 // match the types of the function arguments. 1141 if (parser.resolveOperand(operands[0], wrappedFuncType, result.operands) || 1142 parser.resolveOperands(funcArguments, funcType.getInputs(), 1143 parser.getNameLoc(), result.operands)) 1144 return failure(); 1145 1146 if (!llvmResultType.isa<LLVM::LLVMVoidType>()) 1147 result.addTypes(llvmResultType); 1148 } 1149 1150 return success(); 1151 } 1152 1153 //===----------------------------------------------------------------------===// 1154 // Printing/parsing for LLVM::ExtractElementOp. 1155 //===----------------------------------------------------------------------===// 1156 // Expects vector to be of wrapped LLVM vector type and position to be of 1157 // wrapped LLVM i32 type. 1158 void LLVM::ExtractElementOp::build(OpBuilder &b, OperationState &result, 1159 Value vector, Value position, 1160 ArrayRef<NamedAttribute> attrs) { 1161 auto vectorType = vector.getType(); 1162 auto llvmType = LLVM::getVectorElementType(vectorType); 1163 build(b, result, llvmType, vector, position); 1164 result.addAttributes(attrs); 1165 } 1166 1167 void ExtractElementOp::print(OpAsmPrinter &p) { 1168 p << ' ' << getVector() << "[" << getPosition() << " : " 1169 << getPosition().getType() << "]"; 1170 p.printOptionalAttrDict((*this)->getAttrs()); 1171 p << " : " << getVector().getType(); 1172 } 1173 1174 // <operation> ::= `llvm.extractelement` ssa-use `, ` ssa-use 1175 // attribute-dict? `:` type 1176 ParseResult ExtractElementOp::parse(OpAsmParser &parser, 1177 OperationState &result) { 1178 SMLoc loc; 1179 OpAsmParser::UnresolvedOperand vector, position; 1180 Type type, positionType; 1181 if (parser.getCurrentLocation(&loc) || parser.parseOperand(vector) || 1182 parser.parseLSquare() || parser.parseOperand(position) || 1183 parser.parseColonType(positionType) || parser.parseRSquare() || 1184 parser.parseOptionalAttrDict(result.attributes) || 1185 parser.parseColonType(type) || 1186 parser.resolveOperand(vector, type, result.operands) || 1187 parser.resolveOperand(position, positionType, result.operands)) 1188 return failure(); 1189 if (!LLVM::isCompatibleVectorType(type)) 1190 return parser.emitError( 1191 loc, "expected LLVM dialect-compatible vector type for operand #1"); 1192 result.addTypes(LLVM::getVectorElementType(type)); 1193 return success(); 1194 } 1195 1196 LogicalResult ExtractElementOp::verify() { 1197 Type vectorType = getVector().getType(); 1198 if (!LLVM::isCompatibleVectorType(vectorType)) 1199 return emitOpError("expected LLVM dialect-compatible vector type for " 1200 "operand #1, got") 1201 << vectorType; 1202 Type valueType = LLVM::getVectorElementType(vectorType); 1203 if (valueType != getRes().getType()) 1204 return emitOpError() << "Type mismatch: extracting from " << vectorType 1205 << " should produce " << valueType 1206 << " but this op returns " << getRes().getType(); 1207 return success(); 1208 } 1209 1210 //===----------------------------------------------------------------------===// 1211 // Printing/parsing for LLVM::ExtractValueOp. 1212 //===----------------------------------------------------------------------===// 1213 1214 void ExtractValueOp::print(OpAsmPrinter &p) { 1215 p << ' ' << getContainer() << getPosition(); 1216 p.printOptionalAttrDict((*this)->getAttrs(), {"position"}); 1217 p << " : " << getContainer().getType(); 1218 } 1219 1220 // Extract the type at `position` in the wrapped LLVM IR aggregate type 1221 // `containerType`. Position is an integer array attribute where each value 1222 // is a zero-based position of the element in the aggregate type. Return the 1223 // resulting type wrapped in MLIR, or nullptr on error. 1224 static Type getInsertExtractValueElementType(OpAsmParser &parser, 1225 Type containerType, 1226 ArrayAttr positionAttr, 1227 SMLoc attributeLoc, 1228 SMLoc typeLoc) { 1229 Type llvmType = containerType; 1230 if (!isCompatibleType(containerType)) 1231 return parser.emitError(typeLoc, "expected LLVM IR Dialect type"), nullptr; 1232 1233 // Infer the element type from the structure type: iteratively step inside the 1234 // type by taking the element type, indexed by the position attribute for 1235 // structures. Check the position index before accessing, it is supposed to 1236 // be in bounds. 1237 for (Attribute subAttr : positionAttr) { 1238 auto positionElementAttr = subAttr.dyn_cast<IntegerAttr>(); 1239 if (!positionElementAttr) 1240 return parser.emitError(attributeLoc, 1241 "expected an array of integer literals"), 1242 nullptr; 1243 int position = positionElementAttr.getInt(); 1244 if (auto arrayType = llvmType.dyn_cast<LLVMArrayType>()) { 1245 if (position < 0 || 1246 static_cast<unsigned>(position) >= arrayType.getNumElements()) 1247 return parser.emitError(attributeLoc, "position out of bounds"), 1248 nullptr; 1249 llvmType = arrayType.getElementType(); 1250 } else if (auto structType = llvmType.dyn_cast<LLVMStructType>()) { 1251 if (position < 0 || 1252 static_cast<unsigned>(position) >= structType.getBody().size()) 1253 return parser.emitError(attributeLoc, "position out of bounds"), 1254 nullptr; 1255 llvmType = structType.getBody()[position]; 1256 } else { 1257 return parser.emitError(typeLoc, "expected LLVM IR structure/array type"), 1258 nullptr; 1259 } 1260 } 1261 return llvmType; 1262 } 1263 1264 // Extract the type at `position` in the wrapped LLVM IR aggregate type 1265 // `containerType`. Returns null on failure. 1266 static Type getInsertExtractValueElementType(Type containerType, 1267 ArrayAttr positionAttr, 1268 Operation *op) { 1269 Type llvmType = containerType; 1270 if (!isCompatibleType(containerType)) { 1271 op->emitError("expected LLVM IR Dialect type, got ") << containerType; 1272 return {}; 1273 } 1274 1275 // Infer the element type from the structure type: iteratively step inside the 1276 // type by taking the element type, indexed by the position attribute for 1277 // structures. Check the position index before accessing, it is supposed to 1278 // be in bounds. 1279 for (Attribute subAttr : positionAttr) { 1280 auto positionElementAttr = subAttr.dyn_cast<IntegerAttr>(); 1281 if (!positionElementAttr) { 1282 op->emitOpError("expected an array of integer literals, got: ") 1283 << subAttr; 1284 return {}; 1285 } 1286 int position = positionElementAttr.getInt(); 1287 if (auto arrayType = llvmType.dyn_cast<LLVMArrayType>()) { 1288 if (position < 0 || 1289 static_cast<unsigned>(position) >= arrayType.getNumElements()) { 1290 op->emitOpError("position out of bounds: ") << position; 1291 return {}; 1292 } 1293 llvmType = arrayType.getElementType(); 1294 } else if (auto structType = llvmType.dyn_cast<LLVMStructType>()) { 1295 if (position < 0 || 1296 static_cast<unsigned>(position) >= structType.getBody().size()) { 1297 op->emitOpError("position out of bounds") << position; 1298 return {}; 1299 } 1300 llvmType = structType.getBody()[position]; 1301 } else { 1302 op->emitOpError("expected LLVM IR structure/array type, got: ") 1303 << llvmType; 1304 return {}; 1305 } 1306 } 1307 return llvmType; 1308 } 1309 1310 // <operation> ::= `llvm.extractvalue` ssa-use 1311 // `[` integer-literal (`,` integer-literal)* `]` 1312 // attribute-dict? `:` type 1313 ParseResult ExtractValueOp::parse(OpAsmParser &parser, OperationState &result) { 1314 OpAsmParser::UnresolvedOperand container; 1315 Type containerType; 1316 ArrayAttr positionAttr; 1317 SMLoc attributeLoc, trailingTypeLoc; 1318 1319 if (parser.parseOperand(container) || 1320 parser.getCurrentLocation(&attributeLoc) || 1321 parser.parseAttribute(positionAttr, "position", result.attributes) || 1322 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 1323 parser.getCurrentLocation(&trailingTypeLoc) || 1324 parser.parseType(containerType) || 1325 parser.resolveOperand(container, containerType, result.operands)) 1326 return failure(); 1327 1328 auto elementType = getInsertExtractValueElementType( 1329 parser, containerType, positionAttr, attributeLoc, trailingTypeLoc); 1330 if (!elementType) 1331 return failure(); 1332 1333 result.addTypes(elementType); 1334 return success(); 1335 } 1336 1337 OpFoldResult LLVM::ExtractValueOp::fold(ArrayRef<Attribute> operands) { 1338 auto insertValueOp = getContainer().getDefiningOp<InsertValueOp>(); 1339 OpFoldResult result = {}; 1340 while (insertValueOp) { 1341 if (getPosition() == insertValueOp.getPosition()) 1342 return insertValueOp.getValue(); 1343 unsigned min = 1344 std::min(getPosition().size(), insertValueOp.getPosition().size()); 1345 // If one is fully prefix of the other, stop propagating back as it will 1346 // miss dependencies. For instance, %3 should not fold to %f0 in the 1347 // following example: 1348 // ``` 1349 // %1 = llvm.insertvalue %f0, %0[0, 0] : 1350 // !llvm.array<4 x !llvm.array<4xf32>> 1351 // %2 = llvm.insertvalue %arr, %1[0] : 1352 // !llvm.array<4 x !llvm.array<4xf32>> 1353 // %3 = llvm.extractvalue %2[0, 0] : !llvm.array<4 x !llvm.array<4xf32>> 1354 // ``` 1355 if (getPosition().getValue().take_front(min) == 1356 insertValueOp.getPosition().getValue().take_front(min)) 1357 return result; 1358 1359 // If neither a prefix, nor the exact position, we can extract out of the 1360 // value being inserted into. Moreover, we can try again if that operand 1361 // is itself an insertvalue expression. 1362 getContainerMutable().assign(insertValueOp.getContainer()); 1363 result = getResult(); 1364 insertValueOp = insertValueOp.getContainer().getDefiningOp<InsertValueOp>(); 1365 } 1366 return result; 1367 } 1368 1369 LogicalResult ExtractValueOp::verify() { 1370 Type valueType = getInsertExtractValueElementType(getContainer().getType(), 1371 getPositionAttr(), *this); 1372 if (!valueType) 1373 return failure(); 1374 1375 if (getRes().getType() != valueType) 1376 return emitOpError() << "Type mismatch: extracting from " 1377 << getContainer().getType() << " should produce " 1378 << valueType << " but this op returns " 1379 << getRes().getType(); 1380 return success(); 1381 } 1382 1383 //===----------------------------------------------------------------------===// 1384 // Printing/parsing for LLVM::InsertElementOp. 1385 //===----------------------------------------------------------------------===// 1386 1387 void InsertElementOp::print(OpAsmPrinter &p) { 1388 p << ' ' << getValue() << ", " << getVector() << "[" << getPosition() << " : " 1389 << getPosition().getType() << "]"; 1390 p.printOptionalAttrDict((*this)->getAttrs()); 1391 p << " : " << getVector().getType(); 1392 } 1393 1394 // <operation> ::= `llvm.insertelement` ssa-use `,` ssa-use `,` ssa-use 1395 // attribute-dict? `:` type 1396 ParseResult InsertElementOp::parse(OpAsmParser &parser, 1397 OperationState &result) { 1398 SMLoc loc; 1399 OpAsmParser::UnresolvedOperand vector, value, position; 1400 Type vectorType, positionType; 1401 if (parser.getCurrentLocation(&loc) || parser.parseOperand(value) || 1402 parser.parseComma() || parser.parseOperand(vector) || 1403 parser.parseLSquare() || parser.parseOperand(position) || 1404 parser.parseColonType(positionType) || parser.parseRSquare() || 1405 parser.parseOptionalAttrDict(result.attributes) || 1406 parser.parseColonType(vectorType)) 1407 return failure(); 1408 1409 if (!LLVM::isCompatibleVectorType(vectorType)) 1410 return parser.emitError( 1411 loc, "expected LLVM dialect-compatible vector type for operand #1"); 1412 Type valueType = LLVM::getVectorElementType(vectorType); 1413 if (!valueType) 1414 return failure(); 1415 1416 if (parser.resolveOperand(vector, vectorType, result.operands) || 1417 parser.resolveOperand(value, valueType, result.operands) || 1418 parser.resolveOperand(position, positionType, result.operands)) 1419 return failure(); 1420 1421 result.addTypes(vectorType); 1422 return success(); 1423 } 1424 1425 LogicalResult InsertElementOp::verify() { 1426 Type valueType = LLVM::getVectorElementType(getVector().getType()); 1427 if (valueType != getValue().getType()) 1428 return emitOpError() << "Type mismatch: cannot insert " 1429 << getValue().getType() << " into " 1430 << getVector().getType(); 1431 return success(); 1432 } 1433 1434 //===----------------------------------------------------------------------===// 1435 // Printing/parsing for LLVM::InsertValueOp. 1436 //===----------------------------------------------------------------------===// 1437 1438 void InsertValueOp::print(OpAsmPrinter &p) { 1439 p << ' ' << getValue() << ", " << getContainer() << getPosition(); 1440 p.printOptionalAttrDict((*this)->getAttrs(), {"position"}); 1441 p << " : " << getContainer().getType(); 1442 } 1443 1444 // <operation> ::= `llvm.insertvaluevalue` ssa-use `,` ssa-use 1445 // `[` integer-literal (`,` integer-literal)* `]` 1446 // attribute-dict? `:` type 1447 ParseResult InsertValueOp::parse(OpAsmParser &parser, OperationState &result) { 1448 OpAsmParser::UnresolvedOperand container, value; 1449 Type containerType; 1450 ArrayAttr positionAttr; 1451 SMLoc attributeLoc, trailingTypeLoc; 1452 1453 if (parser.parseOperand(value) || parser.parseComma() || 1454 parser.parseOperand(container) || 1455 parser.getCurrentLocation(&attributeLoc) || 1456 parser.parseAttribute(positionAttr, "position", result.attributes) || 1457 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 1458 parser.getCurrentLocation(&trailingTypeLoc) || 1459 parser.parseType(containerType)) 1460 return failure(); 1461 1462 auto valueType = getInsertExtractValueElementType( 1463 parser, containerType, positionAttr, attributeLoc, trailingTypeLoc); 1464 if (!valueType) 1465 return failure(); 1466 1467 if (parser.resolveOperand(container, containerType, result.operands) || 1468 parser.resolveOperand(value, valueType, result.operands)) 1469 return failure(); 1470 1471 result.addTypes(containerType); 1472 return success(); 1473 } 1474 1475 LogicalResult InsertValueOp::verify() { 1476 Type valueType = getInsertExtractValueElementType(getContainer().getType(), 1477 getPositionAttr(), *this); 1478 if (!valueType) 1479 return failure(); 1480 1481 if (getValue().getType() != valueType) 1482 return emitOpError() << "Type mismatch: cannot insert " 1483 << getValue().getType() << " into " 1484 << getContainer().getType(); 1485 1486 return success(); 1487 } 1488 1489 //===----------------------------------------------------------------------===// 1490 // Printing, parsing and verification for LLVM::ReturnOp. 1491 //===----------------------------------------------------------------------===// 1492 1493 LogicalResult ReturnOp::verify() { 1494 if (getNumOperands() > 1) 1495 return emitOpError("expected at most 1 operand"); 1496 1497 if (auto parent = (*this)->getParentOfType<LLVMFuncOp>()) { 1498 Type expectedType = parent.getFunctionType().getReturnType(); 1499 if (expectedType.isa<LLVMVoidType>()) { 1500 if (getNumOperands() == 0) 1501 return success(); 1502 InFlightDiagnostic diag = emitOpError("expected no operands"); 1503 diag.attachNote(parent->getLoc()) << "when returning from function"; 1504 return diag; 1505 } 1506 if (getNumOperands() == 0) { 1507 if (expectedType.isa<LLVMVoidType>()) 1508 return success(); 1509 InFlightDiagnostic diag = emitOpError("expected 1 operand"); 1510 diag.attachNote(parent->getLoc()) << "when returning from function"; 1511 return diag; 1512 } 1513 if (expectedType != getOperand(0).getType()) { 1514 InFlightDiagnostic diag = emitOpError("mismatching result types"); 1515 diag.attachNote(parent->getLoc()) << "when returning from function"; 1516 return diag; 1517 } 1518 } 1519 return success(); 1520 } 1521 1522 //===----------------------------------------------------------------------===// 1523 // ResumeOp 1524 //===----------------------------------------------------------------------===// 1525 1526 LogicalResult ResumeOp::verify() { 1527 if (!getValue().getDefiningOp<LandingpadOp>()) 1528 return emitOpError("expects landingpad value as operand"); 1529 // No check for personality of function - landingpad op verifies it. 1530 return success(); 1531 } 1532 1533 //===----------------------------------------------------------------------===// 1534 // Verifier for LLVM::AddressOfOp. 1535 //===----------------------------------------------------------------------===// 1536 1537 template <typename OpTy> 1538 static OpTy lookupSymbolInModule(Operation *parent, StringRef name) { 1539 Operation *module = parent; 1540 while (module && !satisfiesLLVMModule(module)) 1541 module = module->getParentOp(); 1542 assert(module && "unexpected operation outside of a module"); 1543 return dyn_cast_or_null<OpTy>( 1544 mlir::SymbolTable::lookupSymbolIn(module, name)); 1545 } 1546 1547 GlobalOp AddressOfOp::getGlobal() { 1548 return lookupSymbolInModule<LLVM::GlobalOp>((*this)->getParentOp(), 1549 getGlobalName()); 1550 } 1551 1552 LLVMFuncOp AddressOfOp::getFunction() { 1553 return lookupSymbolInModule<LLVM::LLVMFuncOp>((*this)->getParentOp(), 1554 getGlobalName()); 1555 } 1556 1557 LogicalResult AddressOfOp::verify() { 1558 auto global = getGlobal(); 1559 auto function = getFunction(); 1560 if (!global && !function) 1561 return emitOpError( 1562 "must reference a global defined by 'llvm.mlir.global' or 'llvm.func'"); 1563 1564 if (global && 1565 LLVM::LLVMPointerType::get(global.getType(), global.getAddrSpace()) != 1566 getResult().getType()) 1567 return emitOpError( 1568 "the type must be a pointer to the type of the referenced global"); 1569 1570 if (function && LLVM::LLVMPointerType::get(function.getFunctionType()) != 1571 getResult().getType()) 1572 return emitOpError( 1573 "the type must be a pointer to the type of the referenced function"); 1574 1575 return success(); 1576 } 1577 1578 //===----------------------------------------------------------------------===// 1579 // Builder, printer and verifier for LLVM::GlobalOp. 1580 //===----------------------------------------------------------------------===// 1581 1582 void GlobalOp::build(OpBuilder &builder, OperationState &result, Type type, 1583 bool isConstant, Linkage linkage, StringRef name, 1584 Attribute value, uint64_t alignment, unsigned addrSpace, 1585 bool dsoLocal, bool threadLocal, 1586 ArrayRef<NamedAttribute> attrs) { 1587 result.addAttribute(getSymNameAttrName(result.name), 1588 builder.getStringAttr(name)); 1589 result.addAttribute(getGlobalTypeAttrName(result.name), TypeAttr::get(type)); 1590 if (isConstant) 1591 result.addAttribute(getConstantAttrName(result.name), 1592 builder.getUnitAttr()); 1593 if (value) 1594 result.addAttribute(getValueAttrName(result.name), value); 1595 if (dsoLocal) 1596 result.addAttribute(getDsoLocalAttrName(result.name), 1597 builder.getUnitAttr()); 1598 if (threadLocal) 1599 result.addAttribute(getThreadLocal_AttrName(result.name), 1600 builder.getUnitAttr()); 1601 1602 // Only add an alignment attribute if the "alignment" input 1603 // is different from 0. The value must also be a power of two, but 1604 // this is tested in GlobalOp::verify, not here. 1605 if (alignment != 0) 1606 result.addAttribute(getAlignmentAttrName(result.name), 1607 builder.getI64IntegerAttr(alignment)); 1608 1609 result.addAttribute(getLinkageAttrName(result.name), 1610 LinkageAttr::get(builder.getContext(), linkage)); 1611 if (addrSpace != 0) 1612 result.addAttribute(getAddrSpaceAttrName(result.name), 1613 builder.getI32IntegerAttr(addrSpace)); 1614 result.attributes.append(attrs.begin(), attrs.end()); 1615 result.addRegion(); 1616 } 1617 1618 void GlobalOp::print(OpAsmPrinter &p) { 1619 p << ' ' << stringifyLinkage(getLinkage()) << ' '; 1620 if (auto unnamedAddr = getUnnamedAddr()) { 1621 StringRef str = stringifyUnnamedAddr(*unnamedAddr); 1622 if (!str.empty()) 1623 p << str << ' '; 1624 } 1625 if (getThreadLocal_()) 1626 p << "thread_local "; 1627 if (getConstant()) 1628 p << "constant "; 1629 p.printSymbolName(getSymName()); 1630 p << '('; 1631 if (auto value = getValueOrNull()) 1632 p.printAttribute(value); 1633 p << ')'; 1634 // Note that the alignment attribute is printed using the 1635 // default syntax here, even though it is an inherent attribute 1636 // (as defined in https://mlir.llvm.org/docs/LangRef/#attributes) 1637 p.printOptionalAttrDict( 1638 (*this)->getAttrs(), 1639 {SymbolTable::getSymbolAttrName(), getGlobalTypeAttrName(), 1640 getConstantAttrName(), getValueAttrName(), getLinkageAttrName(), 1641 getUnnamedAddrAttrName(), getThreadLocal_AttrName()}); 1642 1643 // Print the trailing type unless it's a string global. 1644 if (getValueOrNull().dyn_cast_or_null<StringAttr>()) 1645 return; 1646 p << " : " << getType(); 1647 1648 Region &initializer = getInitializerRegion(); 1649 if (!initializer.empty()) { 1650 p << ' '; 1651 p.printRegion(initializer, /*printEntryBlockArgs=*/false); 1652 } 1653 } 1654 1655 // Parses one of the keywords provided in the list `keywords` and returns the 1656 // position of the parsed keyword in the list. If none of the keywords from the 1657 // list is parsed, returns -1. 1658 static int parseOptionalKeywordAlternative(OpAsmParser &parser, 1659 ArrayRef<StringRef> keywords) { 1660 for (const auto &en : llvm::enumerate(keywords)) { 1661 if (succeeded(parser.parseOptionalKeyword(en.value()))) 1662 return en.index(); 1663 } 1664 return -1; 1665 } 1666 1667 namespace { 1668 template <typename Ty> 1669 struct EnumTraits {}; 1670 1671 #define REGISTER_ENUM_TYPE(Ty) \ 1672 template <> \ 1673 struct EnumTraits<Ty> { \ 1674 static StringRef stringify(Ty value) { return stringify##Ty(value); } \ 1675 static unsigned getMaxEnumVal() { return getMaxEnumValFor##Ty(); } \ 1676 } 1677 1678 REGISTER_ENUM_TYPE(Linkage); 1679 REGISTER_ENUM_TYPE(UnnamedAddr); 1680 } // namespace 1681 1682 /// Parse an enum from the keyword, or default to the provided default value. 1683 /// The return type is the enum type by default, unless overriden with the 1684 /// second template argument. 1685 template <typename EnumTy, typename RetTy = EnumTy> 1686 static RetTy parseOptionalLLVMKeyword(OpAsmParser &parser, 1687 OperationState &result, 1688 EnumTy defaultValue) { 1689 SmallVector<StringRef, 10> names; 1690 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i) 1691 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i))); 1692 1693 int index = parseOptionalKeywordAlternative(parser, names); 1694 if (index == -1) 1695 return static_cast<RetTy>(defaultValue); 1696 return static_cast<RetTy>(index); 1697 } 1698 1699 // operation ::= `llvm.mlir.global` linkage? `constant`? `@` identifier 1700 // `(` attribute? `)` align? attribute-list? (`:` type)? region? 1701 // align ::= `align` `=` UINT64 1702 // 1703 // The type can be omitted for string attributes, in which case it will be 1704 // inferred from the value of the string as [strlen(value) x i8]. 1705 ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) { 1706 MLIRContext *ctx = parser.getContext(); 1707 // Parse optional linkage, default to External. 1708 result.addAttribute(getLinkageAttrName(result.name), 1709 LLVM::LinkageAttr::get( 1710 ctx, parseOptionalLLVMKeyword<Linkage>( 1711 parser, result, LLVM::Linkage::External))); 1712 1713 if (succeeded(parser.parseOptionalKeyword("thread_local"))) 1714 result.addAttribute(getThreadLocal_AttrName(result.name), 1715 parser.getBuilder().getUnitAttr()); 1716 1717 // Parse optional UnnamedAddr, default to None. 1718 result.addAttribute(getUnnamedAddrAttrName(result.name), 1719 parser.getBuilder().getI64IntegerAttr( 1720 parseOptionalLLVMKeyword<UnnamedAddr, int64_t>( 1721 parser, result, LLVM::UnnamedAddr::None))); 1722 1723 if (succeeded(parser.parseOptionalKeyword("constant"))) 1724 result.addAttribute(getConstantAttrName(result.name), 1725 parser.getBuilder().getUnitAttr()); 1726 1727 StringAttr name; 1728 if (parser.parseSymbolName(name, getSymNameAttrName(result.name), 1729 result.attributes) || 1730 parser.parseLParen()) 1731 return failure(); 1732 1733 Attribute value; 1734 if (parser.parseOptionalRParen()) { 1735 if (parser.parseAttribute(value, getValueAttrName(result.name), 1736 result.attributes) || 1737 parser.parseRParen()) 1738 return failure(); 1739 } 1740 1741 SmallVector<Type, 1> types; 1742 if (parser.parseOptionalAttrDict(result.attributes) || 1743 parser.parseOptionalColonTypeList(types)) 1744 return failure(); 1745 1746 if (types.size() > 1) 1747 return parser.emitError(parser.getNameLoc(), "expected zero or one type"); 1748 1749 Region &initRegion = *result.addRegion(); 1750 if (types.empty()) { 1751 if (auto strAttr = value.dyn_cast_or_null<StringAttr>()) { 1752 MLIRContext *context = parser.getContext(); 1753 auto arrayType = LLVM::LLVMArrayType::get(IntegerType::get(context, 8), 1754 strAttr.getValue().size()); 1755 types.push_back(arrayType); 1756 } else { 1757 return parser.emitError(parser.getNameLoc(), 1758 "type can only be omitted for string globals"); 1759 } 1760 } else { 1761 OptionalParseResult parseResult = 1762 parser.parseOptionalRegion(initRegion, /*arguments=*/{}, 1763 /*argTypes=*/{}); 1764 if (parseResult.hasValue() && failed(*parseResult)) 1765 return failure(); 1766 } 1767 1768 result.addAttribute(getGlobalTypeAttrName(result.name), 1769 TypeAttr::get(types[0])); 1770 return success(); 1771 } 1772 1773 static bool isZeroAttribute(Attribute value) { 1774 if (auto intValue = value.dyn_cast<IntegerAttr>()) 1775 return intValue.getValue().isNullValue(); 1776 if (auto fpValue = value.dyn_cast<FloatAttr>()) 1777 return fpValue.getValue().isZero(); 1778 if (auto splatValue = value.dyn_cast<SplatElementsAttr>()) 1779 return isZeroAttribute(splatValue.getSplatValue<Attribute>()); 1780 if (auto elementsValue = value.dyn_cast<ElementsAttr>()) 1781 return llvm::all_of(elementsValue.getValues<Attribute>(), isZeroAttribute); 1782 if (auto arrayValue = value.dyn_cast<ArrayAttr>()) 1783 return llvm::all_of(arrayValue.getValue(), isZeroAttribute); 1784 return false; 1785 } 1786 1787 LogicalResult GlobalOp::verify() { 1788 if (!LLVMPointerType::isValidElementType(getType())) 1789 return emitOpError( 1790 "expects type to be a valid element type for an LLVM pointer"); 1791 if ((*this)->getParentOp() && !satisfiesLLVMModule((*this)->getParentOp())) 1792 return emitOpError("must appear at the module level"); 1793 1794 if (auto strAttr = getValueOrNull().dyn_cast_or_null<StringAttr>()) { 1795 auto type = getType().dyn_cast<LLVMArrayType>(); 1796 IntegerType elementType = 1797 type ? type.getElementType().dyn_cast<IntegerType>() : nullptr; 1798 if (!elementType || elementType.getWidth() != 8 || 1799 type.getNumElements() != strAttr.getValue().size()) 1800 return emitOpError( 1801 "requires an i8 array type of the length equal to that of the string " 1802 "attribute"); 1803 } 1804 1805 if (getLinkage() == Linkage::Common) { 1806 if (Attribute value = getValueOrNull()) { 1807 if (!isZeroAttribute(value)) { 1808 return emitOpError() 1809 << "expected zero value for '" 1810 << stringifyLinkage(Linkage::Common) << "' linkage"; 1811 } 1812 } 1813 } 1814 1815 if (getLinkage() == Linkage::Appending) { 1816 if (!getType().isa<LLVMArrayType>()) { 1817 return emitOpError() << "expected array type for '" 1818 << stringifyLinkage(Linkage::Appending) 1819 << "' linkage"; 1820 } 1821 } 1822 1823 Optional<uint64_t> alignAttr = getAlignment(); 1824 if (alignAttr.hasValue()) { 1825 uint64_t value = alignAttr.getValue(); 1826 if (!llvm::isPowerOf2_64(value)) 1827 return emitError() << "alignment attribute is not a power of 2"; 1828 } 1829 1830 return success(); 1831 } 1832 1833 LogicalResult GlobalOp::verifyRegions() { 1834 if (Block *b = getInitializerBlock()) { 1835 ReturnOp ret = cast<ReturnOp>(b->getTerminator()); 1836 if (ret.operand_type_begin() == ret.operand_type_end()) 1837 return emitOpError("initializer region cannot return void"); 1838 if (*ret.operand_type_begin() != getType()) 1839 return emitOpError("initializer region type ") 1840 << *ret.operand_type_begin() << " does not match global type " 1841 << getType(); 1842 1843 for (Operation &op : *b) { 1844 auto iface = dyn_cast<MemoryEffectOpInterface>(op); 1845 if (!iface || !iface.hasNoEffect()) 1846 return op.emitError() 1847 << "ops with side effects not allowed in global initializers"; 1848 } 1849 1850 if (getValueOrNull()) 1851 return emitOpError("cannot have both initializer value and region"); 1852 } 1853 1854 return success(); 1855 } 1856 1857 //===----------------------------------------------------------------------===// 1858 // LLVM::GlobalCtorsOp 1859 //===----------------------------------------------------------------------===// 1860 1861 LogicalResult 1862 GlobalCtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) { 1863 for (Attribute ctor : getCtors()) { 1864 if (failed(verifySymbolAttrUse(ctor.cast<FlatSymbolRefAttr>(), *this, 1865 symbolTable))) 1866 return failure(); 1867 } 1868 return success(); 1869 } 1870 1871 LogicalResult GlobalCtorsOp::verify() { 1872 if (getCtors().size() != getPriorities().size()) 1873 return emitError( 1874 "mismatch between the number of ctors and the number of priorities"); 1875 return success(); 1876 } 1877 1878 //===----------------------------------------------------------------------===// 1879 // LLVM::GlobalDtorsOp 1880 //===----------------------------------------------------------------------===// 1881 1882 LogicalResult 1883 GlobalDtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) { 1884 for (Attribute dtor : getDtors()) { 1885 if (failed(verifySymbolAttrUse(dtor.cast<FlatSymbolRefAttr>(), *this, 1886 symbolTable))) 1887 return failure(); 1888 } 1889 return success(); 1890 } 1891 1892 LogicalResult GlobalDtorsOp::verify() { 1893 if (getDtors().size() != getPriorities().size()) 1894 return emitError( 1895 "mismatch between the number of dtors and the number of priorities"); 1896 return success(); 1897 } 1898 1899 //===----------------------------------------------------------------------===// 1900 // Printing/parsing for LLVM::ShuffleVectorOp. 1901 //===----------------------------------------------------------------------===// 1902 // Expects vector to be of wrapped LLVM vector type and position to be of 1903 // wrapped LLVM i32 type. 1904 void LLVM::ShuffleVectorOp::build(OpBuilder &b, OperationState &result, 1905 Value v1, Value v2, ArrayAttr mask, 1906 ArrayRef<NamedAttribute> attrs) { 1907 auto containerType = v1.getType(); 1908 auto vType = LLVM::getVectorType( 1909 LLVM::getVectorElementType(containerType), mask.size(), 1910 containerType.cast<VectorType>().isScalable()); 1911 build(b, result, vType, v1, v2, mask); 1912 result.addAttributes(attrs); 1913 } 1914 1915 void ShuffleVectorOp::print(OpAsmPrinter &p) { 1916 p << ' ' << getV1() << ", " << getV2() << " " << getMask(); 1917 p.printOptionalAttrDict((*this)->getAttrs(), {"mask"}); 1918 p << " : " << getV1().getType() << ", " << getV2().getType(); 1919 } 1920 1921 // <operation> ::= `llvm.shufflevector` ssa-use `, ` ssa-use 1922 // `[` integer-literal (`,` integer-literal)* `]` 1923 // attribute-dict? `:` type 1924 ParseResult ShuffleVectorOp::parse(OpAsmParser &parser, 1925 OperationState &result) { 1926 SMLoc loc; 1927 OpAsmParser::UnresolvedOperand v1, v2; 1928 ArrayAttr maskAttr; 1929 Type typeV1, typeV2; 1930 if (parser.getCurrentLocation(&loc) || parser.parseOperand(v1) || 1931 parser.parseComma() || parser.parseOperand(v2) || 1932 parser.parseAttribute(maskAttr, "mask", result.attributes) || 1933 parser.parseOptionalAttrDict(result.attributes) || 1934 parser.parseColonType(typeV1) || parser.parseComma() || 1935 parser.parseType(typeV2) || 1936 parser.resolveOperand(v1, typeV1, result.operands) || 1937 parser.resolveOperand(v2, typeV2, result.operands)) 1938 return failure(); 1939 if (!LLVM::isCompatibleVectorType(typeV1)) 1940 return parser.emitError( 1941 loc, "expected LLVM IR dialect vector type for operand #1"); 1942 auto vType = 1943 LLVM::getVectorType(LLVM::getVectorElementType(typeV1), maskAttr.size(), 1944 typeV1.cast<VectorType>().isScalable()); 1945 result.addTypes(vType); 1946 return success(); 1947 } 1948 1949 LogicalResult ShuffleVectorOp::verify() { 1950 Type type1 = getV1().getType(); 1951 Type type2 = getV2().getType(); 1952 if (LLVM::getVectorElementType(type1) != LLVM::getVectorElementType(type2)) 1953 return emitOpError("expected matching LLVM IR Dialect element types"); 1954 if (LLVM::isScalableVectorType(type1)) 1955 if (llvm::any_of(getMask(), [](Attribute attr) { 1956 return attr.cast<IntegerAttr>().getInt() != 0; 1957 })) 1958 return emitOpError("expected a splat operation for scalable vectors"); 1959 return success(); 1960 } 1961 1962 //===----------------------------------------------------------------------===// 1963 // Implementations for LLVM::LLVMFuncOp. 1964 //===----------------------------------------------------------------------===// 1965 1966 // Add the entry block to the function. 1967 Block *LLVMFuncOp::addEntryBlock() { 1968 assert(empty() && "function already has an entry block"); 1969 assert(!isVarArg() && "unimplemented: non-external variadic functions"); 1970 1971 auto *entry = new Block; 1972 push_back(entry); 1973 1974 // FIXME: Allow passing in proper locations for the entry arguments. 1975 LLVMFunctionType type = getFunctionType(); 1976 for (unsigned i = 0, e = type.getNumParams(); i < e; ++i) 1977 entry->addArgument(type.getParamType(i), getLoc()); 1978 return entry; 1979 } 1980 1981 void LLVMFuncOp::build(OpBuilder &builder, OperationState &result, 1982 StringRef name, Type type, LLVM::Linkage linkage, 1983 bool dsoLocal, ArrayRef<NamedAttribute> attrs, 1984 ArrayRef<DictionaryAttr> argAttrs) { 1985 result.addRegion(); 1986 result.addAttribute(SymbolTable::getSymbolAttrName(), 1987 builder.getStringAttr(name)); 1988 result.addAttribute(getFunctionTypeAttrName(result.name), 1989 TypeAttr::get(type)); 1990 result.addAttribute(getLinkageAttrName(result.name), 1991 LinkageAttr::get(builder.getContext(), linkage)); 1992 result.attributes.append(attrs.begin(), attrs.end()); 1993 if (dsoLocal) 1994 result.addAttribute("dso_local", builder.getUnitAttr()); 1995 if (argAttrs.empty()) 1996 return; 1997 1998 assert(type.cast<LLVMFunctionType>().getNumParams() == argAttrs.size() && 1999 "expected as many argument attribute lists as arguments"); 2000 function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs, 2001 /*resultAttrs=*/llvm::None); 2002 } 2003 2004 // Builds an LLVM function type from the given lists of input and output types. 2005 // Returns a null type if any of the types provided are non-LLVM types, or if 2006 // there is more than one output type. 2007 static Type 2008 buildLLVMFunctionType(OpAsmParser &parser, SMLoc loc, ArrayRef<Type> inputs, 2009 ArrayRef<Type> outputs, 2010 function_interface_impl::VariadicFlag variadicFlag) { 2011 Builder &b = parser.getBuilder(); 2012 if (outputs.size() > 1) { 2013 parser.emitError(loc, "failed to construct function type: expected zero or " 2014 "one function result"); 2015 return {}; 2016 } 2017 2018 // Convert inputs to LLVM types, exit early on error. 2019 SmallVector<Type, 4> llvmInputs; 2020 for (auto t : inputs) { 2021 if (!isCompatibleType(t)) { 2022 parser.emitError(loc, "failed to construct function type: expected LLVM " 2023 "type for function arguments"); 2024 return {}; 2025 } 2026 llvmInputs.push_back(t); 2027 } 2028 2029 // No output is denoted as "void" in LLVM type system. 2030 Type llvmOutput = 2031 outputs.empty() ? LLVMVoidType::get(b.getContext()) : outputs.front(); 2032 if (!isCompatibleType(llvmOutput)) { 2033 parser.emitError(loc, "failed to construct function type: expected LLVM " 2034 "type for function results") 2035 << llvmOutput; 2036 return {}; 2037 } 2038 return LLVMFunctionType::get(llvmOutput, llvmInputs, 2039 variadicFlag.isVariadic()); 2040 } 2041 2042 // Parses an LLVM function. 2043 // 2044 // operation ::= `llvm.func` linkage? function-signature function-attributes? 2045 // function-body 2046 // 2047 ParseResult LLVMFuncOp::parse(OpAsmParser &parser, OperationState &result) { 2048 // Default to external linkage if no keyword is provided. 2049 result.addAttribute( 2050 getLinkageAttrName(result.name), 2051 LinkageAttr::get(parser.getContext(), 2052 parseOptionalLLVMKeyword<Linkage>( 2053 parser, result, LLVM::Linkage::External))); 2054 2055 StringAttr nameAttr; 2056 SmallVector<OpAsmParser::UnresolvedOperand> entryArgs; 2057 SmallVector<NamedAttrList> argAttrs; 2058 SmallVector<NamedAttrList> resultAttrs; 2059 SmallVector<Type> argTypes; 2060 SmallVector<Type> resultTypes; 2061 SmallVector<Location> argLocations; 2062 bool isVariadic; 2063 2064 auto signatureLocation = parser.getCurrentLocation(); 2065 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 2066 result.attributes) || 2067 function_interface_impl::parseFunctionSignature( 2068 parser, /*allowVariadic=*/true, entryArgs, argTypes, argAttrs, 2069 argLocations, isVariadic, resultTypes, resultAttrs)) 2070 return failure(); 2071 2072 auto type = 2073 buildLLVMFunctionType(parser, signatureLocation, argTypes, resultTypes, 2074 function_interface_impl::VariadicFlag(isVariadic)); 2075 if (!type) 2076 return failure(); 2077 result.addAttribute(FunctionOpInterface::getTypeAttrName(), 2078 TypeAttr::get(type)); 2079 2080 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes))) 2081 return failure(); 2082 function_interface_impl::addArgAndResultAttrs(parser.getBuilder(), result, 2083 argAttrs, resultAttrs); 2084 2085 auto *body = result.addRegion(); 2086 OptionalParseResult parseResult = parser.parseOptionalRegion( 2087 *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes); 2088 return failure(parseResult.hasValue() && failed(*parseResult)); 2089 } 2090 2091 // Print the LLVMFuncOp. Collects argument and result types and passes them to 2092 // helper functions. Drops "void" result since it cannot be parsed back. Skips 2093 // the external linkage since it is the default value. 2094 void LLVMFuncOp::print(OpAsmPrinter &p) { 2095 p << ' '; 2096 if (getLinkage() != LLVM::Linkage::External) 2097 p << stringifyLinkage(getLinkage()) << ' '; 2098 p.printSymbolName(getName()); 2099 2100 LLVMFunctionType fnType = getFunctionType(); 2101 SmallVector<Type, 8> argTypes; 2102 SmallVector<Type, 1> resTypes; 2103 argTypes.reserve(fnType.getNumParams()); 2104 for (unsigned i = 0, e = fnType.getNumParams(); i < e; ++i) 2105 argTypes.push_back(fnType.getParamType(i)); 2106 2107 Type returnType = fnType.getReturnType(); 2108 if (!returnType.isa<LLVMVoidType>()) 2109 resTypes.push_back(returnType); 2110 2111 function_interface_impl::printFunctionSignature(p, *this, argTypes, 2112 isVarArg(), resTypes); 2113 function_interface_impl::printFunctionAttributes( 2114 p, *this, argTypes.size(), resTypes.size(), {getLinkageAttrName()}); 2115 2116 // Print the body if this is not an external function. 2117 Region &body = getBody(); 2118 if (!body.empty()) { 2119 p << ' '; 2120 p.printRegion(body, /*printEntryBlockArgs=*/false, 2121 /*printBlockTerminators=*/true); 2122 } 2123 } 2124 2125 // Verifies LLVM- and implementation-specific properties of the LLVM func Op: 2126 // - functions don't have 'common' linkage 2127 // - external functions have 'external' or 'extern_weak' linkage; 2128 // - vararg is (currently) only supported for external functions; 2129 LogicalResult LLVMFuncOp::verify() { 2130 if (getLinkage() == LLVM::Linkage::Common) 2131 return emitOpError() << "functions cannot have '" 2132 << stringifyLinkage(LLVM::Linkage::Common) 2133 << "' linkage"; 2134 2135 // Check to see if this function has a void return with a result attribute to 2136 // it. It isn't clear what semantics we would assign to that. 2137 if (getFunctionType().getReturnType().isa<LLVMVoidType>() && 2138 !getResultAttrs(0).empty()) { 2139 return emitOpError() 2140 << "cannot attach result attributes to functions with a void return"; 2141 } 2142 2143 if (isExternal()) { 2144 if (getLinkage() != LLVM::Linkage::External && 2145 getLinkage() != LLVM::Linkage::ExternWeak) 2146 return emitOpError() << "external functions must have '" 2147 << stringifyLinkage(LLVM::Linkage::External) 2148 << "' or '" 2149 << stringifyLinkage(LLVM::Linkage::ExternWeak) 2150 << "' linkage"; 2151 return success(); 2152 } 2153 2154 if (isVarArg()) 2155 return emitOpError("only external functions can be variadic"); 2156 2157 return success(); 2158 } 2159 2160 /// Verifies LLVM- and implementation-specific properties of the LLVM func Op: 2161 /// - entry block arguments are of LLVM types. 2162 LogicalResult LLVMFuncOp::verifyRegions() { 2163 if (isExternal()) 2164 return success(); 2165 2166 unsigned numArguments = getFunctionType().getNumParams(); 2167 Block &entryBlock = front(); 2168 for (unsigned i = 0; i < numArguments; ++i) { 2169 Type argType = entryBlock.getArgument(i).getType(); 2170 if (!isCompatibleType(argType)) 2171 return emitOpError("entry block argument #") 2172 << i << " is not of LLVM type"; 2173 } 2174 2175 return success(); 2176 } 2177 2178 //===----------------------------------------------------------------------===// 2179 // Verification for LLVM::ConstantOp. 2180 //===----------------------------------------------------------------------===// 2181 2182 LogicalResult LLVM::ConstantOp::verify() { 2183 if (StringAttr sAttr = getValue().dyn_cast<StringAttr>()) { 2184 auto arrayType = getType().dyn_cast<LLVMArrayType>(); 2185 if (!arrayType || arrayType.getNumElements() != sAttr.getValue().size() || 2186 !arrayType.getElementType().isInteger(8)) { 2187 return emitOpError() << "expected array type of " 2188 << sAttr.getValue().size() 2189 << " i8 elements for the string constant"; 2190 } 2191 return success(); 2192 } 2193 if (auto structType = getType().dyn_cast<LLVMStructType>()) { 2194 if (structType.getBody().size() != 2 || 2195 structType.getBody()[0] != structType.getBody()[1]) { 2196 return emitError() << "expected struct type with two elements of the " 2197 "same type, the type of a complex constant"; 2198 } 2199 2200 auto arrayAttr = getValue().dyn_cast<ArrayAttr>(); 2201 if (!arrayAttr || arrayAttr.size() != 2 || 2202 arrayAttr[0].getType() != arrayAttr[1].getType()) { 2203 return emitOpError() << "expected array attribute with two elements, " 2204 "representing a complex constant"; 2205 } 2206 2207 Type elementType = structType.getBody()[0]; 2208 if (!elementType 2209 .isa<IntegerType, Float16Type, Float32Type, Float64Type>()) { 2210 return emitError() 2211 << "expected struct element types to be floating point type or " 2212 "integer type"; 2213 } 2214 return success(); 2215 } 2216 if (!getValue().isa<IntegerAttr, ArrayAttr, FloatAttr, ElementsAttr>()) 2217 return emitOpError() 2218 << "only supports integer, float, string or elements attributes"; 2219 return success(); 2220 } 2221 2222 // Constant op constant-folds to its value. 2223 OpFoldResult LLVM::ConstantOp::fold(ArrayRef<Attribute>) { return getValue(); } 2224 2225 //===----------------------------------------------------------------------===// 2226 // Utility functions for parsing atomic ops 2227 //===----------------------------------------------------------------------===// 2228 2229 // Helper function to parse a keyword into the specified attribute named by 2230 // `attrName`. The keyword must match one of the string values defined by the 2231 // AtomicBinOp enum. The resulting I64 attribute is added to the `result` 2232 // state. 2233 static ParseResult parseAtomicBinOp(OpAsmParser &parser, OperationState &result, 2234 StringRef attrName) { 2235 SMLoc loc; 2236 StringRef keyword; 2237 if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&keyword)) 2238 return failure(); 2239 2240 // Replace the keyword `keyword` with an integer attribute. 2241 auto kind = symbolizeAtomicBinOp(keyword); 2242 if (!kind) { 2243 return parser.emitError(loc) 2244 << "'" << keyword << "' is an incorrect value of the '" << attrName 2245 << "' attribute"; 2246 } 2247 2248 auto value = static_cast<int64_t>(kind.getValue()); 2249 auto attr = parser.getBuilder().getI64IntegerAttr(value); 2250 result.addAttribute(attrName, attr); 2251 2252 return success(); 2253 } 2254 2255 // Helper function to parse a keyword into the specified attribute named by 2256 // `attrName`. The keyword must match one of the string values defined by the 2257 // AtomicOrdering enum. The resulting I64 attribute is added to the `result` 2258 // state. 2259 static ParseResult parseAtomicOrdering(OpAsmParser &parser, 2260 OperationState &result, 2261 StringRef attrName) { 2262 SMLoc loc; 2263 StringRef ordering; 2264 if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&ordering)) 2265 return failure(); 2266 2267 // Replace the keyword `ordering` with an integer attribute. 2268 auto kind = symbolizeAtomicOrdering(ordering); 2269 if (!kind) { 2270 return parser.emitError(loc) 2271 << "'" << ordering << "' is an incorrect value of the '" << attrName 2272 << "' attribute"; 2273 } 2274 2275 auto value = static_cast<int64_t>(kind.getValue()); 2276 auto attr = parser.getBuilder().getI64IntegerAttr(value); 2277 result.addAttribute(attrName, attr); 2278 2279 return success(); 2280 } 2281 2282 //===----------------------------------------------------------------------===// 2283 // Printer, parser and verifier for LLVM::AtomicRMWOp. 2284 //===----------------------------------------------------------------------===// 2285 2286 void AtomicRMWOp::print(OpAsmPrinter &p) { 2287 p << ' ' << stringifyAtomicBinOp(getBinOp()) << ' ' << getPtr() << ", " 2288 << getVal() << ' ' << stringifyAtomicOrdering(getOrdering()) << ' '; 2289 p.printOptionalAttrDict((*this)->getAttrs(), {"bin_op", "ordering"}); 2290 p << " : " << getRes().getType(); 2291 } 2292 2293 // <operation> ::= `llvm.atomicrmw` keyword ssa-use `,` ssa-use keyword 2294 // attribute-dict? `:` type 2295 ParseResult AtomicRMWOp::parse(OpAsmParser &parser, OperationState &result) { 2296 Type type; 2297 OpAsmParser::UnresolvedOperand ptr, val; 2298 if (parseAtomicBinOp(parser, result, "bin_op") || parser.parseOperand(ptr) || 2299 parser.parseComma() || parser.parseOperand(val) || 2300 parseAtomicOrdering(parser, result, "ordering") || 2301 parser.parseOptionalAttrDict(result.attributes) || 2302 parser.parseColonType(type) || 2303 parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type), 2304 result.operands) || 2305 parser.resolveOperand(val, type, result.operands)) 2306 return failure(); 2307 2308 result.addTypes(type); 2309 return success(); 2310 } 2311 2312 LogicalResult AtomicRMWOp::verify() { 2313 auto ptrType = getPtr().getType().cast<LLVM::LLVMPointerType>(); 2314 auto valType = getVal().getType(); 2315 if (valType != ptrType.getElementType()) 2316 return emitOpError("expected LLVM IR element type for operand #0 to " 2317 "match type for operand #1"); 2318 auto resType = getRes().getType(); 2319 if (resType != valType) 2320 return emitOpError( 2321 "expected LLVM IR result type to match type for operand #1"); 2322 if (getBinOp() == AtomicBinOp::fadd || getBinOp() == AtomicBinOp::fsub) { 2323 if (!mlir::LLVM::isCompatibleFloatingPointType(valType)) 2324 return emitOpError("expected LLVM IR floating point type"); 2325 } else if (getBinOp() == AtomicBinOp::xchg) { 2326 auto intType = valType.dyn_cast<IntegerType>(); 2327 unsigned intBitWidth = intType ? intType.getWidth() : 0; 2328 if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 && 2329 intBitWidth != 64 && !valType.isa<BFloat16Type>() && 2330 !valType.isa<Float16Type>() && !valType.isa<Float32Type>() && 2331 !valType.isa<Float64Type>()) 2332 return emitOpError("unexpected LLVM IR type for 'xchg' bin_op"); 2333 } else { 2334 auto intType = valType.dyn_cast<IntegerType>(); 2335 unsigned intBitWidth = intType ? intType.getWidth() : 0; 2336 if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 && 2337 intBitWidth != 64) 2338 return emitOpError("expected LLVM IR integer type"); 2339 } 2340 2341 if (static_cast<unsigned>(getOrdering()) < 2342 static_cast<unsigned>(AtomicOrdering::monotonic)) 2343 return emitOpError() << "expected at least '" 2344 << stringifyAtomicOrdering(AtomicOrdering::monotonic) 2345 << "' ordering"; 2346 2347 return success(); 2348 } 2349 2350 //===----------------------------------------------------------------------===// 2351 // Printer, parser and verifier for LLVM::AtomicCmpXchgOp. 2352 //===----------------------------------------------------------------------===// 2353 2354 void AtomicCmpXchgOp::print(OpAsmPrinter &p) { 2355 p << ' ' << getPtr() << ", " << getCmp() << ", " << getVal() << ' ' 2356 << stringifyAtomicOrdering(getSuccessOrdering()) << ' ' 2357 << stringifyAtomicOrdering(getFailureOrdering()); 2358 p.printOptionalAttrDict((*this)->getAttrs(), 2359 {"success_ordering", "failure_ordering"}); 2360 p << " : " << getVal().getType(); 2361 } 2362 2363 // <operation> ::= `llvm.cmpxchg` ssa-use `,` ssa-use `,` ssa-use 2364 // keyword keyword attribute-dict? `:` type 2365 ParseResult AtomicCmpXchgOp::parse(OpAsmParser &parser, 2366 OperationState &result) { 2367 auto &builder = parser.getBuilder(); 2368 Type type; 2369 OpAsmParser::UnresolvedOperand ptr, cmp, val; 2370 if (parser.parseOperand(ptr) || parser.parseComma() || 2371 parser.parseOperand(cmp) || parser.parseComma() || 2372 parser.parseOperand(val) || 2373 parseAtomicOrdering(parser, result, "success_ordering") || 2374 parseAtomicOrdering(parser, result, "failure_ordering") || 2375 parser.parseOptionalAttrDict(result.attributes) || 2376 parser.parseColonType(type) || 2377 parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type), 2378 result.operands) || 2379 parser.resolveOperand(cmp, type, result.operands) || 2380 parser.resolveOperand(val, type, result.operands)) 2381 return failure(); 2382 2383 auto boolType = IntegerType::get(builder.getContext(), 1); 2384 auto resultType = 2385 LLVMStructType::getLiteral(builder.getContext(), {type, boolType}); 2386 result.addTypes(resultType); 2387 2388 return success(); 2389 } 2390 2391 LogicalResult AtomicCmpXchgOp::verify() { 2392 auto ptrType = getPtr().getType().cast<LLVM::LLVMPointerType>(); 2393 if (!ptrType) 2394 return emitOpError("expected LLVM IR pointer type for operand #0"); 2395 auto cmpType = getCmp().getType(); 2396 auto valType = getVal().getType(); 2397 if (cmpType != ptrType.getElementType() || cmpType != valType) 2398 return emitOpError("expected LLVM IR element type for operand #0 to " 2399 "match type for all other operands"); 2400 auto intType = valType.dyn_cast<IntegerType>(); 2401 unsigned intBitWidth = intType ? intType.getWidth() : 0; 2402 if (!valType.isa<LLVMPointerType>() && intBitWidth != 8 && 2403 intBitWidth != 16 && intBitWidth != 32 && intBitWidth != 64 && 2404 !valType.isa<BFloat16Type>() && !valType.isa<Float16Type>() && 2405 !valType.isa<Float32Type>() && !valType.isa<Float64Type>()) 2406 return emitOpError("unexpected LLVM IR type"); 2407 if (getSuccessOrdering() < AtomicOrdering::monotonic || 2408 getFailureOrdering() < AtomicOrdering::monotonic) 2409 return emitOpError("ordering must be at least 'monotonic'"); 2410 if (getFailureOrdering() == AtomicOrdering::release || 2411 getFailureOrdering() == AtomicOrdering::acq_rel) 2412 return emitOpError("failure ordering cannot be 'release' or 'acq_rel'"); 2413 return success(); 2414 } 2415 2416 //===----------------------------------------------------------------------===// 2417 // Printer, parser and verifier for LLVM::FenceOp. 2418 //===----------------------------------------------------------------------===// 2419 2420 // <operation> ::= `llvm.fence` (`syncscope(`strAttr`)`)? keyword 2421 // attribute-dict? 2422 ParseResult FenceOp::parse(OpAsmParser &parser, OperationState &result) { 2423 StringAttr sScope; 2424 StringRef syncscopeKeyword = "syncscope"; 2425 if (!failed(parser.parseOptionalKeyword(syncscopeKeyword))) { 2426 if (parser.parseLParen() || 2427 parser.parseAttribute(sScope, syncscopeKeyword, result.attributes) || 2428 parser.parseRParen()) 2429 return failure(); 2430 } else { 2431 result.addAttribute(syncscopeKeyword, 2432 parser.getBuilder().getStringAttr("")); 2433 } 2434 if (parseAtomicOrdering(parser, result, "ordering") || 2435 parser.parseOptionalAttrDict(result.attributes)) 2436 return failure(); 2437 return success(); 2438 } 2439 2440 void FenceOp::print(OpAsmPrinter &p) { 2441 StringRef syncscopeKeyword = "syncscope"; 2442 p << ' '; 2443 if (!(*this)->getAttr(syncscopeKeyword).cast<StringAttr>().getValue().empty()) 2444 p << "syncscope(" << (*this)->getAttr(syncscopeKeyword) << ") "; 2445 p << stringifyAtomicOrdering(getOrdering()); 2446 } 2447 2448 LogicalResult FenceOp::verify() { 2449 if (getOrdering() == AtomicOrdering::not_atomic || 2450 getOrdering() == AtomicOrdering::unordered || 2451 getOrdering() == AtomicOrdering::monotonic) 2452 return emitOpError("can be given only acquire, release, acq_rel, " 2453 "and seq_cst orderings"); 2454 return success(); 2455 } 2456 2457 //===----------------------------------------------------------------------===// 2458 // Folder for LLVM::BitcastOp 2459 //===----------------------------------------------------------------------===// 2460 2461 OpFoldResult LLVM::BitcastOp::fold(ArrayRef<Attribute> operands) { 2462 // bitcast(x : T0, T0) -> x 2463 if (getArg().getType() == getType()) 2464 return getArg(); 2465 // bitcast(bitcast(x : T0, T1), T0) -> x 2466 if (auto prev = getArg().getDefiningOp<BitcastOp>()) 2467 if (prev.getArg().getType() == getType()) 2468 return prev.getArg(); 2469 return {}; 2470 } 2471 2472 //===----------------------------------------------------------------------===// 2473 // Folder for LLVM::AddrSpaceCastOp 2474 //===----------------------------------------------------------------------===// 2475 2476 OpFoldResult LLVM::AddrSpaceCastOp::fold(ArrayRef<Attribute> operands) { 2477 // addrcast(x : T0, T0) -> x 2478 if (getArg().getType() == getType()) 2479 return getArg(); 2480 // addrcast(addrcast(x : T0, T1), T0) -> x 2481 if (auto prev = getArg().getDefiningOp<AddrSpaceCastOp>()) 2482 if (prev.getArg().getType() == getType()) 2483 return prev.getArg(); 2484 return {}; 2485 } 2486 2487 //===----------------------------------------------------------------------===// 2488 // Folder for LLVM::GEPOp 2489 //===----------------------------------------------------------------------===// 2490 2491 OpFoldResult LLVM::GEPOp::fold(ArrayRef<Attribute> operands) { 2492 // gep %x:T, 0 -> %x 2493 if (getBase().getType() == getType() && getIndices().size() == 1 && 2494 matchPattern(getIndices()[0], m_Zero())) 2495 return getBase(); 2496 return {}; 2497 } 2498 2499 //===----------------------------------------------------------------------===// 2500 // LLVMDialect initialization, type parsing, and registration. 2501 //===----------------------------------------------------------------------===// 2502 2503 void LLVMDialect::initialize() { 2504 addAttributes<FMFAttr, LinkageAttr, LoopOptionsAttr>(); 2505 2506 // clang-format off 2507 addTypes<LLVMVoidType, 2508 LLVMPPCFP128Type, 2509 LLVMX86MMXType, 2510 LLVMTokenType, 2511 LLVMLabelType, 2512 LLVMMetadataType, 2513 LLVMFunctionType, 2514 LLVMPointerType, 2515 LLVMFixedVectorType, 2516 LLVMScalableVectorType, 2517 LLVMArrayType, 2518 LLVMStructType>(); 2519 // clang-format on 2520 addOperations< 2521 #define GET_OP_LIST 2522 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc" 2523 >(); 2524 2525 // Support unknown operations because not all LLVM operations are registered. 2526 allowUnknownOperations(); 2527 } 2528 2529 #define GET_OP_CLASSES 2530 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc" 2531 2532 /// Parse a type registered to this dialect. 2533 Type LLVMDialect::parseType(DialectAsmParser &parser) const { 2534 return detail::parseType(parser); 2535 } 2536 2537 /// Print a type registered to this dialect. 2538 void LLVMDialect::printType(Type type, DialectAsmPrinter &os) const { 2539 return detail::printType(type, os); 2540 } 2541 2542 LogicalResult LLVMDialect::verifyDataLayoutString( 2543 StringRef descr, llvm::function_ref<void(const Twine &)> reportError) { 2544 llvm::Expected<llvm::DataLayout> maybeDataLayout = 2545 llvm::DataLayout::parse(descr); 2546 if (maybeDataLayout) 2547 return success(); 2548 2549 std::string message; 2550 llvm::raw_string_ostream messageStream(message); 2551 llvm::logAllUnhandledErrors(maybeDataLayout.takeError(), messageStream); 2552 reportError("invalid data layout descriptor: " + messageStream.str()); 2553 return failure(); 2554 } 2555 2556 /// Verify LLVM dialect attributes. 2557 LogicalResult LLVMDialect::verifyOperationAttribute(Operation *op, 2558 NamedAttribute attr) { 2559 // If the `llvm.loop` attribute is present, enforce the following structure, 2560 // which the module translation can assume. 2561 if (attr.getName() == LLVMDialect::getLoopAttrName()) { 2562 auto loopAttr = attr.getValue().dyn_cast<DictionaryAttr>(); 2563 if (!loopAttr) 2564 return op->emitOpError() << "expected '" << LLVMDialect::getLoopAttrName() 2565 << "' to be a dictionary attribute"; 2566 Optional<NamedAttribute> parallelAccessGroup = 2567 loopAttr.getNamed(LLVMDialect::getParallelAccessAttrName()); 2568 if (parallelAccessGroup.hasValue()) { 2569 auto accessGroups = parallelAccessGroup->getValue().dyn_cast<ArrayAttr>(); 2570 if (!accessGroups) 2571 return op->emitOpError() 2572 << "expected '" << LLVMDialect::getParallelAccessAttrName() 2573 << "' to be an array attribute"; 2574 for (Attribute attr : accessGroups) { 2575 auto accessGroupRef = attr.dyn_cast<SymbolRefAttr>(); 2576 if (!accessGroupRef) 2577 return op->emitOpError() 2578 << "expected '" << attr << "' to be a symbol reference"; 2579 StringAttr metadataName = accessGroupRef.getRootReference(); 2580 auto metadataOp = 2581 SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 2582 op->getParentOp(), metadataName); 2583 if (!metadataOp) 2584 return op->emitOpError() 2585 << "expected '" << attr << "' to reference a metadata op"; 2586 StringAttr accessGroupName = accessGroupRef.getLeafReference(); 2587 Operation *accessGroupOp = 2588 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 2589 if (!accessGroupOp) 2590 return op->emitOpError() 2591 << "expected '" << attr << "' to reference an access_group op"; 2592 } 2593 } 2594 2595 Optional<NamedAttribute> loopOptions = 2596 loopAttr.getNamed(LLVMDialect::getLoopOptionsAttrName()); 2597 if (loopOptions.hasValue() && 2598 !loopOptions->getValue().isa<LoopOptionsAttr>()) 2599 return op->emitOpError() 2600 << "expected '" << LLVMDialect::getLoopOptionsAttrName() 2601 << "' to be a `loopopts` attribute"; 2602 } 2603 2604 if (attr.getName() == LLVMDialect::getStructAttrsAttrName()) { 2605 return op->emitOpError() 2606 << "'" << LLVM::LLVMDialect::getStructAttrsAttrName() 2607 << "' is permitted only in argument or result attributes"; 2608 } 2609 2610 // If the data layout attribute is present, it must use the LLVM data layout 2611 // syntax. Try parsing it and report errors in case of failure. Users of this 2612 // attribute may assume it is well-formed and can pass it to the (asserting) 2613 // llvm::DataLayout constructor. 2614 if (attr.getName() != LLVM::LLVMDialect::getDataLayoutAttrName()) 2615 return success(); 2616 if (auto stringAttr = attr.getValue().dyn_cast<StringAttr>()) 2617 return verifyDataLayoutString( 2618 stringAttr.getValue(), 2619 [op](const Twine &message) { op->emitOpError() << message.str(); }); 2620 2621 return op->emitOpError() << "expected '" 2622 << LLVM::LLVMDialect::getDataLayoutAttrName() 2623 << "' to be a string attribute"; 2624 } 2625 2626 LogicalResult LLVMDialect::verifyStructAttr(Operation *op, Attribute attr, 2627 Type annotatedType) { 2628 auto structType = annotatedType.dyn_cast<LLVMStructType>(); 2629 if (!structType) { 2630 const auto emitIncorrectAnnotatedType = [&op]() { 2631 return op->emitError() 2632 << "expected '" << LLVMDialect::getStructAttrsAttrName() 2633 << "' to annotate '!llvm.struct' or '!llvm.ptr<struct<...>>'"; 2634 }; 2635 const auto ptrType = annotatedType.dyn_cast<LLVMPointerType>(); 2636 if (!ptrType) 2637 return emitIncorrectAnnotatedType(); 2638 structType = ptrType.getElementType().dyn_cast<LLVMStructType>(); 2639 if (!structType) 2640 return emitIncorrectAnnotatedType(); 2641 } 2642 2643 const auto arrAttrs = attr.dyn_cast<ArrayAttr>(); 2644 if (!arrAttrs) 2645 return op->emitError() << "expected '" 2646 << LLVMDialect::getStructAttrsAttrName() 2647 << "' to be an array attribute"; 2648 2649 if (structType.getBody().size() != arrAttrs.size()) 2650 return op->emitError() 2651 << "size of '" << LLVMDialect::getStructAttrsAttrName() 2652 << "' must match the size of the annotated '!llvm.struct'"; 2653 return success(); 2654 } 2655 2656 static LogicalResult verifyFuncOpInterfaceStructAttr( 2657 Operation *op, Attribute attr, 2658 const std::function<Type(FunctionOpInterface)> &getAnnotatedType) { 2659 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) 2660 return LLVMDialect::verifyStructAttr(op, attr, getAnnotatedType(funcOp)); 2661 return op->emitError() << "expected '" 2662 << LLVMDialect::getStructAttrsAttrName() 2663 << "' to be used on function-like operations"; 2664 } 2665 2666 /// Verify LLVMIR function argument attributes. 2667 LogicalResult LLVMDialect::verifyRegionArgAttribute(Operation *op, 2668 unsigned regionIdx, 2669 unsigned argIdx, 2670 NamedAttribute argAttr) { 2671 // Check that llvm.noalias is a unit attribute. 2672 if (argAttr.getName() == LLVMDialect::getNoAliasAttrName() && 2673 !argAttr.getValue().isa<UnitAttr>()) 2674 return op->emitError() 2675 << "expected llvm.noalias argument attribute to be a unit attribute"; 2676 // Check that llvm.align is an integer attribute. 2677 if (argAttr.getName() == LLVMDialect::getAlignAttrName() && 2678 !argAttr.getValue().isa<IntegerAttr>()) 2679 return op->emitError() 2680 << "llvm.align argument attribute of non integer type"; 2681 if (argAttr.getName() == LLVMDialect::getStructAttrsAttrName()) { 2682 return verifyFuncOpInterfaceStructAttr( 2683 op, argAttr.getValue(), [argIdx](FunctionOpInterface funcOp) { 2684 return funcOp.getArgumentTypes()[argIdx]; 2685 }); 2686 } 2687 return success(); 2688 } 2689 2690 LogicalResult LLVMDialect::verifyRegionResultAttribute(Operation *op, 2691 unsigned regionIdx, 2692 unsigned resIdx, 2693 NamedAttribute resAttr) { 2694 if (resAttr.getName() == LLVMDialect::getStructAttrsAttrName()) { 2695 return verifyFuncOpInterfaceStructAttr( 2696 op, resAttr.getValue(), [resIdx](FunctionOpInterface funcOp) { 2697 return funcOp.getResultTypes()[resIdx]; 2698 }); 2699 } 2700 return success(); 2701 } 2702 2703 //===----------------------------------------------------------------------===// 2704 // Utility functions. 2705 //===----------------------------------------------------------------------===// 2706 2707 Value mlir::LLVM::createGlobalString(Location loc, OpBuilder &builder, 2708 StringRef name, StringRef value, 2709 LLVM::Linkage linkage) { 2710 assert(builder.getInsertionBlock() && 2711 builder.getInsertionBlock()->getParentOp() && 2712 "expected builder to point to a block constrained in an op"); 2713 auto module = 2714 builder.getInsertionBlock()->getParentOp()->getParentOfType<ModuleOp>(); 2715 assert(module && "builder points to an op outside of a module"); 2716 2717 // Create the global at the entry of the module. 2718 OpBuilder moduleBuilder(module.getBodyRegion(), builder.getListener()); 2719 MLIRContext *ctx = builder.getContext(); 2720 auto type = LLVM::LLVMArrayType::get(IntegerType::get(ctx, 8), value.size()); 2721 auto global = moduleBuilder.create<LLVM::GlobalOp>( 2722 loc, type, /*isConstant=*/true, linkage, name, 2723 builder.getStringAttr(value), /*alignment=*/0); 2724 2725 // Get the pointer to the first character in the global string. 2726 Value globalPtr = builder.create<LLVM::AddressOfOp>(loc, global); 2727 Value cst0 = builder.create<LLVM::ConstantOp>( 2728 loc, IntegerType::get(ctx, 64), 2729 builder.getIntegerAttr(builder.getIndexType(), 0)); 2730 return builder.create<LLVM::GEPOp>( 2731 loc, LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)), globalPtr, 2732 ValueRange{cst0, cst0}); 2733 } 2734 2735 bool mlir::LLVM::satisfiesLLVMModule(Operation *op) { 2736 return op->hasTrait<OpTrait::SymbolTable>() && 2737 op->hasTrait<OpTrait::IsIsolatedFromAbove>(); 2738 } 2739 2740 static constexpr const FastmathFlags fastmathFlagsList[] = { 2741 // clang-format off 2742 FastmathFlags::nnan, 2743 FastmathFlags::ninf, 2744 FastmathFlags::nsz, 2745 FastmathFlags::arcp, 2746 FastmathFlags::contract, 2747 FastmathFlags::afn, 2748 FastmathFlags::reassoc, 2749 FastmathFlags::fast, 2750 // clang-format on 2751 }; 2752 2753 void FMFAttr::print(AsmPrinter &printer) const { 2754 printer << "<"; 2755 auto flags = llvm::make_filter_range(fastmathFlagsList, [&](auto flag) { 2756 return bitEnumContains(this->getFlags(), flag); 2757 }); 2758 llvm::interleaveComma(flags, printer, 2759 [&](auto flag) { printer << stringifyEnum(flag); }); 2760 printer << ">"; 2761 } 2762 2763 Attribute FMFAttr::parse(AsmParser &parser, Type type) { 2764 if (failed(parser.parseLess())) 2765 return {}; 2766 2767 FastmathFlags flags = {}; 2768 if (failed(parser.parseOptionalGreater())) { 2769 do { 2770 StringRef elemName; 2771 if (failed(parser.parseKeyword(&elemName))) 2772 return {}; 2773 2774 auto elem = symbolizeFastmathFlags(elemName); 2775 if (!elem) { 2776 parser.emitError(parser.getNameLoc(), "Unknown fastmath flag: ") 2777 << elemName; 2778 return {}; 2779 } 2780 2781 flags = flags | *elem; 2782 } while (succeeded(parser.parseOptionalComma())); 2783 2784 if (failed(parser.parseGreater())) 2785 return {}; 2786 } 2787 2788 return FMFAttr::get(parser.getContext(), flags); 2789 } 2790 2791 void LinkageAttr::print(AsmPrinter &printer) const { 2792 printer << "<"; 2793 if (static_cast<uint64_t>(getLinkage()) <= getMaxEnumValForLinkage()) 2794 printer << stringifyEnum(getLinkage()); 2795 else 2796 printer << static_cast<uint64_t>(getLinkage()); 2797 printer << ">"; 2798 } 2799 2800 Attribute LinkageAttr::parse(AsmParser &parser, Type type) { 2801 StringRef elemName; 2802 if (parser.parseLess() || parser.parseKeyword(&elemName) || 2803 parser.parseGreater()) 2804 return {}; 2805 auto elem = linkage::symbolizeLinkage(elemName); 2806 if (!elem) { 2807 parser.emitError(parser.getNameLoc(), "Unknown linkage: ") << elemName; 2808 return {}; 2809 } 2810 Linkage linkage = *elem; 2811 return LinkageAttr::get(parser.getContext(), linkage); 2812 } 2813 2814 LoopOptionsAttrBuilder::LoopOptionsAttrBuilder(LoopOptionsAttr attr) 2815 : options(attr.getOptions().begin(), attr.getOptions().end()) {} 2816 2817 template <typename T> 2818 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setOption(LoopOptionCase tag, 2819 Optional<T> value) { 2820 auto option = llvm::find_if( 2821 options, [tag](auto option) { return option.first == tag; }); 2822 if (option != options.end()) { 2823 if (value.hasValue()) 2824 option->second = *value; 2825 else 2826 options.erase(option); 2827 } else { 2828 options.push_back(LoopOptionsAttr::OptionValuePair(tag, *value)); 2829 } 2830 return *this; 2831 } 2832 2833 LoopOptionsAttrBuilder & 2834 LoopOptionsAttrBuilder::setDisableLICM(Optional<bool> value) { 2835 return setOption(LoopOptionCase::disable_licm, value); 2836 } 2837 2838 /// Set the `interleave_count` option to the provided value. If no value 2839 /// is provided the option is deleted. 2840 LoopOptionsAttrBuilder & 2841 LoopOptionsAttrBuilder::setInterleaveCount(Optional<uint64_t> count) { 2842 return setOption(LoopOptionCase::interleave_count, count); 2843 } 2844 2845 /// Set the `disable_unroll` option to the provided value. If no value 2846 /// is provided the option is deleted. 2847 LoopOptionsAttrBuilder & 2848 LoopOptionsAttrBuilder::setDisableUnroll(Optional<bool> value) { 2849 return setOption(LoopOptionCase::disable_unroll, value); 2850 } 2851 2852 /// Set the `disable_pipeline` option to the provided value. If no value 2853 /// is provided the option is deleted. 2854 LoopOptionsAttrBuilder & 2855 LoopOptionsAttrBuilder::setDisablePipeline(Optional<bool> value) { 2856 return setOption(LoopOptionCase::disable_pipeline, value); 2857 } 2858 2859 /// Set the `pipeline_initiation_interval` option to the provided value. 2860 /// If no value is provided the option is deleted. 2861 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setPipelineInitiationInterval( 2862 Optional<uint64_t> count) { 2863 return setOption(LoopOptionCase::pipeline_initiation_interval, count); 2864 } 2865 2866 template <typename T> 2867 static Optional<T> 2868 getOption(ArrayRef<std::pair<LoopOptionCase, int64_t>> options, 2869 LoopOptionCase option) { 2870 auto it = 2871 lower_bound(options, option, [](auto optionPair, LoopOptionCase option) { 2872 return optionPair.first < option; 2873 }); 2874 if (it == options.end()) 2875 return {}; 2876 return static_cast<T>(it->second); 2877 } 2878 2879 Optional<bool> LoopOptionsAttr::disableUnroll() { 2880 return getOption<bool>(getOptions(), LoopOptionCase::disable_unroll); 2881 } 2882 2883 Optional<bool> LoopOptionsAttr::disableLICM() { 2884 return getOption<bool>(getOptions(), LoopOptionCase::disable_licm); 2885 } 2886 2887 Optional<int64_t> LoopOptionsAttr::interleaveCount() { 2888 return getOption<int64_t>(getOptions(), LoopOptionCase::interleave_count); 2889 } 2890 2891 /// Build the LoopOptions Attribute from a sorted array of individual options. 2892 LoopOptionsAttr LoopOptionsAttr::get( 2893 MLIRContext *context, 2894 ArrayRef<std::pair<LoopOptionCase, int64_t>> sortedOptions) { 2895 assert(llvm::is_sorted(sortedOptions, llvm::less_first()) && 2896 "LoopOptionsAttr ctor expects a sorted options array"); 2897 return Base::get(context, sortedOptions); 2898 } 2899 2900 /// Build the LoopOptions Attribute from a sorted array of individual options. 2901 LoopOptionsAttr LoopOptionsAttr::get(MLIRContext *context, 2902 LoopOptionsAttrBuilder &optionBuilders) { 2903 llvm::sort(optionBuilders.options, llvm::less_first()); 2904 return Base::get(context, optionBuilders.options); 2905 } 2906 2907 void LoopOptionsAttr::print(AsmPrinter &printer) const { 2908 printer << "<"; 2909 llvm::interleaveComma(getOptions(), printer, [&](auto option) { 2910 printer << stringifyEnum(option.first) << " = "; 2911 switch (option.first) { 2912 case LoopOptionCase::disable_licm: 2913 case LoopOptionCase::disable_unroll: 2914 case LoopOptionCase::disable_pipeline: 2915 printer << (option.second ? "true" : "false"); 2916 break; 2917 case LoopOptionCase::interleave_count: 2918 case LoopOptionCase::pipeline_initiation_interval: 2919 printer << option.second; 2920 break; 2921 } 2922 }); 2923 printer << ">"; 2924 } 2925 2926 Attribute LoopOptionsAttr::parse(AsmParser &parser, Type type) { 2927 if (failed(parser.parseLess())) 2928 return {}; 2929 2930 SmallVector<std::pair<LoopOptionCase, int64_t>> options; 2931 llvm::SmallDenseSet<LoopOptionCase> seenOptions; 2932 do { 2933 StringRef optionName; 2934 if (parser.parseKeyword(&optionName)) 2935 return {}; 2936 2937 auto option = symbolizeLoopOptionCase(optionName); 2938 if (!option) { 2939 parser.emitError(parser.getNameLoc(), "unknown loop option: ") 2940 << optionName; 2941 return {}; 2942 } 2943 if (!seenOptions.insert(*option).second) { 2944 parser.emitError(parser.getNameLoc(), "loop option present twice"); 2945 return {}; 2946 } 2947 if (failed(parser.parseEqual())) 2948 return {}; 2949 2950 int64_t value; 2951 switch (*option) { 2952 case LoopOptionCase::disable_licm: 2953 case LoopOptionCase::disable_unroll: 2954 case LoopOptionCase::disable_pipeline: 2955 if (succeeded(parser.parseOptionalKeyword("true"))) 2956 value = 1; 2957 else if (succeeded(parser.parseOptionalKeyword("false"))) 2958 value = 0; 2959 else { 2960 parser.emitError(parser.getNameLoc(), 2961 "expected boolean value 'true' or 'false'"); 2962 return {}; 2963 } 2964 break; 2965 case LoopOptionCase::interleave_count: 2966 case LoopOptionCase::pipeline_initiation_interval: 2967 if (failed(parser.parseInteger(value))) { 2968 parser.emitError(parser.getNameLoc(), "expected integer value"); 2969 return {}; 2970 } 2971 break; 2972 } 2973 options.push_back(std::make_pair(*option, value)); 2974 } while (succeeded(parser.parseOptionalComma())); 2975 if (failed(parser.parseGreater())) 2976 return {}; 2977 2978 llvm::sort(options, llvm::less_first()); 2979 return get(parser.getContext(), options); 2980 } 2981