LLVM 18.0.0git
PPCAsmPrinter.cpp
Go to the documentation of this file.
1//===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to PowerPC assembly language. This printer is
11// the output mechanism used by `llc'.
12//
13// Documentation at http://developer.apple.com/documentation/DeveloperTools/
14// Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
15//
16//===----------------------------------------------------------------------===//
17
22#include "PPC.h"
23#include "PPCInstrInfo.h"
25#include "PPCSubtarget.h"
26#include "PPCTargetMachine.h"
27#include "PPCTargetStreamer.h"
29#include "llvm/ADT/MapVector.h"
31#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/Twine.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/Module.h"
50#include "llvm/MC/MCAsmInfo.h"
51#include "llvm/MC/MCContext.h"
53#include "llvm/MC/MCExpr.h"
54#include "llvm/MC/MCInst.h"
58#include "llvm/MC/MCStreamer.h"
59#include "llvm/MC/MCSymbol.h"
60#include "llvm/MC/MCSymbolELF.h"
62#include "llvm/MC/SectionKind.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/Error.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <memory>
79#include <new>
80
81using namespace llvm;
82using namespace llvm::XCOFF;
83
84#define DEBUG_TYPE "asmprinter"
85
86STATISTIC(NumTOCEntries, "Number of Total TOC Entries Emitted.");
87STATISTIC(NumTOCConstPool, "Number of Constant Pool TOC Entries.");
88STATISTIC(NumTOCGlobalInternal,
89 "Number of Internal Linkage Global TOC Entries.");
90STATISTIC(NumTOCGlobalExternal,
91 "Number of External Linkage Global TOC Entries.");
92STATISTIC(NumTOCJumpTable, "Number of Jump Table TOC Entries.");
93STATISTIC(NumTOCThreadLocal, "Number of Thread Local TOC Entries.");
94STATISTIC(NumTOCBlockAddress, "Number of Block Address TOC Entries.");
95STATISTIC(NumTOCEHBlock, "Number of EH Block TOC Entries.");
96
98 "aix-ssp-tb-bit", cl::init(false),
99 cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden);
100
101// Specialize DenseMapInfo to allow
102// std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap.
103// This specialization is needed here because that type is used as keys in the
104// map representing TOC entries.
105namespace llvm {
106template <>
107struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> {
108 using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>;
109
110 static inline TOCKey getEmptyKey() {
112 }
113 static inline TOCKey getTombstoneKey() {
115 }
116 static unsigned getHashValue(const TOCKey &PairVal) {
119 DenseMapInfo<int>::getHashValue(PairVal.second));
120 }
121 static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; }
122};
123} // end namespace llvm
124
125namespace {
126
127enum {
128 // GNU attribute tags for PowerPC ABI
129 Tag_GNU_Power_ABI_FP = 4,
130 Tag_GNU_Power_ABI_Vector = 8,
131 Tag_GNU_Power_ABI_Struct_Return = 12,
132
133 // GNU attribute values for PowerPC float ABI, as combination of two parts
134 Val_GNU_Power_ABI_NoFloat = 0b00,
135 Val_GNU_Power_ABI_HardFloat_DP = 0b01,
136 Val_GNU_Power_ABI_SoftFloat_DP = 0b10,
137 Val_GNU_Power_ABI_HardFloat_SP = 0b11,
138
139 Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100,
140 Val_GNU_Power_ABI_LDBL_64 = 0b1000,
141 Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100,
142};
143
144class PPCAsmPrinter : public AsmPrinter {
145protected:
146 // For TLS on AIX, we need to be able to identify TOC entries of specific
147 // VariantKind so we can add the right relocations when we generate the
148 // entries. So each entry is represented by a pair of MCSymbol and
149 // VariantKind. For example, we need to be able to identify the following
150 // entry as a TLSGD entry so we can add the @m relocation:
151 // .tc .i[TC],i[TL]@m
152 // By default, VK_None is used for the VariantKind.
154 MCSymbol *>
155 TOC;
156 const PPCSubtarget *Subtarget = nullptr;
157
158public:
159 explicit PPCAsmPrinter(TargetMachine &TM,
160 std::unique_ptr<MCStreamer> Streamer)
161 : AsmPrinter(TM, std::move(Streamer)) {}
162
163 StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
164
165 enum TOCEntryType {
166 TOCType_ConstantPool,
167 TOCType_GlobalExternal,
168 TOCType_GlobalInternal,
169 TOCType_JumpTable,
170 TOCType_ThreadLocal,
171 TOCType_BlockAddress,
172 TOCType_EHBlock
173 };
174
175 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym, TOCEntryType Type,
177 MCSymbolRefExpr::VariantKind::VK_None);
178
179 bool doInitialization(Module &M) override {
180 if (!TOC.empty())
181 TOC.clear();
183 }
184
185 void emitInstruction(const MachineInstr *MI) override;
186
187 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
188 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
189 /// The \p MI would be INLINEASM ONLY.
190 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
191
192 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
193 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
194 const char *ExtraCode, raw_ostream &O) override;
195 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
196 const char *ExtraCode, raw_ostream &O) override;
197
198 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
199 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
200 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
201 void EmitAIXTlsCallHelper(const MachineInstr *MI);
202 bool runOnMachineFunction(MachineFunction &MF) override {
203 Subtarget = &MF.getSubtarget<PPCSubtarget>();
204 bool Changed = AsmPrinter::runOnMachineFunction(MF);
206 return Changed;
207 }
208};
209
210/// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
211class PPCLinuxAsmPrinter : public PPCAsmPrinter {
212public:
213 explicit PPCLinuxAsmPrinter(TargetMachine &TM,
214 std::unique_ptr<MCStreamer> Streamer)
215 : PPCAsmPrinter(TM, std::move(Streamer)) {}
216
217 StringRef getPassName() const override {
218 return "Linux PPC Assembly Printer";
219 }
220
221 void emitGNUAttributes(Module &M);
222
223 void emitStartOfAsmFile(Module &M) override;
224 void emitEndOfAsmFile(Module &) override;
225
226 void emitFunctionEntryLabel() override;
227
228 void emitFunctionBodyStart() override;
229 void emitFunctionBodyEnd() override;
230 void emitInstruction(const MachineInstr *MI) override;
231};
232
233class PPCAIXAsmPrinter : public PPCAsmPrinter {
234private:
235 /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
236 /// linkage for them in AIX.
237 SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
238
239 /// A format indicator and unique trailing identifier to form part of the
240 /// sinit/sterm function names.
241 std::string FormatIndicatorAndUniqueModId;
242
243 // Record a list of GlobalAlias associated with a GlobalObject.
244 // This is used for AIX's extra-label-at-definition aliasing strategy.
246 GOAliasMap;
247
248 uint16_t getNumberOfVRSaved();
249 void emitTracebackTable();
250
252
253 void emitGlobalVariableHelper(const GlobalVariable *);
254
255 // Get the offset of an alias based on its AliaseeObject.
256 uint64_t getAliasOffset(const Constant *C);
257
258public:
259 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
260 : PPCAsmPrinter(TM, std::move(Streamer)) {
261 if (MAI->isLittleEndian())
263 "cannot create AIX PPC Assembly Printer for a little-endian target");
264 }
265
266 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
267
268 bool doInitialization(Module &M) override;
269
270 void emitXXStructorList(const DataLayout &DL, const Constant *List,
271 bool IsCtor) override;
272
273 void SetupMachineFunction(MachineFunction &MF) override;
274
275 void emitGlobalVariable(const GlobalVariable *GV) override;
276
277 void emitFunctionDescriptor() override;
278
279 void emitFunctionEntryLabel() override;
280
281 void emitFunctionBodyEnd() override;
282
283 void emitPGORefs(Module &M);
284
285 void emitEndOfAsmFile(Module &) override;
286
287 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
288
289 void emitInstruction(const MachineInstr *MI) override;
290
291 bool doFinalization(Module &M) override;
292
293 void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
294
295 void emitModuleCommandLines(Module &M) override;
296};
297
298} // end anonymous namespace
299
300void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
301 raw_ostream &O) {
302 // Computing the address of a global symbol, not calling it.
303 const GlobalValue *GV = MO.getGlobal();
304 getSymbol(GV)->print(O, MAI);
305 printOffset(MO.getOffset(), O);
306}
307
308void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
309 raw_ostream &O) {
310 const DataLayout &DL = getDataLayout();
311 const MachineOperand &MO = MI->getOperand(OpNo);
312
313 switch (MO.getType()) {
315 // The MI is INLINEASM ONLY and UseVSXReg is always false.
317
318 // Linux assembler (Others?) does not take register mnemonics.
319 // FIXME - What about special registers used in mfspr/mtspr?
321 return;
322 }
324 O << MO.getImm();
325 return;
326
328 MO.getMBB()->getSymbol()->print(O, MAI);
329 return;
331 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
332 << MO.getIndex();
333 return;
335 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
336 return;
338 PrintSymbolOperand(MO, O);
339 return;
340 }
341
342 default:
343 O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
344 return;
345 }
346}
347
348/// PrintAsmOperand - Print out an operand for an inline asm expression.
349///
350bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
351 const char *ExtraCode, raw_ostream &O) {
352 // Does this asm operand have a single letter operand modifier?
353 if (ExtraCode && ExtraCode[0]) {
354 if (ExtraCode[1] != 0) return true; // Unknown modifier.
355
356 switch (ExtraCode[0]) {
357 default:
358 // See if this is a generic print operand
359 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
360 case 'L': // Write second word of DImode reference.
361 // Verify that this operand has two consecutive registers.
362 if (!MI->getOperand(OpNo).isReg() ||
363 OpNo+1 == MI->getNumOperands() ||
364 !MI->getOperand(OpNo+1).isReg())
365 return true;
366 ++OpNo; // Return the high-part.
367 break;
368 case 'I':
369 // Write 'i' if an integer constant, otherwise nothing. Used to print
370 // addi vs add, etc.
371 if (MI->getOperand(OpNo).isImm())
372 O << "i";
373 return false;
374 case 'x':
375 if(!MI->getOperand(OpNo).isReg())
376 return true;
377 // This operand uses VSX numbering.
378 // If the operand is a VMX register, convert it to a VSX register.
379 Register Reg = MI->getOperand(OpNo).getReg();
380 if (PPC::isVRRegister(Reg))
381 Reg = PPC::VSX32 + (Reg - PPC::V0);
382 else if (PPC::isVFRegister(Reg))
383 Reg = PPC::VSX32 + (Reg - PPC::VF0);
384 const char *RegName;
387 O << RegName;
388 return false;
389 }
390 }
391
392 printOperand(MI, OpNo, O);
393 return false;
394}
395
396// At the moment, all inline asm memory operands are a single register.
397// In any case, the output of this routine should always be just one
398// assembler operand.
399bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
400 const char *ExtraCode,
401 raw_ostream &O) {
402 if (ExtraCode && ExtraCode[0]) {
403 if (ExtraCode[1] != 0) return true; // Unknown modifier.
404
405 switch (ExtraCode[0]) {
406 default: return true; // Unknown modifier.
407 case 'L': // A memory reference to the upper word of a double word op.
408 O << getDataLayout().getPointerSize() << "(";
409 printOperand(MI, OpNo, O);
410 O << ")";
411 return false;
412 case 'y': // A memory reference for an X-form instruction
413 O << "0, ";
414 printOperand(MI, OpNo, O);
415 return false;
416 case 'I':
417 // Write 'i' if an integer constant, otherwise nothing. Used to print
418 // addi vs add, etc.
419 if (MI->getOperand(OpNo).isImm())
420 O << "i";
421 return false;
422 case 'U': // Print 'u' for update form.
423 case 'X': // Print 'x' for indexed form.
424 // FIXME: Currently for PowerPC memory operands are always loaded
425 // into a register, so we never get an update or indexed form.
426 // This is bad even for offset forms, since even if we know we
427 // have a value in -16(r1), we will generate a load into r<n>
428 // and then load from 0(r<n>). Until that issue is fixed,
429 // tolerate 'U' and 'X' but don't output anything.
430 assert(MI->getOperand(OpNo).isReg());
431 return false;
432 }
433 }
434
435 assert(MI->getOperand(OpNo).isReg());
436 O << "0(";
437 printOperand(MI, OpNo, O);
438 O << ")";
439 return false;
440}
441
442static void collectTOCStats(PPCAsmPrinter::TOCEntryType Type) {
443 ++NumTOCEntries;
444 switch (Type) {
445 case PPCAsmPrinter::TOCType_ConstantPool:
446 ++NumTOCConstPool;
447 break;
448 case PPCAsmPrinter::TOCType_GlobalInternal:
449 ++NumTOCGlobalInternal;
450 break;
451 case PPCAsmPrinter::TOCType_GlobalExternal:
452 ++NumTOCGlobalExternal;
453 break;
454 case PPCAsmPrinter::TOCType_JumpTable:
455 ++NumTOCJumpTable;
456 break;
457 case PPCAsmPrinter::TOCType_ThreadLocal:
458 ++NumTOCThreadLocal;
459 break;
460 case PPCAsmPrinter::TOCType_BlockAddress:
461 ++NumTOCBlockAddress;
462 break;
463 case PPCAsmPrinter::TOCType_EHBlock:
464 ++NumTOCEHBlock;
465 break;
466 }
467}
468
469/// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
470/// exists for it. If not, create one. Then return a symbol that references
471/// the TOC entry.
472MCSymbol *
473PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym, TOCEntryType Type,
475 // If this is a new TOC entry add statistics about it.
476 if (!TOC.contains({Sym, Kind}))
478
479 MCSymbol *&TOCEntry = TOC[{Sym, Kind}];
480 if (!TOCEntry)
481 TOCEntry = createTempSymbol("C");
482 return TOCEntry;
483}
484
485void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
486 unsigned NumNOPBytes = MI.getOperand(1).getImm();
487
488 auto &Ctx = OutStreamer->getContext();
489 MCSymbol *MILabel = Ctx.createTempSymbol();
490 OutStreamer->emitLabel(MILabel);
491
492 SM.recordStackMap(*MILabel, MI);
493 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
494
495 // Scan ahead to trim the shadow.
496 const MachineBasicBlock &MBB = *MI.getParent();
498 ++MII;
499 while (NumNOPBytes > 0) {
500 if (MII == MBB.end() || MII->isCall() ||
501 MII->getOpcode() == PPC::DBG_VALUE ||
502 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
503 MII->getOpcode() == TargetOpcode::STACKMAP)
504 break;
505 ++MII;
506 NumNOPBytes -= 4;
507 }
508
509 // Emit nops.
510 for (unsigned i = 0; i < NumNOPBytes; i += 4)
511 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
512}
513
514// Lower a patchpoint of the form:
515// [<def>], <id>, <numBytes>, <target>, <numArgs>
516void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
517 auto &Ctx = OutStreamer->getContext();
518 MCSymbol *MILabel = Ctx.createTempSymbol();
519 OutStreamer->emitLabel(MILabel);
520
521 SM.recordPatchPoint(*MILabel, MI);
522 PatchPointOpers Opers(&MI);
523
524 unsigned EncodedBytes = 0;
525 const MachineOperand &CalleeMO = Opers.getCallTarget();
526
527 if (CalleeMO.isImm()) {
528 int64_t CallTarget = CalleeMO.getImm();
529 if (CallTarget) {
530 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
531 "High 16 bits of call target should be zero.");
532 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
533 EncodedBytes = 0;
534 // Materialize the jump address:
535 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
536 .addReg(ScratchReg)
537 .addImm((CallTarget >> 32) & 0xFFFF));
538 ++EncodedBytes;
539 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
540 .addReg(ScratchReg)
541 .addReg(ScratchReg)
542 .addImm(32).addImm(16));
543 ++EncodedBytes;
544 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
545 .addReg(ScratchReg)
546 .addReg(ScratchReg)
547 .addImm((CallTarget >> 16) & 0xFFFF));
548 ++EncodedBytes;
549 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
550 .addReg(ScratchReg)
551 .addReg(ScratchReg)
552 .addImm(CallTarget & 0xFFFF));
553
554 // Save the current TOC pointer before the remote call.
555 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
556 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
557 .addReg(PPC::X2)
558 .addImm(TOCSaveOffset)
559 .addReg(PPC::X1));
560 ++EncodedBytes;
561
562 // If we're on ELFv1, then we need to load the actual function pointer
563 // from the function descriptor.
564 if (!Subtarget->isELFv2ABI()) {
565 // Load the new TOC pointer and the function address, but not r11
566 // (needing this is rare, and loading it here would prevent passing it
567 // via a 'nest' parameter.
568 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
569 .addReg(PPC::X2)
570 .addImm(8)
571 .addReg(ScratchReg));
572 ++EncodedBytes;
573 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
574 .addReg(ScratchReg)
575 .addImm(0)
576 .addReg(ScratchReg));
577 ++EncodedBytes;
578 }
579
580 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
581 .addReg(ScratchReg));
582 ++EncodedBytes;
583 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
584 ++EncodedBytes;
585
586 // Restore the TOC pointer after the call.
587 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
588 .addReg(PPC::X2)
589 .addImm(TOCSaveOffset)
590 .addReg(PPC::X1));
591 ++EncodedBytes;
592 }
593 } else if (CalleeMO.isGlobal()) {
594 const GlobalValue *GValue = CalleeMO.getGlobal();
595 MCSymbol *MOSymbol = getSymbol(GValue);
596 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
597
598 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
599 .addExpr(SymVar));
600 EncodedBytes += 2;
601 }
602
603 // Each instruction is 4 bytes.
604 EncodedBytes *= 4;
605
606 // Emit padding.
607 unsigned NumBytes = Opers.getNumPatchBytes();
608 assert(NumBytes >= EncodedBytes &&
609 "Patchpoint can't request size less than the length of a call.");
610 assert((NumBytes - EncodedBytes) % 4 == 0 &&
611 "Invalid number of NOP bytes requested!");
612 for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
613 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
614}
615
616/// This helper function creates the TlsGetAddr MCSymbol for AIX. We will
617/// create the csect and use the qual-name symbol instead of creating just the
618/// external symbol.
619static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx, unsigned MIOpc) {
620 StringRef SymName =
621 MIOpc == PPC::GETtlsTpointer32AIX ? ".__get_tpointer" : ".__tls_get_addr";
622 return Ctx
626}
627
628void PPCAsmPrinter::EmitAIXTlsCallHelper(const MachineInstr *MI) {
629 assert(Subtarget->isAIXABI() &&
630 "Only expecting to emit calls to get the thread pointer on AIX!");
631
632 MCSymbol *TlsCall = createMCSymbolForTlsGetAddr(OutContext, MI->getOpcode());
633 const MCExpr *TlsRef =
635 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef));
636}
637
638/// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
639/// call to __tls_get_addr to the current output stream.
640void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
643 unsigned Opcode = PPC::BL8_NOP_TLS;
644
645 assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
646 if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
647 MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
649 Opcode = PPC::BL8_NOTOC_TLS;
650 }
651 const Module *M = MF->getFunction().getParent();
652
653 assert(MI->getOperand(0).isReg() &&
654 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
655 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
656 "GETtls[ld]ADDR[32] must define GPR3");
657 assert(MI->getOperand(1).isReg() &&
658 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
659 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
660 "GETtls[ld]ADDR[32] must read GPR3");
661
662 if (Subtarget->isAIXABI()) {
663 // On AIX, the variable offset should already be in R4 and the region handle
664 // should already be in R3.
665 // For TLSGD, which currently is the only supported access model, we only
666 // need to generate an absolute branch to .__tls_get_addr.
667 Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
668 (void)VarOffsetReg;
669 assert(MI->getOperand(2).isReg() &&
670 MI->getOperand(2).getReg() == VarOffsetReg &&
671 "GETtls[ld]ADDR[32] must read GPR4");
672 EmitAIXTlsCallHelper(MI);
673 return;
674 }
675
676 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr");
677
678 if (Subtarget->is32BitELFABI() && isPositionIndependent())
680
681 const MCExpr *TlsRef =
682 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
683
684 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
685 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
686 M->getPICLevel() == PICLevel::BigPIC)
688 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
689 const MachineOperand &MO = MI->getOperand(2);
690 const GlobalValue *GValue = MO.getGlobal();
691 MCSymbol *MOSymbol = getSymbol(GValue);
692 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
693 EmitToStreamer(*OutStreamer,
694 MCInstBuilder(Subtarget->isPPC64() ? Opcode
695 : (unsigned)PPC::BL_TLS)
696 .addExpr(TlsRef)
697 .addExpr(SymVar));
698}
699
700/// Map a machine operand for a TOC pseudo-machine instruction to its
701/// corresponding MCSymbol.
703 AsmPrinter &AP) {
704 switch (MO.getType()) {
706 return AP.getSymbol(MO.getGlobal());
708 return AP.GetCPISymbol(MO.getIndex());
710 return AP.GetJTISymbol(MO.getIndex());
713 default:
714 llvm_unreachable("Unexpected operand type to get symbol.");
715 }
716}
717
718static bool hasTLSFlag(const MachineOperand &MO) {
719 unsigned Flags = MO.getTargetFlags();
720 if (Flags & PPCII::MO_TLSGD_FLAG || Flags & PPCII::MO_TPREL_FLAG ||
722 return true;
723
724 if (Flags == PPCII::MO_TPREL_LO || Flags == PPCII::MO_TPREL_HA ||
725 Flags == PPCII::MO_DTPREL_LO || Flags == PPCII::MO_TLSLD_LO ||
726 Flags == PPCII::MO_TLS)
727 return true;
728
729 return false;
730}
731
732static PPCAsmPrinter::TOCEntryType
734 // Use the target flags to determine if this MO is Thread Local.
735 // If we don't do this it comes out as Global.
736 if (hasTLSFlag(MO))
737 return PPCAsmPrinter::TOCType_ThreadLocal;
738
739 switch (MO.getType()) {
741 const GlobalValue *GlobalV = MO.getGlobal();
742 GlobalValue::LinkageTypes Linkage = GlobalV->getLinkage();
743 if (Linkage == GlobalValue::ExternalLinkage ||
746 return PPCAsmPrinter::TOCType_GlobalExternal;
747
748 return PPCAsmPrinter::TOCType_GlobalInternal;
749 }
751 return PPCAsmPrinter::TOCType_ConstantPool;
753 return PPCAsmPrinter::TOCType_JumpTable;
755 return PPCAsmPrinter::TOCType_BlockAddress;
756 default:
757 llvm_unreachable("Unexpected operand type to get TOC type.");
758 }
759}
760/// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
761/// the current output stream.
762///
763void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
764 PPC_MC::verifyInstructionPredicates(MI->getOpcode(),
765 getSubtargetInfo().getFeatureBits());
766
767 MCInst TmpInst;
768 const bool IsPPC64 = Subtarget->isPPC64();
769 const bool IsAIX = Subtarget->isAIXABI();
770 const Module *M = MF->getFunction().getParent();
771 PICLevel::Level PL = M->getPICLevel();
772
773#ifndef NDEBUG
774 // Validate that SPE and FPU are mutually exclusive in codegen
775 if (!MI->isInlineAsm()) {
776 for (const MachineOperand &MO: MI->operands()) {
777 if (MO.isReg()) {
778 Register Reg = MO.getReg();
779 if (Subtarget->hasSPE()) {
780 if (PPC::F4RCRegClass.contains(Reg) ||
781 PPC::F8RCRegClass.contains(Reg) ||
782 PPC::VFRCRegClass.contains(Reg) ||
783 PPC::VRRCRegClass.contains(Reg) ||
784 PPC::VSFRCRegClass.contains(Reg) ||
785 PPC::VSSRCRegClass.contains(Reg)
786 )
787 llvm_unreachable("SPE targets cannot have FPRegs!");
788 } else {
789 if (PPC::SPERCRegClass.contains(Reg))
790 llvm_unreachable("SPE register found in FPU-targeted code!");
791 }
792 }
793 }
794 }
795#endif
796
797 auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
798 ptrdiff_t OriginalOffset) {
799 // Apply an offset to the TOC-based expression such that the adjusted
800 // notional offset from the TOC base (to be encoded into the instruction's D
801 // or DS field) is the signed 16-bit truncation of the original notional
802 // offset from the TOC base.
803 // This is consistent with the treatment used both by XL C/C++ and
804 // by AIX ld -r.
805 ptrdiff_t Adjustment =
806 OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
808 Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
809 };
810
811 auto getTOCEntryLoadingExprForXCOFF =
812 [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
813 this](const MCSymbol *MOSymbol, const MCExpr *Expr,
815 MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
816 const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
817 const auto TOCEntryIter = TOC.find({MOSymbol, VK});
818 assert(TOCEntryIter != TOC.end() &&
819 "Could not find the TOC entry for this symbol.");
820 const ptrdiff_t EntryDistanceFromTOCBase =
821 (TOCEntryIter - TOC.begin()) * EntryByteSize;
822 constexpr int16_t PositiveTOCRange = INT16_MAX;
823
824 if (EntryDistanceFromTOCBase > PositiveTOCRange)
825 return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
826
827 return Expr;
828 };
829 auto GetVKForMO = [&](const MachineOperand &MO) {
830 // For TLS initial-exec and local-exec accesses on AIX, we have one TOC
831 // entry for the symbol (with the variable offset), which is differentiated
832 // by MO_TPREL_FLAG.
834 assert(MO.isGlobal() && "Only expecting a global MachineOperand here!\n");
835 TLSModel::Model Model = TM.getTLSModel(MO.getGlobal());
836 if (Model == TLSModel::LocalExec)
837 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLE;
838 if (Model == TLSModel::InitialExec)
839 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSIE;
840 llvm_unreachable("Only expecting local-exec or initial-exec accesses!");
841 }
842 // For GD TLS access on AIX, we have two TOC entries for the symbol (one for
843 // the variable offset and the other for the region handle). They are
844 // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
846 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
848 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
849 return MCSymbolRefExpr::VariantKind::VK_None;
850 };
851
852 // Lower multi-instruction pseudo operations.
853 switch (MI->getOpcode()) {
854 default: break;
855 case TargetOpcode::DBG_VALUE:
856 llvm_unreachable("Should be handled target independently");
857 case TargetOpcode::STACKMAP:
858 return LowerSTACKMAP(SM, *MI);
859 case TargetOpcode::PATCHPOINT:
860 return LowerPATCHPOINT(SM, *MI);
861
862 case PPC::MoveGOTtoLR: {
863 // Transform %lr = MoveGOTtoLR
864 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
865 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
866 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
867 // blrl
868 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
869 MCSymbol *GOTSymbol =
870 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
871 const MCExpr *OffsExpr =
874 OutContext),
875 MCConstantExpr::create(4, OutContext),
876 OutContext);
877
878 // Emit the 'bl'.
879 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
880 return;
881 }
882 case PPC::MovePCtoLR:
883 case PPC::MovePCtoLR8: {
884 // Transform %lr = MovePCtoLR
885 // Into this, where the label is the PIC base:
886 // bl L1$pb
887 // L1$pb:
888 MCSymbol *PICBase = MF->getPICBaseSymbol();
889
890 // Emit the 'bl'.
891 EmitToStreamer(*OutStreamer,
892 MCInstBuilder(PPC::BL)
893 // FIXME: We would like an efficient form for this, so we
894 // don't have to do a lot of extra uniquing.
895 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
896
897 // Emit the label.
898 OutStreamer->emitLabel(PICBase);
899 return;
900 }
901 case PPC::UpdateGBR: {
902 // Transform %rd = UpdateGBR(%rt, %ri)
903 // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
904 // add %rd, %rt, %ri
905 // or into (if secure plt mode is on):
906 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
907 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
908 // Get the offset from the GOT Base Register to the GOT
909 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
910 if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
911 unsigned PICR = TmpInst.getOperand(0).getReg();
912 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
913 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
914 : ".LTOC");
915 const MCExpr *PB =
916 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
917
918 const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
919 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
920
921 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
922 EmitToStreamer(
923 *OutStreamer,
924 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
925
926 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
927 EmitToStreamer(
928 *OutStreamer,
929 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
930 return;
931 } else {
932 MCSymbol *PICOffset =
933 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
934 TmpInst.setOpcode(PPC::LWZ);
935 const MCExpr *Exp =
937 const MCExpr *PB =
938 MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
940 OutContext);
941 const MCOperand TR = TmpInst.getOperand(1);
942 const MCOperand PICR = TmpInst.getOperand(0);
943
944 // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
945 TmpInst.getOperand(1) =
947 TmpInst.getOperand(0) = TR;
948 TmpInst.getOperand(2) = PICR;
949 EmitToStreamer(*OutStreamer, TmpInst);
950
951 TmpInst.setOpcode(PPC::ADD4);
952 TmpInst.getOperand(0) = PICR;
953 TmpInst.getOperand(1) = TR;
954 TmpInst.getOperand(2) = PICR;
955 EmitToStreamer(*OutStreamer, TmpInst);
956 return;
957 }
958 }
959 case PPC::LWZtoc: {
960 // Transform %rN = LWZtoc @op1, %r2
961 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
962
963 // Change the opcode to LWZ.
964 TmpInst.setOpcode(PPC::LWZ);
965
966 const MachineOperand &MO = MI->getOperand(1);
967 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
968 "Invalid operand for LWZtoc.");
969
970 // Map the operand to its corresponding MCSymbol.
971 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
972
973 // Create a reference to the GOT entry for the symbol. The GOT entry will be
974 // synthesized later.
975 if (PL == PICLevel::SmallPIC && !IsAIX) {
976 const MCExpr *Exp =
978 OutContext);
979 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
980 EmitToStreamer(*OutStreamer, TmpInst);
981 return;
982 }
983
984 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
985
986 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
987 // storage allocated in the TOC which contains the address of
988 // 'MOSymbol'. Said TOC entry will be synthesized later.
989 MCSymbol *TOCEntry =
990 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
991 const MCExpr *Exp =
993
994 // AIX uses the label directly as the lwz displacement operand for
995 // references into the toc section. The displacement value will be generated
996 // relative to the toc-base.
997 if (IsAIX) {
998 assert(
999 TM.getCodeModel() == CodeModel::Small &&
1000 "This pseudo should only be selected for 32-bit small code model.");
1001 Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
1002 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1003
1004 // Print MO for better readability
1005 if (isVerbose())
1006 OutStreamer->getCommentOS() << MO << '\n';
1007 EmitToStreamer(*OutStreamer, TmpInst);
1008 return;
1009 }
1010
1011 // Create an explicit subtract expression between the local symbol and
1012 // '.LTOC' to manifest the toc-relative offset.
1014 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
1015 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
1016 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1017 EmitToStreamer(*OutStreamer, TmpInst);
1018 return;
1019 }
1020 case PPC::ADDItoc:
1021 case PPC::ADDItoc8: {
1022 assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
1023 "PseudoOp only valid for small code model AIX");
1024
1025 // Transform %rN = ADDItoc/8 @op1, %r2.
1026 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1027
1028 // Change the opcode to load address.
1029 TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
1030
1031 const MachineOperand &MO = MI->getOperand(1);
1032 assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
1033
1034 // Map the operand to its corresponding MCSymbol.
1035 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1036
1037 const MCExpr *Exp =
1039
1040 TmpInst.getOperand(1) = TmpInst.getOperand(2);
1041 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1042 EmitToStreamer(*OutStreamer, TmpInst);
1043 return;
1044 }
1045 case PPC::LDtocJTI:
1046 case PPC::LDtocCPT:
1047 case PPC::LDtocBA:
1048 case PPC::LDtoc: {
1049 // Transform %x3 = LDtoc @min1, %x2
1050 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1051
1052 // Change the opcode to LD.
1053 TmpInst.setOpcode(PPC::LD);
1054
1055 const MachineOperand &MO = MI->getOperand(1);
1056 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1057 "Invalid operand!");
1058
1059 // Map the operand to its corresponding MCSymbol.
1060 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1061
1062 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1063
1064 // Map the machine operand to its corresponding MCSymbol, then map the
1065 // global address operand to be a reference to the TOC entry we will
1066 // synthesize later.
1067 MCSymbol *TOCEntry =
1068 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1069
1072 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
1073 TmpInst.getOperand(1) = MCOperand::createExpr(
1074 IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
1075
1076 // Print MO for better readability
1077 if (isVerbose() && IsAIX)
1078 OutStreamer->getCommentOS() << MO << '\n';
1079 EmitToStreamer(*OutStreamer, TmpInst);
1080 return;
1081 }
1082 case PPC::ADDIStocHA: {
1083 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
1084 "This pseudo should only be selected for 32-bit large code model on"
1085 " AIX.");
1086
1087 // Transform %rd = ADDIStocHA %rA, @sym(%r2)
1088 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1089
1090 // Change the opcode to ADDIS.
1091 TmpInst.setOpcode(PPC::ADDIS);
1092
1093 const MachineOperand &MO = MI->getOperand(2);
1094 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1095 "Invalid operand for ADDIStocHA.");
1096
1097 // Map the machine operand to its corresponding MCSymbol.
1098 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1099
1100 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1101
1102 // Always use TOC on AIX. Map the global address operand to be a reference
1103 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1104 // reference the storage allocated in the TOC which contains the address of
1105 // 'MOSymbol'.
1106 MCSymbol *TOCEntry =
1107 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1108 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1110 OutContext);
1111 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1112 EmitToStreamer(*OutStreamer, TmpInst);
1113 return;
1114 }
1115 case PPC::LWZtocL: {
1116 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
1117 "This pseudo should only be selected for 32-bit large code model on"
1118 " AIX.");
1119
1120 // Transform %rd = LWZtocL @sym, %rs.
1121 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1122
1123 // Change the opcode to lwz.
1124 TmpInst.setOpcode(PPC::LWZ);
1125
1126 const MachineOperand &MO = MI->getOperand(1);
1127 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1128 "Invalid operand for LWZtocL.");
1129
1130 // Map the machine operand to its corresponding MCSymbol.
1131 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1132
1133 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1134
1135 // Always use TOC on AIX. Map the global address operand to be a reference
1136 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1137 // reference the storage allocated in the TOC which contains the address of
1138 // 'MOSymbol'.
1139 MCSymbol *TOCEntry =
1140 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1141 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1143 OutContext);
1144 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1145 EmitToStreamer(*OutStreamer, TmpInst);
1146 return;
1147 }
1148 case PPC::ADDIStocHA8: {
1149 // Transform %xd = ADDIStocHA8 %x2, @sym
1150 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1151
1152 // Change the opcode to ADDIS8. If the global address is the address of
1153 // an external symbol, is a jump table address, is a block address, or is a
1154 // constant pool index with large code model enabled, then generate a TOC
1155 // entry and reference that. Otherwise, reference the symbol directly.
1156 TmpInst.setOpcode(PPC::ADDIS8);
1157
1158 const MachineOperand &MO = MI->getOperand(2);
1159 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1160 "Invalid operand for ADDIStocHA8!");
1161
1162 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1163
1164 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1165
1166 const bool GlobalToc =
1167 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
1168 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
1169 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
1170 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1171
1173
1174 const MCExpr *Exp =
1175 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1176
1177 if (!MO.isJTI() && MO.getOffset())
1180 OutContext),
1181 OutContext);
1182
1183 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1184 EmitToStreamer(*OutStreamer, TmpInst);
1185 return;
1186 }
1187 case PPC::LDtocL: {
1188 // Transform %xd = LDtocL @sym, %xs
1189 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1190
1191 // Change the opcode to LD. If the global address is the address of
1192 // an external symbol, is a jump table address, is a block address, or is
1193 // a constant pool index with large code model enabled, then generate a
1194 // TOC entry and reference that. Otherwise, reference the symbol directly.
1195 TmpInst.setOpcode(PPC::LD);
1196
1197 const MachineOperand &MO = MI->getOperand(1);
1198 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
1199 MO.isBlockAddress()) &&
1200 "Invalid operand for LDtocL!");
1201
1203 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1204 "LDtocL used on symbol that could be accessed directly is "
1205 "invalid. Must match ADDIStocHA8."));
1206
1207 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1208
1209 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1210
1211 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
1212 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1213
1215 const MCExpr *Exp =
1216 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1217 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1218 EmitToStreamer(*OutStreamer, TmpInst);
1219 return;
1220 }
1221 case PPC::ADDItocL: {
1222 // Transform %xd = ADDItocL %xs, @sym
1223 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1224
1225 // Change the opcode to ADDI8. If the global address is external, then
1226 // generate a TOC entry and reference that. Otherwise, reference the
1227 // symbol directly.
1228 TmpInst.setOpcode(PPC::ADDI8);
1229
1230 const MachineOperand &MO = MI->getOperand(2);
1231 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
1232
1234 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1235 "Interposable definitions must use indirect access."));
1236
1237 const MCExpr *Exp =
1239 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
1240 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1241 EmitToStreamer(*OutStreamer, TmpInst);
1242 return;
1243 }
1244 case PPC::ADDISgotTprelHA: {
1245 // Transform: %xd = ADDISgotTprelHA %x2, @sym
1246 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1247 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1248 const MachineOperand &MO = MI->getOperand(2);
1249 const GlobalValue *GValue = MO.getGlobal();
1250 MCSymbol *MOSymbol = getSymbol(GValue);
1251 const MCExpr *SymGotTprel =
1253 OutContext);
1254 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1255 .addReg(MI->getOperand(0).getReg())
1256 .addReg(MI->getOperand(1).getReg())
1257 .addExpr(SymGotTprel));
1258 return;
1259 }
1260 case PPC::LDgotTprelL:
1261 case PPC::LDgotTprelL32: {
1262 // Transform %xd = LDgotTprelL @sym, %xs
1263 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1264
1265 // Change the opcode to LD.
1266 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
1267 const MachineOperand &MO = MI->getOperand(1);
1268 const GlobalValue *GValue = MO.getGlobal();
1269 MCSymbol *MOSymbol = getSymbol(GValue);
1271 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
1273 OutContext);
1274 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1275 EmitToStreamer(*OutStreamer, TmpInst);
1276 return;
1277 }
1278
1279 case PPC::PPC32PICGOT: {
1280 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1281 MCSymbol *GOTRef = OutContext.createTempSymbol();
1282 MCSymbol *NextInstr = OutContext.createTempSymbol();
1283
1284 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1285 // FIXME: We would like an efficient form for this, so we don't have to do
1286 // a lot of extra uniquing.
1287 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1288 const MCExpr *OffsExpr =
1289 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1290 MCSymbolRefExpr::create(GOTRef, OutContext),
1291 OutContext);
1292 OutStreamer->emitLabel(GOTRef);
1293 OutStreamer->emitValue(OffsExpr, 4);
1294 OutStreamer->emitLabel(NextInstr);
1295 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1296 .addReg(MI->getOperand(0).getReg()));
1297 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1298 .addReg(MI->getOperand(1).getReg())
1299 .addImm(0)
1300 .addReg(MI->getOperand(0).getReg()));
1301 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1302 .addReg(MI->getOperand(0).getReg())
1303 .addReg(MI->getOperand(1).getReg())
1304 .addReg(MI->getOperand(0).getReg()));
1305 return;
1306 }
1307 case PPC::PPC32GOT: {
1308 MCSymbol *GOTSymbol =
1309 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1310 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1311 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1312 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1313 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1314 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1315 .addReg(MI->getOperand(0).getReg())
1316 .addExpr(SymGotTlsL));
1317 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1318 .addReg(MI->getOperand(0).getReg())
1319 .addReg(MI->getOperand(0).getReg())
1320 .addExpr(SymGotTlsHA));
1321 return;
1322 }
1323 case PPC::ADDIStlsgdHA: {
1324 // Transform: %xd = ADDIStlsgdHA %x2, @sym
1325 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1326 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1327 const MachineOperand &MO = MI->getOperand(2);
1328 const GlobalValue *GValue = MO.getGlobal();
1329 MCSymbol *MOSymbol = getSymbol(GValue);
1330 const MCExpr *SymGotTlsGD =
1332 OutContext);
1333 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1334 .addReg(MI->getOperand(0).getReg())
1335 .addReg(MI->getOperand(1).getReg())
1336 .addExpr(SymGotTlsGD));
1337 return;
1338 }
1339 case PPC::ADDItlsgdL:
1340 // Transform: %xd = ADDItlsgdL %xs, @sym
1341 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l
1342 case PPC::ADDItlsgdL32: {
1343 // Transform: %rd = ADDItlsgdL32 %rs, @sym
1344 // Into: %rd = ADDI %rs, sym@got@tlsgd
1345 const MachineOperand &MO = MI->getOperand(2);
1346 const GlobalValue *GValue = MO.getGlobal();
1347 MCSymbol *MOSymbol = getSymbol(GValue);
1348 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1349 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1351 OutContext);
1352 EmitToStreamer(*OutStreamer,
1353 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1354 .addReg(MI->getOperand(0).getReg())
1355 .addReg(MI->getOperand(1).getReg())
1356 .addExpr(SymGotTlsGD));
1357 return;
1358 }
1359 case PPC::GETtlsADDR:
1360 // Transform: %x3 = GETtlsADDR %x3, @sym
1361 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1362 case PPC::GETtlsADDRPCREL:
1363 case PPC::GETtlsADDR32AIX:
1364 case PPC::GETtlsADDR64AIX:
1365 // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64).
1366 // Into: BLA .__tls_get_addr()
1367 // Unlike on Linux, there is no symbol or relocation needed for this call.
1368 case PPC::GETtlsADDR32: {
1369 // Transform: %r3 = GETtlsADDR32 %r3, @sym
1370 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1371 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1372 return;
1373 }
1374 case PPC::GETtlsTpointer32AIX: {
1375 // Transform: %r3 = GETtlsTpointer32AIX
1376 // Into: BLA .__get_tpointer()
1377 EmitAIXTlsCallHelper(MI);
1378 return;
1379 }
1380 case PPC::ADDIStlsldHA: {
1381 // Transform: %xd = ADDIStlsldHA %x2, @sym
1382 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha
1383 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1384 const MachineOperand &MO = MI->getOperand(2);
1385 const GlobalValue *GValue = MO.getGlobal();
1386 MCSymbol *MOSymbol = getSymbol(GValue);
1387 const MCExpr *SymGotTlsLD =
1389 OutContext);
1390 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1391 .addReg(MI->getOperand(0).getReg())
1392 .addReg(MI->getOperand(1).getReg())
1393 .addExpr(SymGotTlsLD));
1394 return;
1395 }
1396 case PPC::ADDItlsldL:
1397 // Transform: %xd = ADDItlsldL %xs, @sym
1398 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l
1399 case PPC::ADDItlsldL32: {
1400 // Transform: %rd = ADDItlsldL32 %rs, @sym
1401 // Into: %rd = ADDI %rs, sym@got@tlsld
1402 const MachineOperand &MO = MI->getOperand(2);
1403 const GlobalValue *GValue = MO.getGlobal();
1404 MCSymbol *MOSymbol = getSymbol(GValue);
1405 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1406 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1408 OutContext);
1409 EmitToStreamer(*OutStreamer,
1410 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1411 .addReg(MI->getOperand(0).getReg())
1412 .addReg(MI->getOperand(1).getReg())
1413 .addExpr(SymGotTlsLD));
1414 return;
1415 }
1416 case PPC::GETtlsldADDR:
1417 // Transform: %x3 = GETtlsldADDR %x3, @sym
1418 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1419 case PPC::GETtlsldADDRPCREL:
1420 case PPC::GETtlsldADDR32: {
1421 // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1422 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1423 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1424 return;
1425 }
1426 case PPC::ADDISdtprelHA:
1427 // Transform: %xd = ADDISdtprelHA %xs, @sym
1428 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha
1429 case PPC::ADDISdtprelHA32: {
1430 // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1431 // Into: %rd = ADDIS %rs, sym@dtprel@ha
1432 const MachineOperand &MO = MI->getOperand(2);
1433 const GlobalValue *GValue = MO.getGlobal();
1434 MCSymbol *MOSymbol = getSymbol(GValue);
1435 const MCExpr *SymDtprel =
1437 OutContext);
1438 EmitToStreamer(
1439 *OutStreamer,
1440 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1441 .addReg(MI->getOperand(0).getReg())
1442 .addReg(MI->getOperand(1).getReg())
1443 .addExpr(SymDtprel));
1444 return;
1445 }
1446 case PPC::PADDIdtprel: {
1447 // Transform: %rd = PADDIdtprel %rs, @sym
1448 // Into: %rd = PADDI8 %rs, sym@dtprel
1449 const MachineOperand &MO = MI->getOperand(2);
1450 const GlobalValue *GValue = MO.getGlobal();
1451 MCSymbol *MOSymbol = getSymbol(GValue);
1452 const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1453 MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1454 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1455 .addReg(MI->getOperand(0).getReg())
1456 .addReg(MI->getOperand(1).getReg())
1457 .addExpr(SymDtprel));
1458 return;
1459 }
1460
1461 case PPC::ADDIdtprelL:
1462 // Transform: %xd = ADDIdtprelL %xs, @sym
1463 // Into: %xd = ADDI8 %xs, sym@dtprel@l
1464 case PPC::ADDIdtprelL32: {
1465 // Transform: %rd = ADDIdtprelL32 %rs, @sym
1466 // Into: %rd = ADDI %rs, sym@dtprel@l
1467 const MachineOperand &MO = MI->getOperand(2);
1468 const GlobalValue *GValue = MO.getGlobal();
1469 MCSymbol *MOSymbol = getSymbol(GValue);
1470 const MCExpr *SymDtprel =
1472 OutContext);
1473 EmitToStreamer(*OutStreamer,
1474 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1475 .addReg(MI->getOperand(0).getReg())
1476 .addReg(MI->getOperand(1).getReg())
1477 .addExpr(SymDtprel));
1478 return;
1479 }
1480 case PPC::MFOCRF:
1481 case PPC::MFOCRF8:
1482 if (!Subtarget->hasMFOCRF()) {
1483 // Transform: %r3 = MFOCRF %cr7
1484 // Into: %r3 = MFCR ;; cr7
1485 unsigned NewOpcode =
1486 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1487 OutStreamer->AddComment(PPCInstPrinter::
1488 getRegisterName(MI->getOperand(1).getReg()));
1489 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1490 .addReg(MI->getOperand(0).getReg()));
1491 return;
1492 }
1493 break;
1494 case PPC::MTOCRF:
1495 case PPC::MTOCRF8:
1496 if (!Subtarget->hasMFOCRF()) {
1497 // Transform: %cr7 = MTOCRF %r3
1498 // Into: MTCRF mask, %r3 ;; cr7
1499 unsigned NewOpcode =
1500 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1501 unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1502 ->getEncodingValue(MI->getOperand(0).getReg());
1503 OutStreamer->AddComment(PPCInstPrinter::
1504 getRegisterName(MI->getOperand(0).getReg()));
1505 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1506 .addImm(Mask)
1507 .addReg(MI->getOperand(1).getReg()));
1508 return;
1509 }
1510 break;
1511 case PPC::LD:
1512 case PPC::STD:
1513 case PPC::LWA_32:
1514 case PPC::LWA: {
1515 // Verify alignment is legal, so we don't create relocations
1516 // that can't be supported.
1517 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1518 const MachineOperand &MO = MI->getOperand(OpNum);
1519 if (MO.isGlobal()) {
1520 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1521 if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1522 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1523 }
1524 // Now process the instruction normally.
1525 break;
1526 }
1527 case PPC::PseudoEIEIO: {
1528 EmitToStreamer(
1529 *OutStreamer,
1530 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1531 EmitToStreamer(
1532 *OutStreamer,
1533 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1534 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO));
1535 return;
1536 }
1537 case PPC::ADDI8: {
1538 // The faster non-TOC-based local-exec sequence is represented by `addi`
1539 // with an immediate operand having the MO_TPREL_FLAG. Such an instruction
1540 // does not otherwise arise.
1541 const MachineOperand &MO = MI->getOperand(2);
1542 if ((MO.getTargetFlags() & PPCII::MO_TPREL_FLAG) != 0) {
1543 assert(
1544 Subtarget->hasAIXSmallLocalExecTLS() &&
1545 "addi with thread-pointer only expected with local-exec small TLS");
1546 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1547 TmpInst.setOpcode(PPC::LA8);
1548 EmitToStreamer(*OutStreamer, TmpInst);
1549 return;
1550 }
1551 break;
1552 }
1553 }
1554
1555 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1556 EmitToStreamer(*OutStreamer, TmpInst);
1557}
1558
1559void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
1560 // Emit float ABI into GNU attribute
1561 Metadata *MD = M.getModuleFlag("float-abi");
1562 MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
1563 if (!FloatABI)
1564 return;
1565 StringRef flt = FloatABI->getString();
1566 // TODO: Support emitting soft-fp and hard double/single attributes.
1567 if (flt == "doubledouble")
1568 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1569 Val_GNU_Power_ABI_HardFloat_DP |
1570 Val_GNU_Power_ABI_LDBL_IBM128);
1571 else if (flt == "ieeequad")
1572 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1573 Val_GNU_Power_ABI_HardFloat_DP |
1574 Val_GNU_Power_ABI_LDBL_IEEE128);
1575 else if (flt == "ieeedouble")
1576 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1577 Val_GNU_Power_ABI_HardFloat_DP |
1578 Val_GNU_Power_ABI_LDBL_64);
1579}
1580
1581void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1582 if (!Subtarget->isPPC64())
1583 return PPCAsmPrinter::emitInstruction(MI);
1584
1585 switch (MI->getOpcode()) {
1586 default:
1587 return PPCAsmPrinter::emitInstruction(MI);
1588 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1589 // .begin:
1590 // b .end # lis 0, FuncId[16..32]
1591 // nop # li 0, FuncId[0..15]
1592 // std 0, -8(1)
1593 // mflr 0
1594 // bl __xray_FunctionEntry
1595 // mtlr 0
1596 // .end:
1597 //
1598 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1599 // of instructions change.
1600 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1601 MCSymbol *EndOfSled = OutContext.createTempSymbol();
1602 OutStreamer->emitLabel(BeginOfSled);
1603 EmitToStreamer(*OutStreamer,
1604 MCInstBuilder(PPC::B).addExpr(
1605 MCSymbolRefExpr::create(EndOfSled, OutContext)));
1606 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1607 EmitToStreamer(
1608 *OutStreamer,
1609 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1610 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1611 EmitToStreamer(*OutStreamer,
1612 MCInstBuilder(PPC::BL8_NOP)
1613 .addExpr(MCSymbolRefExpr::create(
1614 OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1615 OutContext)));
1616 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1617 OutStreamer->emitLabel(EndOfSled);
1618 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1619 break;
1620 }
1621 case TargetOpcode::PATCHABLE_RET: {
1622 unsigned RetOpcode = MI->getOperand(0).getImm();
1623 MCInst RetInst;
1624 RetInst.setOpcode(RetOpcode);
1625 for (const auto &MO : llvm::drop_begin(MI->operands())) {
1626 MCOperand MCOp;
1627 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1628 RetInst.addOperand(MCOp);
1629 }
1630
1631 bool IsConditional;
1632 if (RetOpcode == PPC::BCCLR) {
1633 IsConditional = true;
1634 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1635 RetOpcode == PPC::TCRETURNai8) {
1636 break;
1637 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1638 IsConditional = false;
1639 } else {
1640 EmitToStreamer(*OutStreamer, RetInst);
1641 break;
1642 }
1643
1644 MCSymbol *FallthroughLabel;
1645 if (IsConditional) {
1646 // Before:
1647 // bgtlr cr0
1648 //
1649 // After:
1650 // ble cr0, .end
1651 // .p2align 3
1652 // .begin:
1653 // blr # lis 0, FuncId[16..32]
1654 // nop # li 0, FuncId[0..15]
1655 // std 0, -8(1)
1656 // mflr 0
1657 // bl __xray_FunctionExit
1658 // mtlr 0
1659 // blr
1660 // .end:
1661 //
1662 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1663 // of instructions change.
1664 FallthroughLabel = OutContext.createTempSymbol();
1665 EmitToStreamer(
1666 *OutStreamer,
1667 MCInstBuilder(PPC::BCC)
1668 .addImm(PPC::InvertPredicate(
1669 static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1670 .addReg(MI->getOperand(2).getReg())
1671 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1672 RetInst = MCInst();
1673 RetInst.setOpcode(PPC::BLR8);
1674 }
1675 // .p2align 3
1676 // .begin:
1677 // b(lr)? # lis 0, FuncId[16..32]
1678 // nop # li 0, FuncId[0..15]
1679 // std 0, -8(1)
1680 // mflr 0
1681 // bl __xray_FunctionExit
1682 // mtlr 0
1683 // b(lr)?
1684 //
1685 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1686 // of instructions change.
1687 OutStreamer->emitCodeAlignment(Align(8), &getSubtargetInfo());
1688 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1689 OutStreamer->emitLabel(BeginOfSled);
1690 EmitToStreamer(*OutStreamer, RetInst);
1691 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1692 EmitToStreamer(
1693 *OutStreamer,
1694 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1695 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1696 EmitToStreamer(*OutStreamer,
1697 MCInstBuilder(PPC::BL8_NOP)
1698 .addExpr(MCSymbolRefExpr::create(
1699 OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1700 OutContext)));
1701 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1702 EmitToStreamer(*OutStreamer, RetInst);
1703 if (IsConditional)
1704 OutStreamer->emitLabel(FallthroughLabel);
1705 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1706 break;
1707 }
1708 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1709 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1710 case TargetOpcode::PATCHABLE_TAIL_CALL:
1711 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1712 // normal function exit from a tail exit.
1713 llvm_unreachable("Tail call is handled in the normal case. See comments "
1714 "around this assert.");
1715 }
1716}
1717
1718void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1719 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1720 PPCTargetStreamer *TS =
1721 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1722 TS->emitAbiVersion(2);
1723 }
1724
1725 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1726 !isPositionIndependent())
1728
1729 if (M.getPICLevel() == PICLevel::SmallPIC)
1731
1732 OutStreamer->switchSection(OutContext.getELFSection(
1734
1735 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1736 MCSymbol *CurrentPos = OutContext.createTempSymbol();
1737
1738 OutStreamer->emitLabel(CurrentPos);
1739
1740 // The GOT pointer points to the middle of the GOT, in order to reference the
1741 // entire 64kB range. 0x8000 is the midpoint.
1742 const MCExpr *tocExpr =
1743 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1744 MCConstantExpr::create(0x8000, OutContext),
1745 OutContext);
1746
1747 OutStreamer->emitAssignment(TOCSym, tocExpr);
1748
1749 OutStreamer->switchSection(getObjFileLowering().getTextSection());
1750}
1751
1752void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1753 // linux/ppc32 - Normal entry label.
1754 if (!Subtarget->isPPC64() &&
1755 (!isPositionIndependent() ||
1756 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1758
1759 if (!Subtarget->isPPC64()) {
1760 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1761 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1762 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1763 MCSymbol *PICBase = MF->getPICBaseSymbol();
1764 OutStreamer->emitLabel(RelocSymbol);
1765
1766 const MCExpr *OffsExpr =
1768 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1769 OutContext),
1770 MCSymbolRefExpr::create(PICBase, OutContext),
1771 OutContext);
1772 OutStreamer->emitValue(OffsExpr, 4);
1773 OutStreamer->emitLabel(CurrentFnSym);
1774 return;
1775 } else
1777 }
1778
1779 // ELFv2 ABI - Normal entry label.
1780 if (Subtarget->isELFv2ABI()) {
1781 // In the Large code model, we allow arbitrary displacements between
1782 // the text section and its associated TOC section. We place the
1783 // full 8-byte offset to the TOC in memory immediately preceding
1784 // the function global entry point.
1785 if (TM.getCodeModel() == CodeModel::Large
1786 && !MF->getRegInfo().use_empty(PPC::X2)) {
1787 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1788
1789 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1790 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1791 const MCExpr *TOCDeltaExpr =
1792 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1793 MCSymbolRefExpr::create(GlobalEPSymbol,
1794 OutContext),
1795 OutContext);
1796
1797 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1798 OutStreamer->emitValue(TOCDeltaExpr, 8);
1799 }
1801 }
1802
1803 // Emit an official procedure descriptor.
1804 MCSectionSubPair Current = OutStreamer->getCurrentSection();
1805 MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1807 OutStreamer->switchSection(Section);
1808 OutStreamer->emitLabel(CurrentFnSym);
1809 OutStreamer->emitValueToAlignment(Align(8));
1810 MCSymbol *Symbol1 = CurrentFnSymForSize;
1811 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1812 // entry point.
1813 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1814 8 /*size*/);
1815 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1816 // Generates a R_PPC64_TOC relocation for TOC base insertion.
1817 OutStreamer->emitValue(
1819 8/*size*/);
1820 // Emit a null environment pointer.
1821 OutStreamer->emitIntValue(0, 8 /* size */);
1822 OutStreamer->switchSection(Current.first, Current.second);
1823}
1824
1825void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1826 const DataLayout &DL = getDataLayout();
1827
1828 bool isPPC64 = DL.getPointerSizeInBits() == 64;
1829
1830 PPCTargetStreamer *TS =
1831 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1832
1833 emitGNUAttributes(M);
1834
1835 if (!TOC.empty()) {
1836 const char *Name = isPPC64 ? ".toc" : ".got2";
1837 MCSectionELF *Section = OutContext.getELFSection(
1839 OutStreamer->switchSection(Section);
1840 if (!isPPC64)
1841 OutStreamer->emitValueToAlignment(Align(4));
1842
1843 for (const auto &TOCMapPair : TOC) {
1844 const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first;
1845 MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1846
1847 OutStreamer->emitLabel(TOCEntryLabel);
1848 if (isPPC64)
1849 TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second);
1850 else
1851 OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1852 }
1853 }
1854
1855 PPCAsmPrinter::emitEndOfAsmFile(M);
1856}
1857
1858/// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1859void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1860 // In the ELFv2 ABI, in functions that use the TOC register, we need to
1861 // provide two entry points. The ABI guarantees that when calling the
1862 // local entry point, r2 is set up by the caller to contain the TOC base
1863 // for this function, and when calling the global entry point, r12 is set
1864 // up by the caller to hold the address of the global entry point. We
1865 // thus emit a prefix sequence along the following lines:
1866 //
1867 // func:
1868 // .Lfunc_gepNN:
1869 // # global entry point
1870 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1871 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l
1872 // .Lfunc_lepNN:
1873 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1874 // # local entry point, followed by function body
1875 //
1876 // For the Large code model, we create
1877 //
1878 // .Lfunc_tocNN:
1879 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel
1880 // func:
1881 // .Lfunc_gepNN:
1882 // # global entry point
1883 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1884 // add r2,r2,r12
1885 // .Lfunc_lepNN:
1886 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1887 // # local entry point, followed by function body
1888 //
1889 // This ensures we have r2 set up correctly while executing the function
1890 // body, no matter which entry point is called.
1891 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1892 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1893 !MF->getRegInfo().use_empty(PPC::R2);
1894 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1895 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1896 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1897 Subtarget->isELFv2ABI() && UsesX2OrR2;
1898
1899 // Only do all that if the function uses R2 as the TOC pointer
1900 // in the first place. We don't need the global entry point if the
1901 // function uses R2 as an allocatable register.
1902 if (NonPCrelGEPRequired || PCrelGEPRequired) {
1903 // Note: The logic here must be synchronized with the code in the
1904 // branch-selection pass which sets the offset of the first block in the
1905 // function. This matters because it affects the alignment.
1906 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1907 OutStreamer->emitLabel(GlobalEntryLabel);
1908 const MCSymbolRefExpr *GlobalEntryLabelExp =
1909 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1910
1911 if (TM.getCodeModel() != CodeModel::Large) {
1912 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1913 const MCExpr *TOCDeltaExpr =
1914 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1915 GlobalEntryLabelExp, OutContext);
1916
1917 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1918 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1919 .addReg(PPC::X2)
1920 .addReg(PPC::X12)
1921 .addExpr(TOCDeltaHi));
1922
1923 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1924 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1925 .addReg(PPC::X2)
1926 .addReg(PPC::X2)
1927 .addExpr(TOCDeltaLo));
1928 } else {
1929 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1930 const MCExpr *TOCOffsetDeltaExpr =
1931 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1932 GlobalEntryLabelExp, OutContext);
1933
1934 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1935 .addReg(PPC::X2)
1936 .addExpr(TOCOffsetDeltaExpr)
1937 .addReg(PPC::X12));
1938 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1939 .addReg(PPC::X2)
1940 .addReg(PPC::X2)
1941 .addReg(PPC::X12));
1942 }
1943
1944 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1945 OutStreamer->emitLabel(LocalEntryLabel);
1946 const MCSymbolRefExpr *LocalEntryLabelExp =
1947 MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1948 const MCExpr *LocalOffsetExp =
1949 MCBinaryExpr::createSub(LocalEntryLabelExp,
1950 GlobalEntryLabelExp, OutContext);
1951
1952 PPCTargetStreamer *TS =
1953 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1954 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1955 } else if (Subtarget->isUsingPCRelativeCalls()) {
1956 // When generating the entry point for a function we have a few scenarios
1957 // based on whether or not that function uses R2 and whether or not that
1958 // function makes calls (or is a leaf function).
1959 // 1) A leaf function that does not use R2 (or treats it as callee-saved
1960 // and preserves it). In this case st_other=0 and both
1961 // the local and global entry points for the function are the same.
1962 // No special entry point code is required.
1963 // 2) A function uses the TOC pointer R2. This function may or may not have
1964 // calls. In this case st_other=[2,6] and the global and local entry
1965 // points are different. Code to correctly setup the TOC pointer in R2
1966 // is put between the global and local entry points. This case is
1967 // covered by the if statatement above.
1968 // 3) A function does not use the TOC pointer R2 but does have calls.
1969 // In this case st_other=1 since we do not know whether or not any
1970 // of the callees clobber R2. This case is dealt with in this else if
1971 // block. Tail calls are considered calls and the st_other should also
1972 // be set to 1 in that case as well.
1973 // 4) The function does not use the TOC pointer but R2 is used inside
1974 // the function. In this case st_other=1 once again.
1975 // 5) This function uses inline asm. We mark R2 as reserved if the function
1976 // has inline asm as we have to assume that it may be used.
1977 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1978 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1979 PPCTargetStreamer *TS =
1980 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1981 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1982 MCConstantExpr::create(1, OutContext));
1983 }
1984 }
1985}
1986
1987/// EmitFunctionBodyEnd - Print the traceback table before the .size
1988/// directive.
1989///
1990void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1991 // Only the 64-bit target requires a traceback table. For now,
1992 // we only emit the word of zeroes that GDB requires to find
1993 // the end of the function, and zeroes for the eight-byte
1994 // mandatory fields.
1995 // FIXME: We should fill in the eight-byte mandatory fields as described in
1996 // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1997 // currently make use of these fields).
1998 if (Subtarget->isPPC64()) {
1999 OutStreamer->emitIntValue(0, 4/*size*/);
2000 OutStreamer->emitIntValue(0, 8/*size*/);
2001 }
2002}
2003
2004void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
2005 MCSymbol *GVSym) const {
2006
2007 assert(MAI->hasVisibilityOnlyWithLinkage() &&
2008 "AIX's linkage directives take a visibility setting.");
2009
2010 MCSymbolAttr LinkageAttr = MCSA_Invalid;
2011 switch (GV->getLinkage()) {
2013 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
2014 break;
2020 LinkageAttr = MCSA_Weak;
2021 break;
2023 LinkageAttr = MCSA_Extern;
2024 break;
2026 return;
2029 "InternalLinkage should not have other visibility setting.");
2030 LinkageAttr = MCSA_LGlobal;
2031 break;
2033 llvm_unreachable("Should never emit this");
2035 llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
2036 }
2037
2038 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
2039
2040 MCSymbolAttr VisibilityAttr = MCSA_Invalid;
2041 if (!TM.getIgnoreXCOFFVisibility()) {
2044 "Cannot not be both dllexport and non-default visibility");
2045 switch (GV->getVisibility()) {
2046
2047 // TODO: "internal" Visibility needs to go here.
2049 if (GV->hasDLLExportStorageClass())
2050 VisibilityAttr = MAI->getExportedVisibilityAttr();
2051 break;
2053 VisibilityAttr = MAI->getHiddenVisibilityAttr();
2054 break;
2056 VisibilityAttr = MAI->getProtectedVisibilityAttr();
2057 break;
2058 }
2059 }
2060
2061 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
2062 VisibilityAttr);
2063}
2064
2065void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
2066 // Setup CurrentFnDescSym and its containing csect.
2067 MCSectionXCOFF *FnDescSec =
2068 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
2069 &MF.getFunction(), TM));
2070 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
2071
2072 CurrentFnDescSym = FnDescSec->getQualNameSymbol();
2073
2075}
2076
2077uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() {
2078 // Calculate the number of VRs be saved.
2079 // Vector registers 20 through 31 are marked as reserved and cannot be used
2080 // in the default ABI.
2081 const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
2082 if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
2083 TM.getAIXExtendedAltivecABI()) {
2084 const MachineRegisterInfo &MRI = MF->getRegInfo();
2085 for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg)
2086 if (MRI.isPhysRegModified(Reg))
2087 // Number of VRs saved.
2088 return PPC::V31 - Reg + 1;
2089 }
2090 return 0;
2091}
2092
2093void PPCAIXAsmPrinter::emitFunctionBodyEnd() {
2094
2095 if (!TM.getXCOFFTracebackTable())
2096 return;
2097
2098 emitTracebackTable();
2099
2100 // If ShouldEmitEHBlock returns true, then the eh info table
2101 // will be emitted via `AIXException::endFunction`. Otherwise, we
2102 // need to emit a dumy eh info table when VRs are saved. We could not
2103 // consolidate these two places into one because there is no easy way
2104 // to access register information in `AIXException` class.
2106 (getNumberOfVRSaved() > 0)) {
2107 // Emit dummy EH Info Table.
2108 OutStreamer->switchSection(getObjFileLowering().getCompactUnwindSection());
2109 MCSymbol *EHInfoLabel =
2111 OutStreamer->emitLabel(EHInfoLabel);
2112
2113 // Version number.
2114 OutStreamer->emitInt32(0);
2115
2116 const DataLayout &DL = MMI->getModule()->getDataLayout();
2117 const unsigned PointerSize = DL.getPointerSize();
2118 // Add necessary paddings in 64 bit mode.
2119 OutStreamer->emitValueToAlignment(Align(PointerSize));
2120
2121 OutStreamer->emitIntValue(0, PointerSize);
2122 OutStreamer->emitIntValue(0, PointerSize);
2123 OutStreamer->switchSection(MF->getSection());
2124 }
2125}
2126
2127void PPCAIXAsmPrinter::emitTracebackTable() {
2128
2129 // Create a symbol for the end of function.
2130 MCSymbol *FuncEnd = createTempSymbol(MF->getName());
2131 OutStreamer->emitLabel(FuncEnd);
2132
2133 OutStreamer->AddComment("Traceback table begin");
2134 // Begin with a fullword of zero.
2135 OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/);
2136
2137 SmallString<128> CommentString;
2138 raw_svector_ostream CommentOS(CommentString);
2139
2140 auto EmitComment = [&]() {
2141 OutStreamer->AddComment(CommentOS.str());
2142 CommentString.clear();
2143 };
2144
2145 auto EmitCommentAndValue = [&](uint64_t Value, int Size) {
2146 EmitComment();
2147 OutStreamer->emitIntValueInHexWithPadding(Value, Size);
2148 };
2149
2150 unsigned int Version = 0;
2151 CommentOS << "Version = " << Version;
2152 EmitCommentAndValue(Version, 1);
2153
2154 // There is a lack of information in the IR to assist with determining the
2155 // source language. AIX exception handling mechanism would only search for
2156 // personality routine and LSDA area when such language supports exception
2157 // handling. So to be conservatively correct and allow runtime to do its job,
2158 // we need to set it to C++ for now.
2159 TracebackTable::LanguageID LanguageIdentifier =
2161
2162 CommentOS << "Language = "
2163 << getNameForTracebackTableLanguageId(LanguageIdentifier);
2164 EmitCommentAndValue(LanguageIdentifier, 1);
2165
2166 // This is only populated for the third and fourth bytes.
2167 uint32_t FirstHalfOfMandatoryField = 0;
2168
2169 // Emit the 3rd byte of the mandatory field.
2170
2171 // We always set traceback offset bit to true.
2172 FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask;
2173
2174 const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2175 const MachineRegisterInfo &MRI = MF->getRegInfo();
2176
2177 // Check the function uses floating-point processor instructions or not
2178 for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) {
2179 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2180 FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask;
2181 break;
2182 }
2183 }
2184
2185#define GENBOOLCOMMENT(Prefix, V, Field) \
2186 CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-") \
2187 << #Field
2188
2189#define GENVALUECOMMENT(PrefixAndName, V, Field) \
2190 CommentOS << (PrefixAndName) << " = " \
2191 << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >> \
2192 (TracebackTable::Field##Shift))
2193
2194 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage);
2195 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue);
2196 EmitComment();
2197
2198 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset);
2199 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure);
2200 EmitComment();
2201
2202 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage);
2203 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless);
2204 EmitComment();
2205
2206 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent);
2207 EmitComment();
2208 GENBOOLCOMMENT("", FirstHalfOfMandatoryField,
2209 IsFloatingPointOperationLogOrAbortEnabled);
2210 EmitComment();
2211
2212 OutStreamer->emitIntValueInHexWithPadding(
2213 (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2214
2215 // Set the 4th byte of the mandatory field.
2216 FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask;
2217
2218 const PPCRegisterInfo *RegInfo =
2219 static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo());
2220 Register FrameReg = RegInfo->getFrameRegister(*MF);
2221 if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31))
2222 FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask;
2223
2224 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
2225 if (!MustSaveCRs.empty())
2226 FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask;
2227
2228 if (FI->mustSaveLR())
2229 FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask;
2230
2231 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler);
2232 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent);
2233 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed);
2234 EmitComment();
2235 GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField,
2236 OnConditionDirective);
2237 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved);
2238 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved);
2239 EmitComment();
2240 OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff),
2241 1);
2242
2243 // Set the 5th byte of mandatory field.
2244 uint32_t SecondHalfOfMandatoryField = 0;
2245
2246 SecondHalfOfMandatoryField |= MF->getFrameInfo().getStackSize()
2248 : 0;
2249
2250 uint32_t FPRSaved = 0;
2251 for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) {
2252 if (MRI.isPhysRegModified(Reg)) {
2253 FPRSaved = PPC::F31 - Reg + 1;
2254 break;
2255 }
2256 }
2257 SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) &
2259 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored);
2260 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup);
2261 GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved);
2262 EmitComment();
2263 OutStreamer->emitIntValueInHexWithPadding(
2264 (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1);
2265
2266 // Set the 6th byte of mandatory field.
2267
2268 // Check whether has Vector Instruction,We only treat instructions uses vector
2269 // register as vector instructions.
2270 bool HasVectorInst = false;
2271 for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg)
2272 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2273 // Has VMX instruction.
2274 HasVectorInst = true;
2275 break;
2276 }
2277
2278 if (FI->hasVectorParms() || HasVectorInst)
2279 SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask;
2280
2281 uint16_t NumOfVRSaved = getNumberOfVRSaved();
2282 bool ShouldEmitEHBlock =
2284
2285 if (ShouldEmitEHBlock)
2286 SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask;
2287
2288 uint32_t GPRSaved = 0;
2289
2290 // X13 is reserved under 64-bit environment.
2291 unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13;
2292 unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31;
2293
2294 for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) {
2295 if (MRI.isPhysRegModified(Reg)) {
2296 GPRSaved = GPREnd - Reg + 1;
2297 break;
2298 }
2299 }
2300
2301 SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) &
2303
2304 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable);
2305 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo);
2306 GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved);
2307 EmitComment();
2308 OutStreamer->emitIntValueInHexWithPadding(
2309 (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1);
2310
2311 // Set the 7th byte of mandatory field.
2312 uint32_t NumberOfFixedParms = FI->getFixedParmsNum();
2313 SecondHalfOfMandatoryField |=
2314 (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) &
2316 GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField,
2317 NumberOfFixedParms);
2318 EmitComment();
2319 OutStreamer->emitIntValueInHexWithPadding(
2320 (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2321
2322 // Set the 8th byte of mandatory field.
2323
2324 // Always set parameter on stack.
2325 SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask;
2326
2327 uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum();
2328 SecondHalfOfMandatoryField |=
2331
2332 GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField,
2333 NumberOfFloatingPointParms);
2334 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack);
2335 EmitComment();
2336 OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff,
2337 1);
2338
2339 // Generate the optional fields of traceback table.
2340
2341 // Parameter type.
2342 if (NumberOfFixedParms || NumberOfFPParms) {
2343 uint32_t ParmsTypeValue = FI->getParmsType();
2344
2345 Expected<SmallString<32>> ParmsType =
2346 FI->hasVectorParms()
2348 ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms,
2349 FI->getVectorParmsNum())
2350 : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms,
2351 NumberOfFPParms);
2352
2353 assert(ParmsType && toString(ParmsType.takeError()).c_str());
2354 if (ParmsType) {
2355 CommentOS << "Parameter type = " << ParmsType.get();
2356 EmitComment();
2357 }
2358 OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue,
2359 sizeof(ParmsTypeValue));
2360 }
2361 // Traceback table offset.
2362 OutStreamer->AddComment("Function size");
2363 if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) {
2364 MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol(
2365 &(MF->getFunction()), TM);
2366 OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4);
2367 }
2368
2369 // Since we unset the Int_Handler.
2370 if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask)
2371 report_fatal_error("Hand_Mask not implement yet");
2372
2373 if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask)
2374 report_fatal_error("Ctl_Info not implement yet");
2375
2376 if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) {
2377 StringRef Name = MF->getName().substr(0, INT16_MAX);
2378 int16_t NameLength = Name.size();
2379 CommentOS << "Function name len = "
2380 << static_cast<unsigned int>(NameLength);
2381 EmitCommentAndValue(NameLength, 2);
2382 OutStreamer->AddComment("Function Name");
2383 OutStreamer->emitBytes(Name);
2384 }
2385
2386 if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) {
2387 uint8_t AllocReg = XCOFF::AllocRegNo;
2388 OutStreamer->AddComment("AllocaUsed");
2389 OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg));
2390 }
2391
2392 if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) {
2393 uint16_t VRData = 0;
2394 if (NumOfVRSaved) {
2395 // Number of VRs saved.
2396 VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) &
2398 // This bit is supposed to set only when the special register
2399 // VRSAVE is saved on stack.
2400 // However, IBM XL compiler sets the bit when any vector registers
2401 // are saved on the stack. We will follow XL's behavior on AIX
2402 // so that we don't get surprise behavior change for C code.
2404 }
2405
2406 // Set has_varargs.
2407 if (FI->getVarArgsFrameIndex())
2409
2410 // Vector parameters number.
2411 unsigned VectorParmsNum = FI->getVectorParmsNum();
2412 VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) &
2414
2415 if (HasVectorInst)
2417
2418 GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved);
2419 GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack);
2420 GENBOOLCOMMENT(", ", VRData, HasVarArgs);
2421 EmitComment();
2422 OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1);
2423
2424 GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms);
2425 GENBOOLCOMMENT(", ", VRData, HasVMXInstruction);
2426 EmitComment();
2427 OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1);
2428
2429 uint32_t VecParmTypeValue = FI->getVecExtParmsType();
2430
2431 Expected<SmallString<32>> VecParmsType =
2432 XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum);
2433 assert(VecParmsType && toString(VecParmsType.takeError()).c_str());
2434 if (VecParmsType) {
2435 CommentOS << "Vector Parameter type = " << VecParmsType.get();
2436 EmitComment();
2437 }
2438 OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue,
2439 sizeof(VecParmTypeValue));
2440 // Padding 2 bytes.
2441 CommentOS << "Padding";
2442 EmitCommentAndValue(0, 2);
2443 }
2444
2445 uint8_t ExtensionTableFlag = 0;
2446 if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) {
2447 if (ShouldEmitEHBlock)
2448 ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO;
2451 ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY;
2452
2453 CommentOS << "ExtensionTableFlag = "
2454 << getExtendedTBTableFlagString(ExtensionTableFlag);
2455 EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag));
2456 }
2457
2458 if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) {
2459 auto &Ctx = OutStreamer->getContext();
2460 MCSymbol *EHInfoSym =
2462 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym, TOCType_EHBlock);
2463 const MCSymbol *TOCBaseSym =
2464 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2465 ->getQualNameSymbol();
2466 const MCExpr *Exp =
2468 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2469
2470 const DataLayout &DL = getDataLayout();
2471 OutStreamer->emitValueToAlignment(Align(4));
2472 OutStreamer->AddComment("EHInfo Table");
2473 OutStreamer->emitValue(Exp, DL.getPointerSize());
2474 }
2475#undef GENBOOLCOMMENT
2476#undef GENVALUECOMMENT
2477}
2478
2480 return GV->hasAppendingLinkage() &&
2482 // TODO: Linker could still eliminate the GV if we just skip
2483 // handling llvm.used array. Skipping them for now until we or the
2484 // AIX OS team come up with a good solution.
2485 .Case("llvm.used", true)
2486 // It's correct to just skip llvm.compiler.used array here.
2487 .Case("llvm.compiler.used", true)
2488 .Default(false);
2489}
2490
2492 return StringSwitch<bool>(GV->getName())
2493 .Cases("llvm.global_ctors", "llvm.global_dtors", true)
2494 .Default(false);
2495}
2496
2497uint64_t PPCAIXAsmPrinter::getAliasOffset(const Constant *C) {
2498 if (auto *GA = dyn_cast<GlobalAlias>(C))
2499 return getAliasOffset(GA->getAliasee());
2500 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2501 const MCExpr *LowC = lowerConstant(CE);
2502 const MCBinaryExpr *CBE = dyn_cast<MCBinaryExpr>(LowC);
2503 if (!CBE)
2504 return 0;
2505 if (CBE->getOpcode() != MCBinaryExpr::Add)
2506 report_fatal_error("Only adding an offset is supported now.");
2507 auto *RHS = dyn_cast<MCConstantExpr>(CBE->getRHS());
2508 if (!RHS)
2509 report_fatal_error("Unable to get the offset of alias.");
2510 return RHS->getValue();
2511 }
2512 return 0;
2513}
2514
2515void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
2516 // Special LLVM global arrays have been handled at the initialization.
2518 return;
2519
2520 // If the Global Variable has the toc-data attribute, it needs to be emitted
2521 // when we emit the .toc section.
2522 if (GV->hasAttribute("toc-data")) {
2523 TOCDataGlobalVars.push_back(GV);
2524 return;
2525 }
2526
2527 emitGlobalVariableHelper(GV);
2528}
2529
2530void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) {
2531 assert(!GV->getName().startswith("llvm.") &&
2532 "Unhandled intrinsic global variable.");
2533
2534 if (GV->hasComdat())
2535 report_fatal_error("COMDAT not yet supported by AIX.");
2536
2537 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
2538
2539 if (GV->isDeclarationForLinker()) {
2540 emitLinkage(GV, GVSym);
2541 return;
2542 }
2543
2544 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
2545 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() &&
2546 !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS.
2547 report_fatal_error("Encountered a global variable kind that is "
2548 "not supported yet.");
2549
2550 // Print GV in verbose mode
2551 if (isVerbose()) {
2552 if (GV->hasInitializer()) {
2553 GV->printAsOperand(OutStreamer->getCommentOS(),
2554 /*PrintType=*/false, GV->getParent());
2555 OutStreamer->getCommentOS() << '\n';
2556 }
2557 }
2558
2559 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2560 getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
2561
2562 // Switch to the containing csect.
2563 OutStreamer->switchSection(Csect);
2564
2565 const DataLayout &DL = GV->getParent()->getDataLayout();
2566
2567 // Handle common and zero-initialized local symbols.
2568 if (GV->hasCommonLinkage() || GVKind.isBSSLocal() ||
2569 GVKind.isThreadBSSLocal()) {
2570 Align Alignment = GV->getAlign().value_or(DL.getPreferredAlign(GV));
2571 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
2572 GVSym->setStorageClass(
2574
2575 if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal())
2576 OutStreamer->emitXCOFFLocalCommonSymbol(
2577 OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
2578 GVSym, Alignment);
2579 else
2580 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
2581 return;
2582 }
2583
2584 MCSymbol *EmittedInitSym = GVSym;
2585
2586 // Emit linkage for the global variable and its aliases.
2587 emitLinkage(GV, EmittedInitSym);
2588 for (const GlobalAlias *GA : GOAliasMap[GV])
2589 emitLinkage(GA, getSymbol(GA));
2590
2591 emitAlignment(getGVAlignment(GV, DL), GV);
2592
2593 // When -fdata-sections is enabled, every GlobalVariable will
2594 // be put into its own csect; therefore, label is not necessary here.
2595 if (!TM.getDataSections() || GV->hasSection())
2596 OutStreamer->emitLabel(EmittedInitSym);
2597
2598 // No alias to emit.
2599 if (!GOAliasMap[GV].size()) {
2600 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
2601 return;
2602 }
2603
2604 // Aliases with the same offset should be aligned. Record the list of aliases
2605 // associated with the offset.
2606 AliasMapTy AliasList;
2607 for (const GlobalAlias *GA : GOAliasMap[GV])
2608 AliasList[getAliasOffset(GA->getAliasee())].push_back(GA);
2609
2610 // Emit alias label and element value for global variable.
2611 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer(),
2612 &AliasList);
2613}
2614
2615void PPCAIXAsmPrinter::emitFunctionDescriptor() {
2616 const DataLayout &DL = getDataLayout();
2617 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
2618
2619 MCSectionSubPair Current = OutStreamer->getCurrentSection();
2620 // Emit function descriptor.
2621 OutStreamer->switchSection(
2622 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
2623
2624 // Emit aliasing label for function descriptor csect.
2625 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2626 OutStreamer->emitLabel(getSymbol(Alias));
2627
2628 // Emit function entry point address.
2629 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
2630 PointerSize);
2631 // Emit TOC base address.
2632 const MCSymbol *TOCBaseSym =
2633 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2634 ->getQualNameSymbol();
2635 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
2636 PointerSize);
2637 // Emit a null environment pointer.
2638 OutStreamer->emitIntValue(0, PointerSize);
2639
2640 OutStreamer->switchSection(Current.first, Current.second);
2641}
2642
2643void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
2644 // It's not necessary to emit the label when we have individual
2645 // function in its own csect.
2646 if (!TM.getFunctionSections())
2647 PPCAsmPrinter::emitFunctionEntryLabel();
2648
2649 // Emit aliasing label for function entry point label.
2650 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2651 OutStreamer->emitLabel(
2652 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
2653}
2654
2655void PPCAIXAsmPrinter::emitPGORefs(Module &M) {
2656 if (!OutContext.hasXCOFFSection(
2657 "__llvm_prf_cnts",
2659 return;
2660
2661 // When inside a csect `foo`, a .ref directive referring to a csect `bar`
2662 // translates into a relocation entry from `foo` to` bar`. The referring
2663 // csect, `foo`, is identified by its address. If multiple csects have the
2664 // same address (because one or more of them are zero-length), the referring
2665 // csect cannot be determined. Hence, we don't generate the .ref directives
2666 // if `__llvm_prf_cnts` is an empty section.
2667 bool HasNonZeroLengthPrfCntsSection = false;
2668 const DataLayout &DL = M.getDataLayout();
2669 for (GlobalVariable &GV : M.globals())
2670 if (GV.hasSection() && GV.getSection().equals("__llvm_prf_cnts") &&
2671 DL.getTypeAllocSize(GV.getValueType()) > 0) {
2672 HasNonZeroLengthPrfCntsSection = true;
2673 break;
2674 }
2675
2676 if (HasNonZeroLengthPrfCntsSection) {
2677 MCSection *CntsSection = OutContext.getXCOFFSection(
2678 "__llvm_prf_cnts", SectionKind::getData(),
2680 /*MultiSymbolsAllowed*/ true);
2681
2682 OutStreamer->switchSection(CntsSection);
2683 if (OutContext.hasXCOFFSection(
2684 "__llvm_prf_data",
2686 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_data[RW]");
2687 OutStreamer->emitXCOFFRefDirective(S);
2688 }
2689 if (OutContext.hasXCOFFSection(
2690 "__llvm_prf_names",
2692 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_names[RO]");
2693 OutStreamer->emitXCOFFRefDirective(S);
2694 }
2695 if (OutContext.hasXCOFFSection(
2696 "__llvm_prf_vnds",
2698 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_vnds[RW]");
2699 OutStreamer->emitXCOFFRefDirective(S);
2700 }
2701 }
2702}
2703
2704void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
2705 // If there are no functions and there are no toc-data definitions in this
2706 // module, we will never need to reference the TOC base.
2707 if (M.empty() && TOCDataGlobalVars.empty())
2708 return;
2709
2710 emitPGORefs(M);
2711
2712 // Switch to section to emit TOC base.
2713 OutStreamer->switchSection(getObjFileLowering().getTOCBaseSection());
2714
2715 PPCTargetStreamer *TS =
2716 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2717
2718 for (auto &I : TOC) {
2719 MCSectionXCOFF *TCEntry;
2720 // Setup the csect for the current TC entry. If the variant kind is
2721 // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a
2722 // new symbol to prefix the name with a dot.
2723 if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM) {
2725 StringRef Prefix = ".";
2726 Name += Prefix;
2727 Name += cast<MCSymbolXCOFF>(I.first.first)->getSymbolTableName();
2728 MCSymbol *S = OutContext.getOrCreateSymbol(Name);
2729 TCEntry = cast<MCSectionXCOFF>(
2730 getObjFileLowering().getSectionForTOCEntry(S, TM));
2731 } else {
2732 TCEntry = cast<MCSectionXCOFF>(
2733 getObjFileLowering().getSectionForTOCEntry(I.first.first, TM));
2734 }
2735 OutStreamer->switchSection(TCEntry);
2736
2737 OutStreamer->emitLabel(I.second);
2738 TS->emitTCEntry(*I.first.first, I.first.second);
2739 }
2740
2741 for (const auto *GV : TOCDataGlobalVars)
2742 emitGlobalVariableHelper(GV);
2743}
2744
2745bool PPCAIXAsmPrinter::doInitialization(Module &M) {
2746 const bool Result = PPCAsmPrinter::doInitialization(M);
2747
2748 auto setCsectAlignment = [this](const GlobalObject *GO) {
2749 // Declarations have 0 alignment which is set by default.
2750 if (GO->isDeclarationForLinker())
2751 return;
2752
2753 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
2754 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2755 getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
2756
2757 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
2758 Csect->ensureMinAlignment(GOAlign);
2759 };
2760
2761 // We need to know, up front, the alignment of csects for the assembly path,
2762 // because once a .csect directive gets emitted, we could not change the
2763 // alignment value on it.
2764 for (const auto &G : M.globals()) {
2766 continue;
2767
2769 // Generate a format indicator and a unique module id to be a part of
2770 // the sinit and sterm function names.
2771 if (FormatIndicatorAndUniqueModId.empty()) {
2772 std::string UniqueModuleId = getUniqueModuleId(&M);
2773 if (UniqueModuleId != "")
2774 // TODO: Use source file full path to generate the unique module id
2775 // and add a format indicator as a part of function name in case we
2776 // will support more than one format.
2777 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
2778 else {
2779 // Use threadId, Pid, and current time as the unique module id when we
2780 // cannot generate one based on a module's strong external symbols.
2781 auto CurTime =
2782 std::chrono::duration_cast<std::chrono::nanoseconds>(
2783 std::chrono::steady_clock::now().time_since_epoch())
2784 .count();
2785 FormatIndicatorAndUniqueModId =
2786 "clangPidTidTime_" + llvm::itostr(sys::Process::getProcessId()) +
2787 "_" + llvm::itostr(llvm::get_threadid()) + "_" +
2788 llvm::itostr(CurTime);
2789 }
2790 }
2791
2792 emitSpecialLLVMGlobal(&G);
2793 continue;
2794 }
2795
2796 setCsectAlignment(&G);
2797 }
2798
2799 for (const auto &F : M)
2800 setCsectAlignment(&F);
2801
2802 // Construct an aliasing list for each GlobalObject.
2803 for (const auto &Alias : M.aliases()) {
2804 const GlobalObject *Aliasee = Alias.getAliaseeObject();
2805 if (!Aliasee)
2807 "alias without a base object is not yet supported on AIX");
2808
2809 if (Aliasee->hasCommonLinkage()) {
2810 report_fatal_error("Aliases to common variables are not allowed on AIX:"
2811 "\n\tAlias attribute for " +
2812 Alias.getGlobalIdentifier() +
2813 " is invalid because " + Aliasee->getName() +
2814 " is common.",
2815 false);
2816 }
2817
2818 GOAliasMap[Aliasee].push_back(&Alias);
2819 }
2820
2821 return Result;
2822}
2823
2824void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
2825 switch (MI->getOpcode()) {
2826 default:
2827 break;
2828 case PPC::TW:
2829 case PPC::TWI:
2830 case PPC::TD:
2831 case PPC::TDI: {
2832 if (MI->getNumOperands() < 5)
2833 break;
2834 const MachineOperand &LangMO = MI->getOperand(3);
2835 const MachineOperand &ReasonMO = MI->getOperand(4);
2836 if (!LangMO.isImm() || !ReasonMO.isImm())
2837 break;
2838 MCSymbol *TempSym = OutContext.createNamedTempSymbol();
2839 OutStreamer->emitLabel(TempSym);
2840 OutStreamer->emitXCOFFExceptDirective(CurrentFnSym, TempSym,
2841 LangMO.getImm(), ReasonMO.getImm(),
2842 Subtarget->isPPC64() ? MI->getMF()->getInstructionCount() * 8 :
2843 MI->getMF()->getInstructionCount() * 4,
2844 MMI->hasDebugInfo());
2845 break;
2846 }
2847 case PPC::GETtlsTpointer32AIX:
2848 case PPC::GETtlsADDR64AIX:
2849 case PPC::GETtlsADDR32AIX: {
2850 // A reference to .__tls_get_addr/.__get_tpointer is unknown to the
2851 // assembler so we need to emit an external symbol reference.
2852 MCSymbol *TlsGetAddr =
2853 createMCSymbolForTlsGetAddr(OutContext, MI->getOpcode());
2854 ExtSymSDNodeSymbols.insert(TlsGetAddr);
2855 break;
2856 }
2857 case PPC::BL8:
2858 case PPC::BL:
2859 case PPC::BL8_NOP:
2860 case PPC::BL_NOP: {
2861 const MachineOperand &MO = MI->getOperand(0);
2862 if (MO.isSymbol()) {
2863 MCSymbolXCOFF *S =
2864 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
2865 ExtSymSDNodeSymbols.insert(S);
2866 }
2867 } break;
2868 case PPC::BL_TLS:
2869 case PPC::BL8_TLS:
2870 case PPC::BL8_TLS_:
2871 case PPC::BL8_NOP_TLS:
2872 report_fatal_error("TLS call not yet implemented");
2873 case PPC::TAILB:
2874 case PPC::TAILB8:
2875 case PPC::TAILBA:
2876 case PPC::TAILBA8:
2877 case PPC::TAILBCTR:
2878 case PPC::TAILBCTR8:
2879 if (MI->getOperand(0).isSymbol())
2880 report_fatal_error("Tail call for extern symbol not yet supported.");
2881 break;
2882 case PPC::DST:
2883 case PPC::DST64:
2884 case PPC::DSTT:
2885 case PPC::DSTT64:
2886 case PPC::DSTST:
2887 case PPC::DSTST64:
2888 case PPC::DSTSTT:
2889 case PPC::DSTSTT64:
2890 EmitToStreamer(
2891 *OutStreamer,
2892 MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0));
2893 return;
2894 }
2895 return PPCAsmPrinter::emitInstruction(MI);
2896}
2897
2898bool PPCAIXAsmPrinter::doFinalization(Module &M) {
2899 // Do streamer related finalization for DWARF.
2900 if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo())
2901 OutStreamer->doFinalizationAtSectionEnd(
2902 OutStreamer->getContext().getObjectFileInfo()->getTextSection());
2903
2904 for (MCSymbol *Sym : ExtSymSDNodeSymbols)
2905 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
2906 return PPCAsmPrinter::doFinalization(M);
2907}
2908
2909static unsigned mapToSinitPriority(int P) {
2910 if (P < 0 || P > 65535)
2911 report_fatal_error("invalid init priority");
2912
2913 if (P <= 20)
2914 return P;
2915
2916 if (P < 81)
2917 return 20 + (P - 20) * 16;
2918
2919 if (P <= 1124)
2920 return 1004 + (P - 81);
2921
2922 if (P < 64512)
2923 return 2047 + (P - 1124) * 33878;
2924
2925 return 2147482625u + (P - 64512);
2926}
2927
2928static std::string convertToSinitPriority(int Priority) {
2929 // This helper function converts clang init priority to values used in sinit
2930 // and sterm functions.
2931 //
2932 // The conversion strategies are:
2933 // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
2934 // reserved priority range [0, 1023] by
2935 // - directly mapping the first 21 and the last 20 elements of the ranges
2936 // - linear interpolating the intermediate values with a step size of 16.
2937 //
2938 // We map the non reserved clang/gnu priority range of [101, 65535] into the
2939 // sinit/sterm priority range [1024, 2147483648] by:
2940 // - directly mapping the first and the last 1024 elements of the ranges
2941 // - linear interpolating the intermediate values with a step size of 33878.
2942 unsigned int P = mapToSinitPriority(Priority);
2943
2944 std::string PrioritySuffix;
2945 llvm::raw_string_ostream os(PrioritySuffix);
2946 os << llvm::format_hex_no_prefix(P, 8);
2947 os.flush();
2948 return PrioritySuffix;
2949}
2950
2951void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
2952 const Constant *List, bool IsCtor) {
2953 SmallVector<Structor, 8> Structors;
2954 preprocessXXStructorList(DL, List, Structors);
2955 if (Structors.empty())
2956 return;
2957
2958 unsigned Index = 0;
2959 for (Structor &S : Structors) {
2960 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
2961 S.Func = CE->getOperand(0);
2962
2965 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
2966 llvm::Twine(convertToSinitPriority(S.Priority)) +
2967 llvm::Twine("_", FormatIndicatorAndUniqueModId) +
2968 llvm::Twine("_", llvm::utostr(Index++)),
2969 cast<Function>(S.Func));
2970 }
2971}
2972
2973void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV,
2974 unsigned Encoding) {
2975 if (GV) {
2976 TOCEntryType GlobalType = TOCType_GlobalInternal;
2978 if (Linkage == GlobalValue::ExternalLinkage ||
2981 GlobalType = TOCType_GlobalExternal;
2982 MCSymbol *TypeInfoSym = TM.getSymbol(GV);
2983 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym, GlobalType);
2984 const MCSymbol *TOCBaseSym =
2985 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2986 ->getQualNameSymbol();
2987 auto &Ctx = OutStreamer->getContext();
2988 const MCExpr *Exp =
2990 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2991 OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding));
2992 } else
2993 OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding));
2994}
2995
2996// Return a pass that prints the PPC assembly code for a MachineFunction to the
2997// given output stream.
2998static AsmPrinter *
3000 std::unique_ptr<MCStreamer> &&Streamer) {
3001 if (tm.getTargetTriple().isOSAIX())
3002 return new PPCAIXAsmPrinter(tm, std::move(Streamer));
3003
3004 return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
3005}
3006
3007void PPCAIXAsmPrinter::emitModuleCommandLines(Module &M) {
3008 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3009 if (!NMD || !NMD->getNumOperands())
3010 return;
3011
3012 std::string S;
3013 raw_string_ostream RSOS(S);
3014 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3015 const MDNode *N = NMD->getOperand(i);
3016 assert(N->getNumOperands() == 1 &&
3017 "llvm.commandline metadata entry can have only one operand");
3018 const MDString *MDS = cast<MDString>(N->getOperand(0));
3019 // Add "@(#)" to support retrieving the command line information with the
3020 // AIX "what" command
3021 RSOS << "@(#)opt " << MDS->getString() << "\n";
3022 RSOS.write('\0');
3023 }
3024 OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
3025}
3026
3027// Force static initialization.
3037}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:477
IRTranslator LLVM IR MI
#define RegName(no)
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
static std::string getRegisterName(const TargetRegisterInfo *TRI, Register Reg)
Definition: MIParser.cpp:1413
This file implements a map that provides insertion order iteration.
Module.h This file contains the declarations for the Module class.
#define P(N)
static void collectTOCStats(PPCAsmPrinter::TOCEntryType Type)
static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV)
static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter()
#define GENBOOLCOMMENT(Prefix, V, Field)
static bool hasTLSFlag(const MachineOperand &MO)
static MCSymbol * getMCSymbolForTOCPseudoMO(const MachineOperand &MO, AsmPrinter &AP)
Map a machine operand for a TOC pseudo-machine instruction to its corresponding MCSymbol.
static AsmPrinter * createPPCAsmPrinterPass(TargetMachine &tm, std::unique_ptr< MCStreamer > &&Streamer)
static PPCAsmPrinter::TOCEntryType getTOCEntryTypeForMO(const MachineOperand &MO)
static std::string convertToSinitPriority(int Priority)
static MCSymbol * createMCSymbolForTlsGetAddr(MCContext &Ctx, unsigned MIOpc)
This helper function creates the TlsGetAddr MCSymbol for AIX.
#define GENVALUECOMMENT(PrefixAndName, V, Field)
static unsigned mapToSinitPriority(int P)
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)
const char LLVMTargetMachineRef TM
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
Provides a library for accessing information about this process and other processes on the operating ...
static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, const RISCVSubtarget &Subtarget)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
Value * RHS
static constexpr uint32_t Opcode
Definition: aarch32.h:200
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:84
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:571
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:679
void emitXRayTable()
Emit a table with all XRay instrumentation points.
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
virtual void emitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
Definition: AsmPrinter.h:547
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:431
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition: AsmPrinter.h:399
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1002
This is an important base class in LLVM.
Definition: Constant.h:41
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
reference get()
Returns a reference to the stored T value.
Definition: Error.h:571
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:506
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:79
bool hasComdat() const
Definition: GlobalObject.h:127
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:244
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:273
LinkageTypes getLinkage() const
Definition: GlobalValue.h:541
bool hasDefaultVisibility() const
Definition: GlobalValue.h:245
bool hasDLLExportStorageClass() const
Definition: GlobalValue.h:277
bool isDeclarationForLinker() const
Definition: GlobalValue.h:614
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:367
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:63
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:64
@ ProtectedVisibility
The GV is protected.
Definition: GlobalValue.h:65
bool hasCommonLinkage() const
Definition: GlobalValue.h:527
bool hasAppendingLinkage() const
Definition: GlobalValue.h:520
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:58
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:53
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:54
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:49
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:57
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
Type * getValueType() const
Definition: GlobalValue.h:292
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
bool hasInitializer() const
Definitions have initializers, declarations don't.
Binary assembler expressions.
Definition: MCExpr.h:484
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:634
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:528
Opcode getOpcode() const
Get the kind of this binary expression.
Definition: MCExpr.h:628
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:613
@ Add
Addition.
Definition: MCExpr.h:487
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:76
MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, const char *BeginSymName=nullptr, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
Definition: MCContext.cpp:773
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
MCInstBuilder & addReg(unsigned Reg)
Add a new register operand.
Definition: MCInstBuilder.h:31
MCInstBuilder & addImm(int64_t Val)
Add a new integer immediate operand.
Definition: MCInstBuilder.h:37
MCInstBuilder & addExpr(const MCExpr *Val)
Add a new MCExpr operand.
Definition: MCInstBuilder.h:55
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
void setOpcode(unsigned Op)
Definition: MCInst.h:197
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:36
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:162
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:69
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:26
MCSymbolXCOFF * getQualNameSymbol() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
void setAlignment(Align Value)
Definition: MCSection.h:141
void ensureMinAlignment(Align MinAlignment)
Makes sure that Alignment is at least MinAlignment.
Definition: MCSection.h:144
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:389
StringRef getSymbolTableName() const
Definition: MCSymbolXCOFF.h:59
void setStorageClass(XCOFF::StorageClass SC)
Definition: MCSymbolXCOFF.h:36
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:58
Metadata node.
Definition: Metadata.h:1037
A single uniqued string.
Definition: Metadata.h:698
StringRef getString() const
Definition: Metadata.cpp:569
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MCSection * getSection() const
Returns the Section this function belongs to.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Representation of each machine instruction.
Definition: MachineInstr.h:68
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
const BlockAddress * getBlockAddress() const
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:275
A tuple of MDNodes.
Definition: Metadata.h:1692
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1341
unsigned getNumOperands() const
Definition: Metadata.cpp:1337
uint64_t getTOCSaveOffset() const
getTOCSaveOffset - Return the previous frame offset to save the TOC register – 64-bit SVR4 ABI only.
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
MCSymbol * getPICOffsetSymbol(MachineFunction &MF) const
const SmallVectorImpl< Register > & getMustSaveCRs() const
unsigned getFloatingPointParmsNum() const
MCSymbol * getGlobalEPSymbol(MachineFunction &MF) const
MCSymbol * getLocalEPSymbol(MachineFunction &MF) const
unsigned getVectorParmsNum() const
uint32_t getVecExtParmsType() const
MCSymbol * getTOCOffsetSymbol(MachineFunction &MF) const
unsigned getFixedParmsNum() const
static const char * getRegisterName(MCRegister Reg)
static const PPCMCExpr * createLo(const MCExpr *Expr, MCContext &Ctx)
Definition: PPCMCExpr.h:49
static const PPCMCExpr * createHa(const MCExpr *Expr, MCContext &Ctx)
Definition: PPCMCExpr.h:57
bool is32BitELFABI() const
Definition: PPCSubtarget.h:219
bool isAIXABI() const
Definition: PPCSubtarget.h:214
const PPCFrameLowering * getFrameLowering() const override
Definition: PPCSubtarget.h:142
bool isPPC64() const
isPPC64 - Return true if we are generating code for 64-bit pointer mode.
bool isUsingPCRelativeCalls() const
bool isELFv2ABI() const
const PPCRegisterInfo * getRegisterInfo() const override
Definition: PPCSubtarget.h:152
bool isGVIndirectSymbol(const GlobalValue *GV) const
True if the GV will be accessed via an indirect symbol.
Common code between 32-bit and 64-bit PowerPC targets.
virtual void emitAbiVersion(int AbiVersion)
virtual void emitTCEntry(const MCSymbol &S, MCSymbolRefExpr::VariantKind Kind)
virtual void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset)
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
MI-level patchpoint operands.
Definition: StackMaps.h:76
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
bool isThreadBSSLocal() const
Definition: SectionKind.h:163
static SectionKind getText()
Definition: SectionKind.h:190
bool isBSSLocal() const
Definition: SectionKind.h:170
static SectionKind getData()
Definition: SectionKind.h:213
bool isThreadLocal() const
Definition: SectionKind.h:157
bool isReadOnly() const
Definition: SectionKind.h:131
bool isGlobalWriteableData() const
Definition: SectionKind.h:165
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:451
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
void recordPatchPoint(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a patchpoint instruction.
Definition: StackMaps.cpp:554
void recordStackMap(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a stackmap instruction.
Definition: StackMaps.cpp:544
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:575
bool startswith(StringRef Prefix) const
Definition: StringRef.h:261
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:90
static bool ShouldSetSSPCanaryBitInTB(const MachineFunction *MF)
static MCSymbol * getEHInfoTableSymbol(const MachineFunction *MF)
static XCOFF::StorageClass getStorageClassForGlobal(const GlobalValue *GV)
static bool ShouldEmitEHBlock(const MachineFunction *MF)
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:78
const Triple & getTargetTriple() const
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:669
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:4832
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:926
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4915
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:642
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
static Pid getProcessId()
Get the process's identifier.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHT_PROGBITS
Definition: ELF.h:1004
@ SHF_ALLOC
Definition: ELF.h:1093
@ SHF_WRITE
Definition: ELF.h:1090
const uint64_t Version
Definition: InstrProf.h:1027
@ MO_TLSLD_LO
Definition: PPC.h:173
@ MO_TLSGDM_FLAG
MO_TLSGDM_FLAG - If this bit is set the symbol reference is relative to the region handle of TLS Gene...
Definition: PPC.h:143
@ MO_TLSLD_FLAG
MO_TLSLD_FLAG - If this bit is set the symbol reference is relative to TLS Local Dynamic model.
Definition: PPC.h:139
@ MO_TPREL_HA
Definition: PPC.h:168
@ MO_DTPREL_LO
These values identify relocations on immediates folded into memory operations.
Definition: PPC.h:172
@ MO_TLS
Definition: PPC.h:177
@ MO_TPREL_FLAG
MO_TPREL_FLAG - If this bit is set, the symbol reference is relative to the thread pointer and the sy...
Definition: PPC.h:135
@ MO_TPREL_LO
Definition: PPC.h:167
@ MO_GOT_TLSLD_PCREL_FLAG
MO_GOT_TLSLD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition: PPC.h:153
@ MO_TLSGD_FLAG
MO_TLSGD_FLAG - If this bit is set the symbol reference is relative to TLS General Dynamic model for ...
Definition: PPC.h:130
@ MO_GOT_TLSGD_PCREL_FLAG
MO_GOT_TLSGD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition: PPC.h:148
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
const char * stripRegisterPrefix(const char *RegName)
stripRegisterPrefix - This method strips the character prefix from a register name so that only the n...
Predicate InvertPredicate(Predicate Opcode)
Invert the specified predicate. != -> ==, < -> >=.
static bool isVRRegister(unsigned Reg)
static bool isVFRegister(unsigned Reg)
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
SmallString< 32 > getExtendedTBTableFlagString(uint8_t Flag)
Definition: XCOFF.cpp:162
Expected< SmallString< 32 > > parseParmsTypeWithVecInfo(uint32_t Value, unsigned FixedParmsNum, unsigned FloatingParmsNum, unsigned VectorParmsNum)
Definition: XCOFF.cpp:188
Expected< SmallString< 32 > > parseParmsType(uint32_t Value, unsigned FixedParmsNum, unsigned FloatingParmsNum)
Definition: XCOFF.cpp:110
Expected< SmallString< 32 > > parseVectorParmsType(uint32_t Value, unsigned ParmsNum)
Definition: XCOFF.cpp:240
@ XMC_RW
Read Write Data.
Definition: XCOFF.h:116
@ XMC_RO
Read Only Constant.
Definition: XCOFF.h:105
@ XMC_PR
Program Code.
Definition: XCOFF.h:104
StringRef getNameForTracebackTableLanguageId(TracebackTable::LanguageID LangId)
Definition: XCOFF.cpp:87
constexpr uint8_t AllocRegNo
Definition: XCOFF.h:43
@ XTY_SD
Csect definition for initialized storage.
Definition: XCOFF.h:241
@ XTY_ER
External reference.
Definition: XCOFF.h:240
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
static unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
Definition: DenseMapInfo.h:29
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
Target & getThePPC64LETarget()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1684
bool LowerPPCMachineOperandToMCOperand(const MachineOperand &MO, MCOperand &OutMO, AsmPrinter &AP)
Target & getThePPC32Target()
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
void LowerPPCMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI, AsmPrinter &AP)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:200
Target & getThePPC64Target()
uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
Definition: Threading.cpp:33
std::pair< MCSection *, const MCExpr * > MCSectionSubPair
Definition: MCStreamer.h:66
Target & getThePPC32LETarget()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1853
MCSymbolAttr
Definition: MCDirectives.h:18
@ MCSA_Weak
.weak
Definition: MCDirectives.h:45
@ MCSA_Global
.type _foo, @gnu_unique_object
Definition: MCDirectives.h:30
@ MCSA_Extern
.extern (XCOFF)
Definition: MCDirectives.h:32
@ MCSA_LGlobal
.lglobl (XCOFF)
Definition: MCDirectives.h:31
@ MCSA_Invalid
Not a valid directive.
Definition: MCDirectives.h:19
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
std::pair< const MCSymbol *, MCSymbolRefExpr::VariantKind > TOCKey
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:50
static void RegisterAsmPrinter(Target &T, Target::AsmPrinterCtorTy Fn)
RegisterAsmPrinter - Register an AsmPrinter implementation for the given target.
static constexpr uint32_t FPRSavedMask
Definition: XCOFF.h:411
static constexpr uint16_t NumberOfVRSavedMask
Definition: XCOFF.h:441
static constexpr uint8_t NumberOfFloatingPointParmsShift
Definition: XCOFF.h:427
static constexpr uint32_t NumberOfFixedParmsMask
Definition: XCOFF.h:421
static constexpr uint16_t HasVMXInstructionMask
Definition: XCOFF.h:447
static constexpr uint32_t IsLRSavedMask
Definition: XCOFF.h:405
static constexpr uint16_t HasVarArgsMask
Definition: XCOFF.h:443
static constexpr uint32_t IsAllocaUsedMask
Definition: XCOFF.h:402
static constexpr uint16_t IsVRSavedOnStackMask
Definition: XCOFF.h:442
static constexpr uint16_t NumberOfVectorParmsMask
Definition: XCOFF.h:446
static constexpr uint32_t IsFloatingPointPresentMask
Definition: XCOFF.h:395
static constexpr uint32_t FPRSavedShift
Definition: XCOFF.h:412
static constexpr uint32_t NumberOfFloatingPointParmsMask
Definition: XCOFF.h:425
static constexpr uint32_t HasControlledStorageMask
Definition: XCOFF.h:393
static constexpr uint32_t HasExtensionTableMask
Definition: XCOFF.h:415
static constexpr uint32_t HasTraceBackTableOffsetMask
Definition: XCOFF.h:391
static constexpr uint32_t IsCRSavedMask
Definition: XCOFF.h:404
static constexpr uint8_t NumberOfFixedParmsShift
Definition: XCOFF.h:422
static constexpr uint32_t GPRSavedMask
Definition: XCOFF.h:417
static constexpr uint8_t NumberOfVectorParmsShift
Definition: XCOFF.h:448
static constexpr uint32_t HasParmsOnStackMask
Definition: XCOFF.h:426
static constexpr uint32_t IsFunctionNamePresentMask
Definition: XCOFF.h:401
static constexpr uint32_t IsBackChainStoredMask
Definition: XCOFF.h:409
static constexpr uint32_t IsInterruptHandlerMask
Definition: XCOFF.h:400
static constexpr uint32_t HasVectorInfoMask
Definition: XCOFF.h:416
static constexpr uint8_t NumberOfVRSavedShift
Definition: XCOFF.h:444
static constexpr uint32_t GPRSavedShift
Definition: XCOFF.h:418