aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/MC/TargetRegistry.cpp
blob: 217f59b13f60abc13a03481116574a186ae6267e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/MC/TargetRegistry.h"

#include "rcc/Target/TargetMachine.h"

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

namespace rcc {
namespace {

[[nodiscard]] std::vector<const Target *> &registeredTargets() {
  static std::vector<const Target *> Targets;
  return Targets;
}

} // namespace

TargetMachineOptions Target::defaultMachineOptions() const {
  return DefaultOptions();
}

Expected<std::unique_ptr<TargetMachine>>
Target::createTargetMachine(TargetMachineOptions Options) const {
  return TargetMachineCtor(*this, std::move(Options));
}

void TargetRegistry::registerTarget(const Target &RegisteredTarget) {
  std::vector<const Target *> &Targets = registeredTargets();
  if (std::ranges::find(Targets, &RegisteredTarget) == Targets.end())
    Targets.push_back(&RegisteredTarget);
}

Expected<const Target *> TargetRegistry::lookupTarget(std::string_view Triple) {
  const Target *Best = nullptr;
  unsigned BestQuality = 0;
  for (const Target *Candidate : registeredTargets()) {
    const unsigned Quality = Candidate->matchQuality(Triple);
    if (Quality > BestQuality) {
      Best = Candidate;
      BestQuality = Quality;
    } else if (Quality != 0 && Quality == BestQuality) {
      return makeUnexpected(ErrorCode::InvalidInvocation,
                            "target triple matches multiple registered targets");
    }
  }
  if (Best == nullptr) {
    return makeUnexpected(ErrorCode::Unsupported,
                          "no registered target supports triple '" + std::string(Triple) + "'");
  }
  return Best;
}

Expected<const Target *> TargetRegistry::defaultTarget() {
  const Target *Default = nullptr;
  for (const Target *Candidate : registeredTargets()) {
    if (!Candidate->isDefault())
      continue;
    if (Default != nullptr) {
      return makeUnexpected(ErrorCode::InternalError,
                            "multiple targets are registered as the default target");
    }
    Default = Candidate;
  }
  if (Default == nullptr)
    return makeUnexpected(ErrorCode::InternalError, "no default target is registered");
  return Default;
}

} // namespace rcc