aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/CodeGen/CFIInstrInserter.cpp
blob: 45db108a7ad6c9d16bfd8408fca55e4df5ecb71b (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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/CodeGen/CFIInstrInserter.h"

#include "rcc/CodeGen/GenericOpcodes.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineCFIInfo.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineIRBuilder.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineOperand.h"
#include "rcc/CodeGen/TargetDescription.h"
#include "rcc/CodeGen/TargetFrameLowering.h"

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <iterator>
#include <set>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>

namespace rcc {
namespace {

struct SavedLocation final {
  enum class Kind : std::uint8_t {
    Register,
    CFAOffset,
  };

  Kind LocationKind = Kind::Register;
  std::int64_t Value = 0;

  friend bool operator==(SavedLocation Left, SavedLocation Right) noexcept = default;
};

struct BlockCFIInfo final {
  MachineBasicBlock *Block = nullptr;
  std::int64_t IncomingCFAOffset = 0;
  std::int64_t OutgoingCFAOffset = 0;
  DwarfRegisterNumber IncomingCFARegister;
  DwarfRegisterNumber OutgoingCFARegister;
  std::set<std::uint32_t> IncomingSavedRegisters;
  std::set<std::uint32_t> OutgoingSavedRegisters;
  bool Processed = false;
};

using BlockInfoMap = std::unordered_map<MachineBasicBlock *, BlockCFIInfo>;
using SavedLocationMap = std::unordered_map<std::uint32_t, SavedLocation>;

[[noreturn]] void reportFatalCFIError(std::string_view Message) {
  std::fputs("LLVM ERROR: ", stderr);
  std::fwrite(Message.data(), sizeof(char), Message.size(), stderr);
  std::fputc('\n', stderr);
  std::fflush(stderr);
  std::abort();
}

[[nodiscard]] Expected<const MachineCFIInstruction *>
referencedCFI(const MachineInstr &Instruction, const MachineFunction &Function) {
  const MachineOperand *Operand = Instruction.operandAt(0);
  const auto *Index = Operand == nullptr ? nullptr : Operand->getIf<CFIIndexOperand>();
  if (Index == nullptr) {
    return makeUnexpected(ErrorCode::VerificationError, "CFI instruction has no CFI index operand");
  }
  const MachineCFIInstruction *CFI = Function.cfiInfo().instruction(Index->Index);
  if (CFI == nullptr)
    return makeUnexpected(ErrorCode::VerificationError, "CFI instruction index is out of range");
  return CFI;
}

[[nodiscard]] Expected<void> recordSavedLocation(SavedLocationMap &Locations,
                                                 std::set<std::uint32_t> &SavedRegisters,
                                                 DwarfRegisterNumber Register,
                                                 SavedLocation Location) {
  const std::uint32_t Number = Register.value();
  const auto [Position, Inserted] = Locations.emplace(Number, Location);
  if (!Inserted && Position->second != Location)
    reportFatalCFIError("Different saved locations for the same CSR");
  SavedRegisters.insert(Number);
  return {};
}

[[nodiscard]] Expected<void> calculateOutgoingCFI(BlockCFIInfo &Info, MachineFunction &Function,
                                                  SavedLocationMap &Locations) {
  std::int64_t CFAOffset = Info.IncomingCFAOffset;
  DwarfRegisterNumber CFARegister = Info.IncomingCFARegister;
  std::set<std::uint32_t> SavedRegisters;
  std::set<std::uint32_t> RestoredRegisters;
  std::int64_t RememberStateDepth = 0;

  for (MachineInstr *Instruction = Info.Block->firstInstruction(); Instruction != nullptr;
       Instruction = Instruction->next()) {
    if (Instruction->opcode() != opcode(GenericOpcode::CFI_INSTRUCTION))
      continue;
    auto CFIResult = referencedCFI(*Instruction, Function);
    if (!CFIResult)
      return std::unexpected(CFIResult.error());
    const MachineCFIInstruction &CFI = **CFIResult;
    switch (CFI.operation()) {
    case MachineCFIOperation::DefCFARegister: {
      const auto *Rule = CFI.getIf<MachineCFIRegisterRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid def_cfa_register rule");
      CFARegister = Rule->Register;
      break;
    }
    case MachineCFIOperation::DefCFAOffset: {
      const auto *Rule = CFI.getIf<MachineCFIOffsetRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid def_cfa_offset rule");
      CFAOffset = Rule->Offset;
      break;
    }
    case MachineCFIOperation::AdjustCFAOffset: {
      const auto *Rule = CFI.getIf<MachineCFIOffsetRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid adjust_cfa_offset rule");
      CFAOffset += Rule->Offset;
      break;
    }
    case MachineCFIOperation::DefCFA: {
      const auto *Rule = CFI.getIf<MachineCFIRegisterOffsetRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid def_cfa rule");
      CFARegister = Rule->Register;
      CFAOffset = Rule->Offset;
      break;
    }
    case MachineCFIOperation::Offset: {
      const auto *Rule = CFI.getIf<MachineCFIRegisterOffsetRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid CFI offset rule");
      auto Recorded =
          recordSavedLocation(Locations, SavedRegisters, Rule->Register,
                              SavedLocation{SavedLocation::Kind::CFAOffset, Rule->Offset});
      if (!Recorded)
        return std::unexpected(Recorded.error());
      break;
    }
    case MachineCFIOperation::Register: {
      const auto *Rule = CFI.getIf<MachineCFIRegisterRegisterRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid CFI register rule");
      auto Recorded = recordSavedLocation(
          Locations, SavedRegisters, Rule->Register,
          SavedLocation{SavedLocation::Kind::Register,
                        static_cast<std::int64_t>(Rule->SourceRegister.value())});
      if (!Recorded)
        return std::unexpected(Recorded.error());
      break;
    }
    case MachineCFIOperation::RelativeOffset: {
      const auto *Rule = CFI.getIf<MachineCFIRegisterOffsetRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid CFI rel_offset rule");
      auto Recorded = recordSavedLocation(
          Locations, SavedRegisters, Rule->Register,
          SavedLocation{SavedLocation::Kind::CFAOffset, Rule->Offset - CFAOffset});
      if (!Recorded)
        return std::unexpected(Recorded.error());
      break;
    }
    case MachineCFIOperation::Restore: {
      const auto *Rule = CFI.getIf<MachineCFIRegisterRule>();
      if (Rule == nullptr)
        return makeUnexpected(ErrorCode::VerificationError, "invalid CFI restore rule");
      RestoredRegisters.insert(Rule->Register.value());
      break;
    }
    case MachineCFIOperation::RememberState:
      ++RememberStateDepth;
      break;
    case MachineCFIOperation::RestoreState:
      --RememberStateDepth;
      break;
    case MachineCFIOperation::SameValue:
    case MachineCFIOperation::LLVMDefAddressSpaceCFA:
    case MachineCFIOperation::Escape:
    case MachineCFIOperation::Undefined:
    case MachineCFIOperation::WindowSave:
    case MachineCFIOperation::NegateReturnAddressState:
    case MachineCFIOperation::NegateReturnAddressStateWithPC:
    case MachineCFIOperation::GNUArgsSize:
    case MachineCFIOperation::Label:
    case MachineCFIOperation::ValueOffset:
    case MachineCFIOperation::LLVMRegisterPair:
    case MachineCFIOperation::LLVMVectorRegisters:
    case MachineCFIOperation::LLVMVectorOffset:
    case MachineCFIOperation::LLVMVectorRegisterMask:
      break;
    case MachineCFIOperation::Count:
      return makeUnexpected(ErrorCode::VerificationError, "invalid CFI operation");
    }
  }

  if (RememberStateDepth != 0) {
    return makeUnexpected(ErrorCode::Unsupported,
                          "cfi_remember_state and cfi_restore_state must be paired in one block");
  }
  Info.Processed = true;
  Info.OutgoingCFAOffset = CFAOffset;
  Info.OutgoingCFARegister = CFARegister;
  Info.OutgoingSavedRegisters = Info.IncomingSavedRegisters;
  Info.OutgoingSavedRegisters.insert(SavedRegisters.begin(), SavedRegisters.end());
  for (const std::uint32_t Register : RestoredRegisters)
    Info.OutgoingSavedRegisters.erase(Register);
  return {};
}

[[nodiscard]] Expected<void> calculateCFI(BlockInfoMap &BlockInfos, SavedLocationMap &Locations,
                                          MachineFunction &Function) {
  MachineBasicBlock *Entry = Function.firstBlock();
  if (Entry == nullptr)
    return {};
  std::vector<MachineBasicBlock *> Stack{Entry};
  while (!Stack.empty()) {
    MachineBasicBlock *Block = Stack.back();
    Stack.pop_back();
    BlockCFIInfo &Info = BlockInfos.at(Block);
    auto Calculated = calculateOutgoingCFI(Info, Function, Locations);
    if (!Calculated)
      return std::unexpected(Calculated.error());
    for (const MachineSuccessor &Successor : Block->successors()) {
      BlockCFIInfo &SuccessorInfo = BlockInfos.at(Successor.Block);
      if (SuccessorInfo.Processed)
        continue;
      SuccessorInfo.IncomingCFAOffset = Info.OutgoingCFAOffset;
      SuccessorInfo.IncomingCFARegister = Info.OutgoingCFARegister;
      SuccessorInfo.IncomingSavedRegisters = Info.OutgoingSavedRegisters;
      Stack.push_back(Successor.Block);
    }
  }
  return {};
}

[[nodiscard]] Expected<void> emitCFI(MachineFunction &Function, MachineBasicBlock &Block,
                                     MachineInstr *Anchor, const TargetDescription &Target,
                                     MachineCFIInstruction CFI) {
  auto Index = Function.cfiInfo().addInstruction(std::move(CFI));
  if (!Index)
    return std::unexpected(Index.error());
  MachineIRBuilder Builder(Function, Target);
  auto Point =
      Anchor == nullptr ? Builder.setInsertPoint(Block) : Builder.setInsertPointBefore(*Anchor);
  if (!Point)
    return std::unexpected(Point.error());
  auto Pending = Builder.buildInstr(opcode(GenericOpcode::CFI_INSTRUCTION));
  if (!Pending)
    return std::unexpected(Pending.error());
  if (auto Added = Pending->addCFIInstruction(*Index); !Added)
    return std::unexpected(Added.error());
  auto Built = Pending->build();
  if (!Built)
    return std::unexpected(Built.error());
  return {};
}

[[nodiscard]] std::vector<std::uint32_t> setDifference(const std::set<std::uint32_t> &Left,
                                                       const std::set<std::uint32_t> &Right) {
  std::vector<std::uint32_t> Difference;
  std::set_difference(Left.begin(), Left.end(), Right.begin(), Right.end(),
                      std::back_inserter(Difference));
  return Difference;
}

[[nodiscard]] Expected<void> emitSavedLocation(MachineFunction &Function, MachineBasicBlock &Block,
                                               MachineInstr *Anchor,
                                               const TargetDescription &Target,
                                               std::uint32_t Register,
                                               const SavedLocationMap &Locations) {
  const auto Position = Locations.find(Register);
  if (Position == Locations.end()) {
    return makeUnexpected(ErrorCode::InternalError, "saved CFI register has no recorded location");
  }
  const DwarfRegisterNumber DwarfRegister = DwarfRegisterNumber::fromValue(Register);
  const SavedLocation &Location = Position->second;
  if (Location.LocationKind == SavedLocation::Kind::CFAOffset) {
    return emitCFI(Function, Block, Anchor, Target,
                   MachineCFIInstruction::offset(DwarfRegister, Location.Value));
  }
  return emitCFI(Function, Block, Anchor, Target,
                 MachineCFIInstruction::registerRule(
                     DwarfRegister,
                     DwarfRegisterNumber::fromValue(static_cast<std::uint32_t>(Location.Value))));
}

[[nodiscard]] Expected<bool> insertCFIInstructions(BlockInfoMap &BlockInfos,
                                                   const SavedLocationMap &Locations,
                                                   MachineFunction &Function,
                                                   const TargetDescription &Target) {
  MachineBasicBlock *Entry = Function.firstBlock();
  if (Entry == nullptr)
    return false;
  const BlockCFIInfo *PreviousInfo = &BlockInfos.at(Entry);
  bool Changed = false;
  for (MachineBasicBlock *Block = Entry->next(); Block != nullptr; Block = Block->next()) {
    const BlockCFIInfo &Info = BlockInfos.at(Block);
    MachineInstr *Anchor = Block->firstInstruction();
    const MachineBasicBlock *PreviousBlock = Block->previous();
    const bool ForceFullCFA = PreviousBlock != nullptr && PreviousBlock->attributes().sectionID() !=
                                                              Block->attributes().sectionID();

    if ((PreviousInfo->OutgoingCFAOffset != Info.IncomingCFAOffset &&
         PreviousInfo->OutgoingCFARegister != Info.IncomingCFARegister) ||
        ForceFullCFA) {
      auto Emitted =
          emitCFI(Function, *Block, Anchor, Target,
                  MachineCFIInstruction::defCFA(Info.IncomingCFARegister, Info.IncomingCFAOffset));
      if (!Emitted)
        return std::unexpected(Emitted.error());
      Changed = true;
    } else if (PreviousInfo->OutgoingCFAOffset != Info.IncomingCFAOffset) {
      auto Emitted = emitCFI(Function, *Block, Anchor, Target,
                             MachineCFIInstruction::defCFAOffset(Info.IncomingCFAOffset));
      if (!Emitted)
        return std::unexpected(Emitted.error());
      Changed = true;
    } else if (PreviousInfo->OutgoingCFARegister != Info.IncomingCFARegister) {
      auto Emitted = emitCFI(Function, *Block, Anchor, Target,
                             MachineCFIInstruction::defCFARegister(Info.IncomingCFARegister));
      if (!Emitted)
        return std::unexpected(Emitted.error());
      Changed = true;
    }

    if (ForceFullCFA) {
      for (const std::uint32_t Register : Info.IncomingSavedRegisters) {
        auto Emitted = emitSavedLocation(Function, *Block, Anchor, Target, Register, Locations);
        if (!Emitted)
          return std::unexpected(Emitted.error());
      }
      Changed = true;
      PreviousInfo = &Info;
      continue;
    }

    for (const std::uint32_t Register :
         setDifference(PreviousInfo->OutgoingSavedRegisters, Info.IncomingSavedRegisters)) {
      auto Emitted =
          emitCFI(Function, *Block, Anchor, Target,
                  MachineCFIInstruction::restore(DwarfRegisterNumber::fromValue(Register)));
      if (!Emitted)
        return std::unexpected(Emitted.error());
      Changed = true;
    }
    for (const std::uint32_t Register :
         setDifference(Info.IncomingSavedRegisters, PreviousInfo->OutgoingSavedRegisters)) {
      auto Emitted = emitSavedLocation(Function, *Block, Anchor, Target, Register, Locations);
      if (!Emitted)
        return std::unexpected(Emitted.error());
      Changed = true;
    }
    PreviousInfo = &Info;
  }
  return Changed;
}

} // namespace

const MachinePassContract &CFIInstrInserterPass::contract() const noexcept {
  static const MachinePassContract Contract = [] {
    MachinePassContract Value{
        .Name = "cfi-instr-inserter",
        .Requires = {},
        .Sets = {},
        .Clears = {},
        .RequiredAnalyses = {},
        .VerificationStage = std::nullopt,
    };
    Value.ThreadSafety = PassThreadSafety::ThreadSafe;
    Value.DeclaredChanges = {MachinePassChange::Instructions, MachinePassChange::Operands,
                             MachinePassChange::Frame};
    return Value;
  }();
  return Contract;
}

Expected<MachinePassResult> CFIInstrInserterPass::run(MachineFunction &Function,
                                                      const TargetDescription &Target,
                                                      MachineFunctionAnalysisManager &) {
  if (FrameLowering == nullptr) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "CFIInstrInserter requires target frame lowering");
  }
  MachinePassResult Result;
  Result.Preserved = PreservedAnalyses::all();
  if (Function.firstBlock() == nullptr || Function.cfiInfo().instructions().empty())
    return Result;

  const PhysicalRegister InitialRegister = FrameLowering->initialCFARegister(Function, Target);
  const auto InitialDwarfRegister = Target.mirText().dwarfRegister(InitialRegister);
  if (!InitialDwarfRegister) {
    return makeUnexpected(ErrorCode::InternalError,
                          "initial CFA register has no DWARF register number");
  }
  const std::int64_t InitialOffset = FrameLowering->initialCFAOffset(Function);
  BlockInfoMap BlockInfos;
  for (MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr; Block = Block->next()) {
    BlockInfos.emplace(
        Block, BlockCFIInfo{
                   .Block = Block,
                   .IncomingCFAOffset = InitialOffset,
                   .OutgoingCFAOffset = InitialOffset,
                   .IncomingCFARegister = DwarfRegisterNumber::fromValue(*InitialDwarfRegister),
                   .OutgoingCFARegister = DwarfRegisterNumber::fromValue(*InitialDwarfRegister),
                   .IncomingSavedRegisters = {},
                   .OutgoingSavedRegisters = {},
                   .Processed = false,
               });
  }
  SavedLocationMap Locations;
  auto Calculated = calculateCFI(BlockInfos, Locations, Function);
  if (!Calculated)
    return std::unexpected(Calculated.error());
  auto Inserted = insertCFIInstructions(BlockInfos, Locations, Function, Target);
  if (!Inserted)
    return std::unexpected(Inserted.error());
  Result.Changed = *Inserted;
  if (Result.Changed) {
    Result.Changes = {MachinePassChange::Instructions, MachinePassChange::Operands,
                      MachinePassChange::Frame};
  }
  return Result;
}

} // namespace rcc