aboutsummaryrefslogtreecommitdiff
path: root/backend/utils/TableGen/Common/CodeGenTarget.cpp
blob: d4c9795d0606ac84988cdc2769e1855322d77921 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// SPDX-License-Identifier: GPL-3.0-or-later

#include "Common/CodeGenTarget.h"

#include "TableGenBackends.h"
#include "rcc/TableGen/Parser.h"

#include <algorithm>
#include <cstddef>
#include <ranges>
#include <string>
#include <string_view>
#include <unordered_set>
#include <utility>

namespace rcc::targetgen {

[[nodiscard]] bool isPowerOfTwo(std::uint64_t Value) noexcept {
  return Value != 0 && (Value & (Value - 1U)) == 0;
}

CodeGenTarget::CodeGenTarget(const DescriptionAST &Input, std::string SourceName)
    : Input(Input), SourceName(std::move(SourceName)) {}

[[nodiscard]] std::optional<NormalizedTargetModel> CodeGenTarget::normalize() {
  if (!validateTarget())
    return std::nullopt;

  NormalizedTargetModel Result;
  Result.Target = Input.Target;
  Result.RegisterUnits = Input.RegisterUnits;
  Result.MIROperandFlags = Input.MIROperandFlags;
  if (!normalizeRegisterUnits() || !normalizeRegisters(Result) || !normalizeRegisterBanks(Result) ||
      !normalizeRegisterClasses(Result) || !normalizeRegisterMasks(Result) ||
      !normalizeMIROperandFlags(Result) || !normalizeCallingConventions(Result) ||
      !normalizeNamedOperands(Result) || !normalizeImmediatePredicates(Result) ||
      !normalizeSchedulingClasses(Result) || !normalizeEncodingCategories(Result) ||
      !normalizeAssemblyFormats(Result) || !normalizeInstructions(Result) ||
      !normalizeSelectionRules(Result) || !normalizeCombinerRules(Result) ||
      !normalizeMacroFusionRules(Result) || !normalizeMCPseudoExpansions(Result)) {
    return std::nullopt;
  }
  std::ranges::sort(Result.RegisterUnits, {}, &SourceRegisterUnit::ID);
  std::ranges::sort(Result.Registers, {}, &NormalizedRegister::ID);
  std::ranges::sort(Result.RegisterBanks, {}, &NormalizedRegisterBank::ID);
  std::ranges::sort(Result.RegisterClasses, {}, &NormalizedRegisterClass::ID);
  std::ranges::sort(Result.CallingConventions, {}, &NormalizedCallingConvention::ID);
  std::ranges::sort(Result.NamedOperands, {}, &NormalizedNamedOperand::ID);
  std::ranges::sort(Result.ImmediatePredicates, {}, &NormalizedImmediatePredicate::ID);
  std::ranges::sort(Result.SchedulingClasses, {}, &NormalizedSchedulingClass::ID);
  std::ranges::sort(Result.EncodingCategories, {}, &NormalizedEncodingCategory::ID);
  std::ranges::sort(Result.AssemblyFormats, {}, &NormalizedAssemblyFormat::ID);
  return Result;
}

[[nodiscard]] std::vector<TextDiagnostic> CodeGenTarget::takeDiagnostics() {
  return std::move(Diagnostics);
}

void CodeGenTarget::fail(TextRange Range, std::string Message) {
  Diagnostics.push_back({
      .Severity = DiagnosticSeverity::Error,
      .Category = "target-description",
      .Message = std::move(Message),
      .SourceName = SourceName,
      .Range = Range,
  });
}

[[nodiscard]] bool CodeGenTarget::validateTarget() {
  if (!isIdentifier(Input.Target.Namespace)) {
    fail(Input.Target.Range, "target namespace must be a C++ identifier");
    return false;
  }
  if (Input.Target.Name.empty() || Input.Target.Triple.empty() || Input.Target.CPU.empty() ||
      Input.Target.ABI.empty() || Input.Target.DataLayout.empty() ||
      Input.Target.Features.empty()) {
    fail(Input.Target.Range, "target metadata fields and feature list must be nonempty");
    return false;
  }
  std::unordered_set<std::string> Features;
  for (const std::string &Feature : Input.Target.Features) {
    if (Feature.empty() || !Features.insert(Feature).second) {
      fail(Input.Target.Range, "target feature names must be nonempty and unique");
      return false;
    }
  }
  return true;
}

[[nodiscard]] bool CodeGenTarget::normalizeCallingConventions(NormalizedTargetModel &Result) {
  if (Input.CallingConventions.empty()) {
    fail(Input.Target.Range, "target description requires at least one calling convention");
    return false;
  }
  std::unordered_set<std::uint32_t> IDs;
  std::unordered_set<std::string> Symbols;
  std::unordered_set<std::string> Names;
  for (const SourceCallingConvention &Convention : Input.CallingConventions) {
    const auto IntegerClass = ClassBySymbol.find(Convention.IntegerRegisterClassSymbol);
    const auto FloatingClass = ClassBySymbol.find(Convention.FloatingRegisterClassSymbol);
    const auto PreservedMask = std::ranges::find(Result.RegisterMasks, Convention.PreservedMaskName,
                                                 &NormalizedRegisterMask::Name);
    if (Convention.ID == 0 || !isIdentifier(Convention.Symbol) || Convention.Name.empty() ||
        IntegerClass == ClassBySymbol.end() || FloatingClass == ClassBySymbol.end() ||
        PreservedMask == Result.RegisterMasks.end() || Convention.StackAlignmentBytes == 0 ||
        Convention.StackArgumentAlignmentBytes == 0 ||
        !isPowerOfTwo(Convention.StackAlignmentBytes) ||
        !isPowerOfTwo(Convention.StackArgumentAlignmentBytes) ||
        Convention.StackAlignmentBytes % Convention.StackArgumentAlignmentBytes != 0 ||
        Convention.ShadowSpaceBytes % Convention.StackArgumentAlignmentBytes != 0 ||
        !IDs.insert(Convention.ID).second || !Symbols.insert(Convention.Symbol).second ||
        !Names.insert(Convention.Name).second) {
      fail(Convention.Range,
           "calling conventions require unique IDs, symbols, names, declared register classes and "
           "preserved masks, compatible power-of-two stack alignments, and aligned shadow space");
      return false;
    }
    const auto IntegerClassDescription = std::ranges::find(
        Result.RegisterClasses, IntegerClass->second, &NormalizedRegisterClass::ID);
    const auto FloatingClassDescription = std::ranges::find(
        Result.RegisterClasses, FloatingClass->second, &NormalizedRegisterClass::ID);
    if (IntegerClassDescription == Result.RegisterClasses.end() ||
        FloatingClassDescription == Result.RegisterClasses.end()) {
      fail(Convention.Range, "calling convention register classes must resolve");
      return false;
    }
    const auto NormalizeRegisterList = [this,
                                        &Convention](const std::vector<std::string> &Symbols,
                                                     const NormalizedRegisterClass &RegisterClass,
                                                     std::vector<std::uint32_t> &Output) {
      std::unordered_set<std::uint32_t> Registers;
      for (const std::string &Symbol : Symbols) {
        const auto Register = RegisterBySymbol.find(Symbol);
        if (Register == RegisterBySymbol.end() ||
            !std::ranges::contains(RegisterClass.Registers, Register->second) ||
            !Registers.insert(Register->second).second) {
          fail(Convention.Range,
               "calling convention register lists must contain distinct members of their class");
          return false;
        }
        Output.push_back(Register->second);
      }
      return true;
    };
    NormalizedCallingConvention Normalized{
        .ID = Convention.ID,
        .Symbol = Convention.Symbol,
        .Name = Convention.Name,
        .IntegerRegisterClass = IntegerClass->second,
        .FloatingRegisterClass = FloatingClass->second,
        .IntegerArgumentRegisters = {},
        .FloatingArgumentRegisters = {},
        .IntegerReturnRegisters = {},
        .FloatingReturnRegisters = {},
        .PreservedMaskName = Convention.PreservedMaskName,
        .StackAlignmentBytes = Convention.StackAlignmentBytes,
        .StackArgumentAlignmentBytes = Convention.StackArgumentAlignmentBytes,
        .ShadowSpaceBytes = Convention.ShadowSpaceBytes,
        .SupportsVarArgs = Convention.SupportsVarArgs,
        .SupportsTailCalls = Convention.SupportsTailCalls,
    };
    if (!NormalizeRegisterList(Convention.IntegerArgumentRegisterSymbols, *IntegerClassDescription,
                               Normalized.IntegerArgumentRegisters) ||
        !NormalizeRegisterList(Convention.FloatingArgumentRegisterSymbols,
                               *FloatingClassDescription, Normalized.FloatingArgumentRegisters) ||
        !NormalizeRegisterList(Convention.IntegerReturnRegisterSymbols, *IntegerClassDescription,
                               Normalized.IntegerReturnRegisters) ||
        !NormalizeRegisterList(Convention.FloatingReturnRegisterSymbols, *FloatingClassDescription,
                               Normalized.FloatingReturnRegisters)) {
      return false;
    }
    CallingConventionBySymbol.emplace(Convention.Symbol, Convention.ID);
    Result.CallingConventions.push_back(std::move(Normalized));
  }
  return true;
}

[[nodiscard]] const NormalizedRegister &findRegister(const NormalizedTargetModel &Model,
                                                     std::uint32_t ID) {
  const auto Position = std::ranges::find(Model.Registers, ID, &NormalizedRegister::ID);
  return *Position;
}
[[nodiscard]] const SourceRegisterUnit &findRegisterUnit(const NormalizedTargetModel &Model,
                                                         std::uint32_t ID) {
  const auto Position = std::ranges::find(Model.RegisterUnits, ID, &SourceRegisterUnit::ID);
  return *Position;
}
[[nodiscard]] const NormalizedRegisterBank &findRegisterBank(const NormalizedTargetModel &Model,
                                                             std::uint32_t ID) {
  const auto Position = std::ranges::find(Model.RegisterBanks, ID, &NormalizedRegisterBank::ID);
  return *Position;
}

DescriptionGenerationResult generateDescription(const std::string &SourceName,
                                                std::string SourceText) {
  DescriptionParseResult ParseResult = parseDescription(SourceName, std::move(SourceText));
  if (!ParseResult.Records)
    return {.Output = std::nullopt, .Diagnostics = std::move(ParseResult.Diagnostics)};

  CodeGenTarget Target(*ParseResult.Records, SourceName);
  auto Model = Target.normalize();
  if (!Model)
    return {.Output = std::nullopt, .Diagnostics = Target.takeDiagnostics()};

  const std::size_t Separator = SourceName.find_last_of("/\\");
  const std::string_view DisplayName = Separator == std::string::npos
                                           ? std::string_view(SourceName)
                                           : std::string_view(SourceName).substr(Separator + 1);
  return {
      .Output =
          GeneratedDescription{
              .RegisterHeader = emitRegisterHeader(*Model, DisplayName),
              .InstructionHeader = emitInstructionHeader(*Model, DisplayName),
              .TargetTables = emitRegisterInfo(*Model, DisplayName) + emitInstructionInfo(*Model) +
                              emitSubtarget(*Model) + emitCodeEmitter(*Model) +
                              emitAssemblyWriter(*Model) + emitSearchableTables(*Model) +
                              emitCallingConventions(*Model),
              .GlobalISel = emitGlobalISel(*Model, DisplayName),
              .GlobalISelCombiner = emitGlobalISelCombiner(*Model, DisplayName),
              .MacroFusion = emitMacroFusion(*Model, DisplayName),
              .MCPseudoLowering = emitMCPseudoLowering(*Model, DisplayName),
          },
      .Diagnostics = {},
  };
}

} // namespace rcc::targetgen