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