forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPPCAsmPrinter.cpp
2779 lines (2429 loc) · 106 KB
/
PPCAsmPrinter.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
//===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to PowerPC assembly language. This printer is
// the output mechanism used by `llc'.
//
// Documentation at http://developer.apple.com/documentation/DeveloperTools/
// Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/PPCInstPrinter.h"
#include "MCTargetDesc/PPCMCExpr.h"
#include "MCTargetDesc/PPCMCTargetDesc.h"
#include "MCTargetDesc/PPCPredicates.h"
#include "PPC.h"
#include "PPCInstrInfo.h"
#include "PPCMachineFunctionInfo.h"
#include "PPCSubtarget.h"
#include "PPCTargetMachine.h"
#include "PPCTargetStreamer.h"
#include "TargetInfo/PowerPCTargetInfo.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionXCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/MC/MCSymbolXCOFF.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <memory>
#include <new>
using namespace llvm;
using namespace llvm::XCOFF;
#define DEBUG_TYPE "asmprinter"
static cl::opt<bool> EnableSSPCanaryBitInTB(
"aix-ssp-tb-bit", cl::init(false),
cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden);
// Specialize DenseMapInfo to allow
// std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap.
// This specialization is needed here because that type is used as keys in the
// map representing TOC entries.
namespace llvm {
template <>
struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> {
using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>;
static inline TOCKey getEmptyKey() {
return {nullptr, MCSymbolRefExpr::VariantKind::VK_None};
}
static inline TOCKey getTombstoneKey() {
return {nullptr, MCSymbolRefExpr::VariantKind::VK_Invalid};
}
static unsigned getHashValue(const TOCKey &PairVal) {
return detail::combineHashValue(
DenseMapInfo<const MCSymbol *>::getHashValue(PairVal.first),
DenseMapInfo<int>::getHashValue(PairVal.second));
}
static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; }
};
} // end namespace llvm
namespace {
enum {
// GNU attribute tags for PowerPC ABI
Tag_GNU_Power_ABI_FP = 4,
Tag_GNU_Power_ABI_Vector = 8,
Tag_GNU_Power_ABI_Struct_Return = 12,
// GNU attribute values for PowerPC float ABI, as combination of two parts
Val_GNU_Power_ABI_NoFloat = 0b00,
Val_GNU_Power_ABI_HardFloat_DP = 0b01,
Val_GNU_Power_ABI_SoftFloat_DP = 0b10,
Val_GNU_Power_ABI_HardFloat_SP = 0b11,
Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100,
Val_GNU_Power_ABI_LDBL_64 = 0b1000,
Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100,
};
class PPCAsmPrinter : public AsmPrinter {
protected:
// For TLS on AIX, we need to be able to identify TOC entries of specific
// VariantKind so we can add the right relocations when we generate the
// entries. So each entry is represented by a pair of MCSymbol and
// VariantKind. For example, we need to be able to identify the following
// entry as a TLSGD entry so we can add the @m relocation:
// .tc .i[TC],i[TL]@m
// By default, VK_None is used for the VariantKind.
MapVector<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>,
MCSymbol *>
TOC;
const PPCSubtarget *Subtarget = nullptr;
StackMaps SM;
public:
explicit PPCAsmPrinter(TargetMachine &TM,
std::unique_ptr<MCStreamer> Streamer)
: AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym,
MCSymbolRefExpr::VariantKind Kind =
MCSymbolRefExpr::VariantKind::VK_None);
bool doInitialization(Module &M) override {
if (!TOC.empty())
TOC.clear();
return AsmPrinter::doInitialization(M);
}
void emitInstruction(const MachineInstr *MI) override;
/// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
/// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
/// The \p MI would be INLINEASM ONLY.
void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode, raw_ostream &O) override;
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode, raw_ostream &O) override;
void emitEndOfAsmFile(Module &M) override;
void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
bool runOnMachineFunction(MachineFunction &MF) override {
Subtarget = &MF.getSubtarget<PPCSubtarget>();
bool Changed = AsmPrinter::runOnMachineFunction(MF);
emitXRayTable();
return Changed;
}
};
/// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
class PPCLinuxAsmPrinter : public PPCAsmPrinter {
public:
explicit PPCLinuxAsmPrinter(TargetMachine &TM,
std::unique_ptr<MCStreamer> Streamer)
: PPCAsmPrinter(TM, std::move(Streamer)) {}
StringRef getPassName() const override {
return "Linux PPC Assembly Printer";
}
void emitGNUAttributes(Module &M);
void emitStartOfAsmFile(Module &M) override;
void emitEndOfAsmFile(Module &) override;
void emitFunctionEntryLabel() override;
void emitFunctionBodyStart() override;
void emitFunctionBodyEnd() override;
void emitInstruction(const MachineInstr *MI) override;
};
class PPCAIXAsmPrinter : public PPCAsmPrinter {
private:
/// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
/// linkage for them in AIX.
SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
/// A format indicator and unique trailing identifier to form part of the
/// sinit/sterm function names.
std::string FormatIndicatorAndUniqueModId;
// Record a list of GlobalAlias associated with a GlobalObject.
// This is used for AIX's extra-label-at-definition aliasing strategy.
DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>>
GOAliasMap;
uint16_t getNumberOfVRSaved();
void emitTracebackTable();
SmallVector<const GlobalVariable *, 8> TOCDataGlobalVars;
void emitGlobalVariableHelper(const GlobalVariable *);
public:
PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
: PPCAsmPrinter(TM, std::move(Streamer)) {
if (MAI->isLittleEndian())
report_fatal_error(
"cannot create AIX PPC Assembly Printer for a little-endian target");
}
StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
bool doInitialization(Module &M) override;
void emitXXStructorList(const DataLayout &DL, const Constant *List,
bool IsCtor) override;
void SetupMachineFunction(MachineFunction &MF) override;
void emitGlobalVariable(const GlobalVariable *GV) override;
void emitFunctionDescriptor() override;
void emitFunctionEntryLabel() override;
void emitFunctionBodyEnd() override;
void emitPGORefs();
void emitEndOfAsmFile(Module &) override;
void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
void emitInstruction(const MachineInstr *MI) override;
bool doFinalization(Module &M) override;
void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
};
} // end anonymous namespace
void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
raw_ostream &O) {
// Computing the address of a global symbol, not calling it.
const GlobalValue *GV = MO.getGlobal();
getSymbol(GV)->print(O, MAI);
printOffset(MO.getOffset(), O);
}
void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
raw_ostream &O) {
const DataLayout &DL = getDataLayout();
const MachineOperand &MO = MI->getOperand(OpNo);
switch (MO.getType()) {
case MachineOperand::MO_Register: {
// The MI is INLINEASM ONLY and UseVSXReg is always false.
const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
// Linux assembler (Others?) does not take register mnemonics.
// FIXME - What about special registers used in mfspr/mtspr?
O << PPCRegisterInfo::stripRegisterPrefix(RegName);
return;
}
case MachineOperand::MO_Immediate:
O << MO.getImm();
return;
case MachineOperand::MO_MachineBasicBlock:
MO.getMBB()->getSymbol()->print(O, MAI);
return;
case MachineOperand::MO_ConstantPoolIndex:
O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
<< MO.getIndex();
return;
case MachineOperand::MO_BlockAddress:
GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
return;
case MachineOperand::MO_GlobalAddress: {
PrintSymbolOperand(MO, O);
return;
}
default:
O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
return;
}
}
/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode, raw_ostream &O) {
// Does this asm operand have a single letter operand modifier?
if (ExtraCode && ExtraCode[0]) {
if (ExtraCode[1] != 0) return true; // Unknown modifier.
switch (ExtraCode[0]) {
default:
// See if this is a generic print operand
return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
case 'L': // Write second word of DImode reference.
// Verify that this operand has two consecutive registers.
if (!MI->getOperand(OpNo).isReg() ||
OpNo+1 == MI->getNumOperands() ||
!MI->getOperand(OpNo+1).isReg())
return true;
++OpNo; // Return the high-part.
break;
case 'I':
// Write 'i' if an integer constant, otherwise nothing. Used to print
// addi vs add, etc.
if (MI->getOperand(OpNo).isImm())
O << "i";
return false;
case 'x':
if(!MI->getOperand(OpNo).isReg())
return true;
// This operand uses VSX numbering.
// If the operand is a VMX register, convert it to a VSX register.
Register Reg = MI->getOperand(OpNo).getReg();
if (PPCInstrInfo::isVRRegister(Reg))
Reg = PPC::VSX32 + (Reg - PPC::V0);
else if (PPCInstrInfo::isVFRegister(Reg))
Reg = PPC::VSX32 + (Reg - PPC::VF0);
const char *RegName;
RegName = PPCInstPrinter::getRegisterName(Reg);
RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
O << RegName;
return false;
}
}
printOperand(MI, OpNo, O);
return false;
}
// At the moment, all inline asm memory operands are a single register.
// In any case, the output of this routine should always be just one
// assembler operand.
bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode,
raw_ostream &O) {
if (ExtraCode && ExtraCode[0]) {
if (ExtraCode[1] != 0) return true; // Unknown modifier.
switch (ExtraCode[0]) {
default: return true; // Unknown modifier.
case 'L': // A memory reference to the upper word of a double word op.
O << getDataLayout().getPointerSize() << "(";
printOperand(MI, OpNo, O);
O << ")";
return false;
case 'y': // A memory reference for an X-form instruction
O << "0, ";
printOperand(MI, OpNo, O);
return false;
case 'I':
// Write 'i' if an integer constant, otherwise nothing. Used to print
// addi vs add, etc.
if (MI->getOperand(OpNo).isImm())
O << "i";
return false;
case 'U': // Print 'u' for update form.
case 'X': // Print 'x' for indexed form.
// FIXME: Currently for PowerPC memory operands are always loaded
// into a register, so we never get an update or indexed form.
// This is bad even for offset forms, since even if we know we
// have a value in -16(r1), we will generate a load into r<n>
// and then load from 0(r<n>). Until that issue is fixed,
// tolerate 'U' and 'X' but don't output anything.
assert(MI->getOperand(OpNo).isReg());
return false;
}
}
assert(MI->getOperand(OpNo).isReg());
O << "0(";
printOperand(MI, OpNo, O);
O << ")";
return false;
}
/// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
/// exists for it. If not, create one. Then return a symbol that references
/// the TOC entry.
MCSymbol *
PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym,
MCSymbolRefExpr::VariantKind Kind) {
MCSymbol *&TOCEntry = TOC[{Sym, Kind}];
if (!TOCEntry)
TOCEntry = createTempSymbol("C");
return TOCEntry;
}
void PPCAsmPrinter::emitEndOfAsmFile(Module &M) {
emitStackMaps(SM);
}
void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
unsigned NumNOPBytes = MI.getOperand(1).getImm();
auto &Ctx = OutStreamer->getContext();
MCSymbol *MILabel = Ctx.createTempSymbol();
OutStreamer->emitLabel(MILabel);
SM.recordStackMap(*MILabel, MI);
assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
// Scan ahead to trim the shadow.
const MachineBasicBlock &MBB = *MI.getParent();
MachineBasicBlock::const_iterator MII(MI);
++MII;
while (NumNOPBytes > 0) {
if (MII == MBB.end() || MII->isCall() ||
MII->getOpcode() == PPC::DBG_VALUE ||
MII->getOpcode() == TargetOpcode::PATCHPOINT ||
MII->getOpcode() == TargetOpcode::STACKMAP)
break;
++MII;
NumNOPBytes -= 4;
}
// Emit nops.
for (unsigned i = 0; i < NumNOPBytes; i += 4)
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
}
// Lower a patchpoint of the form:
// [<def>], <id>, <numBytes>, <target>, <numArgs>
void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
auto &Ctx = OutStreamer->getContext();
MCSymbol *MILabel = Ctx.createTempSymbol();
OutStreamer->emitLabel(MILabel);
SM.recordPatchPoint(*MILabel, MI);
PatchPointOpers Opers(&MI);
unsigned EncodedBytes = 0;
const MachineOperand &CalleeMO = Opers.getCallTarget();
if (CalleeMO.isImm()) {
int64_t CallTarget = CalleeMO.getImm();
if (CallTarget) {
assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
"High 16 bits of call target should be zero.");
Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
EncodedBytes = 0;
// Materialize the jump address:
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
.addReg(ScratchReg)
.addImm((CallTarget >> 32) & 0xFFFF));
++EncodedBytes;
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
.addReg(ScratchReg)
.addReg(ScratchReg)
.addImm(32).addImm(16));
++EncodedBytes;
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
.addReg(ScratchReg)
.addReg(ScratchReg)
.addImm((CallTarget >> 16) & 0xFFFF));
++EncodedBytes;
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
.addReg(ScratchReg)
.addReg(ScratchReg)
.addImm(CallTarget & 0xFFFF));
// Save the current TOC pointer before the remote call.
int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
.addReg(PPC::X2)
.addImm(TOCSaveOffset)
.addReg(PPC::X1));
++EncodedBytes;
// If we're on ELFv1, then we need to load the actual function pointer
// from the function descriptor.
if (!Subtarget->isELFv2ABI()) {
// Load the new TOC pointer and the function address, but not r11
// (needing this is rare, and loading it here would prevent passing it
// via a 'nest' parameter.
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
.addReg(PPC::X2)
.addImm(8)
.addReg(ScratchReg));
++EncodedBytes;
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
.addReg(ScratchReg)
.addImm(0)
.addReg(ScratchReg));
++EncodedBytes;
}
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
.addReg(ScratchReg));
++EncodedBytes;
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
++EncodedBytes;
// Restore the TOC pointer after the call.
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
.addReg(PPC::X2)
.addImm(TOCSaveOffset)
.addReg(PPC::X1));
++EncodedBytes;
}
} else if (CalleeMO.isGlobal()) {
const GlobalValue *GValue = CalleeMO.getGlobal();
MCSymbol *MOSymbol = getSymbol(GValue);
const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
.addExpr(SymVar));
EncodedBytes += 2;
}
// Each instruction is 4 bytes.
EncodedBytes *= 4;
// Emit padding.
unsigned NumBytes = Opers.getNumPatchBytes();
assert(NumBytes >= EncodedBytes &&
"Patchpoint can't request size less than the length of a call.");
assert((NumBytes - EncodedBytes) % 4 == 0 &&
"Invalid number of NOP bytes requested!");
for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
}
/// This helper function creates the TlsGetAddr MCSymbol for AIX. We will
/// create the csect and use the qual-name symbol instead of creating just the
/// external symbol.
static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx) {
return Ctx
.getXCOFFSection(".__tls_get_addr", SectionKind::getText(),
XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER))
->getQualNameSymbol();
}
/// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
/// call to __tls_get_addr to the current output stream.
void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
MCSymbolRefExpr::VariantKind VK) {
MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
unsigned Opcode = PPC::BL8_NOP_TLS;
assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
Opcode = PPC::BL8_NOTOC_TLS;
}
const Module *M = MF->getFunction().getParent();
assert(MI->getOperand(0).isReg() &&
((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
(!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
"GETtls[ld]ADDR[32] must define GPR3");
assert(MI->getOperand(1).isReg() &&
((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
(!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
"GETtls[ld]ADDR[32] must read GPR3");
if (Subtarget->isAIXABI()) {
// On AIX, the variable offset should already be in R4 and the region handle
// should already be in R3.
// For TLSGD, which currently is the only supported access model, we only
// need to generate an absolute branch to .__tls_get_addr.
Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
(void)VarOffsetReg;
assert(MI->getOperand(2).isReg() &&
MI->getOperand(2).getReg() == VarOffsetReg &&
"GETtls[ld]ADDR[32] must read GPR4");
MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
const MCExpr *TlsRef = MCSymbolRefExpr::create(
TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef));
return;
}
MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr");
if (Subtarget->is32BitELFABI() && isPositionIndependent())
Kind = MCSymbolRefExpr::VK_PLT;
const MCExpr *TlsRef =
MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
// Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
M->getPICLevel() == PICLevel::BigPIC)
TlsRef = MCBinaryExpr::createAdd(
TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
const MachineOperand &MO = MI->getOperand(2);
const GlobalValue *GValue = MO.getGlobal();
MCSymbol *MOSymbol = getSymbol(GValue);
const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
EmitToStreamer(*OutStreamer,
MCInstBuilder(Subtarget->isPPC64() ? Opcode
: (unsigned)PPC::BL_TLS)
.addExpr(TlsRef)
.addExpr(SymVar));
}
/// Map a machine operand for a TOC pseudo-machine instruction to its
/// corresponding MCSymbol.
static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
AsmPrinter &AP) {
switch (MO.getType()) {
case MachineOperand::MO_GlobalAddress:
return AP.getSymbol(MO.getGlobal());
case MachineOperand::MO_ConstantPoolIndex:
return AP.GetCPISymbol(MO.getIndex());
case MachineOperand::MO_JumpTableIndex:
return AP.GetJTISymbol(MO.getIndex());
case MachineOperand::MO_BlockAddress:
return AP.GetBlockAddressSymbol(MO.getBlockAddress());
default:
llvm_unreachable("Unexpected operand type to get symbol.");
}
}
/// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
/// the current output stream.
///
void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
MCInst TmpInst;
const bool IsPPC64 = Subtarget->isPPC64();
const bool IsAIX = Subtarget->isAIXABI();
const Module *M = MF->getFunction().getParent();
PICLevel::Level PL = M->getPICLevel();
#ifndef NDEBUG
// Validate that SPE and FPU are mutually exclusive in codegen
if (!MI->isInlineAsm()) {
for (const MachineOperand &MO: MI->operands()) {
if (MO.isReg()) {
Register Reg = MO.getReg();
if (Subtarget->hasSPE()) {
if (PPC::F4RCRegClass.contains(Reg) ||
PPC::F8RCRegClass.contains(Reg) ||
PPC::VFRCRegClass.contains(Reg) ||
PPC::VRRCRegClass.contains(Reg) ||
PPC::VSFRCRegClass.contains(Reg) ||
PPC::VSSRCRegClass.contains(Reg)
)
llvm_unreachable("SPE targets cannot have FPRegs!");
} else {
if (PPC::SPERCRegClass.contains(Reg))
llvm_unreachable("SPE register found in FPU-targeted code!");
}
}
}
}
#endif
auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
ptrdiff_t OriginalOffset) {
// Apply an offset to the TOC-based expression such that the adjusted
// notional offset from the TOC base (to be encoded into the instruction's D
// or DS field) is the signed 16-bit truncation of the original notional
// offset from the TOC base.
// This is consistent with the treatment used both by XL C/C++ and
// by AIX ld -r.
ptrdiff_t Adjustment =
OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
return MCBinaryExpr::createAdd(
Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
};
auto getTOCEntryLoadingExprForXCOFF =
[IsPPC64, getTOCRelocAdjustedExprForXCOFF,
this](const MCSymbol *MOSymbol, const MCExpr *Expr,
MCSymbolRefExpr::VariantKind VK =
MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
const auto TOCEntryIter = TOC.find({MOSymbol, VK});
assert(TOCEntryIter != TOC.end() &&
"Could not find the TOC entry for this symbol.");
const ptrdiff_t EntryDistanceFromTOCBase =
(TOCEntryIter - TOC.begin()) * EntryByteSize;
constexpr int16_t PositiveTOCRange = INT16_MAX;
if (EntryDistanceFromTOCBase > PositiveTOCRange)
return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
return Expr;
};
auto GetVKForMO = [&](const MachineOperand &MO) {
// For GD TLS access on AIX, we have two TOC entries for the symbol (one for
// the variable offset and the other for the region handle). They are
// differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
if (MO.getTargetFlags() & PPCII::MO_TLSGDM_FLAG)
return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
if (MO.getTargetFlags() & PPCII::MO_TLSGD_FLAG)
return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
return MCSymbolRefExpr::VariantKind::VK_None;
};
// Lower multi-instruction pseudo operations.
switch (MI->getOpcode()) {
default: break;
case TargetOpcode::DBG_VALUE:
llvm_unreachable("Should be handled target independently");
case TargetOpcode::STACKMAP:
return LowerSTACKMAP(SM, *MI);
case TargetOpcode::PATCHPOINT:
return LowerPATCHPOINT(SM, *MI);
case PPC::MoveGOTtoLR: {
// Transform %lr = MoveGOTtoLR
// Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
// _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
// _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
// blrl
// This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
MCSymbol *GOTSymbol =
OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
const MCExpr *OffsExpr =
MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
MCSymbolRefExpr::VK_PPC_LOCAL,
OutContext),
MCConstantExpr::create(4, OutContext),
OutContext);
// Emit the 'bl'.
EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
return;
}
case PPC::MovePCtoLR:
case PPC::MovePCtoLR8: {
// Transform %lr = MovePCtoLR
// Into this, where the label is the PIC base:
// bl L1$pb
// L1$pb:
MCSymbol *PICBase = MF->getPICBaseSymbol();
// Emit the 'bl'.
EmitToStreamer(*OutStreamer,
MCInstBuilder(PPC::BL)
// FIXME: We would like an efficient form for this, so we
// don't have to do a lot of extra uniquing.
.addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
// Emit the label.
OutStreamer->emitLabel(PICBase);
return;
}
case PPC::UpdateGBR: {
// Transform %rd = UpdateGBR(%rt, %ri)
// Into: lwz %rt, .L0$poff - .L0$pb(%ri)
// add %rd, %rt, %ri
// or into (if secure plt mode is on):
// addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
// addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
// Get the offset from the GOT Base Register to the GOT
LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
unsigned PICR = TmpInst.getOperand(0).getReg();
MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
: ".LTOC");
const MCExpr *PB =
MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
EmitToStreamer(
*OutStreamer,
MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
EmitToStreamer(
*OutStreamer,
MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
return;
} else {
MCSymbol *PICOffset =
MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
TmpInst.setOpcode(PPC::LWZ);
const MCExpr *Exp =
MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
const MCExpr *PB =
MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
MCSymbolRefExpr::VK_None,
OutContext);
const MCOperand TR = TmpInst.getOperand(1);
const MCOperand PICR = TmpInst.getOperand(0);
// Step 1: lwz %rt, .L$poff - .L$pb(%ri)
TmpInst.getOperand(1) =
MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
TmpInst.getOperand(0) = TR;
TmpInst.getOperand(2) = PICR;
EmitToStreamer(*OutStreamer, TmpInst);
TmpInst.setOpcode(PPC::ADD4);
TmpInst.getOperand(0) = PICR;
TmpInst.getOperand(1) = TR;
TmpInst.getOperand(2) = PICR;
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
}
case PPC::LWZtoc: {
// Transform %rN = LWZtoc @op1, %r2
LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
// Change the opcode to LWZ.
TmpInst.setOpcode(PPC::LWZ);
const MachineOperand &MO = MI->getOperand(1);
assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
"Invalid operand for LWZtoc.");
// Map the operand to its corresponding MCSymbol.
const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
// Create a reference to the GOT entry for the symbol. The GOT entry will be
// synthesized later.
if (PL == PICLevel::SmallPIC && !IsAIX) {
const MCExpr *Exp =
MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
OutContext);
TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
// Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
// storage allocated in the TOC which contains the address of
// 'MOSymbol'. Said TOC entry will be synthesized later.
MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
const MCExpr *Exp =
MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
// AIX uses the label directly as the lwz displacement operand for
// references into the toc section. The displacement value will be generated
// relative to the toc-base.
if (IsAIX) {
assert(
TM.getCodeModel() == CodeModel::Small &&
"This pseudo should only be selected for 32-bit small code model.");
Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
// Print MO for better readability
if (isVerbose())
OutStreamer->GetCommentOS() << MO << '\n';
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
// Create an explicit subtract expression between the local symbol and
// '.LTOC' to manifest the toc-relative offset.
const MCExpr *PB = MCSymbolRefExpr::create(
OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case PPC::ADDItoc:
case PPC::ADDItoc8: {
assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
"PseudoOp only valid for small code model AIX");
// Transform %rN = ADDItoc/8 @op1, %r2.
LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
// Change the opcode to load address.
TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
const MachineOperand &MO = MI->getOperand(1);
assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
// Map the operand to its corresponding MCSymbol.
const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
const MCExpr *Exp =
MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_None, OutContext);
TmpInst.getOperand(1) = TmpInst.getOperand(2);
TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case PPC::LDtocJTI:
case PPC::LDtocCPT:
case PPC::LDtocBA:
case PPC::LDtoc: {
// Transform %x3 = LDtoc @min1, %x2
LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
// Change the opcode to LD.
TmpInst.setOpcode(PPC::LD);
const MachineOperand &MO = MI->getOperand(1);
assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
"Invalid operand!");
// Map the operand to its corresponding MCSymbol.
const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
// Map the machine operand to its corresponding MCSymbol, then map the
// global address operand to be a reference to the TOC entry we will
// synthesize later.
MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
MCSymbolRefExpr::VariantKind VKExpr =
IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
TmpInst.getOperand(1) = MCOperand::createExpr(
IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
// Print MO for better readability
if (isVerbose() && IsAIX)
OutStreamer->GetCommentOS() << MO << '\n';
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case PPC::ADDIStocHA: {
assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
"This pseudo should only be selected for 32-bit large code model on"
" AIX.");
// Transform %rd = ADDIStocHA %rA, @sym(%r2)
LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
// Change the opcode to ADDIS.
TmpInst.setOpcode(PPC::ADDIS);
const MachineOperand &MO = MI->getOperand(2);
assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
"Invalid operand for ADDIStocHA.");
// Map the machine operand to its corresponding MCSymbol.
MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
// Always use TOC on AIX. Map the global address operand to be a reference
// to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
// reference the storage allocated in the TOC which contains the address of
// 'MOSymbol'.
MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
MCSymbolRefExpr::VK_PPC_U,
OutContext);
TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case PPC::LWZtocL: {
assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
"This pseudo should only be selected for 32-bit large code model on"
" AIX.");
// Transform %rd = LWZtocL @sym, %rs.
LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
// Change the opcode to lwz.
TmpInst.setOpcode(PPC::LWZ);