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