} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc();
- lowerOpToLoops(
- op, operands, rewriter,
- [loc](OpBuilder &builder, ValueRange memRefOperands,
- ValueRange loopIvs) {
- // Generate an adaptor for the remapped operands of the BinaryOp. This
- // allows for using the nice named accessors that are generated by the
- // ODS.
- typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
-
- // Generate loads for the element of 'lhs' and 'rhs' at the inner
- // loop.
- auto loadedLhs = builder.create<AffineLoadOp>(
- loc, binaryAdaptor.getLhs(), loopIvs);
- auto loadedRhs = builder.create<AffineLoadOp>(
- loc, binaryAdaptor.getRhs(), loopIvs);
-
- // Create the binary operation performed on the loaded values.
- return builder.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs);
- });
+ lowerOpToLoops(op, operands, rewriter,
+ [loc](OpBuilder &builder, ValueRange memRefOperands,
+ ValueRange loopIvs) {
+ // Generate an adaptor for the remapped operands of the
+ // BinaryOp. This allows for using the nice named accessors
+ // that are generated by the ODS.
+ typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
+
+ // Generate loads for the element of 'lhs' and 'rhs' at the
+ // inner loop.
+ auto loadedLhs = builder.create<AffineLoadOp>(
+ loc, binaryAdaptor.getLhs(), loopIvs);
+ auto loadedRhs = builder.create<AffineLoadOp>(
+ loc, binaryAdaptor.getRhs(), loopIvs);
+
+ // Create the binary operation performed on the loaded
+ // values.
+ return builder.create<LoweredBinaryOp>(loc, loadedLhs,
+ loadedRhs);
+ });
return success();
}
};
} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc();
- lowerOpToLoops(
- op, operands, rewriter,
- [loc](OpBuilder &builder, ValueRange memRefOperands,
- ValueRange loopIvs) {
- // Generate an adaptor for the remapped operands of the BinaryOp. This
- // allows for using the nice named accessors that are generated by the
- // ODS.
- typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
-
- // Generate loads for the element of 'lhs' and 'rhs' at the inner
- // loop.
- auto loadedLhs = builder.create<AffineLoadOp>(
- loc, binaryAdaptor.getLhs(), loopIvs);
- auto loadedRhs = builder.create<AffineLoadOp>(
- loc, binaryAdaptor.getRhs(), loopIvs);
-
- // Create the binary operation performed on the loaded values.
- return builder.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs);
- });
+ lowerOpToLoops(op, operands, rewriter,
+ [loc](OpBuilder &builder, ValueRange memRefOperands,
+ ValueRange loopIvs) {
+ // Generate an adaptor for the remapped operands of the
+ // BinaryOp. This allows for using the nice named accessors
+ // that are generated by the ODS.
+ typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
+
+ // Generate loads for the element of 'lhs' and 'rhs' at the
+ // inner loop.
+ auto loadedLhs = builder.create<AffineLoadOp>(
+ loc, binaryAdaptor.getLhs(), loopIvs);
+ auto loadedRhs = builder.create<AffineLoadOp>(
+ loc, binaryAdaptor.getRhs(), loopIvs);
+
+ // Create the binary operation performed on the loaded
+ // values.
+ return builder.create<LoweredBinaryOp>(loc, loadedLhs,
+ loadedRhs);
+ });
return success();
}
};
} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc();
- lowerOpToLoops(
- op, operands, rewriter,
- [loc](OpBuilder &builder, ValueRange memRefOperands,
- ValueRange loopIvs) {
- // Generate an adaptor for the remapped operands of the BinaryOp. This
- // allows for using the nice named accessors that are generated by the
- // ODS.
- typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
-
- // Generate loads for the element of 'lhs' and 'rhs' at the inner
- // loop.
- auto loadedLhs = builder.create<AffineLoadOp>(
- loc, binaryAdaptor.getLhs(), loopIvs);
- auto loadedRhs = builder.create<AffineLoadOp>(
- loc, binaryAdaptor.getRhs(), loopIvs);
-
- // Create the binary operation performed on the loaded values.
- return builder.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs);
- });
+ lowerOpToLoops(op, operands, rewriter,
+ [loc](OpBuilder &builder, ValueRange memRefOperands,
+ ValueRange loopIvs) {
+ // Generate an adaptor for the remapped operands of the
+ // BinaryOp. This allows for using the nice named accessors
+ // that are generated by the ODS.
+ typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
+
+ // Generate loads for the element of 'lhs' and 'rhs' at the
+ // inner loop.
+ auto loadedLhs = builder.create<AffineLoadOp>(
+ loc, binaryAdaptor.getLhs(), loopIvs);
+ auto loadedRhs = builder.create<AffineLoadOp>(
+ loc, binaryAdaptor.getRhs(), loopIvs);
+
+ // Create the binary operation performed on the loaded
+ // values.
+ return builder.create<LoweredBinaryOp>(loc, loadedLhs,
+ loadedRhs);
+ });
return success();
}
};
} // namespace
/// Return a formatted string for the location of any node
-template <typename T> static std::string loc(T *node) {
+template <typename T>
+static std::string loc(T *node) {
const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col))
/// `ImplT`. A model is instantiated for each alias analysis implementation
/// to implement the `Concept` without the need for the derived
/// implementation to inherit from the `Concept` class.
- template <typename ImplT> class Model final : public Concept {
+ template <typename ImplT>
+ class Model final : public Concept {
public:
explicit Model(ImplT &&impl) : impl(std::forward<ImplT>(impl)) {}
~Model() override = default;
namespace llvm {
// Provide graph traits for traversing call graphs using standard graph
// traversals.
-template <> struct GraphTraits<const mlir::CallGraphNode *> {
+template <>
+struct GraphTraits<const mlir::CallGraphNode *> {
using NodeRef = mlir::CallGraphNode *;
static NodeRef getEntryNode(NodeRef node) { return node; }
}
template <typename Func, typename... Extra>
- pure_subclass &def(const char *name, Func &&f, const Extra &... extra) {
+ pure_subclass &def(const char *name, Func &&f, const Extra &...extra) {
py::cpp_function cf(
std::forward<Func>(f), py::name(name), py::is_method(thisClass),
py::sibling(py::getattr(thisClass, name, py::none())), extra...);
template <typename Func, typename... Extra>
pure_subclass &def_property_readonly(const char *name, Func &&f,
- const Extra &... extra) {
+ const Extra &...extra) {
py::cpp_function cf(
std::forward<Func>(f), py::name(name), py::is_method(thisClass),
py::sibling(py::getattr(thisClass, name, py::none())), extra...);
template <typename Func, typename... Extra>
pure_subclass &def_staticmethod(const char *name, Func &&f,
- const Extra &... extra) {
+ const Extra &...extra) {
static_assert(!std::is_member_function_pointer<Func>::value,
"def_staticmethod(...) called with a non-static member "
"function pointer");
template <typename Func, typename... Extra>
pure_subclass &def_classmethod(const char *name, Func &&f,
- const Extra &... extra) {
+ const Extra &...extra) {
static_assert(!std::is_member_function_pointer<Func>::value,
"def_classmethod(...) called with a non-static member "
"function pointer");
namespace mlir {
class ModuleOp;
-template <typename T> class OperationPass;
+template <typename T>
+class OperationPass;
std::unique_ptr<OperationPass<ModuleOp>>
createConvertVulkanLaunchFuncToVulkanCallsPass();
/// Allow the given dialects.
///
/// This function adds one or multiple ALLOW entries.
- template <typename... DialectTs> void allowDialect() {
+ template <typename... DialectTs>
+ void allowDialect() {
// The following expands a call to allowDialectImpl for each dialect
// in 'DialectTs'. This magic is necessary due to a limitation in the places
// that a parameter pack can be expanded in c++11.
/// Deny the given dialects.
///
/// This function adds one or multiple DENY entries.
- template <typename... DialectTs> void denyDialect() {
+ template <typename... DialectTs>
+ void denyDialect() {
// FIXME: In c++17 this can be simplified by using 'fold expressions'.
(void)std::initializer_list<int>{0, (denyDialectImpl<DialectTs>(), 0)...};
}
/// Allow the given ops.
///
/// This function adds one or multiple ALLOW entries.
- template <typename... OpTys> void allowOperation() {
+ template <typename... OpTys>
+ void allowOperation() {
// FIXME: In c++17 this can be simplified by using 'fold expressions'.
(void)std::initializer_list<int>{0, (allowOperationImpl<OpTys>(), 0)...};
}
/// Deny the given ops.
///
/// This function adds one or multiple DENY entries.
- template <typename... OpTys> void denyOperation() {
+ template <typename... OpTys>
+ void denyOperation() {
// FIXME: In c++17 this can be simplified by using 'fold expressions'.
(void)std::initializer_list<int>{0, (denyOperationImpl<OpTys>(), 0)...};
}
}
/// Allow a dialect.
- template <typename DialectT> void allowDialectImpl() {
+ template <typename DialectT>
+ void allowDialectImpl() {
allowDialect(DialectT::getDialectNamespace());
}
/// Deny a dialect.
- template <typename DialectT> void denyDialectImpl() {
+ template <typename DialectT>
+ void denyDialectImpl() {
denyDialect(DialectT::getDialectNamespace());
}
/// Allow an op.
- template <typename OpTy> void allowOperationImpl() {
+ template <typename OpTy>
+ void allowOperationImpl() {
allowOperation(OpTy::getOperationName());
}
/// Deny an op.
- template <typename OpTy> void denyOperationImpl() {
+ template <typename OpTy>
+ void denyOperationImpl() {
denyOperation(OpTy::getOperationName());
}
#include <memory>
namespace llvm {
-template <typename T> class Expected;
+template <typename T>
+class Expected;
class Module;
class ExecutionEngine;
class JITEventListener;
/// Coordinate-scheme method for adding a new element.
#define DECL_ADDELT(VNAME, V) \
MLIR_CRUNNERUTILS_EXPORT void *_mlir_ciface_addElt##VNAME( \
- void *coo, \
- StridedMemRefType<V, 0> *vref, StridedMemRefType<index_type, 1> *iref, \
+ void *coo, StridedMemRefType<V, 0> *vref, \
+ StridedMemRefType<index_type, 1> *iref, \
StridedMemRefType<index_type, 1> *pref);
FOREVERY_V(DECL_ADDELT)
#undef DECL_ADDELT
/// just as efficient as having your own switch instruction over the instruction
/// opcode.
-template <typename SubClass, typename RetTy = void> class AffineExprVisitor {
+template <typename SubClass, typename RetTy = void>
+class AffineExprVisitor {
//===--------------------------------------------------------------------===//
// Interface code - This is the public interface of the AffineExprVisitor
// that you use to visit affine expressions...
bool operator!() const { return impl == nullptr; }
- template <typename U> bool isa() const;
+ template <typename U>
+ bool isa() const;
template <typename First, typename Second, typename... Rest>
bool isa() const;
template <typename First, typename... Rest>
bool isa_and_nonnull() const;
- template <typename U> U dyn_cast() const;
- template <typename U> U dyn_cast_or_null() const;
- template <typename U> U cast() const;
+ template <typename U>
+ U dyn_cast() const;
+ template <typename U>
+ U dyn_cast_or_null() const;
+ template <typename U>
+ U cast() const;
// Support dyn_cast'ing Attribute to itself.
static bool classof(Attribute) { return true; }
return os;
}
-template <typename U> bool Attribute::isa() const {
+template <typename U>
+bool Attribute::isa() const {
assert(impl && "isa<> used on a null attribute.");
return U::classof(*this);
}
return impl && isa<First, Rest...>();
}
-template <typename U> U Attribute::dyn_cast() const {
+template <typename U>
+U Attribute::dyn_cast() const {
return isa<U>() ? U(impl) : U(nullptr);
}
-template <typename U> U Attribute::dyn_cast_or_null() const {
+template <typename U>
+U Attribute::dyn_cast_or_null() const {
return (impl && isa<U>()) ? U(impl) : U(nullptr);
}
-template <typename U> U Attribute::cast() const {
+template <typename U>
+U Attribute::cast() const {
assert(isa<U>());
return U(impl);
}
namespace llvm {
// Attribute hash just like pointers.
-template <> struct DenseMapInfo<mlir::Attribute> {
+template <>
+struct DenseMapInfo<mlir::Attribute> {
static mlir::Attribute getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer));
};
/// Allow LLVM to steal the low bits of Attributes.
-template <> struct PointerLikeTypeTraits<mlir::Attribute> {
+template <>
+struct PointerLikeTypeTraits<mlir::Attribute> {
static inline void *getAsVoidPointer(mlir::Attribute attr) {
return const_cast<void *>(attr.getAsOpaquePointer());
}
mlir::AttributeStorage *>::NumLowBitsAvailable;
};
-template <> struct DenseMapInfo<mlir::NamedAttribute> {
+template <>
+struct DenseMapInfo<mlir::NamedAttribute> {
static mlir::NamedAttribute getEmptyKey() {
auto emptyAttr = llvm::DenseMapInfo<mlir::Attribute>::getEmptyKey();
return mlir::NamedAttribute(emptyAttr, emptyAttr);
/// Lookup a mapped value within the map. This asserts the provided value
/// exists within the map.
- template <typename T> T lookup(T from) const {
+ template <typename T>
+ T lookup(T from) const {
auto result = lookupOrNull(from);
assert(result && "expected 'from' to be contained within the map");
return result;
static Block *unwrap(BlockOperand &value);
public:
-
/// Initializes the operand type iterator to the specified operand iterator.
PredecessorIterator(ValueUseIterator<BlockOperand> it)
: llvm::mapped_iterator<ValueUseIterator<BlockOperand>,
static OpT unwrap(Operation &op) { return cast<OpT>(op); }
public:
-
/// Initializes the iterator to the specified filter iterator.
op_iterator(op_filter_iterator<OpT, IteratorT> it)
: llvm::mapped_iterator<op_filter_iterator<OpT, IteratorT>,
};
} // namespace ilist_detail
-template <> struct ilist_traits<::mlir::Operation> {
+template <>
+struct ilist_traits<::mlir::Operation> {
using Operation = ::mlir::Operation;
using op_iterator = simple_ilist<Operation>::iterator;
}
/// Access the element at the given index.
- template <typename T> T at(uint64_t index) const {
+ template <typename T>
+ T at(uint64_t index) const {
if (isSplat)
index = 0;
return isContiguous ? conState.at<T>(index) : nonConState.at<T>(index);
ContiguousState(const void *firstEltPtr) : firstEltPtr(firstEltPtr) {}
/// Access the element at the given index.
- template <typename T> const T &at(uint64_t index) const {
+ template <typename T>
+ const T &at(uint64_t index) const {
return *(reinterpret_cast<const T *>(firstEltPtr) + index);
}
NonContiguousState(NonContiguousState &&other) = default;
/// Access the element at the given index.
- template <typename T> T at(uint64_t index) const {
+ template <typename T>
+ T at(uint64_t index) const {
auto *valueIt = static_cast<OpaqueIteratorValueBase<T> *>(iterator.get());
return valueIt->at(index);
}
};
/// Type trait detector that checks if a given type T is a complex type.
-template <typename T> struct is_complex_t : public std::false_type {};
+template <typename T>
+struct is_complex_t : public std::false_type {};
template <typename T>
struct is_complex_t<std::complex<T>> : public std::true_type {};
} // namespace detail
/// floating point type that can be used to access the underlying element
/// types of a DenseElementsAttr.
// TODO: Use std::disjunction when C++17 is supported.
- template <typename T> struct is_valid_cpp_fp_type {
+ template <typename T>
+ struct is_valid_cpp_fp_type {
/// The type is a valid floating point type if it is a builtin floating
/// point type, or is a potentially user defined floating point type. The
/// latter allows for supporting users that have custom types defined for
/// Stream in an Operation.
Diagnostic &operator<<(Operation &val);
- Diagnostic &operator<<(Operation *val) {
- return *this << *val;
- }
+ Diagnostic &operator<<(Operation *val) { return *this << *val; }
/// Append an operation with the given printing flags.
Diagnostic &appendOp(Operation &val, const OpPrintingFlags &flags);
/// Append arguments to the diagnostic.
template <typename Arg1, typename Arg2, typename... Args>
- Diagnostic &append(Arg1 &&arg1, Arg2 &&arg2, Args &&... args) {
+ Diagnostic &append(Arg1 &&arg1, Arg2 &&arg2, Args &&...args) {
append(std::forward<Arg1>(arg1));
return append(std::forward<Arg2>(arg2), std::forward<Args>(args)...);
}
/// Append one argument to the diagnostic.
- template <typename Arg> Diagnostic &append(Arg &&arg) {
+ template <typename Arg>
+ Diagnostic &append(Arg &&arg) {
*this << std::forward<Arg>(arg);
return *this;
}
}
/// Stream operator for new diagnostic arguments.
- template <typename Arg> InFlightDiagnostic &operator<<(Arg &&arg) & {
+ template <typename Arg>
+ InFlightDiagnostic &operator<<(Arg &&arg) & {
return append(std::forward<Arg>(arg));
}
- template <typename Arg> InFlightDiagnostic &&operator<<(Arg &&arg) && {
+ template <typename Arg>
+ InFlightDiagnostic &&operator<<(Arg &&arg) && {
return std::move(append(std::forward<Arg>(arg)));
}
/// Append arguments to the diagnostic.
- template <typename... Args> InFlightDiagnostic &append(Args &&... args) & {
+ template <typename... Args>
+ InFlightDiagnostic &append(Args &&...args) & {
assert(isActive() && "diagnostic not active");
if (isInFlight())
impl->append(std::forward<Args>(args)...);
return *this;
}
- template <typename... Args> InFlightDiagnostic &&append(Args &&... args) && {
+ template <typename... Args>
+ InFlightDiagnostic &&append(Args &&...args) && {
return std::move(append(std::forward<Args>(args)...));
}
/// the diagnostic arguments directly instead of relying on the returned
/// InFlightDiagnostic.
template <typename... Args>
-LogicalResult emitOptionalError(Optional<Location> loc, Args &&... args) {
+LogicalResult emitOptionalError(Optional<Location> loc, Args &&...args) {
if (loc)
return emitError(*loc).append(std::forward<Args>(args)...);
return failure();
}
template <typename... Args>
-LogicalResult emitOptionalWarning(Optional<Location> loc, Args &&... args) {
+LogicalResult emitOptionalWarning(Optional<Location> loc, Args &&...args) {
if (loc)
return emitWarning(*loc).append(std::forward<Args>(args)...);
return failure();
}
template <typename... Args>
-LogicalResult emitOptionalRemark(Optional<Location> loc, Args &&... args) {
+LogicalResult emitOptionalRemark(Optional<Location> loc, Args &&...args) {
if (loc)
return emitRemark(*loc).append(std::forward<Args>(args)...);
return failure();
protected:
/// Set the handler to manage via RAII.
- template <typename FuncTy> void setHandler(FuncTy &&handler) {
+ template <typename FuncTy>
+ void setHandler(FuncTy &&handler) {
auto &diagEngine = ctx->getDiagEngine();
if (handlerID)
diagEngine.eraseHandler(handlerID);
auto it = registeredInterfaces.find(interfaceID);
return it != registeredInterfaces.end() ? it->getSecond().get() : nullptr;
}
- template <typename InterfaceT> const InterfaceT *getRegisteredInterface() {
+ template <typename InterfaceT>
+ const InterfaceT *getRegisteredInterface() {
return static_cast<const InterfaceT *>(
getRegisteredInterface(InterfaceT::getInterfaceID()));
}
/// This method is used by derived classes to add their operations to the set.
///
- template <typename... Args> void addOperations() {
+ template <typename... Args>
+ void addOperations() {
(void)std::initializer_list<int>{
0, (RegisteredOperationName::insert<Args>(*this), 0)...};
}
/// Register a set of type classes with this dialect.
- template <typename... Args> void addTypes() {
+ template <typename... Args>
+ void addTypes() {
(void)std::initializer_list<int>{0, (addType<Args>(), 0)...};
}
void addType(TypeID typeID, AbstractType &&typeInfo);
/// Register a set of attribute classes with this dialect.
- template <typename... Args> void addAttributes() {
+ template <typename... Args>
+ void addAttributes() {
(void)std::initializer_list<int>{0, (addAttribute<Args>(), 0)...};
}
void operator=(Dialect &) = delete;
/// Register an attribute instance with this dialect.
- template <typename T> void addAttribute() {
+ template <typename T>
+ void addAttribute() {
// Add this attribute to the dialect and register it with the uniquer.
addAttribute(T::getTypeID(), AbstractAttribute::get<T>(*this));
detail::AttributeUniquer::registerAttribute<T>(context);
}
/// Register a type instance with this dialect.
- template <typename T> void addType() {
+ template <typename T>
+ void addType() {
// Add this type to the dialect and register it with the uniquer.
addType(T::getTypeID(), AbstractType::get<T>(*this));
detail::TypeUniquer::registerType<T>(context);
};
/// Iterator access to the held interfaces.
- template <typename InterfaceT> iterator<InterfaceT> interface_begin() const {
+ template <typename InterfaceT>
+ iterator<InterfaceT> interface_begin() const {
return iterator<InterfaceT>(orderedInterfaces.begin());
}
- template <typename InterfaceT> iterator<InterfaceT> interface_end() const {
+ template <typename InterfaceT>
+ iterator<InterfaceT> interface_end() const {
return iterator<InterfaceT>(orderedInterfaces.end());
}
namespace llvm {
// IntegerSet hash just like pointers.
-template <> struct DenseMapInfo<mlir::IntegerSet> {
+template <>
+struct DenseMapInfo<mlir::IntegerSet> {
static mlir::IntegerSet getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::IntegerSet(static_cast<mlir::IntegerSet::ImplType *>(pointer));
LocationAttr *operator->() const { return const_cast<LocationAttr *>(&impl); }
/// Type casting utilities on the underlying location.
- template <typename U> bool isa() const { return impl.isa<U>(); }
- template <typename U> U dyn_cast() const { return impl.dyn_cast<U>(); }
- template <typename U> U cast() const { return impl.cast<U>(); }
+ template <typename U>
+ bool isa() const {
+ return impl.isa<U>();
+ }
+ template <typename U>
+ U dyn_cast() const {
+ return impl.dyn_cast<U>();
+ }
+ template <typename U>
+ U cast() const {
+ return impl.cast<U>();
+ }
/// Comparison operators.
bool operator==(Location rhs) const { return impl == rhs.impl; }
namespace llvm {
// Type hash just like pointers.
-template <> struct DenseMapInfo<mlir::Location> {
+template <>
+struct DenseMapInfo<mlir::Location> {
static mlir::Location getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::Location::getFromOpaquePointer(pointer);
};
/// We align LocationStorage by 8, so allow LLVM to steal the low bits.
-template <> struct PointerLikeTypeTraits<mlir::Location> {
+template <>
+struct PointerLikeTypeTraits<mlir::Location> {
public:
static inline void *getAsVoidPointer(mlir::Location I) {
return const_cast<void *>(I.getAsOpaquePointer());
struct InterfaceTargetOrOpT {
using type = typename T::ConcreteEntity;
};
- template <typename T> struct InterfaceTargetOrOpT<T, false> {
+ template <typename T>
+ struct InterfaceTargetOrOpT<T, false> {
using type = ConcreteType;
};
/// A hook for static assertion that the external interface model T is
/// targeting the concrete type of this op. The model can also be a fallback
/// model that works for every op.
- template <typename T> static void checkInterfaceTarget() {
+ template <typename T>
+ static void checkInterfaceTarget() {
static_assert(std::is_same<typename InterfaceTargetOrOpT<T>::type,
ConcreteType>::value,
"attaching an interface to the wrong op kind");
std::enable_if_t<detect_has_print_method<AttrOrType>::value>
*sfinae = nullptr>
void printStrippedAttrOrType(ArrayRef<AttrOrType> attrOrTypes) {
- llvm::interleaveComma(attrOrTypes, getStream(),
- [this](AttrOrType attrOrType) {
- printStrippedAttrOrType(attrOrType);
- });
+ llvm::interleaveComma(
+ attrOrTypes, getStream(),
+ [this](AttrOrType attrOrType) { printStrippedAttrOrType(attrOrType); });
}
/// SFINAE for printing the provided attribute in the context of an operation
/// Returns true if the operation was registered with a particular trait, e.g.
/// hasTrait<OperandsAreSignlessIntegerLike>(). Returns false if the operation
/// is unregistered.
- template <template <typename T> class Trait> bool hasTrait() const {
+ template <template <typename T> class Trait>
+ bool hasTrait() const {
return hasTrait(TypeID::get<Trait>());
}
bool hasTrait(TypeID traitID) const {
/// Returns true if the operation *might* have the provided trait. This
/// means that either the operation is unregistered, or it was registered with
/// the provide trait.
- template <template <typename T> class Trait> bool mightHaveTrait() const {
+ template <template <typename T> class Trait>
+ bool mightHaveTrait() const {
return mightHaveTrait(TypeID::get<Trait>());
}
bool mightHaveTrait(TypeID traitID) const {
/// Returns an instance of the concept object for the given interface if it
/// was registered to this operation, null otherwise. This should not be used
/// directly.
- template <typename T> typename T::Concept *getInterface() const {
+ template <typename T>
+ typename T::Concept *getInterface() const {
return impl->interfaceMap.lookup<T>();
}
/// Returns true if this operation has the given interface registered to it.
- template <typename T> bool hasInterface() const {
+ template <typename T>
+ bool hasInterface() const {
return hasInterface(TypeID::get<T>());
}
bool hasInterface(TypeID interfaceID) const {
}
/// Returns true if the operation has a particular trait.
- template <template <typename T> class Trait> bool hasTrait() const {
+ template <template <typename T> class Trait>
+ bool hasTrait() const {
return hasTrait(TypeID::get<Trait>());
}
/// This method provides a convenient interface for creating and initializing
/// derived rewrite patterns of the given type `T`.
template <typename T, typename... Args>
- static std::unique_ptr<T> create(Args &&... args) {
+ static std::unique_ptr<T> create(Args &&...args) {
std::unique_ptr<T> pattern =
std::make_unique<T>(std::forward<Args>(args)...);
initializePattern<T>(*pattern);
template <typename... Ts, typename ConstructorArg,
typename... ConstructorArgs,
typename = std::enable_if_t<sizeof...(Ts) != 0>>
- RewritePatternSet &add(ConstructorArg &&arg, ConstructorArgs &&... args) {
+ RewritePatternSet &add(ConstructorArg &&arg, ConstructorArgs &&...args) {
// The following expands a call to emplace_back for each of the pattern
// types 'Ts'. This magic is necessary due to a limitation in the places
// that a parameter pack can be expanded in c++11.
typename = std::enable_if_t<sizeof...(Ts) != 0>>
RewritePatternSet &addWithLabel(ArrayRef<StringRef> debugLabels,
ConstructorArg &&arg,
- ConstructorArgs &&... args) {
+ ConstructorArgs &&...args) {
// The following expands a call to emplace_back for each of the pattern
// types 'Ts'. This magic is necessary due to a limitation in the places
// that a parameter pack can be expanded in c++11.
template <typename... Ts, typename ConstructorArg,
typename... ConstructorArgs,
typename = std::enable_if_t<sizeof...(Ts) != 0>>
- RewritePatternSet &insert(ConstructorArg &&arg, ConstructorArgs &&... args) {
+ RewritePatternSet &insert(ConstructorArg &&arg, ConstructorArgs &&...args) {
// The following expands a call to emplace_back for each of the pattern
// types 'Ts'. This magic is necessary due to a limitation in the places
// that a parameter pack can be expanded in c++11.
/// chaining insertions.
template <typename T, typename... Args>
std::enable_if_t<std::is_base_of<RewritePattern, T>::value>
- addImpl(ArrayRef<StringRef> debugLabels, Args &&... args) {
+ addImpl(ArrayRef<StringRef> debugLabels, Args &&...args) {
std::unique_ptr<T> pattern =
RewritePattern::create<T>(std::forward<Args>(args)...);
pattern->addDebugLabels(debugLabels);
}
template <typename T, typename... Args>
std::enable_if_t<std::is_base_of<PDLPatternModule, T>::value>
- addImpl(ArrayRef<StringRef> debugLabels, Args &&... args) {
+ addImpl(ArrayRef<StringRef> debugLabels, Args &&...args) {
// TODO: Add the provided labels to the PDL pattern when PDL supports
// labels.
pdlPatterns.mergeIn(T(std::forward<Args>(args)...));
#include "llvm/ADT/GraphTraits.h"
namespace llvm {
-template <> struct GraphTraits<mlir::Block *> {
+template <>
+struct GraphTraits<mlir::Block *> {
using ChildIteratorType = mlir::Block::succ_iterator;
using Node = mlir::Block;
using NodeRef = Node *;
static ChildIteratorType child_end(NodeRef node) { return node->succ_end(); }
};
-template <> struct GraphTraits<Inverse<mlir::Block *>> {
+template <>
+struct GraphTraits<Inverse<mlir::Block *>> {
using ChildIteratorType = mlir::Block::pred_iterator;
using Node = mlir::Block;
using NodeRef = Node *;
/// Provide an implementation of 'classof' that compares the type id of the
/// provided value with that of the concrete type.
- template <typename T> static bool classof(T val) {
+ template <typename T>
+ static bool classof(T val) {
static_assert(std::is_convertible<ConcreteT, T>::value,
"casting from a non-convertible type");
return val.getTypeID() == getTypeID();
protected:
/// Mutate the current storage instance. This will not change the unique key.
/// The arguments are forwarded to 'ConcreteT::mutate'.
- template <typename... Args> LogicalResult mutate(Args &&...args) {
+ template <typename... Args>
+ LogicalResult mutate(Args &&...args) {
static_assert(std::is_base_of<StorageUserTrait::IsMutable<ConcreteT>,
ConcreteT>::value,
"The `mutate` function expects mutable trait "
}
/// Default implementation that just returns success.
- template <typename... Args> static LogicalResult verify(Args... args) {
+ template <typename... Args>
+ static LogicalResult verify(Args... args) {
return success();
}
/// Returns an instance of the concept object for the given interface if it
/// was registered to this type, null otherwise. This should not be used
/// directly.
- template <typename T> typename T::Concept *getInterface() const {
+ template <typename T>
+ typename T::Concept *getInterface() const {
return interfaceMap.lookup<T>();
}
bool operator!() const { return impl == nullptr; }
- template <typename U> bool isa() const;
- template <typename First, typename Second, typename... Rest> bool isa() const;
- template <typename U> U dyn_cast() const;
- template <typename U> U dyn_cast_or_null() const;
- template <typename U> U cast() const;
+ template <typename U>
+ bool isa() const;
+ template <typename First, typename Second, typename... Rest>
+ bool isa() const;
+ template <typename U>
+ U dyn_cast() const;
+ template <typename U>
+ U dyn_cast_or_null() const;
+ template <typename U>
+ U cast() const;
// Support type casting Type to itself.
static bool classof(Type) { return true; }
return DenseMapInfo<const Type::ImplType *>::getHashValue(arg.impl);
}
-template <typename U> bool Type::isa() const {
+template <typename U>
+bool Type::isa() const {
assert(impl && "isa<> used on a null type.");
return U::classof(*this);
}
return isa<First>() || isa<Second, Rest...>();
}
-template <typename U> U Type::dyn_cast() const {
+template <typename U>
+U Type::dyn_cast() const {
return isa<U>() ? U(impl) : U(nullptr);
}
-template <typename U> U Type::dyn_cast_or_null() const {
+template <typename U>
+U Type::dyn_cast_or_null() const {
return (impl && isa<U>()) ? U(impl) : U(nullptr);
}
-template <typename U> U Type::cast() const {
+template <typename U>
+U Type::cast() const {
assert(isa<U>());
return U(impl);
}
namespace llvm {
// Type hash just like pointers.
-template <> struct DenseMapInfo<mlir::Type> {
+template <>
+struct DenseMapInfo<mlir::Type> {
static mlir::Type getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer));
};
/// We align TypeStorage by 8, so allow LLVM to steal the low bits.
-template <> struct PointerLikeTypeTraits<mlir::Type> {
+template <>
+struct PointerLikeTypeTraits<mlir::Type> {
public:
static inline void *getAsVoidPointer(mlir::Type I) {
return const_cast<void *>(I.getAsOpaquePointer());
namespace mlir {
class Operation;
-template <typename OperandType> class ValueUseIterator;
-template <typename OperandType> class FilteredValueUseIterator;
-template <typename UseIteratorT, typename OperandType> class ValueUserIterator;
+template <typename OperandType>
+class ValueUseIterator;
+template <typename OperandType>
+class FilteredValueUseIterator;
+template <typename UseIteratorT, typename OperandType>
+class ValueUserIterator;
//===----------------------------------------------------------------------===//
// IROperand
}
/// Insert this operand into the given use list.
- template <typename UseListT> void insertInto(UseListT *useList) {
+ template <typename UseListT>
+ void insertInto(UseListT *useList) {
back = &useList->firstUse;
nextUse = useList->firstUse;
if (nextUse)
//===----------------------------------------------------------------------===//
/// This class represents a single IR object that contains a use list.
-template <typename OperandType> class IRObjectWithUseList {
+template <typename OperandType>
+class IRObjectWithUseList {
public:
~IRObjectWithUseList() {
assert(use_empty() && "Cannot destroy a value that still has uses!");
TypeID getEffectID() const { return id; }
/// Returns a unique instance for the given effect class.
- template <typename DerivedEffect> static DerivedEffect *get() {
+ template <typename DerivedEffect>
+ static DerivedEffect *get() {
static_assert(std::is_base_of<Effect, DerivedEffect>::value,
"expected DerivedEffect to inherit from Effect");
/// applied, and an optional symbol reference or value(either operand, result,
/// or region entry argument) that the effect is applied to, and an optional
/// parameters attribute further specifying the details of the effect.
-template <typename EffectT> class EffectInstance {
+template <typename EffectT>
+class EffectInstance {
public:
EffectInstance(EffectT *effect, Resource *resource = DefaultResource::get())
: effect(effect), resource(resource) {}
bool isNone() const { return preservedIDs.empty(); }
/// Preserve the given analyses.
- template <typename AnalysisT> void preserve() {
+ template <typename AnalysisT>
+ void preserve() {
preserve(TypeID::get<AnalysisT>());
}
template <typename AnalysisT, typename AnalysisT2, typename... OtherAnalysesT>
/// Returns true if the given analysis has been marked as preserved. Note that
/// this simply checks for the presence of a given analysis ID and should not
/// be used as a general preservation checker.
- template <typename AnalysisT> bool isPreserved() const {
+ template <typename AnalysisT>
+ bool isPreserved() const {
return isPreserved(TypeID::get<AnalysisT>());
}
bool isPreserved(TypeID id) const { return preservedIDs.count(id); }
};
/// A derived analysis model used to hold a specific analysis object.
-template <typename AnalysisT> struct AnalysisModel : public AnalysisConcept {
+template <typename AnalysisT>
+struct AnalysisModel : public AnalysisConcept {
template <typename... Args>
explicit AnalysisModel(Args &&...args)
: analysis(std::forward<Args>(args)...) {}
using ConceptMap = llvm::MapVector<TypeID, std::unique_ptr<AnalysisConcept>>;
/// Utility to return the name of the given analysis class.
- template <typename AnalysisT> static StringRef getAnalysisName() {
+ template <typename AnalysisT>
+ static StringRef getAnalysisName() {
StringRef name = llvm::getTypeName<AnalysisT>();
if (!name.consume_front("mlir::"))
name.consume_front("(anonymous namespace)::");
}
/// Query for the given analysis for the current operation.
- template <typename AnalysisT> AnalysisT &getAnalysis() {
+ template <typename AnalysisT>
+ AnalysisT &getAnalysis() {
return impl->analyses.getAnalysis<AnalysisT>(getPassInstrumentor(), *this);
}
}
/// Query for an analysis of a child operation, constructing it if necessary.
- template <typename AnalysisT> AnalysisT &getChildAnalysis(Operation *op) {
+ template <typename AnalysisT>
+ AnalysisT &getChildAnalysis(Operation *op) {
return nest(op).template getAnalysis<AnalysisT>();
}
void signalPassFailure() { getPassState().irAndPassFailed.setInt(true); }
/// Query an analysis for the current ir unit.
- template <typename AnalysisT> AnalysisT &getAnalysis() {
+ template <typename AnalysisT>
+ AnalysisT &getAnalysis() {
return getAnalysisManager().getAnalysis<AnalysisT>();
}
}
/// Mark the provided analyses as preserved.
- template <typename... AnalysesT> void markAnalysesPreserved() {
+ template <typename... AnalysesT>
+ void markAnalysesPreserved() {
getPassState().preservedAnalyses.preserve<AnalysesT...>();
}
void markAnalysesPreserved(TypeID id) {
/// Returns the analysis for the given child operation, or creates it if it
/// doesn't exist.
- template <typename AnalysisT> AnalysisT &getChildAnalysis(Operation *child) {
+ template <typename AnalysisT>
+ AnalysisT &getChildAnalysis(Operation *child) {
return getAnalysisManager().getChildAnalysis<AnalysisT>(child);
}
/// - A 'void runOnOperation()' method.
/// - A 'StringRef getName() const' method.
/// - A 'std::unique_ptr<Pass> clonePass() const' method.
-template <typename OpT = void> class OperationPass : public Pass {
+template <typename OpT = void>
+class OperationPass : public Pass {
protected:
OperationPass(TypeID passID) : Pass(passID, OpT::getOperationName()) {}
OperationPass(const OperationPass &) = default;
/// - A 'void runOnOperation()' method.
/// - A 'StringRef getName() const' method.
/// - A 'std::unique_ptr<Pass> clonePass() const' method.
-template <> class OperationPass<void> : public Pass {
+template <>
+class OperationPass<void> : public Pass {
protected:
OperationPass(TypeID passID) : Pass(passID) {}
OperationPass(const OperationPass &) = default;
/// several necessary utility methods. This should only be used for passes that
/// are not suitably represented using the declarative pass specification(i.e.
/// tablegen backend).
-template <typename PassT, typename BaseT> class PassWrapper : public BaseT {
+template <typename PassT, typename BaseT>
+class PassWrapper : public BaseT {
public:
/// Support isa/dyn_cast functionality for the derived pass class.
static bool classof(const Pass *pass) {
} // namespace mlir
namespace llvm {
-template <> struct DenseMapInfo<mlir::PassInstrumentation::PipelineParentInfo> {
+template <>
+struct DenseMapInfo<mlir::PassInstrumentation::PipelineParentInfo> {
using T = mlir::PassInstrumentation::PipelineParentInfo;
using PairInfo = DenseMapInfo<std::pair<uint64_t, void *>>;
/// pass manager.
OpPassManager &nest(OperationName nestedName);
OpPassManager &nest(StringRef nestedName);
- template <typename OpT> OpPassManager &nest() {
+ template <typename OpT>
+ OpPassManager &nest() {
return nest(OpT::getOperationName());
}
/// Add the given pass to a nested pass manager for the given operation kind
/// `OpT`.
- template <typename OpT> void addNestedPass(std::unique_ptr<Pass> pass) {
+ template <typename OpT>
+ void addNestedPass(std::unique_ptr<Pass> pass) {
nest<OpT>().addPass(std::move(pass));
}
/// /// At namespace scope.
/// static PassRegistration<MyPass> reg;
///
-template <typename ConcretePass> struct PassRegistration {
+template <typename ConcretePass>
+struct PassRegistration {
PassRegistration(const PassAllocatorFunction &constructor) {
registerPass(constructor);
}
/// Convenience specialization of PassPipelineRegistration for EmptyPassOptions
/// that does not pass an empty options struct to the pass builder function.
-template <> struct PassPipelineRegistration<EmptyPipelineOptions> {
+template <>
+struct PassPipelineRegistration<EmptyPipelineOptions> {
PassPipelineRegistration(
StringRef arg, StringRef description,
const std::function<void(OpPassManager &)> &builder) {
/// `Args` are a set of parameters used by handlers of `ActionType` to
/// determine if the action should be executed.
template <typename ActionType, typename... Args>
- bool shouldExecute(Args &&... args) {
+ bool shouldExecute(Args &&...args) {
// The manager is always disabled if built without debug.
#if !LLVM_ENABLE_ABI_BREAKING_CHECKS
return true;
#else
// Invoke the `shouldExecute` method on the provided handler.
- auto shouldExecuteFn = [&](auto *handler, auto &&... handlerParams) {
+ auto shouldExecuteFn = [&](auto *handler, auto &&...handlerParams) {
return handler->shouldExecute(
std::forward<decltype(handlerParams)>(handlerParams)...);
};
template <typename ActionType, typename ResultT, typename HandlerCallbackT,
typename... Args>
FailureOr<ResultT> dispatchToHandler(HandlerCallbackT &&handlerCallback,
- Args &&... args) {
+ Args &&...args) {
static_assert(ActionType::template canHandleWith<Args...>(),
"cannot execute action with the given set of parameters");
/// This class provides a handler class that can be derived from to handle
/// instances of this action. The parameters to its query methods map 1-1 to the
/// types on the action type.
-template <typename... ParameterTs> class DebugAction {
+template <typename... ParameterTs>
+class DebugAction {
public:
class Handler : public DebugActionManager::HandlerBase {
public:
class Interface : public BaseType {
public:
using Concept = typename Traits::Concept;
- template <typename T> using Model = typename Traits::template Model<T>;
+ template <typename T>
+ using Model = typename Traits::template Model<T>;
template <typename T>
using FallbackModel = typename Traits::template FallbackModel<T>;
using InterfaceBase =
/// Returns an instance of the concept object for the given interface if it
/// was registered to this map, null otherwise.
- template <typename T> typename T::Concept *lookup() const {
+ template <typename T>
+ typename T::Concept *lookup() const {
return reinterpret_cast<typename T::Concept *>(lookup(T::getInterfaceID()));
}
// Forward declarations.
namespace llvm {
// String types
-template <unsigned N> class SmallString;
+template <unsigned N>
+class SmallString;
class StringRef;
class StringLiteral;
class Twine;
// Containers.
-template <typename T> class ArrayRef;
+template <typename T>
+class ArrayRef;
class BitVector;
namespace detail {
-template <typename KeyT, typename ValueT> struct DenseMapPair;
+template <typename KeyT, typename ValueT>
+struct DenseMapPair;
} // namespace detail
template <typename KeyT, typename ValueT, typename KeyInfoT, typename BucketT>
class DenseMap;
-template <typename T, typename Enable> struct DenseMapInfo;
-template <typename ValueT, typename ValueInfoT> class DenseSet;
+template <typename T, typename Enable>
+struct DenseMapInfo;
+template <typename ValueT, typename ValueInfoT>
+class DenseSet;
class MallocAllocator;
-template <typename T> class MutableArrayRef;
-template <typename T> class Optional;
-template <typename... PT> class PointerUnion;
-template <typename T, typename Vector, typename Set> class SetVector;
-template <typename T, unsigned N> class SmallPtrSet;
-template <typename T> class SmallPtrSetImpl;
-template <typename T, unsigned N> class SmallVector;
-template <typename T> class SmallVectorImpl;
-template <typename AllocatorTy> class StringSet;
-template <typename T, typename R> class StringSwitch;
-template <typename T> class TinyPtrVector;
-template <typename T, typename ResultT> class TypeSwitch;
+template <typename T>
+class MutableArrayRef;
+template <typename T>
+class Optional;
+template <typename... PT>
+class PointerUnion;
+template <typename T, typename Vector, typename Set>
+class SetVector;
+template <typename T, unsigned N>
+class SmallPtrSet;
+template <typename T>
+class SmallPtrSetImpl;
+template <typename T, unsigned N>
+class SmallVector;
+template <typename T>
+class SmallVectorImpl;
+template <typename AllocatorTy>
+class StringSet;
+template <typename T, typename R>
+class StringSwitch;
+template <typename T>
+class TinyPtrVector;
+template <typename T, typename ResultT>
+class TypeSwitch;
// Other common classes.
class APInt;
class APSInt;
class APFloat;
-template <typename Fn> class function_ref;
-template <typename IteratorT> class iterator_range;
+template <typename Fn>
+class function_ref;
+template <typename IteratorT>
+class iterator_range;
class raw_ostream;
class SMLoc;
class SMRange;
using llvm::APFloat;
using llvm::APInt;
using llvm::APSInt;
-template <typename Fn> using function_ref = llvm::function_ref<Fn>;
+template <typename Fn>
+using function_ref = llvm::function_ref<Fn>;
using llvm::iterator_range;
using llvm::raw_ostream;
using llvm::SMLoc;
/// This class provides support for representing a failure result, or a valid
/// value of type `T`. This allows for integrating with LogicalResult, while
/// also providing a value on the success path.
-template <typename T> class LLVM_NODISCARD FailureOr : public Optional<T> {
+template <typename T>
+class LLVM_NODISCARD FailureOr : public Optional<T> {
public:
/// Allow constructing from a LogicalResult. The result *must* be a failure.
/// Success results should use a proper instance of type `T`.
public:
/// Copy the specified array of elements into memory managed by our bump
/// pointer allocator. This assumes the elements are all PODs.
- template <typename T> ArrayRef<T> copyInto(ArrayRef<T> elements) {
+ template <typename T>
+ ArrayRef<T> copyInto(ArrayRef<T> elements) {
if (elements.empty())
return llvm::None;
auto result = allocator.Allocate<T>(elements.size());
}
/// Allocate an instance of the provided type.
- template <typename T> T *allocate() { return allocator.Allocate<T>(); }
+ template <typename T>
+ T *allocate() {
+ return allocator.Allocate<T>();
+ }
/// Allocate 'size' bytes of 'alignment' aligned memory.
void *allocate(size_t size, size_t alignment) {
/// Register a new parametric storage class, this is necessary to create
/// instances of this class type. `id` is the type identifier that will be
/// used to identify this type when creating instances of it via 'get'.
- template <typename Storage> void registerParametricStorageType(TypeID id) {
+ template <typename Storage>
+ void registerParametricStorageType(TypeID id) {
// If the storage is trivially destructible, we don't need a destructor
// function.
if (std::is_trivially_destructible<Storage>::value)
});
}
/// Utility override when the storage type represents the type id.
- template <typename Storage> void registerParametricStorageType() {
+ template <typename Storage>
+ void registerParametricStorageType() {
registerParametricStorageType<Storage>(TypeID::get<Storage>());
}
/// Register a new singleton storage class, this is necessary to get the
};
registerSingletonImpl(id, ctorFn);
}
- template <typename Storage> void registerSingletonStorageType(TypeID id) {
+ template <typename Storage>
+ void registerSingletonStorageType(TypeID id) {
registerSingletonStorageType<Storage>(id, llvm::None);
}
/// Utility override when the storage type represents the type id.
/// Gets a uniqued instance of 'Storage' which is a singleton storage type.
/// 'id' is the type id used when registering the storage instance.
- template <typename Storage> Storage *get(TypeID id) {
+ template <typename Storage>
+ Storage *get(TypeID id) {
return static_cast<Storage *>(getSingletonImpl(id));
}
/// Utility override when the storage type represents the type id.
- template <typename Storage> Storage *get() {
+ template <typename Storage>
+ Storage *get() {
return get<Storage>(TypeID::get<Storage>());
}
MLIR_DECLARE_EXPLICIT_TYPE_ID(void)
namespace llvm {
-template <> struct DenseMapInfo<mlir::TypeID> {
+template <>
+struct DenseMapInfo<mlir::TypeID> {
static inline mlir::TypeID getEmptyKey() {
void *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::TypeID::getFromOpaquePointer(pointer);
};
/// We align TypeID::Storage by 8, so allow LLVM to steal the low bits.
-template <> struct PointerLikeTypeTraits<mlir::TypeID> {
+template <>
+struct PointerLikeTypeTraits<mlir::TypeID> {
static inline void *getAsVoidPointer(mlir::TypeID info) {
return const_cast<void *>(info.getAsOpaquePointer());
}
std::string escapeString(StringRef value);
namespace detail {
-template <typename> struct stringifier {
- template <typename T> static std::string apply(T &&t) {
+template <typename>
+struct stringifier {
+ template <typename T>
+ static std::string apply(T &&t) {
return std::string(std::forward<T>(t));
}
};
-template <> struct stringifier<Twine> {
- static std::string apply(const Twine &twine) {
- return twine.str();
- }
+template <>
+struct stringifier<Twine> {
+ static std::string apply(const Twine &twine) { return twine.str(); }
};
template <typename OptionalT>
struct stringifier<Optional<OptionalT>> {
} // namespace detail
/// Generically convert a value to a std::string.
-template <typename T> std::string stringify(T &&t) {
+template <typename T>
+std::string stringify(T &&t) {
return detail::stringifier<std::remove_reference_t<std::remove_const_t<T>>>::
apply(std::forward<T>(t));
}
return s.str();
}
- template <unsigned N> SmallString<N> sstr() const {
+ template <unsigned N>
+ SmallString<N> sstr() const {
SmallString<N> result;
llvm::raw_svector_ostream s(result);
format(s);
return result;
}
- template <unsigned N> operator SmallString<N>() const { return sstr<N>(); }
+ template <unsigned N>
+ operator SmallString<N>() const {
+ return sstr<N>();
+ }
operator std::string() const { return str(); }
};
-template <typename Tuple> class FmtObject : public FmtObjectBase {
+template <typename Tuple>
+class FmtObject : public FmtObjectBase {
// Storage for the parameter adapters. Since the base class erases the type
// of the parameters, we have to own the storage for the parameters here, and
// have the base class store type-erased pointers into this tuple.
/// This class provides a convenient API for interacting with source names. It
/// contains a string name as well as the source location for that name.
struct Name {
- static const Name &create(Context &ctx, StringRef name,
- SMRange location);
+ static const Name &create(Context &ctx, StringRef name, SMRange location);
/// Return the raw string name.
StringRef getName() const { return name; }
Name() = delete;
Name(const Name &) = delete;
Name &operator=(const Name &) = delete;
- Name(StringRef name, SMRange location)
- : name(name), location(location) {}
+ Name(StringRef name, SMRange location) : name(name), location(location) {}
/// The string name of the decl.
StringRef name;
/// Lookup a decl with the given name starting from this scope. Returns
/// nullptr if no decl could be found.
Decl *lookup(StringRef name);
- template <typename T> T *lookup(StringRef name) {
+ template <typename T>
+ T *lookup(StringRef name) {
return dyn_cast_or_null<T>(lookup(name));
}
const Decl *lookup(StringRef name) const {
return const_cast<DeclScope *>(this)->lookup(name);
}
- template <typename T> const T *lookup(StringRef name) const {
+ template <typename T>
+ const T *lookup(StringRef name) const {
return dyn_cast_or_null<T>(lookup(name));
}
class Node {
public:
/// This CRTP class provides several utilies when defining new AST nodes.
- template <typename T, typename BaseT> class NodeBase : public BaseT {
+ template <typename T, typename BaseT>
+ class NodeBase : public BaseT {
public:
using Base = NodeBase<T, BaseT>;
/// to define variables.
class LetStmt final : public Node::NodeBase<LetStmt, Stmt> {
public:
- static LetStmt *create(Context &ctx, SMRange loc,
- VariableDecl *varDecl);
+ static LetStmt *create(Context &ctx, SMRange loc, VariableDecl *varDecl);
/// Return the variable defined by this statement.
VariableDecl *getVarDecl() const { return varDecl; }
private:
- LetStmt(SMRange loc, VariableDecl *varDecl)
- : Base(loc), varDecl(varDecl) {}
+ LetStmt(SMRange loc, VariableDecl *varDecl) : Base(loc), varDecl(varDecl) {}
/// The variable defined by this statement.
VariableDecl *varDecl;
static bool classof(const Node *node);
protected:
- Expr(TypeID typeID, SMRange loc, Type type)
- : Stmt(typeID, loc), type(type) {}
+ Expr(TypeID typeID, SMRange loc, Type type) : Stmt(typeID, loc), type(type) {}
private:
/// The type of this expression.
/// textual assembly format of that attribute.
class AttributeExpr : public Node::NodeBase<AttributeExpr, Expr> {
public:
- static AttributeExpr *create(Context &ctx, SMRange loc,
- StringRef value);
+ static AttributeExpr *create(Context &ctx, SMRange loc, StringRef value);
/// Get the raw value of this expression. This is the textual assembly format
/// of the MLIR Attribute.
/// This expression represents a reference to a Decl node.
class DeclRefExpr : public Node::NodeBase<DeclRefExpr, Expr> {
public:
- static DeclRefExpr *create(Context &ctx, SMRange loc, Decl *decl,
- Type type);
+ static DeclRefExpr *create(Context &ctx, SMRange loc, Decl *decl, Type type);
/// Get the decl referenced by this expression.
Decl *getDecl() const { return decl; }
StringRef getMemberName() const { return memberName; }
private:
- MemberAccessExpr(SMRange loc, const Expr *parentExpr,
- StringRef memberName, Type type)
+ MemberAccessExpr(SMRange loc, const Expr *parentExpr, StringRef memberName,
+ Type type)
: Base(loc, type), parentExpr(parentExpr), memberName(memberName) {}
/// The parent expression of this access.
class TupleExpr final : public Node::NodeBase<TupleExpr, Expr>,
private llvm::TrailingObjects<TupleExpr, Expr *> {
public:
- static TupleExpr *create(Context &ctx, SMRange loc,
- ArrayRef<Expr *> elements,
+ static TupleExpr *create(Context &ctx, SMRange loc, ArrayRef<Expr *> elements,
ArrayRef<StringRef> elementNames);
/// Return the element expressions of this tuple.
static bool classof(const Node *node);
protected:
- CoreConstraintDecl(TypeID typeID, SMRange loc,
- const Name *name = nullptr)
+ CoreConstraintDecl(TypeID typeID, SMRange loc, const Name *name = nullptr)
: ConstraintDecl(typeID, loc, name) {}
};
class ValueConstraintDecl
: public Node::NodeBase<ValueConstraintDecl, CoreConstraintDecl> {
public:
- static ValueConstraintDecl *create(Context &ctx, SMRange loc,
- Expr *typeExpr);
+ static ValueConstraintDecl *create(Context &ctx, SMRange loc, Expr *typeExpr);
/// Return the optional type the value is constrained to.
Expr *getTypeExpr() { return typeExpr; }
/// This Decl represents a single Pattern.
class PatternDecl : public Node::NodeBase<PatternDecl, Decl> {
public:
- static PatternDecl *create(Context &ctx, SMRange location,
- const Name *name, Optional<uint16_t> benefit,
+ static PatternDecl *create(Context &ctx, SMRange location, const Name *name,
+ Optional<uint16_t> benefit,
bool hasBoundedRecursion,
const CompoundStmt *body);
class Module final : public Node::NodeBase<Module, Node>,
private llvm::TrailingObjects<Module, Decl *> {
public:
- static Module *create(Context &ctx, SMLoc loc,
- ArrayRef<Decl *> children);
+ static Module *create(Context &ctx, SMLoc loc, ArrayRef<Decl *> children);
/// Return the children of this module.
MutableArrayRef<Decl *> getChildren() {
explicit operator bool() const { return impl; }
/// Provide type casting support.
- template <typename U> bool isa() const {
+ template <typename U>
+ bool isa() const {
assert(impl && "isa<> used on a null type.");
return U::classof(*this);
}
- template <typename U, typename V, typename... Others> bool isa() const {
+ template <typename U, typename V, typename... Others>
+ bool isa() const {
return isa<U>() || isa<V, Others...>();
}
- template <typename U> U dyn_cast() const {
+ template <typename U>
+ U dyn_cast() const {
return isa<U>() ? U(impl) : U(nullptr);
}
- template <typename U> U dyn_cast_or_null() const {
+ template <typename U>
+ U dyn_cast_or_null() const {
return (impl && isa<U>()) ? U(impl) : U(nullptr);
}
- template <typename U> U cast() const {
+ template <typename U>
+ U cast() const {
assert(isa<U>());
return U(impl);
}
protected:
/// Return the internal storage instance of this type reinterpreted as the
/// given derived storage type.
- template <typename T> const T *getImplAs() const {
+ template <typename T>
+ const T *getImplAs() const {
return static_cast<const T *>(impl);
}
MLIR_DECLARE_EXPLICIT_TYPE_ID(mlir::pdll::ast::detail::ValueTypeStorage)
namespace llvm {
-template <> struct DenseMapInfo<mlir::pdll::ast::Type> {
+template <>
+struct DenseMapInfo<mlir::pdll::ast::Type> {
static mlir::pdll::ast::Type getEmptyKey() {
void *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::pdll::ast::Type(
/// the results after folding the operation.
template <typename OpTy, typename... Args>
void create(OpBuilder &builder, SmallVectorImpl<Value> &results,
- Location location, Args &&... args) {
+ Location location, Args &&...args) {
// The op needs to be inserted only if the fold (below) fails, or the number
// of results produced by the successful folding is zero (which is treated
// as an in-place fold). Using create methods of the builder will insert the
template <typename OpTy, typename... Args>
typename std::enable_if<OpTy::template hasTrait<OpTrait::OneResult>(),
Value>::type
- create(OpBuilder &builder, Location location, Args &&... args) {
+ create(OpBuilder &builder, Location location, Args &&...args) {
SmallVector<Value, 1> results;
create<OpTy>(builder, results, location, std::forward<Args>(args)...);
return results.front();
template <typename OpTy, typename... Args>
typename std::enable_if<OpTy::template hasTrait<OpTrait::ZeroResults>(),
OpTy>::type
- create(OpBuilder &builder, Location location, Args &&... args) {
+ create(OpBuilder &builder, Location location, Args &&...args) {
auto op = builder.create<OpTy>(location, std::forward<Args>(args)...);
SmallVector<Value, 0> unused;
(void)tryToFold(op.getOperation(), unused);
class Pass;
/// Creates a pass to print op graphs.
-std::unique_ptr<Pass>
-createPrintOpGraphPass(raw_ostream &os = llvm::errs());
+std::unique_ptr<Pass> createPrintOpGraphPass(raw_ostream &os = llvm::errs());
} // namespace mlir
//
//===----------------------------------------------------------------------===//
-#include "../PassDetail.h"
#include "mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h"
+#include "../PassDetail.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
Value absArg = b.create<complex::AbsOp>(elementType, arg);
Value addAbs = b.create<arith::AddFOp>(absLhs, absArg);
- Value half = b.create<arith::ConstantOp>(
- elementType, b.getFloatAttr(elementType, 0.5));
+ Value half = b.create<arith::ConstantOp>(elementType,
+ b.getFloatAttr(elementType, 0.5));
Value halfAddAbs = b.create<arith::MulFOp>(addAbs, half);
Value sqrtAddAbs = b.create<math::SqrtOp>(halfAddAbs);
return std::make_unique<GpuToLLVMConversionPass>();
}
-void mlir::populateGpuToLLVMConversionPatterns(
- LLVMTypeConverter &converter, RewritePatternSet &patterns,
- StringRef gpuBinaryAnnotation) {
+void mlir::populateGpuToLLVMConversionPatterns(LLVMTypeConverter &converter,
+ RewritePatternSet &patterns,
+ StringRef gpuBinaryAnnotation) {
converter.addConversion(
[context = &converter.getContext()](gpu::AsyncTokenType type) -> Type {
return LLVM::LLVMPointerType::get(IntegerType::get(context, 8));
// TODO: Load to Workgroup storage class first.
-
// Get the input element accessed by this invocation.
Value inputElementPtr = spirv::getElementPtr(
*typeConverter, originalInputType, convertedInput, {x}, loc, rewriter);
return success();
}
-
/// Populate the given list with patterns that convert from Linalg to Standard.
void mlir::linalg::populateLinalgToStandardConversionPatterns(
RewritePatternSet &patterns) {
// AffineMinMaxOpBase
//===----------------------------------------------------------------------===//
-template <typename T> static LogicalResult verifyAffineMinMaxOp(T op) {
+template <typename T>
+static LogicalResult verifyAffineMinMaxOp(T op) {
// Verify that operand count matches affine map dimension and symbol count.
if (op.getNumOperands() !=
op.getMap().getNumDims() + op.getMap().getNumSymbols())
return success();
}
-template <typename T> static void printAffineMinMaxOp(OpAsmPrinter &p, T op) {
+template <typename T>
+static void printAffineMinMaxOp(OpAsmPrinter &p, T op) {
p << ' ' << op->getAttr(T::getMapAttrStrName());
auto operands = op.getOperands();
unsigned numDims = op.getMap().getNumDims();
///
/// %1 = affine.min affine_map<
/// ()[s0, s1] -> (s0 + 4, s1 + 16, s1 * 8)> ()[%sym2, %sym1]
-template <typename T> struct MergeAffineMinMaxOp : public OpRewritePattern<T> {
+template <typename T>
+struct MergeAffineMinMaxOp : public OpRewritePattern<T> {
using OpRewritePattern<T>::OpRewritePattern;
LogicalResult matchAndRewrite(T affineOp,
operands, [](APInt a, const APInt &b) { return std::move(a) + b; });
}
-void arith::AddIOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::AddIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<AddIAddConstant, AddISubConstantRHS, AddISubConstantLHS>(
context);
}
operands, [](APInt a, const APInt &b) { return std::move(a) - b; });
}
-void arith::SubIOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::SubIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns
.add<SubIRHSAddConstant, SubILHSAddConstant, SubIRHSSubConstantRHS,
SubIRHSSubConstantLHS, SubILHSSubConstantRHS, SubILHSSubConstantLHS>(
operands, [](APInt a, const APInt &b) { return std::move(a) ^ b; });
}
-void arith::XOrIOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::XOrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<XOrINotCmpI>(context);
}
return checkWidthChangeCast<std::greater, IntegerType>(inputs, outputs);
}
-void arith::ExtSIOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::ExtSIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<ExtSIOfExtUI>(context);
}
// AndIOp
//===----------------------------------------------------------------------===//
-void arith::AndIOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::AndIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<AndOfExtUI, AndOfExtSI>(context);
}
// OrIOp
//===----------------------------------------------------------------------===//
-void arith::OrIOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::OrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<OrOfExtUI, OrOfExtSI>(context);
}
return IntegerAttr::get(resType, bits);
}
-void arith::BitcastOp::getCanonicalizationPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void arith::BitcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<BitcastOfBitcast>(context);
}
Location loc = op.getLoc();
// If any operand is NaN, 'cmp' will be true (and 'select' returns 'lhs').
static_assert(pred == arith::CmpFPredicate::UGT ||
- pred == arith::CmpFPredicate::ULT,
+ pred == arith::CmpFPredicate::ULT,
"pred must be either UGT or ULT");
Value cmp = rewriter.create<arith::CmpFOp>(loc, pred, lhs, rhs);
Value select = rewriter.create<arith::SelectOp>(loc, cmp, lhs, rhs);
};
// Configure op filter.
- OpFilter::Entry::FilterFn filterFn =
- [&](Operation *op) {
- // Filter may be specified via options.
- if (this->dialectFilter.hasValue())
- return llvm::is_contained(this->dialectFilter,
- op->getDialect()->getNamespace());
- // No filter specified: All other ops are allowed.
- return true;
- };
+ OpFilter::Entry::FilterFn filterFn = [&](Operation *op) {
+ // Filter may be specified via options.
+ if (this->dialectFilter.hasValue())
+ return llvm::is_contained(this->dialectFilter,
+ op->getDialect()->getNamespace());
+ // No filter specified: All other ops are allowed.
+ return true;
+ };
opt.opFilter.allowOperation(filterFn);
} else {
opt = *options;
// Register pass to serialize GPU kernel functions to a CUBIN binary annotation.
void mlir::registerGpuSerializeToCubinPass() {
- PassRegistration<SerializeToCubinPass> registerSerializeToCubin(
- [] {
- // Initialize LLVM NVPTX backend.
- LLVMInitializeNVPTXTarget();
- LLVMInitializeNVPTXTargetInfo();
- LLVMInitializeNVPTXTargetMC();
- LLVMInitializeNVPTXAsmPrinter();
-
- return std::make_unique<SerializeToCubinPass>();
- });
+ PassRegistration<SerializeToCubinPass> registerSerializeToCubin([] {
+ // Initialize LLVM NVPTX backend.
+ LLVMInitializeNVPTXTarget();
+ LLVMInitializeNVPTXTargetInfo();
+ LLVMInitializeNVPTXTargetMC();
+ LLVMInitializeNVPTXAsmPrinter();
+
+ return std::make_unique<SerializeToCubinPass>();
+ });
}
#else // MLIR_GPU_TO_CUBIN_PASS_ENABLE
void mlir::registerGpuSerializeToCubinPass() {}
}
llvm::SourceMgr srcMgr;
- srcMgr.AddNewSourceBuffer(llvm::MemoryBuffer::getMemBuffer(isa),
- SMLoc());
+ srcMgr.AddNewSourceBuffer(llvm::MemoryBuffer::getMemBuffer(isa), SMLoc());
const llvm::MCTargetOptions mcOptions;
std::unique_ptr<llvm::MCRegisterInfo> mri(
// Register pass to serialize GPU kernel functions to a HSACO binary annotation.
void mlir::registerGpuSerializeToHsacoPass() {
- PassRegistration<SerializeToHsacoPass> registerSerializeToHSACO(
- [] {
- // Initialize LLVM AMDGPU backend.
- LLVMInitializeAMDGPUAsmParser();
- LLVMInitializeAMDGPUAsmPrinter();
- LLVMInitializeAMDGPUTarget();
- LLVMInitializeAMDGPUTargetInfo();
- LLVMInitializeAMDGPUTargetMC();
-
- return std::make_unique<SerializeToHsacoPass>("amdgcn-amd-amdhsa", "",
- "", 2);
- });
+ PassRegistration<SerializeToHsacoPass> registerSerializeToHSACO([] {
+ // Initialize LLVM AMDGPU backend.
+ LLVMInitializeAMDGPUAsmParser();
+ LLVMInitializeAMDGPUAsmPrinter();
+ LLVMInitializeAMDGPUTarget();
+ LLVMInitializeAMDGPUTargetInfo();
+ LLVMInitializeAMDGPUTargetMC();
+
+ return std::make_unique<SerializeToHsacoPass>("amdgcn-amd-amdhsa", "", "",
+ 2);
+ });
}
/// Create an instance of the GPU kernel function to HSAco binary serialization
unsigned dynamicIndexPos = indexPos;
if (!isStaticIndex)
dynamicIndexPos = llvm::count(structIndices.take_front(indexPos + 1),
- LLVM::GEPOp::kDynamicIndex) - 1;
+ LLVM::GEPOp::kDynamicIndex) -
+ 1;
return llvm::TypeSwitch<Type, llvm::Error>(baseGEPType)
.Case<LLVMStructType>([&](LLVMStructType structType) -> llvm::Error {
/// error at `subtypesLoc` in case of failure.
static LLVMStructType trySetStructBody(LLVMStructType type,
ArrayRef<Type> subtypes, bool isPacked,
- AsmParser &parser,
- SMLoc subtypesLoc) {
+ AsmParser &parser, SMLoc subtypesLoc) {
for (Type t : subtypes) {
if (!LLVMStructType::isValidElementType(t)) {
parser.emitError(subtypesLoc)
} // namespace
-void mlir::memref::populateComposeSubViewPatterns(
- RewritePatternSet &patterns, MLIRContext *context) {
+void mlir::memref::populateComposeSubViewPatterns(RewritePatternSet &patterns,
+ MLIRContext *context) {
patterns.add<ComposeSubViewOpPattern>(context);
}
// parseAndVerify does the actual parsing and verification of individual
// elements. This is a functor since parsing the last element of the list
// (termination condition) needs partial specialization.
-template <typename ParseType, typename... Args> struct ParseCommaSeparatedList {
+template <typename ParseType, typename... Args>
+struct ParseCommaSeparatedList {
Optional<std::tuple<ParseType, Args...>>
operator()(SPIRVDialect const &dialect, DialectAsmParser &parser) const {
auto parseVal = parseAndVerify<ParseType>(dialect, parser);
// Partial specialization of the function to parse a comma separated list of
// specs to parse the last element of the list.
-template <typename ParseType> struct ParseCommaSeparatedList<ParseType> {
+template <typename ParseType>
+struct ParseCommaSeparatedList<ParseType> {
Optional<std::tuple<ParseType>> operator()(SPIRVDialect const &dialect,
DialectAsmParser &parser) const {
if (auto value = parseAndVerify<ParseType>(dialect, parser))
// ImageType
//===----------------------------------------------------------------------===//
-template <typename T> static constexpr unsigned getNumBits() { return 0; }
-template <> constexpr unsigned getNumBits<Dim>() {
+template <typename T>
+static constexpr unsigned getNumBits() {
+ return 0;
+}
+template <>
+constexpr unsigned getNumBits<Dim>() {
static_assert((1 << 3) > getMaxEnumValForDim(),
"Not enough bits to encode Dim value");
return 3;
}
-template <> constexpr unsigned getNumBits<ImageDepthInfo>() {
+template <>
+constexpr unsigned getNumBits<ImageDepthInfo>() {
static_assert((1 << 2) > getMaxEnumValForImageDepthInfo(),
"Not enough bits to encode ImageDepthInfo value");
return 2;
}
-template <> constexpr unsigned getNumBits<ImageArrayedInfo>() {
+template <>
+constexpr unsigned getNumBits<ImageArrayedInfo>() {
static_assert((1 << 1) > getMaxEnumValForImageArrayedInfo(),
"Not enough bits to encode ImageArrayedInfo value");
return 1;
}
-template <> constexpr unsigned getNumBits<ImageSamplingInfo>() {
+template <>
+constexpr unsigned getNumBits<ImageSamplingInfo>() {
static_assert((1 << 1) > getMaxEnumValForImageSamplingInfo(),
"Not enough bits to encode ImageSamplingInfo value");
return 1;
}
-template <> constexpr unsigned getNumBits<ImageSamplerUseInfo>() {
+template <>
+constexpr unsigned getNumBits<ImageSamplerUseInfo>() {
static_assert((1 << 2) > getMaxEnumValForImageSamplerUseInfo(),
"Not enough bits to encode ImageSamplerUseInfo value");
return 2;
}
-template <> constexpr unsigned getNumBits<ImageFormat>() {
+template <>
+constexpr unsigned getNumBits<ImageFormat>() {
static_assert((1 << 6) > getMaxEnumValForImageFormat(),
"Not enough bits to encode ImageFormat value");
return 6;
#include <utility>
-#include "mlir/IR/AffineExpr.h"
#include "AffineExprDetail.h"
+#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineExprVisitor.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/IntegerSet.h"
};
} // namespace
-SSANameState::SSANameState(
- Operation *op, const OpPrintingFlags &printerFlags)
+SSANameState::SSANameState(Operation *op, const OpPrintingFlags &printerFlags)
: printerFlags(printerFlags) {
llvm::SaveAndRestore<unsigned> valueIDSaver(nextValueID);
llvm::SaveAndRestore<unsigned> argumentIDSaver(nextArgumentID);
SuccessorRange::SuccessorRange() : SuccessorRange(nullptr, 0) {}
SuccessorRange::SuccessorRange(Block *block) : SuccessorRange() {
- if (block->empty() || llvm::hasSingleElement(*block->getParent()))
- return;
- Operation *term = &block->back();
- if ((count = term->getNumSuccessors()))
- base = term->getBlockOperands().data();
+ if (block->empty() || llvm::hasSingleElement(*block->getParent()))
+ return;
+ Operation *term = &block->back();
+ if ((count = term->getNumSuccessors()))
+ base = term->getBlockOperands().data();
}
SuccessorRange::SuccessorRange(Operation *term) : SuccessorRange() {
// Otherwise, try to load the source file.
std::string ignored;
- unsigned id =
- mgr.AddIncludeFile(std::string(filename), SMLoc(), ignored);
+ unsigned id = mgr.AddIncludeFile(std::string(filename), SMLoc(), ignored);
filenameToBufId[filename] = id;
return id;
}
return storage;
}
-TypeRange
-mlir::function_interface_impl::filterTypesOut(TypeRange types,
- const BitVector &indices,
- SmallVectorImpl<Type> &storage) {
+TypeRange mlir::function_interface_impl::filterTypesOut(
+ TypeRange types, const BitVector &indices, SmallVectorImpl<Type> &storage) {
if (indices.none())
return types;
operands[numOperands + i].~OpOperand();
}
-void detail::OperandStorage::eraseOperands(
- const BitVector &eraseIndices) {
+void detail::OperandStorage::eraseOperands(const BitVector &eraseIndices) {
MutableArrayRef<OpOperand> operands = getOperands();
assert(eraseIndices.size() == operands.size());
unsigned OpOperand::getOperandNumber() {
return this - &getOwner()->getOpOperands()[0];
}
-
/// Get the location of the next token and store it into the argument. This
/// always succeeds.
- SMLoc getCurrentLocation() override {
- return parser.getToken().getLoc();
- }
+ SMLoc getCurrentLocation() override { return parser.getToken().getLoc(); }
/// Re-encode the given source location as an MLIR location and return it.
Location getEncodedSourceLoc(SMLoc loc) override {
impl->blocks[it->second]->definition.loc = convertIdLocToRange(location);
}
-void AsmParserState::addDefinition(BlockArgument blockArg,
- SMLoc location) {
+void AsmParserState::addDefinition(BlockArgument blockArg, SMLoc location) {
auto it = impl->blocksToIdx.find(blockArg.getOwner());
assert(it != impl->blocksToIdx.end() &&
"expected owner block to have an entry");
/// Build a dense attribute instance with the parsed elements and the given
/// shaped type.
-DenseElementsAttr TensorLiteralParser::getAttr(SMLoc loc,
- ShapedType type) {
+DenseElementsAttr TensorLiteralParser::getAttr(SMLoc loc, ShapedType type) {
Type eltType = type.getElementType();
// Check to see if we parse the literal from a hex string.
}
/// Build a Dense String attribute for the given type.
-DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc,
- ShapedType type,
+DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc, ShapedType type,
Type eltTy) {
if (hexStorage.has_value()) {
auto stringValue = hexStorage.value().getStringValue();
}
/// Build a Dense attribute with hex data for the given type.
-DenseElementsAttr TensorLiteralParser::getHexAttr(SMLoc loc,
- ShapedType type) {
+DenseElementsAttr TensorLiteralParser::getHexAttr(SMLoc loc, ShapedType type) {
Type elementType = type.getElementType();
if (!elementType.isIntOrIndexOrFloat() && !elementType.isa<ComplexType>()) {
p.emitError(loc)
}
private:
- template <typename T> void addDataToHash(llvm::SHA1 &hasher, const T &data) {
+ template <typename T>
+ void addDataToHash(llvm::SHA1 &hasher, const T &data) {
hasher.update(
ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(&data), sizeof(T)));
}
#include <utility>
-#include "mlir/Pass/PassRegistry.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
+#include "mlir/Pass/PassRegistry.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#ifndef NDEBUG
/// Log a message for a pattern that is impossible to match.
static void logImpossibleToMatch(const Pattern &pattern) {
- llvm::dbgs() << "Ignoring pattern '" << pattern.getRootKind()
- << "' because it is impossible to match or cannot lead "
- "to legal IR (by cost model)\n";
+ llvm::dbgs() << "Ignoring pattern '" << pattern.getRootKind()
+ << "' because it is impossible to match or cannot lead "
+ "to legal IR (by cost model)\n";
}
/// Log IR after pattern application.
mapperAllocas)))
return failure();
- if (failed(processOperands(builder, moduleTranslation, op,
- op.createOperands(), totalNbOperand,
- kCreateFlag | kHoldFlag, flags, names, index,
- mapperAllocas)))
+ if (failed(processOperands(
+ builder, moduleTranslation, op, op.createOperands(), totalNbOperand,
+ kCreateFlag | kHoldFlag, flags, names, index, mapperAllocas)))
return failure();
// TODO create zero currenlty handled as create. Update when extension
mapperAllocas)))
return failure();
- if (failed(processOperands(builder, moduleTranslation, op,
- op.presentOperands(), totalNbOperand,
- kPresentFlag | kHoldFlag, flags, names, index,
- mapperAllocas)))
+ if (failed(processOperands(
+ builder, moduleTranslation, op, op.presentOperands(), totalNbOperand,
+ kPresentFlag | kHoldFlag, flags, names, index, mapperAllocas)))
return failure();
llvm::GlobalVariable *maptypes =
/// Method to deserialize an operation in the SPIR-V dialect that is a mirror
/// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode
/// == 1 and autogenSerialization == 1 in ODS.
- template <typename OpTy> LogicalResult processOp(ArrayRef<uint32_t> words) {
+ template <typename OpTy>
+ LogicalResult processOp(ArrayRef<uint32_t> words) {
return emitError(unknownLoc, "unsupported deserialization for ")
<< OpTy::getOperationName() << " op";
}
/// Serializes an operation in the SPIR-V dialect that is a mirror of an
/// instruction in the SPIR-V spec. This is auto generated if hasOpcode == 1
/// and autogenSerialization == 1 in ODS.
- template <typename OpTy> LogicalResult processOp(OpTy op) {
+ template <typename OpTy>
+ LogicalResult processOp(OpTy op) {
return op.emitError("unsupported op serialization");
}
// LetStmt
//===----------------------------------------------------------------------===//
-LetStmt *LetStmt::create(Context &ctx, SMRange loc,
- VariableDecl *varDecl) {
+LetStmt *LetStmt::create(Context &ctx, SMRange loc, VariableDecl *varDecl) {
return new (ctx.getAllocator().Allocate<LetStmt>()) LetStmt(loc, varDecl);
}
// TypeConstraintDecl
//===----------------------------------------------------------------------===//
-TypeConstraintDecl *TypeConstraintDecl::create(Context &ctx,
- SMRange loc) {
+TypeConstraintDecl *TypeConstraintDecl::create(Context &ctx, SMRange loc) {
return new (ctx.getAllocator().Allocate<TypeConstraintDecl>())
TypeConstraintDecl(loc);
}
// ValueConstraintDecl
//===----------------------------------------------------------------------===//
-ValueConstraintDecl *
-ValueConstraintDecl::create(Context &ctx, SMRange loc, Expr *typeExpr) {
+ValueConstraintDecl *ValueConstraintDecl::create(Context &ctx, SMRange loc,
+ Expr *typeExpr) {
return new (ctx.getAllocator().Allocate<ValueConstraintDecl>())
ValueConstraintDecl(loc, typeExpr);
}
// ValueRangeConstraintDecl
//===----------------------------------------------------------------------===//
-ValueRangeConstraintDecl *ValueRangeConstraintDecl::create(Context &ctx,
- SMRange loc,
- Expr *typeExpr) {
+ValueRangeConstraintDecl *
+ValueRangeConstraintDecl::create(Context &ctx, SMRange loc, Expr *typeExpr) {
return new (ctx.getAllocator().Allocate<ValueRangeConstraintDecl>())
ValueRangeConstraintDecl(loc, typeExpr);
}
// PatternDecl
//===----------------------------------------------------------------------===//
-PatternDecl *PatternDecl::create(Context &ctx, SMRange loc,
- const Name *name, Optional<uint16_t> benefit,
+PatternDecl *PatternDecl::create(Context &ctx, SMRange loc, const Name *name,
+ Optional<uint16_t> benefit,
bool hasBoundedRecursion,
const CompoundStmt *body) {
return new (ctx.getAllocator().Allocate<PatternDecl>())
// Module
//===----------------------------------------------------------------------===//
-Module *Module::create(Context &ctx, SMLoc loc,
- ArrayRef<Decl *> children) {
+Module *Module::create(Context &ctx, SMLoc loc, ArrayRef<Decl *> children) {
unsigned allocSize = Module::totalSizeToAlloc<Decl *>(children.size());
void *rawData = ctx.getAllocator().Allocate(allocSize, alignof(Module));
assert(i + 1 <= e && "invalid string should be caught by lexer");
auto c1 = bytes[i++];
switch (c1) {
- case '"':
- case '\\':
- result.push_back(c1);
- continue;
- case 'n':
- result.push_back('\n');
- continue;
- case 't':
- result.push_back('\t');
- continue;
- default:
- break;
+ case '"':
+ case '\\':
+ result.push_back(c1);
+ continue;
+ case 'n':
+ result.push_back('\n');
+ continue;
+ case 't':
+ result.push_back('\t');
+ continue;
+ default:
+ break;
}
assert(i + 1 <= e && "invalid string should be caught by lexer");
}
Lexer::~Lexer() {
- if (addedHandlerToDiagEngine) diagEngine.setHandlerFn(nullptr);
+ if (addedHandlerToDiagEngine)
+ diagEngine.setHandlerFn(nullptr);
}
LogicalResult Lexer::pushInclude(StringRef filename, SMRange includeLoc) {
diagEngine.emitError(loc, msg);
return formToken(Token::error, loc.Start.getPointer());
}
-Token Lexer::emitErrorAndNote(SMRange loc, const Twine &msg,
- SMRange noteLoc, const Twine ¬e) {
+Token Lexer::emitErrorAndNote(SMRange loc, const Twine &msg, SMRange noteLoc,
+ const Twine ¬e) {
diagEngine.emitError(loc, msg)->attachNote(note, noteLoc);
return formToken(Token::error, loc.Start.getPointer());
}
Token Lexer::emitError(const char *loc, const Twine &msg) {
- return emitError(SMRange(SMLoc::getFromPointer(loc),
- SMLoc::getFromPointer(loc + 1)),
- msg);
+ return emitError(
+ SMRange(SMLoc::getFromPointer(loc), SMLoc::getFromPointer(loc + 1)), msg);
}
int Lexer::getNextChar() {
char curChar = *curPtr++;
switch (curChar) {
- default:
- return static_cast<unsigned char>(curChar);
- case 0: {
- // A nul character in the stream is either the end of the current buffer
- // or a random nul in the file. Disambiguate that here.
- if (curPtr - 1 != curBuffer.end()) return 0;
-
- // Otherwise, return end of file.
- --curPtr;
- return EOF;
- }
- case '\n':
- case '\r':
- // Handle the newline character by ignoring it and incrementing the line
- // count. However, be careful about 'dos style' files with \n\r in them.
- // Only treat a \n\r or \r\n as a single line.
- if ((*curPtr == '\n' || (*curPtr == '\r')) && *curPtr != curChar)
- ++curPtr;
- return '\n';
+ default:
+ return static_cast<unsigned char>(curChar);
+ case 0: {
+ // A nul character in the stream is either the end of the current buffer
+ // or a random nul in the file. Disambiguate that here.
+ if (curPtr - 1 != curBuffer.end())
+ return 0;
+
+ // Otherwise, return end of file.
+ --curPtr;
+ return EOF;
+ }
+ case '\n':
+ case '\r':
+ // Handle the newline character by ignoring it and incrementing the line
+ // count. However, be careful about 'dos style' files with \n\r in them.
+ // Only treat a \n\r or \r\n as a single line.
+ if ((*curPtr == '\n' || (*curPtr == '\r')) && *curPtr != curChar)
+ ++curPtr;
+ return '\n';
}
}
// This always consumes at least one character.
int curChar = getNextChar();
switch (curChar) {
- default:
- // Handle identifiers: [a-zA-Z_]
- if (isalpha(curChar) || curChar == '_') return lexIdentifier(tokStart);
-
- // Unknown character, emit an error.
- return emitError(tokStart, "unexpected character");
- case EOF: {
- // Return EOF denoting the end of lexing.
- Token eof = formToken(Token::eof, tokStart);
-
- // Check to see if we are in an included file.
- SMLoc parentIncludeLoc = srcMgr.getParentIncludeLoc(curBufferID);
- if (parentIncludeLoc.isValid()) {
- curBufferID = srcMgr.FindBufferContainingLoc(parentIncludeLoc);
- curBuffer = srcMgr.getMemoryBuffer(curBufferID)->getBuffer();
- curPtr = parentIncludeLoc.getPointer();
- }
-
- return eof;
+ default:
+ // Handle identifiers: [a-zA-Z_]
+ if (isalpha(curChar) || curChar == '_')
+ return lexIdentifier(tokStart);
+
+ // Unknown character, emit an error.
+ return emitError(tokStart, "unexpected character");
+ case EOF: {
+ // Return EOF denoting the end of lexing.
+ Token eof = formToken(Token::eof, tokStart);
+
+ // Check to see if we are in an included file.
+ SMLoc parentIncludeLoc = srcMgr.getParentIncludeLoc(curBufferID);
+ if (parentIncludeLoc.isValid()) {
+ curBufferID = srcMgr.FindBufferContainingLoc(parentIncludeLoc);
+ curBuffer = srcMgr.getMemoryBuffer(curBufferID)->getBuffer();
+ curPtr = parentIncludeLoc.getPointer();
+ }
+
+ return eof;
+ }
+
+ // Lex punctuation.
+ case '-':
+ if (*curPtr == '>') {
+ ++curPtr;
+ return formToken(Token::arrow, tokStart);
+ }
+ return emitError(tokStart, "unexpected character");
+ case ':':
+ return formToken(Token::colon, tokStart);
+ case ',':
+ return formToken(Token::comma, tokStart);
+ case '.':
+ return formToken(Token::dot, tokStart);
+ case '=':
+ if (*curPtr == '>') {
+ ++curPtr;
+ return formToken(Token::equal_arrow, tokStart);
+ }
+ return formToken(Token::equal, tokStart);
+ case ';':
+ return formToken(Token::semicolon, tokStart);
+ case '[':
+ if (*curPtr == '{') {
+ ++curPtr;
+ return lexString(tokStart, /*isStringBlock=*/true);
}
+ return formToken(Token::l_square, tokStart);
+ case ']':
+ return formToken(Token::r_square, tokStart);
+
+ case '<':
+ return formToken(Token::less, tokStart);
+ case '>':
+ return formToken(Token::greater, tokStart);
+ case '{':
+ return formToken(Token::l_brace, tokStart);
+ case '}':
+ return formToken(Token::r_brace, tokStart);
+ case '(':
+ return formToken(Token::l_paren, tokStart);
+ case ')':
+ return formToken(Token::r_paren, tokStart);
+ case '/':
+ if (*curPtr == '/') {
+ lexComment();
+ continue;
+ }
+ return emitError(tokStart, "unexpected character");
- // Lex punctuation.
- case '-':
- if (*curPtr == '>') {
- ++curPtr;
- return formToken(Token::arrow, tokStart);
- }
- return emitError(tokStart, "unexpected character");
- case ':':
- return formToken(Token::colon, tokStart);
- case ',':
- return formToken(Token::comma, tokStart);
- case '.':
- return formToken(Token::dot, tokStart);
- case '=':
- if (*curPtr == '>') {
- ++curPtr;
- return formToken(Token::equal_arrow, tokStart);
- }
- return formToken(Token::equal, tokStart);
- case ';':
- return formToken(Token::semicolon, tokStart);
- case '[':
- if (*curPtr == '{') {
- ++curPtr;
- return lexString(tokStart, /*isStringBlock=*/true);
- }
- return formToken(Token::l_square, tokStart);
- case ']':
- return formToken(Token::r_square, tokStart);
-
- case '<':
- return formToken(Token::less, tokStart);
- case '>':
- return formToken(Token::greater, tokStart);
- case '{':
- return formToken(Token::l_brace, tokStart);
- case '}':
- return formToken(Token::r_brace, tokStart);
- case '(':
- return formToken(Token::l_paren, tokStart);
- case ')':
- return formToken(Token::r_paren, tokStart);
- case '/':
- if (*curPtr == '/') {
- lexComment();
- continue;
- }
- return emitError(tokStart, "unexpected character");
-
- // Ignore whitespace characters.
- case 0:
- case ' ':
- case '\t':
- case '\n':
- return lexToken();
-
- case '#':
- return lexDirective(tokStart);
- case '"':
- return lexString(tokStart, /*isStringBlock=*/false);
-
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- return lexNumber(tokStart);
+ // Ignore whitespace characters.
+ case 0:
+ case ' ':
+ case '\t':
+ case '\n':
+ return lexToken();
+
+ case '#':
+ return lexDirective(tokStart);
+ case '"':
+ return lexString(tokStart, /*isStringBlock=*/false);
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ return lexNumber(tokStart);
}
}
}
while (true) {
switch (*curPtr++) {
- case '\n':
- case '\r':
- // Newline is end of comment.
+ case '\n':
+ case '\r':
+ // Newline is end of comment.
+ return;
+ case 0:
+ // If this is the end of the buffer, end the comment.
+ if (curPtr - 1 == curBuffer.end()) {
+ --curPtr;
return;
- case 0:
- // If this is the end of the buffer, end the comment.
- if (curPtr - 1 == curBuffer.end()) {
- --curPtr;
- return;
- }
- LLVM_FALLTHROUGH;
- default:
- // Skip over other characters.
- break;
+ }
+ LLVM_FALLTHROUGH;
+ default:
+ // Skip over other characters.
+ break;
}
}
}
Token Lexer::lexDirective(const char *tokStart) {
// Match the rest with an identifier regex: [0-9a-zA-Z_]*
- while (isalnum(*curPtr) || *curPtr == '_') ++curPtr;
+ while (isalnum(*curPtr) || *curPtr == '_')
+ ++curPtr;
StringRef str(tokStart, curPtr - tokStart);
return Token(Token::directive, str);
Token Lexer::lexIdentifier(const char *tokStart) {
// Match the rest of the identifier regex: [0-9a-zA-Z_]*
- while (isalnum(*curPtr) || *curPtr == '_') ++curPtr;
+ while (isalnum(*curPtr) || *curPtr == '_')
+ ++curPtr;
// Check to see if this identifier is a keyword.
StringRef str(tokStart, curPtr - tokStart);
assert(isdigit(curPtr[-1]));
// Handle the normal decimal case.
- while (isdigit(*curPtr)) ++curPtr;
+ while (isdigit(*curPtr))
+ ++curPtr;
return formToken(Token::integer, tokStart);
}
}
switch (*curPtr++) {
- case '"':
- // If this is a string block, we only end the string when we encounter a
- // `}]`.
- if (!isStringBlock)
- return formToken(Token::string, tokStart);
+ case '"':
+ // If this is a string block, we only end the string when we encounter a
+ // `}]`.
+ if (!isStringBlock)
+ return formToken(Token::string, tokStart);
+ continue;
+ case '}':
+ // If this is a string block, we only end the string when we encounter a
+ // `}]`.
+ if (!isStringBlock || *curPtr != ']')
continue;
- case '}':
- // If this is a string block, we only end the string when we encounter a
- // `}]`.
- if (!isStringBlock || *curPtr != ']')
- continue;
- ++curPtr;
- return formToken(Token::string_block, tokStart);
- case 0: {
- // If this is a random nul character in the middle of a string, just
- // include it. If it is the end of file, then it is an error.
- if (curPtr - 1 != curBuffer.end())
- continue;
- --curPtr;
+ ++curPtr;
+ return formToken(Token::string_block, tokStart);
+ case 0: {
+ // If this is a random nul character in the middle of a string, just
+ // include it. If it is the end of file, then it is an error.
+ if (curPtr - 1 != curBuffer.end())
+ continue;
+ --curPtr;
- StringRef expectedEndStr = isStringBlock ? "}]" : "\"";
- return emitError(curPtr - 1,
- "expected '" + expectedEndStr + "' in string literal");
- }
+ StringRef expectedEndStr = isStringBlock ? "}]" : "\"";
+ return emitError(curPtr - 1,
+ "expected '" + expectedEndStr + "' in string literal");
+ }
- case '\n':
- case '\v':
- case '\f':
- // String blocks allow multiple lines.
- if (!isStringBlock)
- return emitError(curPtr - 1, "expected '\"' in string literal");
- continue;
+ case '\n':
+ case '\v':
+ case '\f':
+ // String blocks allow multiple lines.
+ if (!isStringBlock)
+ return emitError(curPtr - 1, "expected '\"' in string literal");
+ continue;
- case '\\':
- // Handle explicitly a few escapes.
- if (*curPtr == '"' || *curPtr == '\\' || *curPtr == 'n' ||
- *curPtr == 't') {
- ++curPtr;
- } else if (llvm::isHexDigit(*curPtr) && llvm::isHexDigit(curPtr[1])) {
- // Support \xx for two hex digits.
- curPtr += 2;
- } else {
- return emitError(curPtr - 1, "unknown escape in string literal");
- }
- continue;
+ case '\\':
+ // Handle explicitly a few escapes.
+ if (*curPtr == '"' || *curPtr == '\\' || *curPtr == 'n' ||
+ *curPtr == 't') {
+ ++curPtr;
+ } else if (llvm::isHexDigit(*curPtr) && llvm::isHexDigit(curPtr[1])) {
+ // Support \xx for two hex digits.
+ curPtr += 2;
+ } else {
+ return emitError(curPtr - 1, "unknown escape in string literal");
+ }
+ continue;
- default:
- continue;
+ default:
+ continue;
}
}
}
/// Return if the token does not have the given kind.
bool isNot(Kind k) const { return k != kind; }
- template <typename... T> bool isNot(Kind k1, Kind k2, T... others) const {
+ template <typename... T>
+ bool isNot(Kind k1, Kind k2, T... others) const {
return !isAny(k1, k2, others...);
}
bool is(Kind k) const { return kind == k; }
/// Return a location for the start of this token.
- SMLoc getStartLoc() const {
- return SMLoc::getFromPointer(spelling.data());
- }
+ SMLoc getStartLoc() const { return SMLoc::getFromPointer(spelling.data()); }
/// Return a location at the end of this token.
SMLoc getEndLoc() const {
return SMLoc::getFromPointer(spelling.data() + spelling.size());
}
/// Return a location for the range of this token.
- SMRange getLoc() const {
- return SMRange(getStartLoc(), getEndLoc());
- }
+ SMRange getLoc() const { return SMRange(getStartLoc(), getEndLoc()); }
private:
/// Discriminator that indicates the kind of token this is.
/// Emit an error to the lexer with the given location and message.
Token emitError(SMRange loc, const Twine &msg);
Token emitError(const char *loc, const Twine &msg);
- Token emitErrorAndNote(SMRange loc, const Twine &msg,
- SMRange noteLoc, const Twine ¬e);
+ Token emitErrorAndNote(SMRange loc, const Twine &msg, SMRange noteLoc,
+ const Twine ¬e);
private:
Token formToken(Token::Kind kind, const char *tokStart) {
} // namespace
-std::unique_ptr<Pass>
-mlir::createPrintOpGraphPass(raw_ostream &os) {
+std::unique_ptr<Pass> mlir::createPrintOpGraphPass(raw_ostream &os) {
return std::make_unique<PrintOpPass>(os);
}
/// Function to find an element within the given range that has the same name as
/// 'name'.
-template <typename RangeT> static auto findArg(RangeT &&range, StringRef name) {
+template <typename RangeT>
+static auto findArg(RangeT &&range, StringRef name) {
auto it = llvm::find_if(range, [=](auto &arg) { return arg.name == name; });
return it != range.end() ? &*it : nullptr;
}
// Handler that uses the number of action executions as the decider.
struct DebugCounterHandler : public SimpleAction::Handler {
- FailureOr<bool> shouldExecute() final {
- return numExecutions++ < 3;
- }
+ FailureOr<bool> shouldExecute() final { return numExecutions++ < 3; }
unsigned numExecutions = 0;
};
manager.registerActionHandler<DebugCounterHandler>();
verifyOp(std::move(op), {i32Ty}, {*cstI32, *cstI32}, noAttrs);
// Test collective params build method.
- op =
- builder.create<OpTy>(loc, TypeRange{i32Ty}, ValueRange{*cstI32, *cstI32});
+ op = builder.create<OpTy>(loc, TypeRange{i32Ty},
+ ValueRange{*cstI32, *cstI32});
verifyOp(std::move(op), {i32Ty}, {*cstI32, *cstI32}, noAttrs);
// Test build method with no result types, default value of attributes.