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