forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMachineBasicBlock.cpp
1624 lines (1410 loc) · 55.1 KB
/
MachineBasicBlock.cpp
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
//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Collect the sequence of machine instructions for a basic block.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/CodeGen/LiveIntervals.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/ModuleSlotTracker.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_TYPE "codegen"
static cl::opt<bool> PrintSlotIndexes(
"print-slotindexes",
cl::desc("When printing machine IR, annotate instructions and blocks with "
"SlotIndexes when available"),
cl::init(true), cl::Hidden);
MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
: BB(B), Number(-1), xParent(&MF) {
Insts.Parent = this;
if (B)
IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
}
MachineBasicBlock::~MachineBasicBlock() = default;
/// Return the MCSymbol for this basic block.
MCSymbol *MachineBasicBlock::getSymbol() const {
if (!CachedMCSymbol) {
const MachineFunction *MF = getParent();
MCContext &Ctx = MF->getContext();
// We emit a non-temporary symbol -- with a descriptive name -- if it begins
// a section (with basic block sections). Otherwise we fall back to use temp
// label.
if (MF->hasBBSections() && isBeginSection()) {
SmallString<5> Suffix;
if (SectionID == MBBSectionID::ColdSectionID) {
Suffix += ".cold";
} else if (SectionID == MBBSectionID::ExceptionSectionID) {
Suffix += ".eh";
} else {
// For symbols that represent basic block sections, we add ".__part." to
// allow tools like symbolizers to know that this represents a part of
// the original function.
Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
}
CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
} else {
const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
Twine(MF->getFunctionNumber()) +
"_" + Twine(getNumber()));
}
}
return CachedMCSymbol;
}
MCSymbol *MachineBasicBlock::getEHCatchretSymbol() const {
if (!CachedEHCatchretMCSymbol) {
const MachineFunction *MF = getParent();
SmallString<128> SymbolName;
raw_svector_ostream(SymbolName)
<< "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
}
return CachedEHCatchretMCSymbol;
}
MCSymbol *MachineBasicBlock::getEndSymbol() const {
if (!CachedEndMCSymbol) {
const MachineFunction *MF = getParent();
MCContext &Ctx = MF->getContext();
auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
CachedEndMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB_END" +
Twine(MF->getFunctionNumber()) +
"_" + Twine(getNumber()));
}
return CachedEndMCSymbol;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
MBB.print(OS);
return OS;
}
Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
}
/// When an MBB is added to an MF, we need to update the parent pointer of the
/// MBB, the MBB numbering, and any instructions in the MBB to be on the right
/// operand list for registers.
///
/// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
/// gets the next available unique MBB number. If it is removed from a
/// MachineFunction, it goes back to being #-1.
void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
MachineBasicBlock *N) {
MachineFunction &MF = *N->getParent();
N->Number = MF.addToMBBNumbering(N);
// Make sure the instructions have their operands in the reginfo lists.
MachineRegisterInfo &RegInfo = MF.getRegInfo();
for (MachineInstr &MI : N->instrs())
MI.AddRegOperandsToUseLists(RegInfo);
}
void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
MachineBasicBlock *N) {
N->getParent()->removeFromMBBNumbering(N->Number);
N->Number = -1;
}
/// When we add an instruction to a basic block list, we update its parent
/// pointer and add its operands from reg use/def lists if appropriate.
void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
assert(!N->getParent() && "machine instruction already in a basic block");
N->setParent(Parent);
// Add the instruction's register operands to their corresponding
// use/def lists.
MachineFunction *MF = Parent->getParent();
N->AddRegOperandsToUseLists(MF->getRegInfo());
MF->handleInsertion(*N);
}
/// When we remove an instruction from a basic block list, we update its parent
/// pointer and remove its operands from reg use/def lists if appropriate.
void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
assert(N->getParent() && "machine instruction not in a basic block");
// Remove from the use/def lists.
if (MachineFunction *MF = N->getMF()) {
MF->handleRemoval(*N);
N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
}
N->setParent(nullptr);
}
/// When moving a range of instructions from one MBB list to another, we need to
/// update the parent pointers and the use/def lists.
void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
instr_iterator First,
instr_iterator Last) {
assert(Parent->getParent() == FromList.Parent->getParent() &&
"cannot transfer MachineInstrs between MachineFunctions");
// If it's within the same BB, there's nothing to do.
if (this == &FromList)
return;
assert(Parent != FromList.Parent && "Two lists have the same parent?");
// If splicing between two blocks within the same function, just update the
// parent pointers.
for (; First != Last; ++First)
First->setParent(Parent);
}
void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
assert(!MI->getParent() && "MI is still in a block!");
Parent->getParent()->deleteMachineInstr(MI);
}
MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
instr_iterator I = instr_begin(), E = instr_end();
while (I != E && I->isPHI())
++I;
assert((I == E || !I->isInsideBundle()) &&
"First non-phi MI cannot be inside a bundle!");
return I;
}
MachineBasicBlock::iterator
MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
iterator E = end();
while (I != E && (I->isPHI() || I->isPosition() ||
TII->isBasicBlockPrologue(*I)))
++I;
// FIXME: This needs to change if we wish to bundle labels
// inside the bundle.
assert((I == E || !I->isInsideBundle()) &&
"First non-phi / non-label instruction is inside a bundle!");
return I;
}
MachineBasicBlock::iterator
MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
bool SkipPseudoOp) {
const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
iterator E = end();
while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
(SkipPseudoOp && I->isPseudoProbe()) ||
TII->isBasicBlockPrologue(*I)))
++I;
// FIXME: This needs to change if we wish to bundle labels / dbg_values
// inside the bundle.
assert((I == E || !I->isInsideBundle()) &&
"First non-phi / non-label / non-debug "
"instruction is inside a bundle!");
return I;
}
MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
iterator B = begin(), E = end(), I = E;
while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
; /*noop */
while (I != E && !I->isTerminator())
++I;
return I;
}
MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
instr_iterator B = instr_begin(), E = instr_end(), I = E;
while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
; /*noop */
while (I != E && !I->isTerminator())
++I;
return I;
}
MachineBasicBlock::iterator
MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) {
// Skip over begin-of-block dbg_value instructions.
return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
}
MachineBasicBlock::iterator
MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) {
// Skip over end-of-block dbg_value instructions.
instr_iterator B = instr_begin(), I = instr_end();
while (I != B) {
--I;
// Return instruction that starts a bundle.
if (I->isDebugInstr() || I->isInsideBundle())
continue;
if (SkipPseudoOp && I->isPseudoProbe())
continue;
return I;
}
// The block is all debug values.
return end();
}
bool MachineBasicBlock::hasEHPadSuccessor() const {
for (const MachineBasicBlock *Succ : successors())
if (Succ->isEHPad())
return true;
return false;
}
bool MachineBasicBlock::isEntryBlock() const {
return getParent()->begin() == getIterator();
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
print(dbgs());
}
#endif
bool MachineBasicBlock::mayHaveInlineAsmBr() const {
for (const MachineBasicBlock *Succ : successors()) {
if (Succ->isInlineAsmBrIndirectTarget())
return true;
}
return false;
}
bool MachineBasicBlock::isLegalToHoistInto() const {
if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
return false;
return true;
}
StringRef MachineBasicBlock::getName() const {
if (const BasicBlock *LBB = getBasicBlock())
return LBB->getName();
else
return StringRef("", 0);
}
/// Return a hopefully unique identifier for this block.
std::string MachineBasicBlock::getFullName() const {
std::string Name;
if (getParent())
Name = (getParent()->getName() + ":").str();
if (getBasicBlock())
Name += getBasicBlock()->getName();
else
Name += ("BB" + Twine(getNumber())).str();
return Name;
}
void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
bool IsStandalone) const {
const MachineFunction *MF = getParent();
if (!MF) {
OS << "Can't print out MachineBasicBlock because parent MachineFunction"
<< " is null\n";
return;
}
const Function &F = MF->getFunction();
const Module *M = F.getParent();
ModuleSlotTracker MST(M);
MST.incorporateFunction(F);
print(OS, MST, Indexes, IsStandalone);
}
void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
const SlotIndexes *Indexes,
bool IsStandalone) const {
const MachineFunction *MF = getParent();
if (!MF) {
OS << "Can't print out MachineBasicBlock because parent MachineFunction"
<< " is null\n";
return;
}
if (Indexes && PrintSlotIndexes)
OS << Indexes->getMBBStartIdx(this) << '\t';
printName(OS, PrintNameIr | PrintNameAttributes, &MST);
OS << ":\n";
const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
const MachineRegisterInfo &MRI = MF->getRegInfo();
const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
bool HasLineAttributes = false;
// Print the preds of this block according to the CFG.
if (!pred_empty() && IsStandalone) {
if (Indexes) OS << '\t';
// Don't indent(2), align with previous line attributes.
OS << "; predecessors: ";
ListSeparator LS;
for (auto *Pred : predecessors())
OS << LS << printMBBReference(*Pred);
OS << '\n';
HasLineAttributes = true;
}
if (!succ_empty()) {
if (Indexes) OS << '\t';
// Print the successors
OS.indent(2) << "successors: ";
ListSeparator LS;
for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
OS << LS << printMBBReference(**I);
if (!Probs.empty())
OS << '('
<< format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
<< ')';
}
if (!Probs.empty() && IsStandalone) {
// Print human readable probabilities as comments.
OS << "; ";
ListSeparator LS;
for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
const BranchProbability &BP = getSuccProbability(I);
OS << LS << printMBBReference(**I) << '('
<< format("%.2f%%",
rint(((double)BP.getNumerator() / BP.getDenominator()) *
100.0 * 100.0) /
100.0)
<< ')';
}
}
OS << '\n';
HasLineAttributes = true;
}
if (!livein_empty() && MRI.tracksLiveness()) {
if (Indexes) OS << '\t';
OS.indent(2) << "liveins: ";
ListSeparator LS;
for (const auto &LI : liveins()) {
OS << LS << printReg(LI.PhysReg, TRI);
if (!LI.LaneMask.all())
OS << ":0x" << PrintLaneMask(LI.LaneMask);
}
HasLineAttributes = true;
}
if (HasLineAttributes)
OS << '\n';
bool IsInBundle = false;
for (const MachineInstr &MI : instrs()) {
if (Indexes && PrintSlotIndexes) {
if (Indexes->hasIndex(MI))
OS << Indexes->getInstructionIndex(MI);
OS << '\t';
}
if (IsInBundle && !MI.isInsideBundle()) {
OS.indent(2) << "}\n";
IsInBundle = false;
}
OS.indent(IsInBundle ? 4 : 2);
MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
/*AddNewLine=*/false, &TII);
if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
OS << " {";
IsInBundle = true;
}
OS << '\n';
}
if (IsInBundle)
OS.indent(2) << "}\n";
if (IrrLoopHeaderWeight && IsStandalone) {
if (Indexes) OS << '\t';
OS.indent(2) << "; Irreducible loop header weight: "
<< IrrLoopHeaderWeight.getValue() << '\n';
}
}
/// Print the basic block's name as:
///
/// bb.{number}[.{ir-name}] [(attributes...)]
///
/// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
/// (which is the default). If the IR block has no name, it is identified
/// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
///
/// When the \ref PrintNameAttributes flag is passed, additional attributes
/// of the block are printed when set.
///
/// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
/// the parts to print.
/// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
/// incorporate its own tracker when necessary to
/// determine the block's IR name.
void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
ModuleSlotTracker *moduleSlotTracker) const {
os << "bb." << getNumber();
bool hasAttributes = false;
if (printNameFlags & PrintNameIr) {
if (const auto *bb = getBasicBlock()) {
if (bb->hasName()) {
os << '.' << bb->getName();
} else {
hasAttributes = true;
os << " (";
int slot = -1;
if (moduleSlotTracker) {
slot = moduleSlotTracker->getLocalSlot(bb);
} else if (bb->getParent()) {
ModuleSlotTracker tmpTracker(bb->getModule(), false);
tmpTracker.incorporateFunction(*bb->getParent());
slot = tmpTracker.getLocalSlot(bb);
}
if (slot == -1)
os << "<ir-block badref>";
else
os << (Twine("%ir-block.") + Twine(slot)).str();
}
}
}
if (printNameFlags & PrintNameAttributes) {
if (hasAddressTaken()) {
os << (hasAttributes ? ", " : " (");
os << "address-taken";
hasAttributes = true;
}
if (isEHPad()) {
os << (hasAttributes ? ", " : " (");
os << "landing-pad";
hasAttributes = true;
}
if (isInlineAsmBrIndirectTarget()) {
os << (hasAttributes ? ", " : " (");
os << "inlineasm-br-indirect-target";
hasAttributes = true;
}
if (isEHFuncletEntry()) {
os << (hasAttributes ? ", " : " (");
os << "ehfunclet-entry";
hasAttributes = true;
}
if (getAlignment() != Align(1)) {
os << (hasAttributes ? ", " : " (");
os << "align " << getAlignment().value();
hasAttributes = true;
}
if (getSectionID() != MBBSectionID(0)) {
os << (hasAttributes ? ", " : " (");
os << "bbsections ";
switch (getSectionID().Type) {
case MBBSectionID::SectionType::Exception:
os << "Exception";
break;
case MBBSectionID::SectionType::Cold:
os << "Cold";
break;
default:
os << getSectionID().Number;
}
hasAttributes = true;
}
}
if (hasAttributes)
os << ')';
}
void MachineBasicBlock::printAsOperand(raw_ostream &OS,
bool /*PrintType*/) const {
OS << '%';
printName(OS, 0);
}
void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
LiveInVector::iterator I = find_if(
LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
if (I == LiveIns.end())
return;
I->LaneMask &= ~LaneMask;
if (I->LaneMask.none())
LiveIns.erase(I);
}
MachineBasicBlock::livein_iterator
MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
// Get non-const version of iterator.
LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
return LiveIns.erase(LI);
}
bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
livein_iterator I = find_if(
LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
return I != livein_end() && (I->LaneMask & LaneMask).any();
}
void MachineBasicBlock::sortUniqueLiveIns() {
llvm::sort(LiveIns,
[](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
return LI0.PhysReg < LI1.PhysReg;
});
// Liveins are sorted by physreg now we can merge their lanemasks.
LiveInVector::const_iterator I = LiveIns.begin();
LiveInVector::const_iterator J;
LiveInVector::iterator Out = LiveIns.begin();
for (; I != LiveIns.end(); ++Out, I = J) {
MCRegister PhysReg = I->PhysReg;
LaneBitmask LaneMask = I->LaneMask;
for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
LaneMask |= J->LaneMask;
Out->PhysReg = PhysReg;
Out->LaneMask = LaneMask;
}
LiveIns.erase(Out, LiveIns.end());
}
Register
MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
assert(getParent() && "MBB must be inserted in function");
assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
assert(RC && "Register class is required");
assert((isEHPad() || this == &getParent()->front()) &&
"Only the entry block and landing pads can have physreg live ins");
bool LiveIn = isLiveIn(PhysReg);
iterator I = SkipPHIsAndLabels(begin()), E = end();
MachineRegisterInfo &MRI = getParent()->getRegInfo();
const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
// Look for an existing copy.
if (LiveIn)
for (;I != E && I->isCopy(); ++I)
if (I->getOperand(1).getReg() == PhysReg) {
Register VirtReg = I->getOperand(0).getReg();
if (!MRI.constrainRegClass(VirtReg, RC))
llvm_unreachable("Incompatible live-in register class.");
return VirtReg;
}
// No luck, create a virtual register.
Register VirtReg = MRI.createVirtualRegister(RC);
BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
.addReg(PhysReg, RegState::Kill);
if (!LiveIn)
addLiveIn(PhysReg);
return VirtReg;
}
void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
getParent()->splice(NewAfter->getIterator(), getIterator());
}
void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
getParent()->splice(++NewBefore->getIterator(), getIterator());
}
void MachineBasicBlock::updateTerminator(
MachineBasicBlock *PreviousLayoutSuccessor) {
LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
<< "\n");
const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
// A block with no successors has no concerns with fall-through edges.
if (this->succ_empty())
return;
MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
SmallVector<MachineOperand, 4> Cond;
DebugLoc DL = findBranchDebugLoc();
bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
(void) B;
assert(!B && "UpdateTerminators requires analyzable predecessors!");
if (Cond.empty()) {
if (TBB) {
// The block has an unconditional branch. If its successor is now its
// layout successor, delete the branch.
if (isLayoutSuccessor(TBB))
TII->removeBranch(*this);
} else {
// The block has an unconditional fallthrough, or the end of the block is
// unreachable.
// Unfortunately, whether the end of the block is unreachable is not
// immediately obvious; we must fall back to checking the successor list,
// and assuming that if the passed in block is in the succesor list and
// not an EHPad, it must be the intended target.
if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
PreviousLayoutSuccessor->isEHPad())
return;
// If the unconditional successor block is not the current layout
// successor, insert a branch to jump to it.
if (!isLayoutSuccessor(PreviousLayoutSuccessor))
TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
}
return;
}
if (FBB) {
// The block has a non-fallthrough conditional branch. If one of its
// successors is its layout successor, rewrite it to a fallthrough
// conditional branch.
if (isLayoutSuccessor(TBB)) {
if (TII->reverseBranchCondition(Cond))
return;
TII->removeBranch(*this);
TII->insertBranch(*this, FBB, nullptr, Cond, DL);
} else if (isLayoutSuccessor(FBB)) {
TII->removeBranch(*this);
TII->insertBranch(*this, TBB, nullptr, Cond, DL);
}
return;
}
// We now know we're going to fallthrough to PreviousLayoutSuccessor.
assert(PreviousLayoutSuccessor);
assert(!PreviousLayoutSuccessor->isEHPad());
assert(isSuccessor(PreviousLayoutSuccessor));
if (PreviousLayoutSuccessor == TBB) {
// We had a fallthrough to the same basic block as the conditional jump
// targets. Remove the conditional jump, leaving an unconditional
// fallthrough or an unconditional jump.
TII->removeBranch(*this);
if (!isLayoutSuccessor(TBB)) {
Cond.clear();
TII->insertBranch(*this, TBB, nullptr, Cond, DL);
}
return;
}
// The block has a fallthrough conditional branch.
if (isLayoutSuccessor(TBB)) {
if (TII->reverseBranchCondition(Cond)) {
// We can't reverse the condition, add an unconditional branch.
Cond.clear();
TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
return;
}
TII->removeBranch(*this);
TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
} else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
TII->removeBranch(*this);
TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
}
}
void MachineBasicBlock::validateSuccProbs() const {
#ifndef NDEBUG
int64_t Sum = 0;
for (auto Prob : Probs)
Sum += Prob.getNumerator();
// Due to precision issue, we assume that the sum of probabilities is one if
// the difference between the sum of their numerators and the denominator is
// no greater than the number of successors.
assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
Probs.size() &&
"The sum of successors's probabilities exceeds one.");
#endif // NDEBUG
}
void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
BranchProbability Prob) {
// Probability list is either empty (if successor list isn't empty, this means
// disabled optimization) or has the same size as successor list.
if (!(Probs.empty() && !Successors.empty()))
Probs.push_back(Prob);
Successors.push_back(Succ);
Succ->addPredecessor(this);
}
void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
// We need to make sure probability list is either empty or has the same size
// of successor list. When this function is called, we can safely delete all
// probability in the list.
Probs.clear();
Successors.push_back(Succ);
Succ->addPredecessor(this);
}
void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
MachineBasicBlock *New,
bool NormalizeSuccProbs) {
succ_iterator OldI = llvm::find(successors(), Old);
assert(OldI != succ_end() && "Old is not a successor of this block!");
assert(!llvm::is_contained(successors(), New) &&
"New is already a successor of this block!");
// Add a new successor with equal probability as the original one. Note
// that we directly copy the probability using the iterator rather than
// getting a potentially synthetic probability computed when unknown. This
// preserves the probabilities as-is and then we can renormalize them and
// query them effectively afterward.
addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
: *getProbabilityIterator(OldI));
if (NormalizeSuccProbs)
normalizeSuccProbs();
}
void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
bool NormalizeSuccProbs) {
succ_iterator I = find(Successors, Succ);
removeSuccessor(I, NormalizeSuccProbs);
}
MachineBasicBlock::succ_iterator
MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
assert(I != Successors.end() && "Not a current successor!");
// If probability list is empty it means we don't use it (disabled
// optimization).
if (!Probs.empty()) {
probability_iterator WI = getProbabilityIterator(I);
Probs.erase(WI);
if (NormalizeSuccProbs)
normalizeSuccProbs();
}
(*I)->removePredecessor(this);
return Successors.erase(I);
}
void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
MachineBasicBlock *New) {
if (Old == New)
return;
succ_iterator E = succ_end();
succ_iterator NewI = E;
succ_iterator OldI = E;
for (succ_iterator I = succ_begin(); I != E; ++I) {
if (*I == Old) {
OldI = I;
if (NewI != E)
break;
}
if (*I == New) {
NewI = I;
if (OldI != E)
break;
}
}
assert(OldI != E && "Old is not a successor of this block");
// If New isn't already a successor, let it take Old's place.
if (NewI == E) {
Old->removePredecessor(this);
New->addPredecessor(this);
*OldI = New;
return;
}
// New is already a successor.
// Update its probability instead of adding a duplicate edge.
if (!Probs.empty()) {
auto ProbIter = getProbabilityIterator(NewI);
if (!ProbIter->isUnknown())
*ProbIter += *getProbabilityIterator(OldI);
}
removeSuccessor(OldI);
}
void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig,
succ_iterator I) {
if (!Orig->Probs.empty())
addSuccessor(*I, Orig->getSuccProbability(I));
else
addSuccessorWithoutProb(*I);
}
void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
Predecessors.push_back(Pred);
}
void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
pred_iterator I = find(Predecessors, Pred);
assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
Predecessors.erase(I);
}
void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
if (this == FromMBB)
return;
while (!FromMBB->succ_empty()) {
MachineBasicBlock *Succ = *FromMBB->succ_begin();
// If probability list is empty it means we don't use it (disabled
// optimization).
if (!FromMBB->Probs.empty()) {
auto Prob = *FromMBB->Probs.begin();
addSuccessor(Succ, Prob);
} else
addSuccessorWithoutProb(Succ);
FromMBB->removeSuccessor(Succ);
}
}
void
MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
if (this == FromMBB)
return;
while (!FromMBB->succ_empty()) {
MachineBasicBlock *Succ = *FromMBB->succ_begin();
if (!FromMBB->Probs.empty()) {
auto Prob = *FromMBB->Probs.begin();
addSuccessor(Succ, Prob);
} else
addSuccessorWithoutProb(Succ);
FromMBB->removeSuccessor(Succ);
// Fix up any PHI nodes in the successor.
Succ->replacePhiUsesWith(FromMBB, this);
}
normalizeSuccProbs();
}
bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
return is_contained(predecessors(), MBB);
}
bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
return is_contained(successors(), MBB);
}
bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
MachineFunction::const_iterator I(this);
return std::next(I) == MachineFunction::const_iterator(MBB);
}
MachineBasicBlock *MachineBasicBlock::getFallThrough() {
MachineFunction::iterator Fallthrough = getIterator();
++Fallthrough;
// If FallthroughBlock is off the end of the function, it can't fall through.
if (Fallthrough == getParent()->end())
return nullptr;
// If FallthroughBlock isn't a successor, no fallthrough is possible.
if (!isSuccessor(&*Fallthrough))
return nullptr;
// Analyze the branches, if any, at the end of the block.
MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
SmallVector<MachineOperand, 4> Cond;
const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
// If we couldn't analyze the branch, examine the last instruction.
// If the block doesn't end in a known control barrier, assume fallthrough
// is possible. The isPredicated check is needed because this code can be
// called during IfConversion, where an instruction which is normally a
// Barrier is predicated and thus no longer an actual control barrier.
return (empty() || !back().isBarrier() || TII->isPredicated(back()))
? &*Fallthrough
: nullptr;
}
// If there is no branch, control always falls through.
if (!TBB) return &*Fallthrough;
// If there is some explicit branch to the fallthrough block, it can obviously
// reach, even though the branch should get folded to fall through implicitly.
if (MachineFunction::iterator(TBB) == Fallthrough ||
MachineFunction::iterator(FBB) == Fallthrough)
return &*Fallthrough;
// If it's an unconditional branch to some block not the fall through, it
// doesn't fall through.
if (Cond.empty()) return nullptr;
// Otherwise, if it is conditional and has no explicit false block, it falls
// through.
return (FBB == nullptr) ? &*Fallthrough : nullptr;
}
bool MachineBasicBlock::canFallThrough() {
return getFallThrough() != nullptr;
}
MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
bool UpdateLiveIns,
LiveIntervals *LIS) {
MachineBasicBlock::iterator SplitPoint(&MI);
++SplitPoint;
if (SplitPoint == end()) {
// Don't bother with a new block.
return this;
}
MachineFunction *MF = getParent();
LivePhysRegs LiveRegs;
if (UpdateLiveIns) {
// Make sure we add any physregs we define in the block as liveins to the
// new block.
MachineBasicBlock::iterator Prev(&MI);
LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
LiveRegs.addLiveOuts(*this);
for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
LiveRegs.stepBackward(*I);
}
MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
MF->insert(++MachineFunction::iterator(this), SplitBB);
SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
SplitBB->transferSuccessorsAndUpdatePHIs(this);
addSuccessor(SplitBB);
if (UpdateLiveIns)