aboutsummaryrefslogtreecommitdiff
path: root/backend/tools/AssemblyEmitter/AssemblyEmitterMain.cpp
blob: 8697754bc4d254c76b2378309954c687059c006d (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
229
230
231
232
233
234
235
236
237
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineOptimizationPipeline.h"
#include "rcc/CodeGen/MachinePass.h"
#include "rcc/CodeGen/MachinePipelinePasses.h"
#include "rcc/CodeGen/MachineSSAExit.h"
#include "rcc/CodeGen/RegAllocPBQP.h"
#include "rcc/MIR/MIRDocument.h"
#include "rcc/Support/TextDiagnostic.h"
#include "rcc/Target/RISCV/RISCVAssemblyPrinter.h"
#include "rcc/Target/RISCV/RISCVCodeGen.h"
#include "rcc/Target/RISCV/RISCVObjectFile.h"
#include "rcc/Target/RISCV/RISCVTarget.h"

#include <cstdint>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

namespace {

enum class OutputKind : std::uint8_t {
  Assembly,
  Object,
};

struct CommandLine final {
  std::string InputPath;
  std::string OutputPath = "-";
  OutputKind Kind = OutputKind::Assembly;
};

void printUsage() {
  std::cerr << "usage: rcc-backend-asm --input <mir-file|-> "
               "[--filetype asm|obj] [--output <file|->]\n";
}

[[nodiscard]] bool parseCommandLine(int ArgumentCount, char *Arguments[], CommandLine &Result) {
  for (int Index = 1; Index < ArgumentCount; ++Index) {
    const std::string_view Argument(Arguments[Index]);
    if (Argument == "--input" && Index + 1 < ArgumentCount) {
      Result.InputPath = Arguments[++Index];
      continue;
    }
    if ((Argument == "--output" || Argument == "-o") && Index + 1 < ArgumentCount) {
      Result.OutputPath = Arguments[++Index];
      continue;
    }
    if (Argument == "--filetype" && Index + 1 < ArgumentCount) {
      const std::string_view Value(Arguments[++Index]);
      if (Value == "asm" || Value == "assembly") {
        Result.Kind = OutputKind::Assembly;
      } else if (Value == "obj" || Value == "object") {
        Result.Kind = OutputKind::Object;
      } else {
        printUsage();
        return false;
      }
      continue;
    }
    {
      printUsage();
      return false;
    }
  }
  if (Result.InputPath.empty()) {
    printUsage();
    return false;
  }
  return true;
}

[[nodiscard]] bool writeOutput(const CommandLine &Command, std::span<const std::uint8_t> Contents) {
  if (Command.OutputPath == "-") {
    std::cout.write(reinterpret_cast<const char *>(Contents.data()),
                    static_cast<std::streamsize>(Contents.size()));
    return static_cast<bool>(std::cout);
  }
  std::ofstream Output(Command.OutputPath, std::ios::binary);
  if (!Output) {
    std::cerr << "rcc-backend-asm: cannot open output '" << Command.OutputPath << "'\n";
    return false;
  }
  Output.write(reinterpret_cast<const char *>(Contents.data()),
               static_cast<std::streamsize>(Contents.size()));
  if (!Output) {
    std::cerr << "rcc-backend-asm: cannot write output '" << Command.OutputPath << "'\n";
    return false;
  }
  return true;
}

[[nodiscard]] bool writeOutput(const CommandLine &Command, std::string_view Contents) {
  const auto *Data = reinterpret_cast<const std::uint8_t *>(Contents.data());
  return writeOutput(Command, std::span<const std::uint8_t>(Data, Contents.size()));
}

[[nodiscard]] bool readInput(const CommandLine &Command, std::string &Contents) {
  if (Command.InputPath == "-") {
    Contents.assign(std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>());
    return true;
  }
  std::ifstream Input(Command.InputPath, std::ios::binary);
  if (!Input) {
    std::cerr << "rcc-backend-asm: cannot open input '" << Command.InputPath << "'\n";
    return false;
  }
  Contents.assign(std::istreambuf_iterator<char>(Input), std::istreambuf_iterator<char>());
  return true;
}

template <typename PassT, typename... ArgumentT>
[[nodiscard]] rcc::Expected<void> addPass(rcc::MachinePassManager &Pipeline,
                                          ArgumentT &&...Arguments) {
  return Pipeline.addPass(std::make_unique<PassT>(std::forward<ArgumentT>(Arguments)...));
}

[[nodiscard]] rcc::Expected<void> runBackendPipeline(rcc::MachineFunction &Function,
                                                     const rcc::TargetDescription &Target) {
  rcc::MachinePassManager Pipeline;
  const rcc::MachineOptimizationPipelineTargetInfo TargetInfo =
      rcc::riscv::optimizationPipelineInfo();

  if (!Function.properties().has(rcc::MachineFunctionProperty::Legalized)) {
    auto Added = addPass<rcc::LegalizerPass>(Pipeline, rcc::riscv::legalizerInfo());
    if (!Added)
      return std::unexpected(Added.error());
  }
  if (!Function.properties().has(rcc::MachineFunctionProperty::RegBankSelected)) {
    auto Added = addPass<rcc::RegisterBankSelectPass>(Pipeline, rcc::riscv::registerBankInfo());
    if (!Added)
      return std::unexpected(Added.error());
  }
  if (!Function.properties().has(rcc::MachineFunctionProperty::Selected)) {
    auto Added = addPass<rcc::InstructionSelectPass>(Pipeline, rcc::riscv::instructionSelector());
    if (!Added)
      return std::unexpected(Added.error());
  }
  if (!Function.properties().has(rcc::MachineFunctionProperty::NoPHIs)) {
    auto Added = rcc::addSelectedSSAOptimizationPipeline(Pipeline, TargetInfo);
    if (!Added)
      return std::unexpected(Added.error());
    Added = addPass<rcc::PHIEliminationPass>(Pipeline, rcc::riscv::ssaInfo());
    if (!Added)
      return std::unexpected(Added.error());
  }
  if (!Function.properties().has(rcc::MachineFunctionProperty::TiedOpsRewritten)) {
    auto Added = addPass<rcc::TwoAddressRewritePass>(Pipeline, rcc::riscv::ssaInfo());
    if (!Added)
      return std::unexpected(Added.error());
  }
  if (!Function.properties().has(rcc::MachineFunctionProperty::NoVRegs)) {
    auto Added = rcc::addPreRegisterAllocationOptimizationPipeline(Pipeline, TargetInfo);
    if (!Added)
      return std::unexpected(Added.error());
    Added = addPass<rcc::PBQPAllocatorPass>(Pipeline, rcc::riscv::registerAllocationInfo());
    if (!Added)
      return std::unexpected(Added.error());
  }
  if (!Function.properties().has(rcc::MachineFunctionProperty::NoExecutablePseudos)) {
    auto Added = rcc::addPostRegisterAllocationPipeline(Pipeline, TargetInfo);
    if (!Added)
      return std::unexpected(Added.error());
  }

  rcc::MachineAnalysisManager Analyses;
  auto Registered = rcc::registerMachineOptimizationAnalyses(Analyses);
  if (!Registered)
    return std::unexpected(Registered.error());
  return Pipeline.run(Function, Target, Analyses);
}

} // namespace

int main(int ArgumentCount, char *Arguments[]) {
  CommandLine Command;
  if (!parseCommandLine(ArgumentCount, Arguments, Command))
    return 1;

  std::string SourceText;
  if (!readInput(Command, SourceText))
    return 1;

  auto Target = rcc::riscv::createTargetDescription();
  if (!Target) {
    std::cerr << "rcc-backend-asm: cannot create RV64GC target: " << Target.error().message()
              << '\n';
    return 1;
  }
  rcc::mir::MIRDocumentParserOptions Options;
  Options.DataLayout = "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128";
  Options.DefaultPointerSizeInBits = 64;
  auto Parsed =
      rcc::mir::parseMIRDocument(*Target, Command.InputPath, std::move(SourceText), Options);
  if (!Parsed.succeeded()) {
    for (const rcc::TextDiagnostic &Diagnostic : Parsed.diagnostics())
      std::cerr << rcc::formatTextDiagnostic(Diagnostic, Parsed.source()) << '\n';
    return 1;
  }

  rcc::CompilationUnit &Unit = Parsed.document()->unit();
  for (std::size_t Index = 0; Index < Unit.functionCount(); ++Index) {
    rcc::MachineFunction *Function = Unit.functionAt(Index);
    if (Function == nullptr) {
      std::cerr << "rcc-backend-asm: parsed document contains a null function\n";
      return 1;
    }
    auto Run = runBackendPipeline(*Function, *Target);
    if (!Run) {
      std::cerr << "rcc-backend-asm: backend pipeline failed for '" << Function->name()
                << "': " << Run.error().message() << '\n';
      return 1;
    }
  }

  if (Command.Kind == OutputKind::Object) {
    auto Object = rcc::riscv::emitObject(Unit, *Target);
    if (!Object) {
      std::cerr << "rcc-backend-asm: object emission failed: " << Object.error().message() << '\n';
      return 1;
    }
    return writeOutput(Command, *Object) ? 0 : 1;
  }
  auto Assembly = rcc::riscv::emitAssembly(Unit, *Target);
  if (!Assembly) {
    std::cerr << "rcc-backend-asm: assembly emission failed: " << Assembly.error().message()
              << '\n';
    return 1;
  }
  return writeOutput(Command, *Assembly) ? 0 : 1;
}