1//===- TargetToTargetFeatures.cpp - extract features from TargetMachine ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "mlir/Target/LLVMIR/Transforms/Passes.h"
10#include "mlir/Target/LLVMIR/Transforms/TargetUtils.h"
11#include "llvm/ADT/SmallVectorExtras.h"
12
13#include "mlir/Dialect/DLTI/DLTI.h"
14#include "mlir/Dialect/LLVMIR/LLVMDialectDecl.h"
15#include "mlir/Target/LLVMIR/Import.h"
16
17#include "llvm/MC/MCSubtargetInfo.h"
18
19namespace mlir {
20namespace LLVM {
21#define GEN_PASS_DEF_LLVMTARGETTOTARGETFEATURES
22#include "mlir/Target/LLVMIR/Transforms/Passes.h.inc"
23} // namespace LLVM
24} // namespace mlir
25
26using namespace mlir;
27
28struct TargetToTargetFeaturesPass
29 : public LLVM::impl::LLVMTargetToTargetFeaturesBase<
30 TargetToTargetFeaturesPass> {
31 using LLVM::impl::LLVMTargetToTargetFeaturesBase<
32 TargetToTargetFeaturesPass>::LLVMTargetToTargetFeaturesBase;
33
34 void runOnOperation() override {
35 Operation *op = getOperation();
36
37 if (initializeLLVMTargets)
38 LLVM::detail::initializeBackendsOnce();
39
40 auto targetAttr = op->getDiscardableAttrOfType<LLVM::TargetAttr>(
41 name: LLVM::LLVMDialect::getTargetAttrName());
42 if (!targetAttr) {
43 op->emitError() << "no LLVM::TargetAttr attribute at key \""
44 << LLVM::LLVMDialect::getTargetAttrName() << "\"";
45 return signalPassFailure();
46 }
47
48 FailureOr<std::unique_ptr<llvm::TargetMachine>> targetMachine =
49 LLVM::detail::getTargetMachine(attr: targetAttr);
50 if (failed(Result: targetMachine)) {
51 op->emitError() << "failed to obtain llvm::TargetMachine for "
52 << targetAttr;
53 return signalPassFailure();
54 }
55
56 llvm::MCSubtargetInfo const &subTargetInfo =
57 (*targetMachine)->getMCSubtargetInfo();
58
59 const std::vector<const llvm::SubtargetFeatureKV *> enabledFeatures =
60 subTargetInfo.getEnabledProcessorFeatures();
61
62 auto plussedFeatures = llvm::map_to_vector(
63 C: enabledFeatures, F: [](const llvm::SubtargetFeatureKV *feature) {
64 return std::string("+") + feature->key();
65 });
66
67 auto plussedFeaturesRefs = llvm::map_to_vector(
68 C&: plussedFeatures, F: [](auto &it) { return StringRef(it.c_str()); });
69
70 auto fullTargetFeaturesAttr =
71 LLVM::TargetFeaturesAttr::get(context: &getContext(), features: plussedFeaturesRefs);
72
73 auto queryOp = dyn_cast<DLTIQueryOpInterface>(Val: op);
74 if (!queryOp ||
75 failed(Result: queryOp.setDlti(key: StringAttr::get(context: &getContext(), bytes: "features"),
76 value: fullTargetFeaturesAttr))) {
77 op->emitError() << "failed to update DLTI target features";
78 return signalPassFailure();
79 }
80 }
81};
82