aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/CodeGen/LiveVariables.cpp
blob: 3c91cfb74b0b37dc75b2392b31e55235d2357dcd (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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/CodeGen/LiveVariables.h"

#include "rcc/CodeGen/LiveInterval.h"
#include "rcc/CodeGen/LiveIntervals.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineOperand.h"
#include "rcc/CodeGen/MachineRegisterInfo.h"
#include "rcc/CodeGen/ReachingDefAnalysis.h"
#include "rcc/CodeGen/RegisterMask.h"
#include "rcc/CodeGen/SlotIndexes.h"
#include "rcc/CodeGen/TargetDescription.h"
#include "rcc/CodeGen/TargetRegisterInfo.h"
#include "rcc/CodeGen/VirtRegMap.h"

#include <algorithm>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <optional>
#include <ranges>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

namespace rcc {

namespace {
[[nodiscard]] LaneMask subtractLanes(LaneMask Left, LaneMask Right) noexcept {
  return LaneMask::fromRaw(Left.rawValue() & ~Right.rawValue());
}

template <typename KeyT>
void addLanes(std::unordered_map<KeyT, LaneMask> &Values, KeyT Key, LaneMask Lanes) {
  if (Lanes.empty())
    return;
  const auto Position = Values.find(Key);
  if (Position == Values.end()) {
    Values.emplace(Key, Lanes);
    return;
  }
  Position->second = Position->second | Lanes;
}

template <typename KeyT>
void removeLanes(std::unordered_map<KeyT, LaneMask> &Values, KeyT Key, LaneMask Lanes) {
  const auto Position = Values.find(Key);
  if (Position == Values.end() || Lanes.empty())
    return;
  Position->second = subtractLanes(Position->second, Lanes);
  if (Position->second.empty())
    Values.erase(Position);
}

template <typename KeyT>
[[nodiscard]] LaneMask lanesFor(const std::unordered_map<KeyT, LaneMask> &Values,
                                KeyT Key) noexcept {
  const auto Position = Values.find(Key);
  return Position == Values.end() ? LaneMask{} : Position->second;
}

template <typename KeyT>
[[nodiscard]] bool containsLanes(const std::unordered_map<KeyT, LaneMask> &Values, KeyT Key,
                                 LaneMask Lanes) noexcept {
  const LaneMask Present = lanesFor(Values, Key);
  return !Present.empty() && Present.contains(Lanes);
}

template <typename KeyT>
[[nodiscard]] bool intersectsLanes(const std::unordered_map<KeyT, LaneMask> &Values, KeyT Key,
                                   LaneMask Lanes) noexcept {
  return lanesFor(Values, Key).intersects(Lanes);
}

template <typename KeyT>
void uniteLanes(std::unordered_map<KeyT, LaneMask> &Values,
                const std::unordered_map<KeyT, LaneMask> &Other) {
  for (const auto &[Key, Lanes] : Other)
    addLanes(Values, Key, Lanes);
}

template <typename KeyT>
void subtractLaneSets(std::unordered_map<KeyT, LaneMask> &Values,
                      const std::unordered_map<KeyT, LaneMask> &Other) {
  for (const auto &[Key, Lanes] : Other)
    removeLanes(Values, Key, Lanes);
}

[[nodiscard]] Expected<void> addOperandUse(RegisterLaneSet &VirtualUses, LiveRegUnits &PhysicalUses,
                                           const MachineOperand &Operand,
                                           const MachineFunction &Function,
                                           const TargetDescription &Target) {
  const Register *Reg = Operand.getIf<Register>();
  if (Reg == nullptr || Reg->isNoRegister() || Operand.isDebugUse() ||
      Operand.registerFlags().has(RegisterOperandFlag::Undef)) {
    return {};
  }
  if (Reg->isVirtual()) {
    auto Lanes = virtualOperandLanes(Operand, Function, Target);
    if (!Lanes)
      return std::unexpected(Lanes.error());
    VirtualUses.add(*Reg, *Lanes);
    return {};
  }
  if (isReservedPhysicalRegister(*Reg, Function, Target))
    return {};
  auto Units = physicalOperandUnits(Operand, Target);
  if (!Units)
    return std::unexpected(Units.error());
  for (const PhysicalUnitAccess &Unit : *Units)
    PhysicalUses.add(Unit.Unit, Unit.Lanes);
  return {};
}

[[nodiscard]] Expected<void> addOperandDef(RegisterLaneSet &VirtualDefs, LiveRegUnits &PhysicalDefs,
                                           const MachineOperand &Operand,
                                           const MachineFunction &Function,
                                           const TargetDescription &Target) {
  const Register *Reg = Operand.getIf<Register>();
  if (Reg == nullptr || Reg->isNoRegister())
    return {};
  if (Reg->isVirtual()) {
    auto Lanes = virtualOperandLanes(Operand, Function, Target);
    if (!Lanes)
      return std::unexpected(Lanes.error());
    VirtualDefs.add(*Reg, *Lanes);
    return {};
  }
  auto Units = physicalOperandUnits(Operand, Target);
  if (!Units)
    return std::unexpected(Units.error());
  for (const PhysicalUnitAccess &Unit : *Units)
    PhysicalDefs.add(Unit.Unit, Unit.Lanes);
  return {};
}

struct LivenessEdgeKey final {
  const MachineBasicBlock *Predecessor = nullptr;
  const MachineBasicBlock *Successor = nullptr;

  friend bool operator==(const LivenessEdgeKey &, const LivenessEdgeKey &) = default;
};

struct LivenessEdgeKeyHash final {
  [[nodiscard]] std::size_t operator()(const LivenessEdgeKey &Key) const noexcept {
    const std::size_t Left = std::hash<const MachineBasicBlock *>{}(Key.Predecessor);
    const std::size_t Right = std::hash<const MachineBasicBlock *>{}(Key.Successor);
    return Left ^ (Right + 0x9e3779b9U + (Left << 6U) + (Left >> 2U));
  }
};

struct EdgeLivenessUses final {
  RegisterLaneSet Virtual;
  LiveRegUnits Physical;
};

[[nodiscard]] Expected<LiveVariablesAnalysis::Result>
computeLiveVariables(const MachineFunction &Function, const TargetDescription &Target) {
  LiveVariablesAnalysis::Result Result;
  std::vector<const MachineBasicBlock *> Blocks;
  std::unordered_map<LivenessEdgeKey, EdgeLivenessUses, LivenessEdgeKeyHash> EdgeUses;
  for (const MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr;
       Block = Block->next()) {
    Blocks.push_back(Block);
    (void)Result.getOrCreateBlock(*Block);
  }

  for (const MachineBasicBlock *Block : Blocks) {
    MachineBlockLiveness &Liveness = Result.getOrCreateBlock(*Block);
    if (Block == Function.firstBlock()) {
      for (const PhysicalRegisterLiveIn &LiveIn : Function.registerInfo().liveIns()) {
        const PhysicalRegisterDesc *Description =
            Target.registers().physicalRegister(LiveIn.PhysReg);
        if (Description == nullptr) {
          return makeUnexpected(ErrorCode::VerificationError,
                                "function live-in references an unknown physical register");
        }
        addPhysicalRegister(Liveness.PhysicalUses, *Description);
        if (LiveIn.InitialVirtualRegister) {
          auto Lanes = virtualRegisterLanes(*LiveIn.InitialVirtualRegister, Function, Target);
          if (!Lanes)
            return std::unexpected(Lanes.error());
          Liveness.VirtualDefs.add(*LiveIn.InitialVirtualRegister, *Lanes);
        }
      }
    }
    for (const MachineInstr *Instruction = Block->firstInstruction(); Instruction != nullptr;
         Instruction = Instruction->next()) {
      const InstructionDescriptor *Descriptor = Target.instructionDescriptor(Instruction->opcode());
      if (Descriptor == nullptr) {
        return makeUnexpected(ErrorCode::VerificationError,
                              "liveness encountered an unknown instruction descriptor");
      }
      const bool IsPhi = Descriptor->Flags.has(InstructionFlag::Phi);
      if (IsPhi) {
        if (Instruction->operandCount() < 3 || (Instruction->operandCount() - 1U) % 2U != 0) {
          return makeUnexpected(ErrorCode::VerificationError,
                                "liveness encountered a malformed PHI instruction");
        }
        std::unordered_set<const MachineBasicBlock *> IncomingBlocks;
        for (std::size_t Index = 1; Index < Instruction->operandCount(); Index += 2U) {
          const MachineOperand *Incoming = Instruction->operandAt(Index);
          const MachineOperand *PredecessorOperand = Instruction->operandAt(Index + 1U);
          const auto *Predecessor = PredecessorOperand == nullptr
                                        ? nullptr
                                        : PredecessorOperand->getIf<BasicBlockOperand>();
          if (Incoming == nullptr || Predecessor == nullptr || Predecessor->Block == nullptr) {
            return makeUnexpected(ErrorCode::VerificationError,
                                  "liveness encountered a malformed PHI incoming pair");
          }
          const MachineBasicBlock *IncomingBlock = Predecessor->Block;
          const bool HasPredecessor = std::ranges::find(Block->predecessors(), IncomingBlock) !=
                                      Block->predecessors().end();
          const bool HasSuccessor = std::ranges::any_of(
              IncomingBlock->successors(),
              [Block](const MachineSuccessor &Successor) { return Successor.Block == Block; });
          if (&IncomingBlock->function() != &Function || !IncomingBlock->isLinked() ||
              !HasPredecessor || !HasSuccessor || !IncomingBlocks.insert(IncomingBlock).second) {
            return makeUnexpected(ErrorCode::VerificationError,
                                  "liveness encountered a PHI incoming without a unique CFG edge");
          }
          EdgeLivenessUses &Uses = EdgeUses[{IncomingBlock, Block}];
          auto Added = addOperandUse(Uses.Virtual, Uses.Physical, *Incoming, Function, Target);
          if (!Added)
            return std::unexpected(Added.error());
        }
      }

      RegisterLaneSet InstructionVirtualUses;
      RegisterLaneSet InstructionVirtualDefs;
      LiveRegUnits InstructionPhysicalUses;
      LiveRegUnits InstructionPhysicalDefs;
      for (std::size_t Index = 0; Index < Instruction->operandCount(); ++Index) {
        const MachineOperand &Operand = *Instruction->operandAt(Index);
        if (Operand.isRegister()) {
          if (Operand.isUse() && (!IsPhi || Index == 0)) {
            auto Use = addOperandUse(InstructionVirtualUses, InstructionPhysicalUses, Operand,
                                     Function, Target);
            if (!Use)
              return std::unexpected(Use.error());
          }
          if (Operand.isDef()) {
            auto Def = addOperandDef(InstructionVirtualDefs, InstructionPhysicalDefs, Operand,
                                     Function, Target);
            if (!Def)
              return std::unexpected(Def.error());
          }
          continue;
        }
        if (const auto *MaskOperand = Operand.getIf<RegisterMaskOperand>();
            MaskOperand != nullptr) {
          if (!MaskOperand->Mask)
            return makeUnexpected(ErrorCode::VerificationError,
                                  "liveness encountered a null register mask");
          auto Added = addRegisterMaskDefs(InstructionPhysicalDefs, *MaskOperand->Mask, Target);
          if (!Added)
            return std::unexpected(Added.error());
          continue;
        }
        if (const auto *MaskOperand = Operand.getIf<LiveOutRegisterMaskOperand>();
            MaskOperand != nullptr) {
          if (!MaskOperand->Mask)
            return makeUnexpected(ErrorCode::VerificationError,
                                  "liveness encountered a null live-out register mask");
          auto Added = addRegisterMaskUses(InstructionPhysicalUses, *MaskOperand->Mask, Target);
          if (!Added)
            return std::unexpected(Added.error());
        }
      }

      RegisterLaneSet NewVirtualUses = InstructionVirtualUses;
      NewVirtualUses.subtract(Liveness.VirtualDefs);
      Liveness.VirtualUses.unite(NewVirtualUses);
      Liveness.VirtualDefs.unite(InstructionVirtualDefs);

      LiveRegUnits NewPhysicalUses = InstructionPhysicalUses;
      NewPhysicalUses.subtract(Liveness.PhysicalDefs);
      Liveness.PhysicalUses.unite(NewPhysicalUses);
      Liveness.PhysicalDefs.unite(InstructionPhysicalDefs);
    }
  }

  bool Changed = true;
  while (Changed) {
    Changed = false;
    for (const MachineBasicBlock *Block : Blocks | std::views::reverse) {
      MachineBlockLiveness &Liveness = Result.getOrCreateBlock(*Block);
      RegisterLaneSet VirtualOut;
      LiveRegUnits PhysicalOut;
      for (const MachineSuccessor &Successor : Block->successors()) {
        if (Successor.Block == nullptr || Result.block(*Successor.Block) == nullptr) {
          return makeUnexpected(ErrorCode::VerificationError,
                                "liveness encountered an invalid CFG successor");
        }
        const MachineBlockLiveness &SuccessorLiveness = *Result.block(*Successor.Block);
        VirtualOut.unite(SuccessorLiveness.VirtualLiveIn);
        PhysicalOut.unite(SuccessorLiveness.PhysicalLiveIn);
        const auto Edge = EdgeUses.find({Block, Successor.Block});
        if (Edge != EdgeUses.end()) {
          VirtualOut.unite(Edge->second.Virtual);
          PhysicalOut.unite(Edge->second.Physical);
        }
      }

      RegisterLaneSet VirtualIn = VirtualOut;
      VirtualIn.subtract(Liveness.VirtualDefs);
      VirtualIn.unite(Liveness.VirtualUses);
      LiveRegUnits PhysicalIn = PhysicalOut;
      PhysicalIn.subtract(Liveness.PhysicalDefs);
      PhysicalIn.unite(Liveness.PhysicalUses);

      if (VirtualOut != Liveness.VirtualLiveOut || VirtualIn != Liveness.VirtualLiveIn ||
          PhysicalOut != Liveness.PhysicalLiveOut || PhysicalIn != Liveness.PhysicalLiveIn) {
        Liveness.VirtualLiveOut = std::move(VirtualOut);
        Liveness.VirtualLiveIn = std::move(VirtualIn);
        Liveness.PhysicalLiveOut = std::move(PhysicalOut);
        Liveness.PhysicalLiveIn = std::move(PhysicalIn);
        Changed = true;
      }
    }
  }
  return Result;
}
[[nodiscard]] Expected<std::vector<MachineBasicBlockLiveIn>>
canonicalPhysicalLiveIns(const LiveRegUnits &Units, const TargetDescription &Target) {
  struct Candidate final {
    const PhysicalRegisterDesc *Description = nullptr;
    LaneMask RegisterLanes;
    LiveRegUnits Coverage;
    std::size_t ExtraLanes = 0;
    bool Selected = false;
  };

  std::vector<Candidate> Candidates;
  for (const PhysicalRegisterDesc &Description : Target.registers().physicalRegisters()) {
    const LaneMask FullLanes = physicalRegisterLanes(Description);
    std::uint64_t SelectableLanes = 0;
    LaneMask RelevantLanes;
    for (const RegisterUnitLane &Unit : Description.Units) {
      RelevantLanes = RelevantLanes | denormalizeUnitLanes(Units.lanes(Unit.Unit), Unit.Lanes);
    }
    std::uint64_t PendingLanes = RelevantLanes.rawValue();
    while (PendingLanes != 0) {
      const std::uint64_t Lane = std::uint64_t{1} << std::countr_zero(PendingLanes);
      const LiveRegUnits Coverage = physicalRegisterCoverage(Description, LaneMask::fromRaw(Lane));
      if (isSubset(Coverage, Units))
        SelectableLanes |= Lane;
      PendingLanes &= PendingLanes - 1U;
    }
    if (SelectableLanes == 0)
      continue;
    Candidate Value;
    Value.Description = &Description;
    Value.RegisterLanes = LaneMask::fromRaw(SelectableLanes);
    Value.Coverage = physicalRegisterCoverage(Description, Value.RegisterLanes);
    Value.ExtraLanes = static_cast<std::size_t>(std::popcount(FullLanes.rawValue()) -
                                                std::popcount(SelectableLanes));
    Candidates.push_back(std::move(Value));
  }

  LiveRegUnits Covered;
  std::vector<MachineBasicBlockLiveIn> Result;
  while (Covered != Units) {
    Candidate *Best = nullptr;
    std::size_t BestNewLanes = 0;
    std::size_t BestCoverage = 0;
    for (Candidate &Value : Candidates) {
      if (Value.Selected)
        continue;
      LiveRegUnits NewCoverage = Value.Coverage;
      NewCoverage.subtract(Covered);
      const std::size_t NewLanes = laneCount(NewCoverage);
      if (NewLanes == 0)
        continue;
      const std::size_t Coverage = laneCount(Value.Coverage);
      if (Best == nullptr || NewLanes > BestNewLanes ||
          (NewLanes == BestNewLanes && Value.ExtraLanes < Best->ExtraLanes) ||
          (NewLanes == BestNewLanes && Value.ExtraLanes == Best->ExtraLanes &&
           Coverage > BestCoverage) ||
          (NewLanes == BestNewLanes && Value.ExtraLanes == Best->ExtraLanes &&
           Coverage == BestCoverage &&
           Value.Description->Reg.number() < Best->Description->Reg.number())) {
        Best = &Value;
        BestNewLanes = NewLanes;
        BestCoverage = Coverage;
      }
    }
    if (Best == nullptr) {
      return makeUnexpected(ErrorCode::VerificationError,
                            "physical live-in units cannot be represented by target registers");
    }
    Best->Selected = true;
    Covered.unite(Best->Coverage);
    const LaneMask FullLanes = physicalRegisterLanes(*Best->Description);
    const LaneMask Lanes = Best->RegisterLanes == FullLanes ? LaneMask::all() : Best->RegisterLanes;
    Result.push_back({Best->Description->Reg, Lanes});
  }
  std::ranges::sort(Result,
                    [](const MachineBasicBlockLiveIn &Left, const MachineBasicBlockLiveIn &Right) {
                      return Left.PhysReg.number() < Right.PhysReg.number();
                    });
  return Result;
}

[[nodiscard]] Expected<LiveRegUnits> liveInUnits(std::span<const MachineBasicBlockLiveIn> LiveIns,
                                                 const TargetDescription &Target) {
  LiveRegUnits Result;
  for (const MachineBasicBlockLiveIn &LiveIn : LiveIns) {
    const PhysicalRegisterDesc *Description = Target.registers().physicalRegister(LiveIn.PhysReg);
    if (Description == nullptr) {
      return makeUnexpected(ErrorCode::VerificationError,
                            "block live-in references an unknown physical register");
    }
    Result.unite(physicalRegisterCoverage(*Description, LiveIn.Lanes));
  }
  return Result;
}

struct OperandFlagPlan final {
  MachineInstrStableID Instruction;
  std::size_t OperandIndex = 0;
  RegisterOperandFlags Original;
  RegisterOperandFlags Rebuilt;
  bool KillIsValid = false;
  bool DeadIsValid = false;
};

struct BlockLivenessPlan final {
  MachineBlockStableID Block;
  std::vector<MachineBasicBlockLiveIn> OriginalLiveIns;
  std::vector<MachineBasicBlockLiveIn> RebuiltLiveIns;
};

struct LivenessRebuildPlan final {
  std::vector<BlockLivenessPlan> Blocks;
  std::vector<OperandFlagPlan> Operands;
};

[[nodiscard]] Expected<bool> liveSetIntersects(const MachineOperand &Operand,
                                               const RegisterLaneSet &Virtual,
                                               const LiveRegUnits &Physical,
                                               const MachineFunction &Function,
                                               const TargetDescription &Target) {
  const Register *Reg = Operand.getIf<Register>();
  if (Reg == nullptr || Reg->isNoRegister())
    return false;
  if (Reg->isVirtual()) {
    auto Lanes = virtualOperandLanes(Operand, Function, Target);
    if (!Lanes)
      return std::unexpected(Lanes.error());
    return Virtual.intersects(*Reg, *Lanes);
  }
  auto Units = physicalOperandUnits(Operand, Target);
  if (!Units)
    return std::unexpected(Units.error());
  return std::ranges::any_of(*Units, [&Physical](const PhysicalUnitAccess &Unit) {
    return Physical.intersects(Unit.Unit, Unit.Lanes);
  });
}

[[nodiscard]] Expected<void> removeOperandFromLiveSet(const MachineOperand &Operand,
                                                      RegisterLaneSet &Virtual,
                                                      LiveRegUnits &Physical,
                                                      const MachineFunction &Function,
                                                      const TargetDescription &Target) {
  const Register *Reg = Operand.getIf<Register>();
  if (Reg == nullptr || Reg->isNoRegister())
    return {};
  if (Reg->isVirtual()) {
    auto Lanes = virtualOperandLanes(Operand, Function, Target);
    if (!Lanes)
      return std::unexpected(Lanes.error());
    Virtual.remove(*Reg, *Lanes);
    return {};
  }
  auto Units = physicalOperandUnits(Operand, Target);
  if (!Units)
    return std::unexpected(Units.error());
  for (const PhysicalUnitAccess &Unit : *Units)
    Physical.remove(Unit.Unit, Unit.Lanes);
  return {};
}

[[nodiscard]] Expected<void> addOperandToLiveSet(const MachineOperand &Operand,
                                                 RegisterLaneSet &Virtual, LiveRegUnits &Physical,
                                                 const MachineFunction &Function,
                                                 const TargetDescription &Target) {
  return addOperandUse(Virtual, Physical, Operand, Function, Target);
}

[[nodiscard]] Expected<LiveRegUnits> requiredLocalPhysicalLiveIns(const MachineBasicBlock &Block,
                                                                  const MachineFunction &Function,
                                                                  const TargetDescription &Target) {
  RegisterLaneSet Virtual;
  LiveRegUnits Physical;
  for (const MachineInstr *Instruction = Block.lastInstruction(); Instruction != nullptr;
       Instruction = Instruction->previous()) {
    const InstructionDescriptor *Descriptor = Target.instructionDescriptor(Instruction->opcode());
    if (Descriptor == nullptr) {
      return makeUnexpected(ErrorCode::VerificationError,
                            "liveness verification encountered an unknown instruction descriptor");
    }
    const bool IsPhi = Descriptor->Flags.has(InstructionFlag::Phi);
    for (const MachineOperand &Operand : Instruction->operands()) {
      const auto *MaskOperand = Operand.getIf<LiveOutRegisterMaskOperand>();
      if (MaskOperand == nullptr)
        continue;
      if (!MaskOperand->Mask) {
        return makeUnexpected(ErrorCode::VerificationError,
                              "liveness verification encountered a null live-out register mask");
      }
      auto Added = addRegisterMaskUses(Physical, *MaskOperand->Mask, Target);
      if (!Added)
        return std::unexpected(Added.error());
    }

    for (const MachineOperand &Operand : Instruction->operands()) {
      if (Operand.isRegister() && Operand.isDef()) {
        auto Removed = removeOperandFromLiveSet(Operand, Virtual, Physical, Function, Target);
        if (!Removed)
          return std::unexpected(Removed.error());
        continue;
      }
      const auto *MaskOperand = Operand.getIf<RegisterMaskOperand>();
      if (MaskOperand == nullptr)
        continue;
      if (!MaskOperand->Mask) {
        return makeUnexpected(ErrorCode::VerificationError,
                              "liveness verification encountered a null register mask");
      }
      LiveRegUnits Clobbers;
      auto Added = addRegisterMaskDefs(Clobbers, *MaskOperand->Mask, Target);
      if (!Added)
        return std::unexpected(Added.error());
      Physical.subtract(Clobbers);
    }

    if (IsPhi)
      continue;
    for (const MachineOperand &Operand : Instruction->operands()) {
      if (!Operand.isRegister() || !Operand.isUse())
        continue;
      const Register *Reg = Operand.getIf<Register>();
      if (Reg != nullptr && Reg->isPhysical() &&
          isReservedPhysicalRegister(*Reg, Function, Target)) {
        continue;
      }
      auto Added = addOperandToLiveSet(Operand, Virtual, Physical, Function, Target);
      if (!Added)
        return std::unexpected(Added.error());
    }
  }
  return Physical;
}

[[nodiscard]] Expected<LivenessRebuildPlan>
buildLivenessRebuildPlan(const MachineFunction &Function, const TargetDescription &Target) {
  auto Variables = computeLiveVariables(Function, Target);
  if (!Variables)
    return std::unexpected(Variables.error());

  LivenessRebuildPlan Plan;
  for (const MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr;
       Block = Block->next()) {
    const MachineBlockLiveness *BlockVariables = Variables->block(*Block);
    if (BlockVariables == nullptr)
      return makeUnexpected(ErrorCode::InternalError, "liveness result omitted a machine block");
    auto NewLiveIns = canonicalPhysicalLiveIns(BlockVariables->PhysicalLiveIn, Target);
    if (!NewLiveIns)
      return std::unexpected(NewLiveIns.error());
    Plan.Blocks.push_back(
        {Block->stableID(),
         std::vector<MachineBasicBlockLiveIn>(Block->liveIns().begin(), Block->liveIns().end()),
         std::move(*NewLiveIns)});

    RegisterLaneSet Virtual = BlockVariables->VirtualLiveOut;
    LiveRegUnits Physical = BlockVariables->PhysicalLiveOut;
    for (const MachineInstr *Instruction = Block->lastInstruction(); Instruction != nullptr;
         Instruction = Instruction->previous()) {
      const InstructionDescriptor *Descriptor = Target.instructionDescriptor(Instruction->opcode());
      if (Descriptor == nullptr) {
        return makeUnexpected(ErrorCode::VerificationError,
                              "liveness rebuild encountered an unknown instruction descriptor");
      }
      const bool IsPhi = Descriptor->Flags.has(InstructionFlag::Phi);
      for (const MachineOperand &Operand : Instruction->operands()) {
        const auto *MaskOperand = Operand.getIf<LiveOutRegisterMaskOperand>();
        if (MaskOperand == nullptr)
          continue;
        if (!MaskOperand->Mask)
          return makeUnexpected(ErrorCode::VerificationError,
                                "liveness rebuild encountered a null live-out register mask");
        auto Added = addRegisterMaskUses(Physical, *MaskOperand->Mask, Target);
        if (!Added)
          return std::unexpected(Added.error());
      }

      for (std::size_t Index = 0; Index < Instruction->operandCount(); ++Index) {
        const MachineOperand *Operand = Instruction->operandAt(Index);
        if (Operand == nullptr || !Operand->isRegister() || !Operand->isDef())
          continue;
        auto IsLive = liveSetIntersects(*Operand, Virtual, Physical, Function, Target);
        if (!IsLive)
          return std::unexpected(IsLive.error());
        RegisterOperandFlags Flags = Operand->registerFlags();
        Flags.clear(RegisterOperandFlag::Dead);
        if (!*IsLive)
          Flags.set(RegisterOperandFlag::Dead);
        Plan.Operands.push_back(
            {Instruction->stableID(), Index, Operand->registerFlags(), Flags, false, !*IsLive});
      }

      for (const MachineOperand &Operand : Instruction->operands()) {
        if (Operand.isRegister() && Operand.isDef()) {
          auto Removed = removeOperandFromLiveSet(Operand, Virtual, Physical, Function, Target);
          if (!Removed)
            return std::unexpected(Removed.error());
          continue;
        }
        const auto *MaskOperand = Operand.getIf<RegisterMaskOperand>();
        if (MaskOperand == nullptr)
          continue;
        if (!MaskOperand->Mask)
          return makeUnexpected(ErrorCode::VerificationError,
                                "liveness rebuild encountered a null register mask");
        LiveRegUnits Clobbers;
        auto Added = addRegisterMaskDefs(Clobbers, *MaskOperand->Mask, Target);
        if (!Added)
          return std::unexpected(Added.error());
        Physical.subtract(Clobbers);
      }

      for (std::size_t Index = 0; Index < Instruction->operandCount(); ++Index) {
        const MachineOperand *Operand = Instruction->operandAt(Index);
        if (Operand == nullptr || !Operand->isRegister() || !Operand->isUse())
          continue;
        if (IsPhi) {
          RegisterOperandFlags Flags = Operand->registerFlags();
          Flags.clear(RegisterOperandFlag::Kill);
          const auto Existing = std::ranges::find_if(
              Plan.Operands, [Instruction, Index](const OperandFlagPlan &Entry) {
                return Entry.Instruction == Instruction->stableID() && Entry.OperandIndex == Index;
              });
          if (Existing == Plan.Operands.end()) {
            Plan.Operands.push_back(
                {Instruction->stableID(), Index, Operand->registerFlags(), Flags, false, false});
          } else {
            Existing->Rebuilt.clear(RegisterOperandFlag::Kill);
            Existing->KillIsValid = false;
          }
          continue;
        }
        const Register OperandRegister = *Operand->registerValue();
        const auto PhysicalRegister = OperandRegister.physicalRegister();
        const PhysicalRegisterDesc *PhysicalDescription =
            PhysicalRegister ? Target.registers().physicalRegister(*PhysicalRegister) : nullptr;
        const bool IsSemanticUse =
            !Operand->isDebugUse() && !Operand->registerFlags().has(RegisterOperandFlag::Undef) &&
            !OperandRegister.isNoRegister() &&
            (PhysicalDescription == nullptr || !PhysicalDescription->IsConstant);
        bool IsKill = false;
        if (IsSemanticUse) {
          auto IsLive = liveSetIntersects(*Operand, Virtual, Physical, Function, Target);
          if (!IsLive)
            return std::unexpected(IsLive.error());
          IsKill = !*IsLive;
        }
        RegisterOperandFlags Flags = Operand->registerFlags();
        Flags.clear(RegisterOperandFlag::Kill);
        if (IsKill)
          Flags.set(RegisterOperandFlag::Kill);

        const auto Existing =
            std::ranges::find_if(Plan.Operands, [Instruction, Index](const OperandFlagPlan &Entry) {
              return Entry.Instruction == Instruction->stableID() && Entry.OperandIndex == Index;
            });
        if (Existing == Plan.Operands.end()) {
          Plan.Operands.push_back(
              {Instruction->stableID(), Index, Operand->registerFlags(), Flags, IsKill, false});
        } else {
          Existing->Rebuilt.clear(RegisterOperandFlag::Kill);
          if (IsKill)
            Existing->Rebuilt.set(RegisterOperandFlag::Kill);
          Existing->KillIsValid = IsKill;
        }
        if (IsSemanticUse) {
          auto Added = addOperandToLiveSet(*Operand, Virtual, Physical, Function, Target);
          if (!Added)
            return std::unexpected(Added.error());
        }
      }
    }

    if (Block == Function.firstBlock()) {
      for (const PhysicalRegisterLiveIn &LiveIn : Function.registerInfo().liveIns()) {
        const PhysicalRegisterDesc *Description =
            Target.registers().physicalRegister(LiveIn.PhysReg);
        if (Description == nullptr) {
          return makeUnexpected(ErrorCode::VerificationError,
                                "liveness rebuild encountered an unknown function live-in");
        }
        addPhysicalRegister(Physical, *Description);
        if (LiveIn.InitialVirtualRegister) {
          auto Lanes = virtualRegisterLanes(*LiveIn.InitialVirtualRegister, Function, Target);
          if (!Lanes)
            return std::unexpected(Lanes.error());
          Virtual.remove(*LiveIn.InitialVirtualRegister, *Lanes);
        }
      }
    }

    if (Virtual != BlockVariables->VirtualLiveIn || Physical != BlockVariables->PhysicalLiveIn) {
      return makeUnexpected(ErrorCode::InternalError,
                            "reverse liveness reconstruction disagrees with block dataflow");
    }
  }
  return Plan;
}

struct ResolvedBlockLivenessPlan final {
  MachineBasicBlock *Block = nullptr;
  const BlockLivenessPlan *Plan = nullptr;
};

struct ResolvedOperandFlagPlan final {
  MachineOperand *Operand = nullptr;
  const OperandFlagPlan *Plan = nullptr;
};

struct ResolvedLivenessRebuildPlan final {
  std::vector<ResolvedBlockLivenessPlan> Blocks;
  std::vector<ResolvedOperandFlagPlan> Operands;
};

[[nodiscard]] Expected<ResolvedLivenessRebuildPlan>
resolveLivenessPlan(MachineFunction &Function, const LivenessRebuildPlan &Plan) {
  ResolvedLivenessRebuildPlan Result;
  Result.Blocks.reserve(Plan.Blocks.size());
  for (const BlockLivenessPlan &BlockPlan : Plan.Blocks) {
    const auto Position =
        std::ranges::find_if(Function.allBlocks(), [&BlockPlan](const MachineBasicBlock *Block) {
          return Block != nullptr && Block->stableID() == BlockPlan.Block;
        });
    if (Position == Function.allBlocks().end() || !(*Position)->isLinked()) {
      return makeUnexpected(ErrorCode::InternalError,
                            "liveness rebuild plan references an unavailable machine block");
    }
    Result.Blocks.push_back({*Position, &BlockPlan});
  }

  Result.Operands.reserve(Plan.Operands.size());
  for (const OperandFlagPlan &OperandPlan : Plan.Operands) {
    const auto Position = std::ranges::find_if(
        Function.allInstructions(), [&OperandPlan](const MachineInstr *Instruction) {
          return Instruction != nullptr && Instruction->stableID() == OperandPlan.Instruction;
        });
    if (Position == Function.allInstructions().end() || !(*Position)->isLinked()) {
      return makeUnexpected(ErrorCode::InternalError,
                            "liveness rebuild plan references an unavailable instruction");
    }
    MachineOperand *Operand = (*Position)->operandAt(OperandPlan.OperandIndex);
    if (Operand == nullptr) {
      return makeUnexpected(ErrorCode::InternalError,
                            "liveness rebuild plan references an unavailable operand");
    }
    Result.Operands.push_back({Operand, &OperandPlan});
  }
  return Result;
}

[[nodiscard]] Expected<void> restoreLivenessPlan(const ResolvedLivenessRebuildPlan &Plan) {
  for (const ResolvedBlockLivenessPlan &Resolved : Plan.Blocks) {
    Resolved.Block->clearLiveIns();
    for (const MachineBasicBlockLiveIn &LiveIn : Resolved.Plan->OriginalLiveIns) {
      auto Restored = Resolved.Block->addLiveIn(LiveIn.PhysReg, LiveIn.Lanes);
      if (!Restored)
        return std::unexpected(Restored.error());
    }
  }
  for (const ResolvedOperandFlagPlan &Resolved : Plan.Operands) {
    auto Restored = Resolved.Operand->setRegisterFlags(Resolved.Plan->Original);
    if (!Restored)
      return std::unexpected(Restored.error());
  }
  return {};
}

[[nodiscard]] Expected<bool> applyLivenessPlan(MachineFunction &Function,
                                               const LivenessRebuildPlan &Plan) {
  auto Resolved = resolveLivenessPlan(Function, Plan);
  if (!Resolved)
    return std::unexpected(Resolved.error());

  bool Changed = false;
  for (const ResolvedBlockLivenessPlan &BlockPlan : Resolved->Blocks) {
    Changed |= BlockPlan.Plan->OriginalLiveIns != BlockPlan.Plan->RebuiltLiveIns;
    BlockPlan.Block->clearLiveIns();
    for (const MachineBasicBlockLiveIn &LiveIn : BlockPlan.Plan->RebuiltLiveIns) {
      auto Added = BlockPlan.Block->addLiveIn(LiveIn.PhysReg, LiveIn.Lanes);
      if (!Added) {
        auto Restored = restoreLivenessPlan(*Resolved);
        if (!Restored)
          return makeUnexpected(ErrorCode::InternalError,
                                "liveness rebuild failed and rollback also failed");
        return std::unexpected(Added.error());
      }
    }
  }
  for (const ResolvedOperandFlagPlan &OperandPlan : Resolved->Operands) {
    Changed |= OperandPlan.Plan->Original != OperandPlan.Plan->Rebuilt;
    auto Updated = OperandPlan.Operand->setRegisterFlags(OperandPlan.Plan->Rebuilt);
    if (!Updated) {
      auto Restored = restoreLivenessPlan(*Resolved);
      if (!Restored)
        return makeUnexpected(ErrorCode::InternalError,
                              "liveness rebuild failed and rollback also failed");
      return std::unexpected(Updated.error());
    }
  }
  return Changed;
}
} // namespace

LaneMask RegisterLaneSet::lanes(Register Reg) const noexcept {
  return lanesFor(Values, Reg);
}

bool RegisterLaneSet::contains(Register Reg, LaneMask Lanes) const noexcept {
  return containsLanes(Values, Reg, Lanes);
}

bool RegisterLaneSet::intersects(Register Reg, LaneMask Lanes) const noexcept {
  return intersectsLanes(Values, Reg, Lanes);
}

void RegisterLaneSet::add(Register Reg, LaneMask Lanes) {
  if (!Reg.isNoRegister())
    addLanes(Values, Reg, Lanes);
}

void RegisterLaneSet::remove(Register Reg, LaneMask Lanes) {
  removeLanes(Values, Reg, Lanes);
}

void RegisterLaneSet::unite(const RegisterLaneSet &Other) {
  uniteLanes(Values, Other.Values);
}

void RegisterLaneSet::subtract(const RegisterLaneSet &Other) {
  subtractLaneSets(Values, Other.Values);
}
const MachineBlockLiveness *
LiveVariablesAnalysis::Result::block(const MachineBasicBlock &Block) const noexcept {
  const auto Position = Blocks.find(&Block);
  return Position == Blocks.end() ? nullptr : &Position->second;
}

MachineBlockLiveness &
LiveVariablesAnalysis::Result::getOrCreateBlock(const MachineBasicBlock &Block) {
  return Blocks[&Block];
}

bool LiveVariablesAnalysis::Result::isLiveIn(const MachineBasicBlock &Block, Register Reg,
                                             LaneMask Lanes) const noexcept {
  const MachineBlockLiveness *Value = block(Block);
  return Value != nullptr && Value->VirtualLiveIn.intersects(Reg, Lanes);
}

bool LiveVariablesAnalysis::Result::isLiveOut(const MachineBasicBlock &Block, Register Reg,
                                              LaneMask Lanes) const noexcept {
  const MachineBlockLiveness *Value = block(Block);
  return Value != nullptr && Value->VirtualLiveOut.intersects(Reg, Lanes);
}

bool LiveVariablesAnalysis::Result::isUnitLiveIn(const MachineBasicBlock &Block,
                                                 RegisterUnitID Unit,
                                                 LaneMask Lanes) const noexcept {
  const MachineBlockLiveness *Value = block(Block);
  return Value != nullptr && Value->PhysicalLiveIn.intersects(Unit, Lanes);
}

bool LiveVariablesAnalysis::Result::isUnitLiveOut(const MachineBasicBlock &Block,
                                                  RegisterUnitID Unit,
                                                  LaneMask Lanes) const noexcept {
  const MachineBlockLiveness *Value = block(Block);
  return Value != nullptr && Value->PhysicalLiveOut.intersects(Unit, Lanes);
}

bool LiveVariablesAnalysis::Result::invalidate(const MachineFunction &,
                                               const PreservedAnalyses &Preserved) const noexcept {
  return !Preserved.preserves(MachineFunctionAnalysisManager::id<LiveVariablesAnalysis>());
}

Expected<LiveVariablesAnalysis::Result>
LiveVariablesAnalysis::run(MachineFunction &Function, const TargetDescription &Target,
                           MachineFunctionAnalysisManager &) {
  return computeLiveVariables(Function, Target);
}
const MachinePassContract &RebuildMachineLivenessPass::contract() const noexcept {
  static const MachinePassContract Contract = [] {
    MachinePassContract Value{
        .Name = "RebuildMachineLiveness",
        .Requires = {MachineFunctionProperty::Selected, MachineFunctionProperty::NoPHIs,
                     MachineFunctionProperty::TiedOpsRewritten},
        .Sets = {MachineFunctionProperty::TracksLiveness},
        .Clears = {},
        .RequiredAnalyses = {},
        .VerificationStage = std::nullopt,
    };
    Value.DeclaredChanges = {MachinePassChange::Operands};
    return Value;
  }();
  return Contract;
}

Expected<MachinePassResult> RebuildMachineLivenessPass::run(MachineFunction &Function,
                                                            const TargetDescription &Target,
                                                            MachineFunctionAnalysisManager &) {
  const MachineFunctionProperties Missing = contract().Requires.missingFrom(Function.properties());
  if (!Missing.empty()) {
    return makeUnexpected(ErrorCode::VerificationError,
                          "RebuildMachineLiveness requires properties: " + Missing.toString());
  }
  auto Applied = rebuildMachineLiveness(Function, Target);
  if (!Applied)
    return std::unexpected(Applied.error());

  MachinePassResult Result;
  Result.Changed = *Applied;
  if (Result.Changed)
    Result.Changes.add(MachinePassChange::Operands);
  Result.Preserved = PreservedAnalyses::all();
  return Result;
}

Expected<bool> rebuildMachineLiveness(MachineFunction &Function, const TargetDescription &Target) {
  auto Plan = buildLivenessRebuildPlan(Function, Target);
  if (!Plan)
    return std::unexpected(Plan.error());
  return applyLivenessPlan(Function, *Plan);
}

Expected<void> verifyTrackedMachineLiveness(const MachineFunction &Function,
                                            const TargetDescription &Target) {
  auto Plan = buildLivenessRebuildPlan(Function, Target);
  if (!Plan)
    return std::unexpected(Plan.error());
  for (const MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr;
       Block = Block->next()) {
    auto Actual = liveInUnits(Block->liveIns(), Target);
    if (!Actual)
      return std::unexpected(Actual.error());
    auto Expected = requiredLocalPhysicalLiveIns(*Block, Function, Target);
    if (!Expected)
      return std::unexpected(Expected.error());
    if (!isSubset(*Expected, *Actual)) {
      const auto Missing = std::ranges::find_if(Expected->entries(), [&Actual](const auto &Entry) {
        return !Actual->contains(Entry.first, Entry.second);
      });
      if (Missing != Expected->entries().end()) {
        return makeUnexpected(ErrorCode::VerificationError,
                              "TracksLiveness block " + std::to_string(Block->stableID().value()) +
                                  " is missing required physical register unit " +
                                  std::to_string(Missing->first.value()));
      }
      return makeUnexpected(ErrorCode::VerificationError,
                            "TracksLiveness block is missing required physical live-ins");
    }
  }
  for (const OperandFlagPlan &OperandPlan : Plan->Operands) {
    if (OperandPlan.Original.has(RegisterOperandFlag::Kill) && !OperandPlan.KillIsValid) {
      return makeUnexpected(ErrorCode::VerificationError,
                            "TracksLiveness operand has a stale kill flag");
    }
    if (OperandPlan.Original.has(RegisterOperandFlag::Dead) && !OperandPlan.DeadIsValid) {
      return makeUnexpected(ErrorCode::VerificationError,
                            "TracksLiveness operand has a stale dead flag");
    }
  }
  return {};
}

Expected<void> registerStage11MachineAnalyses(MachineFunctionAnalysisManager &Analyses) {
  const std::array IDs{
      MachineFunctionAnalysisManager::id<SlotIndexesAnalysis>(),
      MachineFunctionAnalysisManager::id<LiveVariablesAnalysis>(),
      MachineFunctionAnalysisManager::id<LiveIntervalsAnalysis>(),
      MachineFunctionAnalysisManager::id<VirtRegMapAnalysis>(),
      MachineFunctionAnalysisManager::id<ReachingDefAnalysis>(),
  };
  const std::size_t Registered = static_cast<std::size_t>(
      std::ranges::count_if(IDs, [&Analyses](AnalysisID ID) { return Analyses.isRegistered(ID); }));
  if (Registered == IDs.size())
    return {};
  if (Registered != 0) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "standard liveness analyses are only partially registered");
  }

  auto Candidate = Analyses.forkEmpty();
  if (!Candidate)
    return std::unexpected(Candidate.error());
  MachineFunctionAnalysisManager &Staging = **Candidate;
  auto Slots = Staging.registerAnalysis<SlotIndexesAnalysis>({
      .Name = "SlotIndexes",
      .Dependencies = {},
      .InvalidatedBy = {MachinePassChange::Instructions, MachinePassChange::BlockLayout},
      .ThreadSafety = PassThreadSafety::ThreadSafe,
  });
  if (!Slots)
    return std::unexpected(Slots.error());
  auto Variables = Staging.registerAnalysis<LiveVariablesAnalysis>({
      .Name = "LiveVariables",
      .Dependencies = {},
      .InvalidatedBy = {MachinePassChange::Instructions, MachinePassChange::Operands,
                        MachinePassChange::Registers, MachinePassChange::CFG,
                        MachinePassChange::TargetState},
      .ThreadSafety = PassThreadSafety::ThreadSafe,
  });
  if (!Variables)
    return std::unexpected(Variables.error());
  auto Intervals = Staging.registerAnalysis<LiveIntervalsAnalysis>({
      .Name = "LiveIntervals",
      .Dependencies = {MachineFunctionAnalysisManager::id<SlotIndexesAnalysis>(),
                       MachineFunctionAnalysisManager::id<LiveVariablesAnalysis>()},
      .InvalidatedBy = {MachinePassChange::Instructions, MachinePassChange::Operands,
                        MachinePassChange::Registers, MachinePassChange::CFG,
                        MachinePassChange::BlockLayout, MachinePassChange::TargetState},
      .ThreadSafety = PassThreadSafety::ThreadSafe,
  });
  if (!Intervals)
    return std::unexpected(Intervals.error());
  auto Mapping = Staging.registerAnalysis<VirtRegMapAnalysis>({
      .Name = "VirtRegMap",
      .Dependencies = {},
      .InvalidatedBy = MachinePassChanges::all(),
      .ThreadSafety = PassThreadSafety::ThreadSafe,
  });
  if (!Mapping)
    return std::unexpected(Mapping.error());
  auto ReachingDefinitions = Staging.registerAnalysis<ReachingDefAnalysis>({
      .Name = "ReachingDefAnalysis",
      .Dependencies = {},
      .InvalidatedBy = {MachinePassChange::Instructions, MachinePassChange::Operands,
                        MachinePassChange::Registers, MachinePassChange::CFG,
                        MachinePassChange::BlockLayout, MachinePassChange::Frame,
                        MachinePassChange::TargetState},
      .ThreadSafety = PassThreadSafety::ThreadSafe,
  });
  if (!ReachingDefinitions)
    return std::unexpected(ReachingDefinitions.error());
  return Analyses.replaceRegistrations(std::move(Staging));
}

} // namespace rcc