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