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     if (getValueOrNull())
1802       return emitOpError("cannot have both initializer value and region");
1803   }
1804 
1805   if (getLinkage() == Linkage::Common) {
1806     if (Attribute value = getValueOrNull()) {
1807       if (!isZeroAttribute(value)) {
1808         return emitOpError()
1809                << "expected zero value for '"
1810                << stringifyLinkage(Linkage::Common) << "' linkage";
1811       }
1812     }
1813   }
1814 
1815   if (getLinkage() == Linkage::Appending) {
1816     if (!getType().isa<LLVMArrayType>()) {
1817       return emitOpError() << "expected array type for '"
1818                            << stringifyLinkage(Linkage::Appending)
1819                            << "' linkage";
1820     }
1821   }
1822 
1823   Optional<uint64_t> alignAttr = getAlignment();
1824   if (alignAttr.hasValue()) {
1825     uint64_t value = alignAttr.getValue();
1826     if (!llvm::isPowerOf2_64(value))
1827       return emitError() << "alignment attribute is not a power of 2";
1828   }
1829 
1830   return success();
1831 }
1832 
1833 //===----------------------------------------------------------------------===//
1834 // LLVM::GlobalCtorsOp
1835 //===----------------------------------------------------------------------===//
1836 
1837 LogicalResult
1838 GlobalCtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1839   for (Attribute ctor : getCtors()) {
1840     if (failed(verifySymbolAttrUse(ctor.cast<FlatSymbolRefAttr>(), *this,
1841                                    symbolTable)))
1842       return failure();
1843   }
1844   return success();
1845 }
1846 
1847 LogicalResult GlobalCtorsOp::verify() {
1848   if (getCtors().size() != getPriorities().size())
1849     return emitError(
1850         "mismatch between the number of ctors and the number of priorities");
1851   return success();
1852 }
1853 
1854 //===----------------------------------------------------------------------===//
1855 // LLVM::GlobalDtorsOp
1856 //===----------------------------------------------------------------------===//
1857 
1858 LogicalResult
1859 GlobalDtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1860   for (Attribute dtor : getDtors()) {
1861     if (failed(verifySymbolAttrUse(dtor.cast<FlatSymbolRefAttr>(), *this,
1862                                    symbolTable)))
1863       return failure();
1864   }
1865   return success();
1866 }
1867 
1868 LogicalResult GlobalDtorsOp::verify() {
1869   if (getDtors().size() != getPriorities().size())
1870     return emitError(
1871         "mismatch between the number of dtors and the number of priorities");
1872   return success();
1873 }
1874 
1875 //===----------------------------------------------------------------------===//
1876 // Printing/parsing for LLVM::ShuffleVectorOp.
1877 //===----------------------------------------------------------------------===//
1878 // Expects vector to be of wrapped LLVM vector type and position to be of
1879 // wrapped LLVM i32 type.
1880 void LLVM::ShuffleVectorOp::build(OpBuilder &b, OperationState &result,
1881                                   Value v1, Value v2, ArrayAttr mask,
1882                                   ArrayRef<NamedAttribute> attrs) {
1883   auto containerType = v1.getType();
1884   auto vType = LLVM::getFixedVectorType(
1885       LLVM::getVectorElementType(containerType), mask.size());
1886   build(b, result, vType, v1, v2, mask);
1887   result.addAttributes(attrs);
1888 }
1889 
1890 void ShuffleVectorOp::print(OpAsmPrinter &p) {
1891   p << ' ' << getV1() << ", " << getV2() << " " << getMask();
1892   p.printOptionalAttrDict((*this)->getAttrs(), {"mask"});
1893   p << " : " << getV1().getType() << ", " << getV2().getType();
1894 }
1895 
1896 // <operation> ::= `llvm.shufflevector` ssa-use `, ` ssa-use
1897 //                 `[` integer-literal (`,` integer-literal)* `]`
1898 //                 attribute-dict? `:` type
1899 ParseResult ShuffleVectorOp::parse(OpAsmParser &parser,
1900                                    OperationState &result) {
1901   SMLoc loc;
1902   OpAsmParser::OperandType v1, v2;
1903   ArrayAttr maskAttr;
1904   Type typeV1, typeV2;
1905   if (parser.getCurrentLocation(&loc) || parser.parseOperand(v1) ||
1906       parser.parseComma() || parser.parseOperand(v2) ||
1907       parser.parseAttribute(maskAttr, "mask", result.attributes) ||
1908       parser.parseOptionalAttrDict(result.attributes) ||
1909       parser.parseColonType(typeV1) || parser.parseComma() ||
1910       parser.parseType(typeV2) ||
1911       parser.resolveOperand(v1, typeV1, result.operands) ||
1912       parser.resolveOperand(v2, typeV2, result.operands))
1913     return failure();
1914   if (!LLVM::isCompatibleVectorType(typeV1))
1915     return parser.emitError(
1916         loc, "expected LLVM IR dialect vector type for operand #1");
1917   auto vType = LLVM::getFixedVectorType(LLVM::getVectorElementType(typeV1),
1918                                         maskAttr.size());
1919   result.addTypes(vType);
1920   return success();
1921 }
1922 
1923 LogicalResult ShuffleVectorOp::verify() {
1924   Type type1 = getV1().getType();
1925   Type type2 = getV2().getType();
1926   if (LLVM::getVectorElementType(type1) != LLVM::getVectorElementType(type2))
1927     return emitOpError("expected matching LLVM IR Dialect element types");
1928   return success();
1929 }
1930 
1931 //===----------------------------------------------------------------------===//
1932 // Implementations for LLVM::LLVMFuncOp.
1933 //===----------------------------------------------------------------------===//
1934 
1935 // Add the entry block to the function.
1936 Block *LLVMFuncOp::addEntryBlock() {
1937   assert(empty() && "function already has an entry block");
1938   assert(!isVarArg() && "unimplemented: non-external variadic functions");
1939 
1940   auto *entry = new Block;
1941   push_back(entry);
1942 
1943   // FIXME: Allow passing in proper locations for the entry arguments.
1944   LLVMFunctionType type = getType();
1945   for (unsigned i = 0, e = type.getNumParams(); i < e; ++i)
1946     entry->addArgument(type.getParamType(i), getLoc());
1947   return entry;
1948 }
1949 
1950 void LLVMFuncOp::build(OpBuilder &builder, OperationState &result,
1951                        StringRef name, Type type, LLVM::Linkage linkage,
1952                        bool dsoLocal, ArrayRef<NamedAttribute> attrs,
1953                        ArrayRef<DictionaryAttr> argAttrs) {
1954   result.addRegion();
1955   result.addAttribute(SymbolTable::getSymbolAttrName(),
1956                       builder.getStringAttr(name));
1957   result.addAttribute("type", TypeAttr::get(type));
1958   result.addAttribute(::getLinkageAttrName(),
1959                       LinkageAttr::get(builder.getContext(), linkage));
1960   result.attributes.append(attrs.begin(), attrs.end());
1961   if (dsoLocal)
1962     result.addAttribute("dso_local", builder.getUnitAttr());
1963   if (argAttrs.empty())
1964     return;
1965 
1966   assert(type.cast<LLVMFunctionType>().getNumParams() == argAttrs.size() &&
1967          "expected as many argument attribute lists as arguments");
1968   function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs,
1969                                                 /*resultAttrs=*/llvm::None);
1970 }
1971 
1972 // Builds an LLVM function type from the given lists of input and output types.
1973 // Returns a null type if any of the types provided are non-LLVM types, or if
1974 // there is more than one output type.
1975 static Type
1976 buildLLVMFunctionType(OpAsmParser &parser, SMLoc loc,
1977                       ArrayRef<Type> inputs, ArrayRef<Type> outputs,
1978                       function_interface_impl::VariadicFlag variadicFlag) {
1979   Builder &b = parser.getBuilder();
1980   if (outputs.size() > 1) {
1981     parser.emitError(loc, "failed to construct function type: expected zero or "
1982                           "one function result");
1983     return {};
1984   }
1985 
1986   // Convert inputs to LLVM types, exit early on error.
1987   SmallVector<Type, 4> llvmInputs;
1988   for (auto t : inputs) {
1989     if (!isCompatibleType(t)) {
1990       parser.emitError(loc, "failed to construct function type: expected LLVM "
1991                             "type for function arguments");
1992       return {};
1993     }
1994     llvmInputs.push_back(t);
1995   }
1996 
1997   // No output is denoted as "void" in LLVM type system.
1998   Type llvmOutput =
1999       outputs.empty() ? LLVMVoidType::get(b.getContext()) : outputs.front();
2000   if (!isCompatibleType(llvmOutput)) {
2001     parser.emitError(loc, "failed to construct function type: expected LLVM "
2002                           "type for function results")
2003         << llvmOutput;
2004     return {};
2005   }
2006   return LLVMFunctionType::get(llvmOutput, llvmInputs,
2007                                variadicFlag.isVariadic());
2008 }
2009 
2010 // Parses an LLVM function.
2011 //
2012 // operation ::= `llvm.func` linkage? function-signature function-attributes?
2013 //               function-body
2014 //
2015 ParseResult LLVMFuncOp::parse(OpAsmParser &parser, OperationState &result) {
2016   // Default to external linkage if no keyword is provided.
2017   result.addAttribute(
2018       ::getLinkageAttrName(),
2019       LinkageAttr::get(parser.getContext(),
2020                        parseOptionalLLVMKeyword<Linkage>(
2021                            parser, result, LLVM::Linkage::External)));
2022 
2023   StringAttr nameAttr;
2024   SmallVector<OpAsmParser::OperandType> entryArgs;
2025   SmallVector<NamedAttrList> argAttrs;
2026   SmallVector<NamedAttrList> resultAttrs;
2027   SmallVector<Type> argTypes;
2028   SmallVector<Type> resultTypes;
2029   SmallVector<Location> argLocations;
2030   bool isVariadic;
2031 
2032   auto signatureLocation = parser.getCurrentLocation();
2033   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2034                              result.attributes) ||
2035       function_interface_impl::parseFunctionSignature(
2036           parser, /*allowVariadic=*/true, entryArgs, argTypes, argAttrs,
2037           argLocations, isVariadic, resultTypes, resultAttrs))
2038     return failure();
2039 
2040   auto type =
2041       buildLLVMFunctionType(parser, signatureLocation, argTypes, resultTypes,
2042                             function_interface_impl::VariadicFlag(isVariadic));
2043   if (!type)
2044     return failure();
2045   result.addAttribute(FunctionOpInterface::getTypeAttrName(),
2046                       TypeAttr::get(type));
2047 
2048   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
2049     return failure();
2050   function_interface_impl::addArgAndResultAttrs(parser.getBuilder(), result,
2051                                                 argAttrs, resultAttrs);
2052 
2053   auto *body = result.addRegion();
2054   OptionalParseResult parseResult = parser.parseOptionalRegion(
2055       *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes);
2056   return failure(parseResult.hasValue() && failed(*parseResult));
2057 }
2058 
2059 // Print the LLVMFuncOp. Collects argument and result types and passes them to
2060 // helper functions. Drops "void" result since it cannot be parsed back. Skips
2061 // the external linkage since it is the default value.
2062 void LLVMFuncOp::print(OpAsmPrinter &p) {
2063   p << ' ';
2064   if (getLinkage() != LLVM::Linkage::External)
2065     p << stringifyLinkage(getLinkage()) << ' ';
2066   p.printSymbolName(getName());
2067 
2068   LLVMFunctionType fnType = getType();
2069   SmallVector<Type, 8> argTypes;
2070   SmallVector<Type, 1> resTypes;
2071   argTypes.reserve(fnType.getNumParams());
2072   for (unsigned i = 0, e = fnType.getNumParams(); i < e; ++i)
2073     argTypes.push_back(fnType.getParamType(i));
2074 
2075   Type returnType = fnType.getReturnType();
2076   if (!returnType.isa<LLVMVoidType>())
2077     resTypes.push_back(returnType);
2078 
2079   function_interface_impl::printFunctionSignature(p, *this, argTypes,
2080                                                   isVarArg(), resTypes);
2081   function_interface_impl::printFunctionAttributes(
2082       p, *this, argTypes.size(), resTypes.size(), {getLinkageAttrName()});
2083 
2084   // Print the body if this is not an external function.
2085   Region &body = getBody();
2086   if (!body.empty()) {
2087     p << ' ';
2088     p.printRegion(body, /*printEntryBlockArgs=*/false,
2089                   /*printBlockTerminators=*/true);
2090   }
2091 }
2092 
2093 LogicalResult LLVMFuncOp::verifyType() {
2094   auto llvmType = getTypeAttr().getValue().dyn_cast_or_null<LLVMFunctionType>();
2095   if (!llvmType)
2096     return emitOpError("requires '" + getTypeAttrName() +
2097                        "' attribute of wrapped LLVM function type");
2098 
2099   return success();
2100 }
2101 
2102 // Verifies LLVM- and implementation-specific properties of the LLVM func Op:
2103 // - functions don't have 'common' linkage
2104 // - external functions have 'external' or 'extern_weak' linkage;
2105 // - vararg is (currently) only supported for external functions;
2106 // - entry block arguments are of LLVM types and match the function signature.
2107 LogicalResult LLVMFuncOp::verify() {
2108   if (getLinkage() == LLVM::Linkage::Common)
2109     return emitOpError() << "functions cannot have '"
2110                          << stringifyLinkage(LLVM::Linkage::Common)
2111                          << "' linkage";
2112 
2113   // Check to see if this function has a void return with a result attribute to
2114   // it. It isn't clear what semantics we would assign to that.
2115   if (getType().getReturnType().isa<LLVMVoidType>() &&
2116       !getResultAttrs(0).empty()) {
2117     return emitOpError()
2118            << "cannot attach result attributes to functions with a void return";
2119   }
2120 
2121   if (isExternal()) {
2122     if (getLinkage() != LLVM::Linkage::External &&
2123         getLinkage() != LLVM::Linkage::ExternWeak)
2124       return emitOpError() << "external functions must have '"
2125                            << stringifyLinkage(LLVM::Linkage::External)
2126                            << "' or '"
2127                            << stringifyLinkage(LLVM::Linkage::ExternWeak)
2128                            << "' linkage";
2129     return success();
2130   }
2131 
2132   if (isVarArg())
2133     return emitOpError("only external functions can be variadic");
2134 
2135   unsigned numArguments = getType().getNumParams();
2136   Block &entryBlock = front();
2137   for (unsigned i = 0; i < numArguments; ++i) {
2138     Type argType = entryBlock.getArgument(i).getType();
2139     if (!isCompatibleType(argType))
2140       return emitOpError("entry block argument #")
2141              << i << " is not of LLVM type";
2142     if (getType().getParamType(i) != argType)
2143       return emitOpError("the type of entry block argument #")
2144              << i << " does not match the function signature";
2145   }
2146 
2147   return success();
2148 }
2149 
2150 //===----------------------------------------------------------------------===//
2151 // Verification for LLVM::ConstantOp.
2152 //===----------------------------------------------------------------------===//
2153 
2154 LogicalResult LLVM::ConstantOp::verify() {
2155   if (StringAttr sAttr = getValue().dyn_cast<StringAttr>()) {
2156     auto arrayType = getType().dyn_cast<LLVMArrayType>();
2157     if (!arrayType || arrayType.getNumElements() != sAttr.getValue().size() ||
2158         !arrayType.getElementType().isInteger(8)) {
2159       return emitOpError() << "expected array type of "
2160                            << sAttr.getValue().size()
2161                            << " i8 elements for the string constant";
2162     }
2163     return success();
2164   }
2165   if (auto structType = getType().dyn_cast<LLVMStructType>()) {
2166     if (structType.getBody().size() != 2 ||
2167         structType.getBody()[0] != structType.getBody()[1]) {
2168       return emitError() << "expected struct type with two elements of the "
2169                             "same type, the type of a complex constant";
2170     }
2171 
2172     auto arrayAttr = getValue().dyn_cast<ArrayAttr>();
2173     if (!arrayAttr || arrayAttr.size() != 2 ||
2174         arrayAttr[0].getType() != arrayAttr[1].getType()) {
2175       return emitOpError() << "expected array attribute with two elements, "
2176                               "representing a complex constant";
2177     }
2178 
2179     Type elementType = structType.getBody()[0];
2180     if (!elementType
2181              .isa<IntegerType, Float16Type, Float32Type, Float64Type>()) {
2182       return emitError()
2183              << "expected struct element types to be floating point type or "
2184                 "integer type";
2185     }
2186     return success();
2187   }
2188   if (!getValue().isa<IntegerAttr, ArrayAttr, FloatAttr, ElementsAttr>())
2189     return emitOpError()
2190            << "only supports integer, float, string or elements attributes";
2191   return success();
2192 }
2193 
2194 // Constant op constant-folds to its value.
2195 OpFoldResult LLVM::ConstantOp::fold(ArrayRef<Attribute>) { return getValue(); }
2196 
2197 //===----------------------------------------------------------------------===//
2198 // Utility functions for parsing atomic ops
2199 //===----------------------------------------------------------------------===//
2200 
2201 // Helper function to parse a keyword into the specified attribute named by
2202 // `attrName`. The keyword must match one of the string values defined by the
2203 // AtomicBinOp enum. The resulting I64 attribute is added to the `result`
2204 // state.
2205 static ParseResult parseAtomicBinOp(OpAsmParser &parser, OperationState &result,
2206                                     StringRef attrName) {
2207   SMLoc loc;
2208   StringRef keyword;
2209   if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&keyword))
2210     return failure();
2211 
2212   // Replace the keyword `keyword` with an integer attribute.
2213   auto kind = symbolizeAtomicBinOp(keyword);
2214   if (!kind) {
2215     return parser.emitError(loc)
2216            << "'" << keyword << "' is an incorrect value of the '" << attrName
2217            << "' attribute";
2218   }
2219 
2220   auto value = static_cast<int64_t>(kind.getValue());
2221   auto attr = parser.getBuilder().getI64IntegerAttr(value);
2222   result.addAttribute(attrName, attr);
2223 
2224   return success();
2225 }
2226 
2227 // Helper function to parse a keyword into the specified attribute named by
2228 // `attrName`. The keyword must match one of the string values defined by the
2229 // AtomicOrdering enum. The resulting I64 attribute is added to the `result`
2230 // state.
2231 static ParseResult parseAtomicOrdering(OpAsmParser &parser,
2232                                        OperationState &result,
2233                                        StringRef attrName) {
2234   SMLoc loc;
2235   StringRef ordering;
2236   if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&ordering))
2237     return failure();
2238 
2239   // Replace the keyword `ordering` with an integer attribute.
2240   auto kind = symbolizeAtomicOrdering(ordering);
2241   if (!kind) {
2242     return parser.emitError(loc)
2243            << "'" << ordering << "' is an incorrect value of the '" << attrName
2244            << "' attribute";
2245   }
2246 
2247   auto value = static_cast<int64_t>(kind.getValue());
2248   auto attr = parser.getBuilder().getI64IntegerAttr(value);
2249   result.addAttribute(attrName, attr);
2250 
2251   return success();
2252 }
2253 
2254 //===----------------------------------------------------------------------===//
2255 // Printer, parser and verifier for LLVM::AtomicRMWOp.
2256 //===----------------------------------------------------------------------===//
2257 
2258 void AtomicRMWOp::print(OpAsmPrinter &p) {
2259   p << ' ' << stringifyAtomicBinOp(getBinOp()) << ' ' << getPtr() << ", "
2260     << getVal() << ' ' << stringifyAtomicOrdering(getOrdering()) << ' ';
2261   p.printOptionalAttrDict((*this)->getAttrs(), {"bin_op", "ordering"});
2262   p << " : " << getRes().getType();
2263 }
2264 
2265 // <operation> ::= `llvm.atomicrmw` keyword ssa-use `,` ssa-use keyword
2266 //                 attribute-dict? `:` type
2267 ParseResult AtomicRMWOp::parse(OpAsmParser &parser, OperationState &result) {
2268   Type type;
2269   OpAsmParser::OperandType ptr, val;
2270   if (parseAtomicBinOp(parser, result, "bin_op") || parser.parseOperand(ptr) ||
2271       parser.parseComma() || parser.parseOperand(val) ||
2272       parseAtomicOrdering(parser, result, "ordering") ||
2273       parser.parseOptionalAttrDict(result.attributes) ||
2274       parser.parseColonType(type) ||
2275       parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type),
2276                             result.operands) ||
2277       parser.resolveOperand(val, type, result.operands))
2278     return failure();
2279 
2280   result.addTypes(type);
2281   return success();
2282 }
2283 
2284 LogicalResult AtomicRMWOp::verify() {
2285   auto ptrType = getPtr().getType().cast<LLVM::LLVMPointerType>();
2286   auto valType = getVal().getType();
2287   if (valType != ptrType.getElementType())
2288     return emitOpError("expected LLVM IR element type for operand #0 to "
2289                        "match type for operand #1");
2290   auto resType = getRes().getType();
2291   if (resType != valType)
2292     return emitOpError(
2293         "expected LLVM IR result type to match type for operand #1");
2294   if (getBinOp() == AtomicBinOp::fadd || getBinOp() == AtomicBinOp::fsub) {
2295     if (!mlir::LLVM::isCompatibleFloatingPointType(valType))
2296       return emitOpError("expected LLVM IR floating point type");
2297   } else if (getBinOp() == AtomicBinOp::xchg) {
2298     auto intType = valType.dyn_cast<IntegerType>();
2299     unsigned intBitWidth = intType ? intType.getWidth() : 0;
2300     if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 &&
2301         intBitWidth != 64 && !valType.isa<BFloat16Type>() &&
2302         !valType.isa<Float16Type>() && !valType.isa<Float32Type>() &&
2303         !valType.isa<Float64Type>())
2304       return emitOpError("unexpected LLVM IR type for 'xchg' bin_op");
2305   } else {
2306     auto intType = valType.dyn_cast<IntegerType>();
2307     unsigned intBitWidth = intType ? intType.getWidth() : 0;
2308     if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 &&
2309         intBitWidth != 64)
2310       return emitOpError("expected LLVM IR integer type");
2311   }
2312 
2313   if (static_cast<unsigned>(getOrdering()) <
2314       static_cast<unsigned>(AtomicOrdering::monotonic))
2315     return emitOpError() << "expected at least '"
2316                          << stringifyAtomicOrdering(AtomicOrdering::monotonic)
2317                          << "' ordering";
2318 
2319   return success();
2320 }
2321 
2322 //===----------------------------------------------------------------------===//
2323 // Printer, parser and verifier for LLVM::AtomicCmpXchgOp.
2324 //===----------------------------------------------------------------------===//
2325 
2326 void AtomicCmpXchgOp::print(OpAsmPrinter &p) {
2327   p << ' ' << getPtr() << ", " << getCmp() << ", " << getVal() << ' '
2328     << stringifyAtomicOrdering(getSuccessOrdering()) << ' '
2329     << stringifyAtomicOrdering(getFailureOrdering());
2330   p.printOptionalAttrDict((*this)->getAttrs(),
2331                           {"success_ordering", "failure_ordering"});
2332   p << " : " << getVal().getType();
2333 }
2334 
2335 // <operation> ::= `llvm.cmpxchg` ssa-use `,` ssa-use `,` ssa-use
2336 //                 keyword keyword attribute-dict? `:` type
2337 ParseResult AtomicCmpXchgOp::parse(OpAsmParser &parser,
2338                                    OperationState &result) {
2339   auto &builder = parser.getBuilder();
2340   Type type;
2341   OpAsmParser::OperandType ptr, cmp, val;
2342   if (parser.parseOperand(ptr) || parser.parseComma() ||
2343       parser.parseOperand(cmp) || parser.parseComma() ||
2344       parser.parseOperand(val) ||
2345       parseAtomicOrdering(parser, result, "success_ordering") ||
2346       parseAtomicOrdering(parser, result, "failure_ordering") ||
2347       parser.parseOptionalAttrDict(result.attributes) ||
2348       parser.parseColonType(type) ||
2349       parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type),
2350                             result.operands) ||
2351       parser.resolveOperand(cmp, type, result.operands) ||
2352       parser.resolveOperand(val, type, result.operands))
2353     return failure();
2354 
2355   auto boolType = IntegerType::get(builder.getContext(), 1);
2356   auto resultType =
2357       LLVMStructType::getLiteral(builder.getContext(), {type, boolType});
2358   result.addTypes(resultType);
2359 
2360   return success();
2361 }
2362 
2363 LogicalResult AtomicCmpXchgOp::verify() {
2364   auto ptrType = getPtr().getType().cast<LLVM::LLVMPointerType>();
2365   if (!ptrType)
2366     return emitOpError("expected LLVM IR pointer type for operand #0");
2367   auto cmpType = getCmp().getType();
2368   auto valType = getVal().getType();
2369   if (cmpType != ptrType.getElementType() || cmpType != valType)
2370     return emitOpError("expected LLVM IR element type for operand #0 to "
2371                        "match type for all other operands");
2372   auto intType = valType.dyn_cast<IntegerType>();
2373   unsigned intBitWidth = intType ? intType.getWidth() : 0;
2374   if (!valType.isa<LLVMPointerType>() && intBitWidth != 8 &&
2375       intBitWidth != 16 && intBitWidth != 32 && intBitWidth != 64 &&
2376       !valType.isa<BFloat16Type>() && !valType.isa<Float16Type>() &&
2377       !valType.isa<Float32Type>() && !valType.isa<Float64Type>())
2378     return emitOpError("unexpected LLVM IR type");
2379   if (getSuccessOrdering() < AtomicOrdering::monotonic ||
2380       getFailureOrdering() < AtomicOrdering::monotonic)
2381     return emitOpError("ordering must be at least 'monotonic'");
2382   if (getFailureOrdering() == AtomicOrdering::release ||
2383       getFailureOrdering() == AtomicOrdering::acq_rel)
2384     return emitOpError("failure ordering cannot be 'release' or 'acq_rel'");
2385   return success();
2386 }
2387 
2388 //===----------------------------------------------------------------------===//
2389 // Printer, parser and verifier for LLVM::FenceOp.
2390 //===----------------------------------------------------------------------===//
2391 
2392 // <operation> ::= `llvm.fence` (`syncscope(`strAttr`)`)? keyword
2393 // attribute-dict?
2394 ParseResult FenceOp::parse(OpAsmParser &parser, OperationState &result) {
2395   StringAttr sScope;
2396   StringRef syncscopeKeyword = "syncscope";
2397   if (!failed(parser.parseOptionalKeyword(syncscopeKeyword))) {
2398     if (parser.parseLParen() ||
2399         parser.parseAttribute(sScope, syncscopeKeyword, result.attributes) ||
2400         parser.parseRParen())
2401       return failure();
2402   } else {
2403     result.addAttribute(syncscopeKeyword,
2404                         parser.getBuilder().getStringAttr(""));
2405   }
2406   if (parseAtomicOrdering(parser, result, "ordering") ||
2407       parser.parseOptionalAttrDict(result.attributes))
2408     return failure();
2409   return success();
2410 }
2411 
2412 void FenceOp::print(OpAsmPrinter &p) {
2413   StringRef syncscopeKeyword = "syncscope";
2414   p << ' ';
2415   if (!(*this)->getAttr(syncscopeKeyword).cast<StringAttr>().getValue().empty())
2416     p << "syncscope(" << (*this)->getAttr(syncscopeKeyword) << ") ";
2417   p << stringifyAtomicOrdering(getOrdering());
2418 }
2419 
2420 LogicalResult FenceOp::verify() {
2421   if (getOrdering() == AtomicOrdering::not_atomic ||
2422       getOrdering() == AtomicOrdering::unordered ||
2423       getOrdering() == AtomicOrdering::monotonic)
2424     return emitOpError("can be given only acquire, release, acq_rel, "
2425                        "and seq_cst orderings");
2426   return success();
2427 }
2428 
2429 //===----------------------------------------------------------------------===//
2430 // Folder for LLVM::BitcastOp
2431 //===----------------------------------------------------------------------===//
2432 
2433 OpFoldResult LLVM::BitcastOp::fold(ArrayRef<Attribute> operands) {
2434   // bitcast(x : T0, T0) -> x
2435   if (getArg().getType() == getType())
2436     return getArg();
2437   // bitcast(bitcast(x : T0, T1), T0) -> x
2438   if (auto prev = getArg().getDefiningOp<BitcastOp>())
2439     if (prev.getArg().getType() == getType())
2440       return prev.getArg();
2441   return {};
2442 }
2443 
2444 //===----------------------------------------------------------------------===//
2445 // Folder for LLVM::AddrSpaceCastOp
2446 //===----------------------------------------------------------------------===//
2447 
2448 OpFoldResult LLVM::AddrSpaceCastOp::fold(ArrayRef<Attribute> operands) {
2449   // addrcast(x : T0, T0) -> x
2450   if (getArg().getType() == getType())
2451     return getArg();
2452   // addrcast(addrcast(x : T0, T1), T0) -> x
2453   if (auto prev = getArg().getDefiningOp<AddrSpaceCastOp>())
2454     if (prev.getArg().getType() == getType())
2455       return prev.getArg();
2456   return {};
2457 }
2458 
2459 //===----------------------------------------------------------------------===//
2460 // Folder for LLVM::GEPOp
2461 //===----------------------------------------------------------------------===//
2462 
2463 OpFoldResult LLVM::GEPOp::fold(ArrayRef<Attribute> operands) {
2464   // gep %x:T, 0 -> %x
2465   if (getBase().getType() == getType() && getIndices().size() == 1 &&
2466       matchPattern(getIndices()[0], m_Zero()))
2467     return getBase();
2468   return {};
2469 }
2470 
2471 //===----------------------------------------------------------------------===//
2472 // LLVMDialect initialization, type parsing, and registration.
2473 //===----------------------------------------------------------------------===//
2474 
2475 void LLVMDialect::initialize() {
2476   addAttributes<FMFAttr, LinkageAttr, LoopOptionsAttr>();
2477 
2478   // clang-format off
2479   addTypes<LLVMVoidType,
2480            LLVMPPCFP128Type,
2481            LLVMX86MMXType,
2482            LLVMTokenType,
2483            LLVMLabelType,
2484            LLVMMetadataType,
2485            LLVMFunctionType,
2486            LLVMPointerType,
2487            LLVMFixedVectorType,
2488            LLVMScalableVectorType,
2489            LLVMArrayType,
2490            LLVMStructType>();
2491   // clang-format on
2492   addOperations<
2493 #define GET_OP_LIST
2494 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc"
2495       >();
2496 
2497   // Support unknown operations because not all LLVM operations are registered.
2498   allowUnknownOperations();
2499 }
2500 
2501 #define GET_OP_CLASSES
2502 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc"
2503 
2504 /// Parse a type registered to this dialect.
2505 Type LLVMDialect::parseType(DialectAsmParser &parser) const {
2506   return detail::parseType(parser);
2507 }
2508 
2509 /// Print a type registered to this dialect.
2510 void LLVMDialect::printType(Type type, DialectAsmPrinter &os) const {
2511   return detail::printType(type, os);
2512 }
2513 
2514 LogicalResult LLVMDialect::verifyDataLayoutString(
2515     StringRef descr, llvm::function_ref<void(const Twine &)> reportError) {
2516   llvm::Expected<llvm::DataLayout> maybeDataLayout =
2517       llvm::DataLayout::parse(descr);
2518   if (maybeDataLayout)
2519     return success();
2520 
2521   std::string message;
2522   llvm::raw_string_ostream messageStream(message);
2523   llvm::logAllUnhandledErrors(maybeDataLayout.takeError(), messageStream);
2524   reportError("invalid data layout descriptor: " + messageStream.str());
2525   return failure();
2526 }
2527 
2528 /// Verify LLVM dialect attributes.
2529 LogicalResult LLVMDialect::verifyOperationAttribute(Operation *op,
2530                                                     NamedAttribute attr) {
2531   // If the `llvm.loop` attribute is present, enforce the following structure,
2532   // which the module translation can assume.
2533   if (attr.getName() == LLVMDialect::getLoopAttrName()) {
2534     auto loopAttr = attr.getValue().dyn_cast<DictionaryAttr>();
2535     if (!loopAttr)
2536       return op->emitOpError() << "expected '" << LLVMDialect::getLoopAttrName()
2537                                << "' to be a dictionary attribute";
2538     Optional<NamedAttribute> parallelAccessGroup =
2539         loopAttr.getNamed(LLVMDialect::getParallelAccessAttrName());
2540     if (parallelAccessGroup.hasValue()) {
2541       auto accessGroups = parallelAccessGroup->getValue().dyn_cast<ArrayAttr>();
2542       if (!accessGroups)
2543         return op->emitOpError()
2544                << "expected '" << LLVMDialect::getParallelAccessAttrName()
2545                << "' to be an array attribute";
2546       for (Attribute attr : accessGroups) {
2547         auto accessGroupRef = attr.dyn_cast<SymbolRefAttr>();
2548         if (!accessGroupRef)
2549           return op->emitOpError()
2550                  << "expected '" << attr << "' to be a symbol reference";
2551         StringAttr metadataName = accessGroupRef.getRootReference();
2552         auto metadataOp =
2553             SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
2554                 op->getParentOp(), metadataName);
2555         if (!metadataOp)
2556           return op->emitOpError()
2557                  << "expected '" << attr << "' to reference a metadata op";
2558         StringAttr accessGroupName = accessGroupRef.getLeafReference();
2559         Operation *accessGroupOp =
2560             SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
2561         if (!accessGroupOp)
2562           return op->emitOpError()
2563                  << "expected '" << attr << "' to reference an access_group op";
2564       }
2565     }
2566 
2567     Optional<NamedAttribute> loopOptions =
2568         loopAttr.getNamed(LLVMDialect::getLoopOptionsAttrName());
2569     if (loopOptions.hasValue() &&
2570         !loopOptions->getValue().isa<LoopOptionsAttr>())
2571       return op->emitOpError()
2572              << "expected '" << LLVMDialect::getLoopOptionsAttrName()
2573              << "' to be a `loopopts` attribute";
2574   }
2575 
2576   // If the data layout attribute is present, it must use the LLVM data layout
2577   // syntax. Try parsing it and report errors in case of failure. Users of this
2578   // attribute may assume it is well-formed and can pass it to the (asserting)
2579   // llvm::DataLayout constructor.
2580   if (attr.getName() != LLVM::LLVMDialect::getDataLayoutAttrName())
2581     return success();
2582   if (auto stringAttr = attr.getValue().dyn_cast<StringAttr>())
2583     return verifyDataLayoutString(
2584         stringAttr.getValue(),
2585         [op](const Twine &message) { op->emitOpError() << message.str(); });
2586 
2587   return op->emitOpError() << "expected '"
2588                            << LLVM::LLVMDialect::getDataLayoutAttrName()
2589                            << "' to be a string attribute";
2590 }
2591 
2592 /// Verify LLVMIR function argument attributes.
2593 LogicalResult LLVMDialect::verifyRegionArgAttribute(Operation *op,
2594                                                     unsigned regionIdx,
2595                                                     unsigned argIdx,
2596                                                     NamedAttribute argAttr) {
2597   // Check that llvm.noalias is a unit attribute.
2598   if (argAttr.getName() == LLVMDialect::getNoAliasAttrName() &&
2599       !argAttr.getValue().isa<UnitAttr>())
2600     return op->emitError()
2601            << "expected llvm.noalias argument attribute to be a unit attribute";
2602   // Check that llvm.align is an integer attribute.
2603   if (argAttr.getName() == LLVMDialect::getAlignAttrName() &&
2604       !argAttr.getValue().isa<IntegerAttr>())
2605     return op->emitError()
2606            << "llvm.align argument attribute of non integer type";
2607   return success();
2608 }
2609 
2610 //===----------------------------------------------------------------------===//
2611 // Utility functions.
2612 //===----------------------------------------------------------------------===//
2613 
2614 Value mlir::LLVM::createGlobalString(Location loc, OpBuilder &builder,
2615                                      StringRef name, StringRef value,
2616                                      LLVM::Linkage linkage) {
2617   assert(builder.getInsertionBlock() &&
2618          builder.getInsertionBlock()->getParentOp() &&
2619          "expected builder to point to a block constrained in an op");
2620   auto module =
2621       builder.getInsertionBlock()->getParentOp()->getParentOfType<ModuleOp>();
2622   assert(module && "builder points to an op outside of a module");
2623 
2624   // Create the global at the entry of the module.
2625   OpBuilder moduleBuilder(module.getBodyRegion(), builder.getListener());
2626   MLIRContext *ctx = builder.getContext();
2627   auto type = LLVM::LLVMArrayType::get(IntegerType::get(ctx, 8), value.size());
2628   auto global = moduleBuilder.create<LLVM::GlobalOp>(
2629       loc, type, /*isConstant=*/true, linkage, name,
2630       builder.getStringAttr(value), /*alignment=*/0);
2631 
2632   // Get the pointer to the first character in the global string.
2633   Value globalPtr = builder.create<LLVM::AddressOfOp>(loc, global);
2634   Value cst0 = builder.create<LLVM::ConstantOp>(
2635       loc, IntegerType::get(ctx, 64),
2636       builder.getIntegerAttr(builder.getIndexType(), 0));
2637   return builder.create<LLVM::GEPOp>(
2638       loc, LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)), globalPtr,
2639       ValueRange{cst0, cst0});
2640 }
2641 
2642 bool mlir::LLVM::satisfiesLLVMModule(Operation *op) {
2643   return op->hasTrait<OpTrait::SymbolTable>() &&
2644          op->hasTrait<OpTrait::IsIsolatedFromAbove>();
2645 }
2646 
2647 static constexpr const FastmathFlags fastmathFlagsList[] = {
2648     // clang-format off
2649     FastmathFlags::nnan,
2650     FastmathFlags::ninf,
2651     FastmathFlags::nsz,
2652     FastmathFlags::arcp,
2653     FastmathFlags::contract,
2654     FastmathFlags::afn,
2655     FastmathFlags::reassoc,
2656     FastmathFlags::fast,
2657     // clang-format on
2658 };
2659 
2660 void FMFAttr::print(AsmPrinter &printer) const {
2661   printer << "<";
2662   auto flags = llvm::make_filter_range(fastmathFlagsList, [&](auto flag) {
2663     return bitEnumContains(this->getFlags(), flag);
2664   });
2665   llvm::interleaveComma(flags, printer,
2666                         [&](auto flag) { printer << stringifyEnum(flag); });
2667   printer << ">";
2668 }
2669 
2670 Attribute FMFAttr::parse(AsmParser &parser, Type type) {
2671   if (failed(parser.parseLess()))
2672     return {};
2673 
2674   FastmathFlags flags = {};
2675   if (failed(parser.parseOptionalGreater())) {
2676     do {
2677       StringRef elemName;
2678       if (failed(parser.parseKeyword(&elemName)))
2679         return {};
2680 
2681       auto elem = symbolizeFastmathFlags(elemName);
2682       if (!elem) {
2683         parser.emitError(parser.getNameLoc(), "Unknown fastmath flag: ")
2684             << elemName;
2685         return {};
2686       }
2687 
2688       flags = flags | *elem;
2689     } while (succeeded(parser.parseOptionalComma()));
2690 
2691     if (failed(parser.parseGreater()))
2692       return {};
2693   }
2694 
2695   return FMFAttr::get(parser.getContext(), flags);
2696 }
2697 
2698 void LinkageAttr::print(AsmPrinter &printer) const {
2699   printer << "<";
2700   if (static_cast<uint64_t>(getLinkage()) <= getMaxEnumValForLinkage())
2701     printer << stringifyEnum(getLinkage());
2702   else
2703     printer << static_cast<uint64_t>(getLinkage());
2704   printer << ">";
2705 }
2706 
2707 Attribute LinkageAttr::parse(AsmParser &parser, Type type) {
2708   StringRef elemName;
2709   if (parser.parseLess() || parser.parseKeyword(&elemName) ||
2710       parser.parseGreater())
2711     return {};
2712   auto elem = linkage::symbolizeLinkage(elemName);
2713   if (!elem) {
2714     parser.emitError(parser.getNameLoc(), "Unknown linkage: ") << elemName;
2715     return {};
2716   }
2717   Linkage linkage = *elem;
2718   return LinkageAttr::get(parser.getContext(), linkage);
2719 }
2720 
2721 LoopOptionsAttrBuilder::LoopOptionsAttrBuilder(LoopOptionsAttr attr)
2722     : options(attr.getOptions().begin(), attr.getOptions().end()) {}
2723 
2724 template <typename T>
2725 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setOption(LoopOptionCase tag,
2726                                                           Optional<T> value) {
2727   auto option = llvm::find_if(
2728       options, [tag](auto option) { return option.first == tag; });
2729   if (option != options.end()) {
2730     if (value.hasValue())
2731       option->second = *value;
2732     else
2733       options.erase(option);
2734   } else {
2735     options.push_back(LoopOptionsAttr::OptionValuePair(tag, *value));
2736   }
2737   return *this;
2738 }
2739 
2740 LoopOptionsAttrBuilder &
2741 LoopOptionsAttrBuilder::setDisableLICM(Optional<bool> value) {
2742   return setOption(LoopOptionCase::disable_licm, value);
2743 }
2744 
2745 /// Set the `interleave_count` option to the provided value. If no value
2746 /// is provided the option is deleted.
2747 LoopOptionsAttrBuilder &
2748 LoopOptionsAttrBuilder::setInterleaveCount(Optional<uint64_t> count) {
2749   return setOption(LoopOptionCase::interleave_count, count);
2750 }
2751 
2752 /// Set the `disable_unroll` option to the provided value. If no value
2753 /// is provided the option is deleted.
2754 LoopOptionsAttrBuilder &
2755 LoopOptionsAttrBuilder::setDisableUnroll(Optional<bool> value) {
2756   return setOption(LoopOptionCase::disable_unroll, value);
2757 }
2758 
2759 /// Set the `disable_pipeline` option to the provided value. If no value
2760 /// is provided the option is deleted.
2761 LoopOptionsAttrBuilder &
2762 LoopOptionsAttrBuilder::setDisablePipeline(Optional<bool> value) {
2763   return setOption(LoopOptionCase::disable_pipeline, value);
2764 }
2765 
2766 /// Set the `pipeline_initiation_interval` option to the provided value.
2767 /// If no value is provided the option is deleted.
2768 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setPipelineInitiationInterval(
2769     Optional<uint64_t> count) {
2770   return setOption(LoopOptionCase::pipeline_initiation_interval, count);
2771 }
2772 
2773 template <typename T>
2774 static Optional<T>
2775 getOption(ArrayRef<std::pair<LoopOptionCase, int64_t>> options,
2776           LoopOptionCase option) {
2777   auto it =
2778       lower_bound(options, option, [](auto optionPair, LoopOptionCase option) {
2779         return optionPair.first < option;
2780       });
2781   if (it == options.end())
2782     return {};
2783   return static_cast<T>(it->second);
2784 }
2785 
2786 Optional<bool> LoopOptionsAttr::disableUnroll() {
2787   return getOption<bool>(getOptions(), LoopOptionCase::disable_unroll);
2788 }
2789 
2790 Optional<bool> LoopOptionsAttr::disableLICM() {
2791   return getOption<bool>(getOptions(), LoopOptionCase::disable_licm);
2792 }
2793 
2794 Optional<int64_t> LoopOptionsAttr::interleaveCount() {
2795   return getOption<int64_t>(getOptions(), LoopOptionCase::interleave_count);
2796 }
2797 
2798 /// Build the LoopOptions Attribute from a sorted array of individual options.
2799 LoopOptionsAttr LoopOptionsAttr::get(
2800     MLIRContext *context,
2801     ArrayRef<std::pair<LoopOptionCase, int64_t>> sortedOptions) {
2802   assert(llvm::is_sorted(sortedOptions, llvm::less_first()) &&
2803          "LoopOptionsAttr ctor expects a sorted options array");
2804   return Base::get(context, sortedOptions);
2805 }
2806 
2807 /// Build the LoopOptions Attribute from a sorted array of individual options.
2808 LoopOptionsAttr LoopOptionsAttr::get(MLIRContext *context,
2809                                      LoopOptionsAttrBuilder &optionBuilders) {
2810   llvm::sort(optionBuilders.options, llvm::less_first());
2811   return Base::get(context, optionBuilders.options);
2812 }
2813 
2814 void LoopOptionsAttr::print(AsmPrinter &printer) const {
2815   printer << "<";
2816   llvm::interleaveComma(getOptions(), printer, [&](auto option) {
2817     printer << stringifyEnum(option.first) << " = ";
2818     switch (option.first) {
2819     case LoopOptionCase::disable_licm:
2820     case LoopOptionCase::disable_unroll:
2821     case LoopOptionCase::disable_pipeline:
2822       printer << (option.second ? "true" : "false");
2823       break;
2824     case LoopOptionCase::interleave_count:
2825     case LoopOptionCase::pipeline_initiation_interval:
2826       printer << option.second;
2827       break;
2828     }
2829   });
2830   printer << ">";
2831 }
2832 
2833 Attribute LoopOptionsAttr::parse(AsmParser &parser, Type type) {
2834   if (failed(parser.parseLess()))
2835     return {};
2836 
2837   SmallVector<std::pair<LoopOptionCase, int64_t>> options;
2838   llvm::SmallDenseSet<LoopOptionCase> seenOptions;
2839   do {
2840     StringRef optionName;
2841     if (parser.parseKeyword(&optionName))
2842       return {};
2843 
2844     auto option = symbolizeLoopOptionCase(optionName);
2845     if (!option) {
2846       parser.emitError(parser.getNameLoc(), "unknown loop option: ")
2847           << optionName;
2848       return {};
2849     }
2850     if (!seenOptions.insert(*option).second) {
2851       parser.emitError(parser.getNameLoc(), "loop option present twice");
2852       return {};
2853     }
2854     if (failed(parser.parseEqual()))
2855       return {};
2856 
2857     int64_t value;
2858     switch (*option) {
2859     case LoopOptionCase::disable_licm:
2860     case LoopOptionCase::disable_unroll:
2861     case LoopOptionCase::disable_pipeline:
2862       if (succeeded(parser.parseOptionalKeyword("true")))
2863         value = 1;
2864       else if (succeeded(parser.parseOptionalKeyword("false")))
2865         value = 0;
2866       else {
2867         parser.emitError(parser.getNameLoc(),
2868                          "expected boolean value 'true' or 'false'");
2869         return {};
2870       }
2871       break;
2872     case LoopOptionCase::interleave_count:
2873     case LoopOptionCase::pipeline_initiation_interval:
2874       if (failed(parser.parseInteger(value))) {
2875         parser.emitError(parser.getNameLoc(), "expected integer value");
2876         return {};
2877       }
2878       break;
2879     }
2880     options.push_back(std::make_pair(*option, value));
2881   } while (succeeded(parser.parseOptionalComma()));
2882   if (failed(parser.parseGreater()))
2883     return {};
2884 
2885   llvm::sort(options, llvm::less_first());
2886   return get(parser.getContext(), options);
2887 }
2888