aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/Tooling/MIRReducer.cpp
blob: a2475848556dd88075ac8c5ee619a9ec7e1af4ef (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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/Tooling/MIRReducer.h"

#include "rcc/CodeGen/TargetDescription.h"
#include "rcc/Tooling/ArtifactStore.h"

#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <ranges>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

namespace rcc::tooling {
namespace {

struct Line final {
  std::size_t Begin = 0;
  std::size_t End = 0;
  std::size_t ContentEnd = 0;
  std::size_t Indent = 0;
};

struct Candidate final {
  std::string MIR;
  BackendInvocation Invocation;
  std::string Description;
};

[[nodiscard]] std::vector<ReductionGranularity> defaultGranularities() {
  return {
      ReductionGranularity::MachineFunction, ReductionGranularity::BasicBlock,
      ReductionGranularity::CFGEdge,         ReductionGranularity::RegisterSubgraph,
      ReductionGranularity::Instruction,     ReductionGranularity::Operand,
      ReductionGranularity::FrameObject,     ReductionGranularity::ConstantPool,
      ReductionGranularity::JumpTable,       ReductionGranularity::TargetFeature,
      ReductionGranularity::PassPipeline,
  };
}

[[nodiscard]] std::vector<Line> lines(std::string_view Text) {
  std::vector<Line> Result;
  std::size_t Begin = 0;
  while (Begin < Text.size()) {
    const std::size_t Newline = Text.find('\n', Begin);
    const std::size_t End = Newline == std::string_view::npos ? Text.size() : Newline + 1U;
    std::size_t ContentEnd = Newline == std::string_view::npos ? Text.size() : Newline;
    if (ContentEnd > Begin && Text[ContentEnd - 1U] == '\r')
      --ContentEnd;
    std::size_t Indent = 0;
    while (Begin + Indent < ContentEnd && Text[Begin + Indent] == ' ')
      ++Indent;
    Result.push_back({Begin, End, ContentEnd, Indent});
    Begin = End;
  }
  if (Text.empty())
    Result.push_back({});
  return Result;
}

[[nodiscard]] std::string_view lineText(std::string_view Text, const Line &Value) {
  return Text.substr(Value.Begin, Value.ContentEnd - Value.Begin);
}

[[nodiscard]] std::string_view trimmedLine(std::string_view Text, const Line &Value) {
  return Text.substr(Value.Begin + Value.Indent, Value.ContentEnd - Value.Begin - Value.Indent);
}

[[nodiscard]] std::string withoutRange(std::string_view Text, std::size_t Begin, std::size_t End) {
  std::string Result;
  Result.reserve(Text.size() - (End - Begin));
  Result.append(Text.substr(0, Begin));
  Result.append(Text.substr(End));
  return Result;
}

void addCandidate(std::vector<Candidate> &Result, std::set<std::string> &Seen,
                  std::string CandidateMIR, const BackendInvocation &Invocation,
                  std::string Description, std::string_view OriginalMIR) {
  if (CandidateMIR == OriginalMIR || !Seen.insert(CandidateMIR).second)
    return;
  Result.push_back({std::move(CandidateMIR), Invocation, std::move(Description)});
}

[[nodiscard]] bool isBodyStart(std::string_view Text, const Line &Value) {
  return Value.Indent == 0 && trimmedLine(Text, Value) == "body: |";
}

[[nodiscard]] bool isBlockLabel(std::string_view Text, const Line &Value) {
  const std::string_view Trimmed = trimmedLine(Text, Value);
  return Value.Indent == 2 && Trimmed.starts_with("bb.") && Trimmed.ends_with(':');
}

[[nodiscard]] bool isInstructionLine(std::string_view Text, const Line &Value, bool InBody) {
  if (!InBody || Value.Indent < 4)
    return false;
  const std::string_view Trimmed = trimmedLine(Text, Value);
  return !Trimmed.empty() && !Trimmed.starts_with("liveins:") &&
         !Trimmed.starts_with("successors:") && !Trimmed.starts_with("align ") &&
         !Trimmed.starts_with(';');
}

[[nodiscard]] std::vector<Candidate> functionCandidates(std::string_view MIR,
                                                        const BackendInvocation &Invocation) {
  const std::vector<Line> Lines = lines(MIR);
  std::vector<std::size_t> Starts;
  for (std::size_t Index = 0; Index < Lines.size(); ++Index) {
    if (lineText(MIR, Lines[Index]) == "---")
      Starts.push_back(Index);
  }
  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  if (Starts.size() <= 1)
    return Result;
  for (std::size_t Position = 0; Position < Starts.size(); ++Position) {
    const std::size_t Begin = Lines[Starts[Position]].Begin;
    const std::size_t End =
        Position + 1U < Starts.size() ? Lines[Starts[Position + 1U]].Begin : MIR.size();
    addCandidate(Result, Seen, withoutRange(MIR, Begin, End), Invocation,
                 "remove YAML document " + std::to_string(Position), MIR);
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> blockCandidates(std::string_view MIR,
                                                     const BackendInvocation &Invocation) {
  const std::vector<Line> Lines = lines(MIR);
  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  bool InBody = false;
  for (std::size_t Index = 0; Index < Lines.size(); ++Index) {
    if (isBodyStart(MIR, Lines[Index])) {
      InBody = true;
      continue;
    }
    if (InBody && Lines[Index].Indent == 0) {
      InBody = isBodyStart(MIR, Lines[Index]);
      continue;
    }
    if (!InBody || !isBlockLabel(MIR, Lines[Index]))
      continue;
    std::size_t EndIndex = Index + 1U;
    while (EndIndex < Lines.size() && Lines[EndIndex].Indent != 0 &&
           !isBlockLabel(MIR, Lines[EndIndex])) {
      ++EndIndex;
    }
    const std::size_t End = EndIndex < Lines.size() ? Lines[EndIndex].Begin : MIR.size();
    addCandidate(Result, Seen, withoutRange(MIR, Lines[Index].Begin, End), Invocation,
                 "remove machine basic block", MIR);
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> instructionCandidates(std::string_view MIR,
                                                           const BackendInvocation &Invocation) {
  const std::vector<Line> Lines = lines(MIR);
  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  bool InBody = false;
  for (const Line &Value : Lines) {
    if (isBodyStart(MIR, Value)) {
      InBody = true;
      continue;
    }
    if (InBody && Value.Indent == 0) {
      InBody = false;
      continue;
    }
    if (!isInstructionLine(MIR, Value, InBody))
      continue;
    addCandidate(Result, Seen, withoutRange(MIR, Value.Begin, Value.End), Invocation,
                 "remove machine instruction", MIR);
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> cfgEdgeCandidates(std::string_view MIR,
                                                       const BackendInvocation &Invocation) {
  const std::vector<Line> Lines = lines(MIR);
  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  bool InBody = false;
  for (const Line &Value : Lines) {
    if (isBodyStart(MIR, Value)) {
      InBody = true;
      continue;
    }
    if (InBody && Value.Indent == 0) {
      InBody = false;
      continue;
    }
    const std::string_view Trimmed = trimmedLine(MIR, Value);
    if (!InBody || !Trimmed.starts_with("successors:"))
      continue;
    const std::size_t LastComma = Trimmed.rfind(',');
    if (LastComma == std::string_view::npos) {
      addCandidate(Result, Seen, withoutRange(MIR, Value.Begin, Value.End), Invocation,
                   "remove CFG successor list", MIR);
      continue;
    }
    const std::size_t EraseBegin = Value.Begin + Value.Indent + LastComma;
    addCandidate(Result, Seen, withoutRange(MIR, EraseBegin, Value.ContentEnd), Invocation,
                 "remove CFG successor", MIR);
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> operandCandidates(std::string_view MIR,
                                                       const BackendInvocation &Invocation) {
  const std::vector<Line> Lines = lines(MIR);
  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  bool InBody = false;
  for (const Line &Value : Lines) {
    if (isBodyStart(MIR, Value)) {
      InBody = true;
      continue;
    }
    if (InBody && Value.Indent == 0) {
      InBody = false;
      continue;
    }
    if (!isInstructionLine(MIR, Value, InBody))
      continue;
    const std::string_view Text = lineText(MIR, Value);
    const std::size_t LastComma = Text.rfind(',');
    if (LastComma != std::string_view::npos) {
      addCandidate(Result, Seen, withoutRange(MIR, Value.Begin + LastComma, Value.ContentEnd),
                   Invocation, "remove trailing machine operand", MIR);
    }
    const std::size_t Implicit = Text.rfind(" implicit ");
    if (Implicit != std::string_view::npos) {
      addCandidate(Result, Seen, withoutRange(MIR, Value.Begin + Implicit, Value.ContentEnd),
                   Invocation, "remove implicit machine operand", MIR);
    }
  }
  return Result;
}

[[nodiscard]] bool containsRegisterToken(std::string_view LineText, std::string_view Token) {
  std::size_t Position = 0;
  while ((Position = LineText.find(Token, Position)) != std::string_view::npos) {
    const std::size_t End = Position + Token.size();
    const bool LeftBoundary = Position == 0 || LineText[Position - 1U] != '%';
    const bool RightBoundary =
        End == LineText.size() || std::isdigit(static_cast<unsigned char>(LineText[End])) == 0;
    if (LeftBoundary && RightBoundary)
      return true;
    Position = End;
  }
  return false;
}

[[nodiscard]] std::vector<Candidate> registerCandidates(std::string_view MIR,
                                                        const BackendInvocation &Invocation) {
  const std::vector<Line> Lines = lines(MIR);
  std::set<std::string> Registers;
  bool InBody = false;
  for (const Line &Value : Lines) {
    if (isBodyStart(MIR, Value)) {
      InBody = true;
      continue;
    }
    if (InBody && Value.Indent == 0) {
      InBody = false;
      continue;
    }
    if (!isInstructionLine(MIR, Value, InBody))
      continue;
    const std::string_view Text = lineText(MIR, Value);
    for (std::size_t Position = 0; Position < Text.size(); ++Position) {
      if (Text[Position] != '%' || Position + 1U >= Text.size() ||
          std::isdigit(static_cast<unsigned char>(Text[Position + 1U])) == 0) {
        continue;
      }
      std::size_t End = Position + 2U;
      while (End < Text.size() && std::isdigit(static_cast<unsigned char>(Text[End])) != 0) {
        ++End;
      }
      Registers.emplace(Text.substr(Position, End - Position));
      Position = End - 1U;
    }
  }

  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  for (const std::string &Register : Registers) {
    std::string CandidateMIR;
    CandidateMIR.reserve(MIR.size());
    InBody = false;
    for (const Line &Value : Lines) {
      if (isBodyStart(MIR, Value))
        InBody = true;
      else if (InBody && Value.Indent == 0)
        InBody = false;
      if (isInstructionLine(MIR, Value, InBody) &&
          containsRegisterToken(lineText(MIR, Value), Register)) {
        continue;
      }
      CandidateMIR.append(MIR.substr(Value.Begin, Value.End - Value.Begin));
    }
    addCandidate(Result, Seen, std::move(CandidateMIR), Invocation,
                 "remove register subgraph " + Register, MIR);
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> sequenceItemCandidates(std::string_view MIR,
                                                            const BackendInvocation &Invocation,
                                                            std::string_view Field,
                                                            std::size_t ItemIndent,
                                                            std::string_view Description) {
  const std::vector<Line> Lines = lines(MIR);
  std::vector<Candidate> Result;
  std::set<std::string> Seen;
  bool InField = false;
  for (std::size_t Index = 0; Index < Lines.size(); ++Index) {
    const std::string_view Trimmed = trimmedLine(MIR, Lines[Index]);
    if (Lines[Index].Indent == 0 && Trimmed == std::string(Field) + ":") {
      InField = true;
      continue;
    }
    if (InField && Lines[Index].Indent == 0) {
      InField = false;
      continue;
    }
    if (!InField || Lines[Index].Indent != ItemIndent || !Trimmed.starts_with("- "))
      continue;
    std::size_t EndIndex = Index + 1U;
    while (EndIndex < Lines.size() && Lines[EndIndex].Indent > ItemIndent)
      ++EndIndex;
    const std::size_t End = EndIndex < Lines.size() ? Lines[EndIndex].Begin : MIR.size();
    addCandidate(Result, Seen, withoutRange(MIR, Lines[Index].Begin, End), Invocation,
                 std::string(Description), MIR);
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> invocationCandidates(std::string_view MIR,
                                                          const BackendInvocation &Invocation,
                                                          ReductionGranularity Granularity) {
  std::vector<Candidate> Result;
  if (Granularity == ReductionGranularity::TargetFeature) {
    for (std::size_t Index = Invocation.Features.size(); Index > 0; --Index) {
      BackendInvocation CandidateInvocation = Invocation;
      const std::string Feature = CandidateInvocation.Features[Index - 1U];
      CandidateInvocation.Features.erase(CandidateInvocation.Features.begin() +
                                         static_cast<std::ptrdiff_t>(Index - 1U));
      auto Verified = CandidateInvocation.canonicalizeAndVerify();
      if (Verified) {
        Result.push_back(
            {std::string(MIR), std::move(CandidateInvocation), "remove target feature " + Feature});
      }
    }
  } else if (Granularity == ReductionGranularity::PassPipeline &&
             (Invocation.PassPipeline.size() != 1 ||
              Invocation.PassPipeline.front() != "default")) {
    for (std::size_t Index = Invocation.PassPipeline.size(); Index > 0; --Index) {
      if (Invocation.PassPipeline.size() == 1)
        break;
      BackendInvocation CandidateInvocation = Invocation;
      const std::string Pass = CandidateInvocation.PassPipeline[Index - 1U];
      CandidateInvocation.PassPipeline.erase(CandidateInvocation.PassPipeline.begin() +
                                             static_cast<std::ptrdiff_t>(Index - 1U));
      Result.push_back(
          {std::string(MIR), std::move(CandidateInvocation), "remove pipeline pass " + Pass});
    }
  }
  return Result;
}

[[nodiscard]] std::vector<Candidate> candidatesFor(ReductionGranularity Granularity,
                                                   std::string_view MIR,
                                                   const BackendInvocation &Invocation) {
  switch (Granularity) {
  case ReductionGranularity::CompilationUnit:
  case ReductionGranularity::MachineFunction:
    return functionCandidates(MIR, Invocation);
  case ReductionGranularity::BasicBlock:
    return blockCandidates(MIR, Invocation);
  case ReductionGranularity::CFGEdge:
    return cfgEdgeCandidates(MIR, Invocation);
  case ReductionGranularity::Instruction:
    return instructionCandidates(MIR, Invocation);
  case ReductionGranularity::Operand:
    return operandCandidates(MIR, Invocation);
  case ReductionGranularity::RegisterSubgraph:
    return registerCandidates(MIR, Invocation);
  case ReductionGranularity::FrameObject: {
    std::vector<Candidate> Result =
        sequenceItemCandidates(MIR, Invocation, "fixedStack", 2, "remove fixed stack object");
    std::vector<Candidate> Stack =
        sequenceItemCandidates(MIR, Invocation, "stack", 2, "remove stack object");
    Result.insert(Result.end(), std::make_move_iterator(Stack.begin()),
                  std::make_move_iterator(Stack.end()));
    return Result;
  }
  case ReductionGranularity::ConstantPool:
    return sequenceItemCandidates(MIR, Invocation, "constants", 2, "remove constant-pool entry");
  case ReductionGranularity::JumpTable:
    return sequenceItemCandidates(MIR, Invocation, "entries", 4, "remove jump-table entry");
  case ReductionGranularity::TargetFeature:
  case ReductionGranularity::PassPipeline:
    return invocationCandidates(MIR, Invocation, Granularity);
  }
  return {};
}

} // namespace

std::string_view spelling(ReductionGranularity Granularity) noexcept {
  switch (Granularity) {
  case ReductionGranularity::CompilationUnit:
    return "compilation-unit";
  case ReductionGranularity::MachineFunction:
    return "machine-function";
  case ReductionGranularity::BasicBlock:
    return "basic-block";
  case ReductionGranularity::CFGEdge:
    return "cfg-edge";
  case ReductionGranularity::Instruction:
    return "instruction";
  case ReductionGranularity::Operand:
    return "operand";
  case ReductionGranularity::RegisterSubgraph:
    return "register-subgraph";
  case ReductionGranularity::FrameObject:
    return "frame-object";
  case ReductionGranularity::ConstantPool:
    return "constant-pool";
  case ReductionGranularity::JumpTable:
    return "jump-table";
  case ReductionGranularity::TargetFeature:
    return "target-feature";
  case ReductionGranularity::PassPipeline:
    return "pass-pipeline";
  }
  return "invalid";
}

Expected<MIRReductionResult> reduceMIR(std::string SourceName, std::string SourceText,
                                       BackendInvocation Invocation,
                                       const TargetDescription &Target,
                                       const MIRInterestingnessTest &Interesting,
                                       MIRReducerOptions Options) {
  if (Options.Mode == ReductionMode::PreserveFailure && !Interesting)
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "failure-preserving MIR reduction requires an interestingness test");
  if (Options.MaximumAttempts == 0)
    return makeUnexpected(ErrorCode::InvalidArgument, "MIR reducer attempt budget must be nonzero");
  std::set<ReductionGranularity> SeenGranularities;
  for (ReductionGranularity Granularity : Options.Granularities) {
    if (spelling(Granularity) == "invalid") {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "MIR reducer granularity is not recognized");
    }
    if (!SeenGranularities.insert(Granularity).second) {
      return makeUnexpected(ErrorCode::InvalidArgument, "MIR reducer granularities must be unique");
    }
  }
  auto InvocationVerification = Invocation.canonicalizeAndVerify();
  if (!InvocationVerification)
    return std::unexpected(InvocationVerification.error());
  auto Initial =
      parseAndCanonicalizeMIR(std::move(SourceName), std::move(SourceText), Target, Invocation);
  if (!Initial)
    return std::unexpected(Initial.error());
  if (Options.Mode == ReductionMode::PreserveFailure) {
    auto InitiallyInteresting = Interesting(Initial->Text, Invocation);
    if (!InitiallyInteresting)
      return std::unexpected(InitiallyInteresting.error());
    if (!*InitiallyInteresting) {
      return makeUnexpected(ErrorCode::ReductionFailed,
                            "initial MIR input does not satisfy the interestingness test");
    }
  }
  if (Options.Granularities.empty())
    Options.Granularities = defaultGranularities();

  MIRReductionResult Result{
      .MIR = std::move(Initial->Text),
      .Invocation = std::move(Invocation),
      .Steps = {},
      .Attempts = 0,
      .Exhausted = false,
  };
  for (ReductionGranularity Granularity : Options.Granularities) {
    bool Changed = true;
    while (Changed && Result.Attempts < Options.MaximumAttempts) {
      Changed = false;
      std::vector<Candidate> Candidates = candidatesFor(Granularity, Result.MIR, Result.Invocation);
      for (Candidate &CandidateValue : Candidates) {
        if (Result.Attempts == Options.MaximumAttempts)
          break;
        ++Result.Attempts;
        auto Canonical = parseAndCanonicalizeMIR("reducer-candidate.mir", CandidateValue.MIR,
                                                 Target, CandidateValue.Invocation);
        if (!Canonical)
          continue;
        if (Canonical->Text == Result.MIR && CandidateValue.Invocation == Result.Invocation)
          continue;
        if (Options.Mode == ReductionMode::PreserveFailure) {
          auto IsInteresting = Interesting(Canonical->Text, CandidateValue.Invocation);
          if (!IsInteresting)
            return std::unexpected(IsInteresting.error());
          if (!*IsInteresting)
            continue;
        }
        const std::size_t PreviousSize = Result.MIR.size();
        Result.MIR = std::move(Canonical->Text);
        Result.Invocation = std::move(CandidateValue.Invocation);
        Result.Steps.push_back({
            .Granularity = Granularity,
            .Description = std::move(CandidateValue.Description),
            .PreviousSize = PreviousSize,
            .ReducedSize = Result.MIR.size(),
        });
        Changed = true;
        break;
      }
    }
  }
  Result.Exhausted = Result.Attempts == Options.MaximumAttempts;
  return Result;
}

} // namespace rcc::tooling