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"
30#include "llvm/ADT/SetVector.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 *getAdjustedFasterLocalExpr(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 SmallSetVector<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 HasAIXSmallLocalTLS = Subtarget->hasAIXSmallLocalExecTLS() ||
807 Subtarget->hasAIXSmallLocalDynamicTLS();
808 const Module *M = MF->getFunction().getParent();
809 PICLevel::Level PL = M->getPICLevel();
810
811#ifndef NDEBUG
812 // Validate that SPE and FPU are mutually exclusive in codegen
813 if (!MI->isInlineAsm()) {
814 for (const MachineOperand &MO: MI->operands()) {
815 if (MO.isReg()) {
816 Register Reg = MO.getReg();
817 if (Subtarget->hasSPE()) {
818 if (PPC::F4RCRegClass.contains(Reg) ||
819 PPC::F8RCRegClass.contains(Reg) ||
820 PPC::VFRCRegClass.contains(Reg) ||
821 PPC::VRRCRegClass.contains(Reg) ||
822 PPC::VSFRCRegClass.contains(Reg) ||
823 PPC::VSSRCRegClass.contains(Reg)
824 )
825 llvm_unreachable("SPE targets cannot have FPRegs!");
826 } else {
827 if (PPC::SPERCRegClass.contains(Reg))
828 llvm_unreachable("SPE register found in FPU-targeted code!");
829 }
830 }
831 }
832 }
833#endif
834
835 auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
836 ptrdiff_t OriginalOffset) {
837 // Apply an offset to the TOC-based expression such that the adjusted
838 // notional offset from the TOC base (to be encoded into the instruction's D
839 // or DS field) is the signed 16-bit truncation of the original notional
840 // offset from the TOC base.
841 // This is consistent with the treatment used both by XL C/C++ and
842 // by AIX ld -r.
843 ptrdiff_t Adjustment =
844 OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
846 Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
847 };
848
849 auto getTOCEntryLoadingExprForXCOFF =
850 [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
851 this](const MCSymbol *MOSymbol, const MCExpr *Expr,
853 MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
854 const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
855 const auto TOCEntryIter = TOC.find({MOSymbol, VK});
856 assert(TOCEntryIter != TOC.end() &&
857 "Could not find the TOC entry for this symbol.");
858 const ptrdiff_t EntryDistanceFromTOCBase =
859 (TOCEntryIter - TOC.begin()) * EntryByteSize;
860 constexpr int16_t PositiveTOCRange = INT16_MAX;
861
862 if (EntryDistanceFromTOCBase > PositiveTOCRange)
863 return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
864
865 return Expr;
866 };
867 auto GetVKForMO = [&](const MachineOperand &MO) {
868 // For TLS initial-exec and local-exec accesses on AIX, we have one TOC
869 // entry for the symbol (with the variable offset), which is differentiated
870 // by MO_TPREL_FLAG.
871 unsigned Flag = MO.getTargetFlags();
872 if (Flag == PPCII::MO_TPREL_FLAG ||
875 assert(MO.isGlobal() && "Only expecting a global MachineOperand here!\n");
876 TLSModel::Model Model = TM.getTLSModel(MO.getGlobal());
877 if (Model == TLSModel::LocalExec)
878 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLE;
879 if (Model == TLSModel::InitialExec)
880 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSIE;
881 // On AIX, TLS model opt may have turned local-dynamic accesses into
882 // initial-exec accesses.
883 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
884 if (Model == TLSModel::LocalDynamic &&
885 FuncInfo->isAIXFuncUseTLSIEForLD()) {
887 dbgs() << "Current function uses IE access for default LD vars.\n");
888 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSIE;
889 }
890 llvm_unreachable("Only expecting local-exec or initial-exec accesses!");
891 }
892 // For GD TLS access on AIX, we have two TOC entries for the symbol (one for
893 // the variable offset and the other for the region handle). They are
894 // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
895 if (Flag == PPCII::MO_TLSGDM_FLAG)
896 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
898 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
899 // For local-dynamic TLS access on AIX, we have one TOC entry for the symbol
900 // (the variable offset) and one shared TOC entry for the module handle.
901 // They are differentiated by MO_TLSLD_FLAG and MO_TLSLDM_FLAG.
902 if (Flag == PPCII::MO_TLSLD_FLAG && IsAIX)
903 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLD;
904 if (Flag == PPCII::MO_TLSLDM_FLAG && IsAIX)
905 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSML;
906 return MCSymbolRefExpr::VariantKind::VK_None;
907 };
908
909 // Lower multi-instruction pseudo operations.
910 switch (MI->getOpcode()) {
911 default: break;
912 case TargetOpcode::DBG_VALUE:
913 llvm_unreachable("Should be handled target independently");
914 case TargetOpcode::STACKMAP:
915 return LowerSTACKMAP(SM, *MI);
916 case TargetOpcode::PATCHPOINT:
917 return LowerPATCHPOINT(SM, *MI);
918
919 case PPC::MoveGOTtoLR: {
920 // Transform %lr = MoveGOTtoLR
921 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
922 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
923 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
924 // blrl
925 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
926 MCSymbol *GOTSymbol =
927 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
928 const MCExpr *OffsExpr =
931 OutContext),
932 MCConstantExpr::create(4, OutContext),
933 OutContext);
934
935 // Emit the 'bl'.
936 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
937 return;
938 }
939 case PPC::MovePCtoLR:
940 case PPC::MovePCtoLR8: {
941 // Transform %lr = MovePCtoLR
942 // Into this, where the label is the PIC base:
943 // bl L1$pb
944 // L1$pb:
945 MCSymbol *PICBase = MF->getPICBaseSymbol();
946
947 // Emit the 'bl'.
948 EmitToStreamer(*OutStreamer,
949 MCInstBuilder(PPC::BL)
950 // FIXME: We would like an efficient form for this, so we
951 // don't have to do a lot of extra uniquing.
952 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
953
954 // Emit the label.
955 OutStreamer->emitLabel(PICBase);
956 return;
957 }
958 case PPC::UpdateGBR: {
959 // Transform %rd = UpdateGBR(%rt, %ri)
960 // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
961 // add %rd, %rt, %ri
962 // or into (if secure plt mode is on):
963 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
964 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
965 // Get the offset from the GOT Base Register to the GOT
966 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
967 if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
968 unsigned PICR = TmpInst.getOperand(0).getReg();
969 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
970 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
971 : ".LTOC");
972 const MCExpr *PB =
973 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
974
975 const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
976 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
977
978 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
979 EmitToStreamer(
980 *OutStreamer,
981 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
982
983 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
984 EmitToStreamer(
985 *OutStreamer,
986 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
987 return;
988 } else {
989 MCSymbol *PICOffset =
990 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
991 TmpInst.setOpcode(PPC::LWZ);
992 const MCExpr *Exp =
994 const MCExpr *PB =
995 MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
997 OutContext);
998 const MCOperand TR = TmpInst.getOperand(1);
999 const MCOperand PICR = TmpInst.getOperand(0);
1000
1001 // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
1002 TmpInst.getOperand(1) =
1004 TmpInst.getOperand(0) = TR;
1005 TmpInst.getOperand(2) = PICR;
1006 EmitToStreamer(*OutStreamer, TmpInst);
1007
1008 TmpInst.setOpcode(PPC::ADD4);
1009 TmpInst.getOperand(0) = PICR;
1010 TmpInst.getOperand(1) = TR;
1011 TmpInst.getOperand(2) = PICR;
1012 EmitToStreamer(*OutStreamer, TmpInst);
1013 return;
1014 }
1015 }
1016 case PPC::LWZtoc: {
1017 // Transform %rN = LWZtoc @op1, %r2
1018 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1019
1020 // Change the opcode to LWZ.
1021 TmpInst.setOpcode(PPC::LWZ);
1022
1023 const MachineOperand &MO = MI->getOperand(1);
1024 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1025 "Invalid operand for LWZtoc.");
1026
1027 // Map the operand to its corresponding MCSymbol.
1028 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1029
1030 // Create a reference to the GOT entry for the symbol. The GOT entry will be
1031 // synthesized later.
1032 if (PL == PICLevel::SmallPIC && !IsAIX) {
1033 const MCExpr *Exp =
1035 OutContext);
1036 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1037 EmitToStreamer(*OutStreamer, TmpInst);
1038 return;
1039 }
1040
1041 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1042
1043 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
1044 // storage allocated in the TOC which contains the address of
1045 // 'MOSymbol'. Said TOC entry will be synthesized later.
1046 MCSymbol *TOCEntry =
1047 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1048 const MCExpr *Exp =
1050
1051 // AIX uses the label directly as the lwz displacement operand for
1052 // references into the toc section. The displacement value will be generated
1053 // relative to the toc-base.
1054 if (IsAIX) {
1055 assert(
1056 getCodeModel(*Subtarget, TM, MO) == CodeModel::Small &&
1057 "This pseudo should only be selected for 32-bit small code model.");
1058 Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
1059 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1060
1061 // Print MO for better readability
1062 if (isVerbose())
1063 OutStreamer->getCommentOS() << MO << '\n';
1064 EmitToStreamer(*OutStreamer, TmpInst);
1065 return;
1066 }
1067
1068 // Create an explicit subtract expression between the local symbol and
1069 // '.LTOC' to manifest the toc-relative offset.
1071 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
1072 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
1073 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1074 EmitToStreamer(*OutStreamer, TmpInst);
1075 return;
1076 }
1077 case PPC::ADDItoc:
1078 case PPC::ADDItoc8: {
1079 assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
1080 "PseudoOp only valid for small code model AIX");
1081
1082 // Transform %rN = ADDItoc/8 @op1, %r2.
1083 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1084
1085 // Change the opcode to load address.
1086 TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
1087
1088 const MachineOperand &MO = MI->getOperand(1);
1089 assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
1090
1091 // Map the operand to its corresponding MCSymbol.
1092 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1093
1094 const MCExpr *Exp =
1096
1097 TmpInst.getOperand(1) = TmpInst.getOperand(2);
1098 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1099 EmitToStreamer(*OutStreamer, TmpInst);
1100 return;
1101 }
1102 case PPC::LDtocJTI:
1103 case PPC::LDtocCPT:
1104 case PPC::LDtocBA:
1105 case PPC::LDtoc: {
1106 // Transform %x3 = LDtoc @min1, %x2
1107 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1108
1109 // Change the opcode to LD.
1110 TmpInst.setOpcode(PPC::LD);
1111
1112 const MachineOperand &MO = MI->getOperand(1);
1113 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1114 "Invalid operand!");
1115
1116 // Map the operand to its corresponding MCSymbol.
1117 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1118
1119 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1120
1121 // Map the machine operand to its corresponding MCSymbol, then map the
1122 // global address operand to be a reference to the TOC entry we will
1123 // synthesize later.
1124 MCSymbol *TOCEntry =
1125 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1126
1129 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
1130 TmpInst.getOperand(1) = MCOperand::createExpr(
1131 IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
1132
1133 // Print MO for better readability
1134 if (isVerbose() && IsAIX)
1135 OutStreamer->getCommentOS() << MO << '\n';
1136 EmitToStreamer(*OutStreamer, TmpInst);
1137 return;
1138 }
1139 case PPC::ADDIStocHA: {
1140 const MachineOperand &MO = MI->getOperand(2);
1141
1142 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1143 "Invalid operand for ADDIStocHA.");
1144 assert((IsAIX && !IsPPC64 &&
1145 getCodeModel(*Subtarget, TM, MO) == CodeModel::Large) &&
1146 "This pseudo should only be selected for 32-bit large code model on"
1147 " AIX.");
1148
1149 // Transform %rd = ADDIStocHA %rA, @sym(%r2)
1150 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1151
1152 // Change the opcode to ADDIS.
1153 TmpInst.setOpcode(PPC::ADDIS);
1154
1155 // Map the machine operand to its corresponding MCSymbol.
1156 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1157
1158 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1159
1160 // If the symbol isn't toc-data then use the TOC on AIX.
1161 // Map the global address operand to be a reference to the TOC entry we
1162 // will synthesize later. 'TOCEntry' is a label used to reference the
1163 // storage allocated in the TOC which contains the address of 'MOSymbol'.
1164 // If the toc-data attribute is used, the TOC entry contains the data
1165 // rather than the address of the MOSymbol.
1166 if (![](const MachineOperand &MO) {
1167 if (!MO.isGlobal())
1168 return false;
1169
1170 const GlobalVariable *GV = dyn_cast<GlobalVariable>(MO.getGlobal());
1171 if (!GV)
1172 return false;
1173
1174 return GV->hasAttribute("toc-data");
1175 }(MO)) {
1176 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1177 }
1178
1180 MOSymbol, MCSymbolRefExpr::VK_PPC_U, OutContext);
1181 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1182 EmitToStreamer(*OutStreamer, TmpInst);
1183 return;
1184 }
1185 case PPC::LWZtocL: {
1186 const MachineOperand &MO = MI->getOperand(1);
1187
1188 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1189 "Invalid operand for LWZtocL.");
1190 assert(IsAIX && !IsPPC64 &&
1191 getCodeModel(*Subtarget, TM, MO) == CodeModel::Large &&
1192 "This pseudo should only be selected for 32-bit large code model on"
1193 " AIX.");
1194
1195 // Transform %rd = LWZtocL @sym, %rs.
1196 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1197
1198 // Change the opcode to lwz.
1199 TmpInst.setOpcode(PPC::LWZ);
1200
1201 // Map the machine operand to its corresponding MCSymbol.
1202 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1203
1204 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1205
1206 // Always use TOC on AIX. Map the global address operand to be a reference
1207 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1208 // reference the storage allocated in the TOC which contains the address of
1209 // 'MOSymbol'.
1210 MCSymbol *TOCEntry =
1211 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1212 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1214 OutContext);
1215 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1216 EmitToStreamer(*OutStreamer, TmpInst);
1217 return;
1218 }
1219 case PPC::ADDIStocHA8: {
1220 // Transform %xd = ADDIStocHA8 %x2, @sym
1221 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1222
1223 // Change the opcode to ADDIS8. If the global address is the address of
1224 // an external symbol, is a jump table address, is a block address, or is a
1225 // constant pool index with large code model enabled, then generate a TOC
1226 // entry and reference that. Otherwise, reference the symbol directly.
1227 TmpInst.setOpcode(PPC::ADDIS8);
1228
1229 const MachineOperand &MO = MI->getOperand(2);
1230 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1231 "Invalid operand for ADDIStocHA8!");
1232
1233 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1234
1235 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1236
1237 const bool GlobalToc =
1238 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
1239
1240 const CodeModel::Model CM =
1241 IsAIX ? getCodeModel(*Subtarget, TM, MO) : TM.getCodeModel();
1242
1243 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
1244 (MO.isCPI() && CM == CodeModel::Large))
1245 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1246
1248
1249 const MCExpr *Exp =
1250 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1251
1252 if (!MO.isJTI() && MO.getOffset())
1255 OutContext),
1256 OutContext);
1257
1258 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1259 EmitToStreamer(*OutStreamer, TmpInst);
1260 return;
1261 }
1262 case PPC::LDtocL: {
1263 // Transform %xd = LDtocL @sym, %xs
1264 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1265
1266 // Change the opcode to LD. If the global address is the address of
1267 // an external symbol, is a jump table address, is a block address, or is
1268 // a constant pool index with large code model enabled, then generate a
1269 // TOC entry and reference that. Otherwise, reference the symbol directly.
1270 TmpInst.setOpcode(PPC::LD);
1271
1272 const MachineOperand &MO = MI->getOperand(1);
1273 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
1274 MO.isBlockAddress()) &&
1275 "Invalid operand for LDtocL!");
1276
1278 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1279 "LDtocL used on symbol that could be accessed directly is "
1280 "invalid. Must match ADDIStocHA8."));
1281
1282 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1283
1284 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1285 CodeModel::Model CM =
1286 IsAIX ? getCodeModel(*Subtarget, TM, MO) : TM.getCodeModel();
1287 if (!MO.isCPI() || CM == CodeModel::Large)
1288 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1289
1291 const MCExpr *Exp =
1292 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1293 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1294 EmitToStreamer(*OutStreamer, TmpInst);
1295 return;
1296 }
1297 case PPC::ADDItocL:
1298 case PPC::ADDItocL8: {
1299 // Transform %xd = ADDItocL %xs, @sym
1300 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1301
1302 unsigned Op = MI->getOpcode();
1303
1304 // Change the opcode to load address for tocdata
1305 TmpInst.setOpcode(Op == PPC::ADDItocL8 ? PPC::ADDI8 : PPC::LA);
1306
1307 const MachineOperand &MO = MI->getOperand(2);
1308 assert((Op == PPC::ADDItocL8)
1309 ? (MO.isGlobal() || MO.isCPI())
1310 : MO.isGlobal() && "Invalid operand for ADDItocL8.");
1311 assert(!(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1312 "Interposable definitions must use indirect accesses.");
1313
1314 // Map the operand to its corresponding MCSymbol.
1315 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1316
1318 MOSymbol,
1319 Op == PPC::ADDItocL8 ? MCSymbolRefExpr::VK_PPC_TOC_LO
1321 OutContext);
1322
1323 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1324 EmitToStreamer(*OutStreamer, TmpInst);
1325 return;
1326 }
1327 case PPC::ADDISgotTprelHA: {
1328 // Transform: %xd = ADDISgotTprelHA %x2, @sym
1329 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1330 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1331 const MachineOperand &MO = MI->getOperand(2);
1332 const GlobalValue *GValue = MO.getGlobal();
1333 MCSymbol *MOSymbol = getSymbol(GValue);
1334 const MCExpr *SymGotTprel =
1336 OutContext);
1337 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1338 .addReg(MI->getOperand(0).getReg())
1339 .addReg(MI->getOperand(1).getReg())
1340 .addExpr(SymGotTprel));
1341 return;
1342 }
1343 case PPC::LDgotTprelL:
1344 case PPC::LDgotTprelL32: {
1345 // Transform %xd = LDgotTprelL @sym, %xs
1346 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1347
1348 // Change the opcode to LD.
1349 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
1350 const MachineOperand &MO = MI->getOperand(1);
1351 const GlobalValue *GValue = MO.getGlobal();
1352 MCSymbol *MOSymbol = getSymbol(GValue);
1354 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
1356 OutContext);
1357 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1358 EmitToStreamer(*OutStreamer, TmpInst);
1359 return;
1360 }
1361
1362 case PPC::PPC32PICGOT: {
1363 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1364 MCSymbol *GOTRef = OutContext.createTempSymbol();
1365 MCSymbol *NextInstr = OutContext.createTempSymbol();
1366
1367 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1368 // FIXME: We would like an efficient form for this, so we don't have to do
1369 // a lot of extra uniquing.
1370 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1371 const MCExpr *OffsExpr =
1372 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1373 MCSymbolRefExpr::create(GOTRef, OutContext),
1374 OutContext);
1375 OutStreamer->emitLabel(GOTRef);
1376 OutStreamer->emitValue(OffsExpr, 4);
1377 OutStreamer->emitLabel(NextInstr);
1378 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1379 .addReg(MI->getOperand(0).getReg()));
1380 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1381 .addReg(MI->getOperand(1).getReg())
1382 .addImm(0)
1383 .addReg(MI->getOperand(0).getReg()));
1384 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1385 .addReg(MI->getOperand(0).getReg())
1386 .addReg(MI->getOperand(1).getReg())
1387 .addReg(MI->getOperand(0).getReg()));
1388 return;
1389 }
1390 case PPC::PPC32GOT: {
1391 MCSymbol *GOTSymbol =
1392 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1393 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1394 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1395 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1396 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1397 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1398 .addReg(MI->getOperand(0).getReg())
1399 .addExpr(SymGotTlsL));
1400 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1401 .addReg(MI->getOperand(0).getReg())
1402 .addReg(MI->getOperand(0).getReg())
1403 .addExpr(SymGotTlsHA));
1404 return;
1405 }
1406 case PPC::ADDIStlsgdHA: {
1407 // Transform: %xd = ADDIStlsgdHA %x2, @sym
1408 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1409 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1410 const MachineOperand &MO = MI->getOperand(2);
1411 const GlobalValue *GValue = MO.getGlobal();
1412 MCSymbol *MOSymbol = getSymbol(GValue);
1413 const MCExpr *SymGotTlsGD =
1415 OutContext);
1416 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1417 .addReg(MI->getOperand(0).getReg())
1418 .addReg(MI->getOperand(1).getReg())
1419 .addExpr(SymGotTlsGD));
1420 return;
1421 }
1422 case PPC::ADDItlsgdL:
1423 // Transform: %xd = ADDItlsgdL %xs, @sym
1424 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l
1425 case PPC::ADDItlsgdL32: {
1426 // Transform: %rd = ADDItlsgdL32 %rs, @sym
1427 // Into: %rd = ADDI %rs, sym@got@tlsgd
1428 const MachineOperand &MO = MI->getOperand(2);
1429 const GlobalValue *GValue = MO.getGlobal();
1430 MCSymbol *MOSymbol = getSymbol(GValue);
1431 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1432 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1434 OutContext);
1435 EmitToStreamer(*OutStreamer,
1436 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1437 .addReg(MI->getOperand(0).getReg())
1438 .addReg(MI->getOperand(1).getReg())
1439 .addExpr(SymGotTlsGD));
1440 return;
1441 }
1442 case PPC::GETtlsMOD32AIX:
1443 case PPC::GETtlsMOD64AIX:
1444 // Transform: %r3 = GETtlsMODNNAIX %r3 (for NN == 32/64).
1445 // Into: BLA .__tls_get_mod()
1446 // Input parameter is a module handle (_$TLSML[TC]@ml) for all variables.
1447 case PPC::GETtlsADDR:
1448 // Transform: %x3 = GETtlsADDR %x3, @sym
1449 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1450 case PPC::GETtlsADDRPCREL:
1451 case PPC::GETtlsADDR32AIX:
1452 case PPC::GETtlsADDR64AIX:
1453 // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64).
1454 // Into: BLA .__tls_get_addr()
1455 // Unlike on Linux, there is no symbol or relocation needed for this call.
1456 case PPC::GETtlsADDR32: {
1457 // Transform: %r3 = GETtlsADDR32 %r3, @sym
1458 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1459 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1460 return;
1461 }
1462 case PPC::GETtlsTpointer32AIX: {
1463 // Transform: %r3 = GETtlsTpointer32AIX
1464 // Into: BLA .__get_tpointer()
1465 EmitAIXTlsCallHelper(MI);
1466 return;
1467 }
1468 case PPC::ADDIStlsldHA: {
1469 // Transform: %xd = ADDIStlsldHA %x2, @sym
1470 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha
1471 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1472 const MachineOperand &MO = MI->getOperand(2);
1473 const GlobalValue *GValue = MO.getGlobal();
1474 MCSymbol *MOSymbol = getSymbol(GValue);
1475 const MCExpr *SymGotTlsLD =
1477 OutContext);
1478 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1479 .addReg(MI->getOperand(0).getReg())
1480 .addReg(MI->getOperand(1).getReg())
1481 .addExpr(SymGotTlsLD));
1482 return;
1483 }
1484 case PPC::ADDItlsldL:
1485 // Transform: %xd = ADDItlsldL %xs, @sym
1486 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l
1487 case PPC::ADDItlsldL32: {
1488 // Transform: %rd = ADDItlsldL32 %rs, @sym
1489 // Into: %rd = ADDI %rs, sym@got@tlsld
1490 const MachineOperand &MO = MI->getOperand(2);
1491 const GlobalValue *GValue = MO.getGlobal();
1492 MCSymbol *MOSymbol = getSymbol(GValue);
1493 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1494 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1496 OutContext);
1497 EmitToStreamer(*OutStreamer,
1498 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1499 .addReg(MI->getOperand(0).getReg())
1500 .addReg(MI->getOperand(1).getReg())
1501 .addExpr(SymGotTlsLD));
1502 return;
1503 }
1504 case PPC::GETtlsldADDR:
1505 // Transform: %x3 = GETtlsldADDR %x3, @sym
1506 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1507 case PPC::GETtlsldADDRPCREL:
1508 case PPC::GETtlsldADDR32: {
1509 // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1510 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1511 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1512 return;
1513 }
1514 case PPC::ADDISdtprelHA:
1515 // Transform: %xd = ADDISdtprelHA %xs, @sym
1516 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha
1517 case PPC::ADDISdtprelHA32: {
1518 // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1519 // Into: %rd = ADDIS %rs, sym@dtprel@ha
1520 const MachineOperand &MO = MI->getOperand(2);
1521 const GlobalValue *GValue = MO.getGlobal();
1522 MCSymbol *MOSymbol = getSymbol(GValue);
1523 const MCExpr *SymDtprel =
1525 OutContext);
1526 EmitToStreamer(
1527 *OutStreamer,
1528 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1529 .addReg(MI->getOperand(0).getReg())
1530 .addReg(MI->getOperand(1).getReg())
1531 .addExpr(SymDtprel));
1532 return;
1533 }
1534 case PPC::PADDIdtprel: {
1535 // Transform: %rd = PADDIdtprel %rs, @sym
1536 // Into: %rd = PADDI8 %rs, sym@dtprel
1537 const MachineOperand &MO = MI->getOperand(2);
1538 const GlobalValue *GValue = MO.getGlobal();
1539 MCSymbol *MOSymbol = getSymbol(GValue);
1540 const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1541 MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1542 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1543 .addReg(MI->getOperand(0).getReg())
1544 .addReg(MI->getOperand(1).getReg())
1545 .addExpr(SymDtprel));
1546 return;
1547 }
1548
1549 case PPC::ADDIdtprelL:
1550 // Transform: %xd = ADDIdtprelL %xs, @sym
1551 // Into: %xd = ADDI8 %xs, sym@dtprel@l
1552 case PPC::ADDIdtprelL32: {
1553 // Transform: %rd = ADDIdtprelL32 %rs, @sym
1554 // Into: %rd = ADDI %rs, sym@dtprel@l
1555 const MachineOperand &MO = MI->getOperand(2);
1556 const GlobalValue *GValue = MO.getGlobal();
1557 MCSymbol *MOSymbol = getSymbol(GValue);
1558 const MCExpr *SymDtprel =
1560 OutContext);
1561 EmitToStreamer(*OutStreamer,
1562 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1563 .addReg(MI->getOperand(0).getReg())
1564 .addReg(MI->getOperand(1).getReg())
1565 .addExpr(SymDtprel));
1566 return;
1567 }
1568 case PPC::MFOCRF:
1569 case PPC::MFOCRF8:
1570 if (!Subtarget->hasMFOCRF()) {
1571 // Transform: %r3 = MFOCRF %cr7
1572 // Into: %r3 = MFCR ;; cr7
1573 unsigned NewOpcode =
1574 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1575 OutStreamer->AddComment(PPCInstPrinter::
1576 getRegisterName(MI->getOperand(1).getReg()));
1577 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1578 .addReg(MI->getOperand(0).getReg()));
1579 return;
1580 }
1581 break;
1582 case PPC::MTOCRF:
1583 case PPC::MTOCRF8:
1584 if (!Subtarget->hasMFOCRF()) {
1585 // Transform: %cr7 = MTOCRF %r3
1586 // Into: MTCRF mask, %r3 ;; cr7
1587 unsigned NewOpcode =
1588 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1589 unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1590 ->getEncodingValue(MI->getOperand(0).getReg());
1591 OutStreamer->AddComment(PPCInstPrinter::
1592 getRegisterName(MI->getOperand(0).getReg()));
1593 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1594 .addImm(Mask)
1595 .addReg(MI->getOperand(1).getReg()));
1596 return;
1597 }
1598 break;
1599 case PPC::LD:
1600 case PPC::STD:
1601 case PPC::LWA_32:
1602 case PPC::LWA: {
1603 // Verify alignment is legal, so we don't create relocations
1604 // that can't be supported.
1605 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1606 // For non-TOC-based local-exec TLS accesses with non-zero offsets, the
1607 // machine operand (which is a TargetGlobalTLSAddress) is expected to be
1608 // the same operand for both loads and stores.
1609 for (const MachineOperand &TempMO : MI->operands()) {
1610 if (((TempMO.getTargetFlags() == PPCII::MO_TPREL_FLAG ||
1611 TempMO.getTargetFlags() == PPCII::MO_TLSLD_FLAG)) &&
1612 TempMO.getOperandNo() == 1)
1613 OpNum = 1;
1614 }
1615 const MachineOperand &MO = MI->getOperand(OpNum);
1616 if (MO.isGlobal()) {
1617 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1618 if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1619 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1620 }
1621 // As these load/stores share common code with the following load/stores,
1622 // fall through to the subsequent cases in order to either process the
1623 // non-TOC-based local-exec sequence or to process the instruction normally.
1624 [[fallthrough]];
1625 }
1626 case PPC::LBZ:
1627 case PPC::LBZ8:
1628 case PPC::LHA:
1629 case PPC::LHA8:
1630 case PPC::LHZ:
1631 case PPC::LHZ8:
1632 case PPC::LWZ:
1633 case PPC::LWZ8:
1634 case PPC::STB:
1635 case PPC::STB8:
1636 case PPC::STH:
1637 case PPC::STH8:
1638 case PPC::STW:
1639 case PPC::STW8:
1640 case PPC::LFS:
1641 case PPC::STFS:
1642 case PPC::LFD:
1643 case PPC::STFD:
1644 case PPC::ADDI8: {
1645 // A faster non-TOC-based local-[exec|dynamic] sequence is represented by
1646 // `addi` or a load/store instruction (that directly loads or stores off of
1647 // the thread pointer) with an immediate operand having the
1648 // [MO_TPREL_FLAG|MO_TLSLD_FLAG]. Such instructions do not otherwise arise.
1649 if (!HasAIXSmallLocalTLS)
1650 break;
1651 bool IsMIADDI8 = MI->getOpcode() == PPC::ADDI8;
1652 unsigned OpNum = IsMIADDI8 ? 2 : 1;
1653 const MachineOperand &MO = MI->getOperand(OpNum);
1654 unsigned Flag = MO.getTargetFlags();
1655 if (Flag == PPCII::MO_TPREL_FLAG ||
1658 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1659
1660 const MCExpr *Expr = getAdjustedFasterLocalExpr(MO, MO.getOffset());
1661 if (Expr)
1662 TmpInst.getOperand(OpNum) = MCOperand::createExpr(Expr);
1663
1664 // Change the opcode to load address if the original opcode is an `addi`.
1665 if (IsMIADDI8)
1666 TmpInst.setOpcode(PPC::LA8);
1667
1668 EmitToStreamer(*OutStreamer, TmpInst);
1669 return;
1670 }
1671 // Now process the instruction normally.
1672 break;
1673 }
1674 case PPC::PseudoEIEIO: {
1675 EmitToStreamer(
1676 *OutStreamer,
1677 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1678 EmitToStreamer(
1679 *OutStreamer,
1680 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1681 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO));
1682 return;
1683 }
1684 }
1685
1686 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1687 EmitToStreamer(*OutStreamer, TmpInst);
1688}
1689
1690// For non-TOC-based local-[exec|dynamic] variables that have a non-zero offset,
1691// we need to create a new MCExpr that adds the non-zero offset to the address
1692// of the local-[exec|dynamic] variable that will be used in either an addi,
1693// load or store. However, the final displacement for these instructions must be
1694// between [-32768, 32768), so if the TLS address + its non-zero offset is
1695// greater than 32KB, a new MCExpr is produced to accommodate this situation.
1696const MCExpr *
1697PPCAsmPrinter::getAdjustedFasterLocalExpr(const MachineOperand &MO,
1698 int64_t Offset) {
1699 // Non-zero offsets (for loads, stores or `addi`) require additional handling.
1700 // When the offset is zero, there is no need to create an adjusted MCExpr.
1701 if (!Offset)
1702 return nullptr;
1703
1704 assert(MO.isGlobal() && "Only expecting a global MachineOperand here!");
1705 const GlobalValue *GValue = MO.getGlobal();
1706 TLSModel::Model Model = TM.getTLSModel(GValue);
1707 assert((Model == TLSModel::LocalExec || Model == TLSModel::LocalDynamic) &&
1708 "Only local-[exec|dynamic] accesses are handled!");
1709
1710 bool IsGlobalADeclaration = GValue->isDeclarationForLinker();
1711 // Find the GlobalVariable that corresponds to the particular TLS variable
1712 // in the TLS variable-to-address mapping. All TLS variables should exist
1713 // within this map, with the exception of TLS variables marked as extern.
1714 const auto TLSVarsMapEntryIter = TLSVarsToAddressMapping.find(GValue);
1715 if (TLSVarsMapEntryIter == TLSVarsToAddressMapping.end())
1716 assert(IsGlobalADeclaration &&
1717 "Only expecting to find extern TLS variables not present in the TLS "
1718 "variable-to-address map!");
1719
1720 unsigned TLSVarAddress =
1721 IsGlobalADeclaration ? 0 : TLSVarsMapEntryIter->second;
1722 ptrdiff_t FinalAddress = (TLSVarAddress + Offset);
1723 // If the address of the TLS variable + the offset is less than 32KB,
1724 // or if the TLS variable is extern, we simply produce an MCExpr to add the
1725 // non-zero offset to the TLS variable address.
1726 // For when TLS variables are extern, this is safe to do because we can
1727 // assume that the address of extern TLS variables are zero.
1728 const MCExpr *Expr = MCSymbolRefExpr::create(
1729 getSymbol(GValue),
1732 OutContext);
1734 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1735 if (FinalAddress >= 32768) {
1736 // Handle the written offset for cases where:
1737 // TLS variable address + Offset > 32KB.
1738
1739 // The assembly that is printed will look like:
1740 // TLSVar@le + Offset - Delta
1741 // where Delta is a multiple of 64KB: ((FinalAddress + 32768) & ~0xFFFF).
1742 ptrdiff_t Delta = ((FinalAddress + 32768) & ~0xFFFF);
1743 // Check that the total instruction displacement fits within [-32768,32768).
1744 [[maybe_unused]] ptrdiff_t InstDisp = TLSVarAddress + Offset - Delta;
1745 assert(
1746 ((InstDisp < 32768) && (InstDisp >= -32768)) &&
1747 "Expecting the instruction displacement for local-[exec|dynamic] TLS "
1748 "variables to be between [-32768, 32768)!");
1750 Expr, MCConstantExpr::create(-Delta, OutContext), OutContext);
1751 }
1752
1753 return Expr;
1754}
1755
1756void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
1757 // Emit float ABI into GNU attribute
1758 Metadata *MD = M.getModuleFlag("float-abi");
1759 MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
1760 if (!FloatABI)
1761 return;
1762 StringRef flt = FloatABI->getString();
1763 // TODO: Support emitting soft-fp and hard double/single attributes.
1764 if (flt == "doubledouble")
1765 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1766 Val_GNU_Power_ABI_HardFloat_DP |
1767 Val_GNU_Power_ABI_LDBL_IBM128);
1768 else if (flt == "ieeequad")
1769 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1770 Val_GNU_Power_ABI_HardFloat_DP |
1771 Val_GNU_Power_ABI_LDBL_IEEE128);
1772 else if (flt == "ieeedouble")
1773 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1774 Val_GNU_Power_ABI_HardFloat_DP |
1775 Val_GNU_Power_ABI_LDBL_64);
1776}
1777
1778void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1779 if (!Subtarget->isPPC64())
1780 return PPCAsmPrinter::emitInstruction(MI);
1781
1782 switch (MI->getOpcode()) {
1783 default:
1784 return PPCAsmPrinter::emitInstruction(MI);
1785 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1786 // .begin:
1787 // b .end # lis 0, FuncId[16..32]
1788 // nop # li 0, FuncId[0..15]
1789 // std 0, -8(1)
1790 // mflr 0
1791 // bl __xray_FunctionEntry
1792 // mtlr 0
1793 // .end:
1794 //
1795 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1796 // of instructions change.
1797 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1798 MCSymbol *EndOfSled = OutContext.createTempSymbol();
1799 OutStreamer->emitLabel(BeginOfSled);
1800 EmitToStreamer(*OutStreamer,
1801 MCInstBuilder(PPC::B).addExpr(
1802 MCSymbolRefExpr::create(EndOfSled, OutContext)));
1803 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1804 EmitToStreamer(
1805 *OutStreamer,
1806 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1807 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1808 EmitToStreamer(*OutStreamer,
1809 MCInstBuilder(PPC::BL8_NOP)
1810 .addExpr(MCSymbolRefExpr::create(
1811 OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1812 OutContext)));
1813 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1814 OutStreamer->emitLabel(EndOfSled);
1815 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1816 break;
1817 }
1818 case TargetOpcode::PATCHABLE_RET: {
1819 unsigned RetOpcode = MI->getOperand(0).getImm();
1820 MCInst RetInst;
1821 RetInst.setOpcode(RetOpcode);
1822 for (const auto &MO : llvm::drop_begin(MI->operands())) {
1823 MCOperand MCOp;
1824 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1825 RetInst.addOperand(MCOp);
1826 }
1827
1828 bool IsConditional;
1829 if (RetOpcode == PPC::BCCLR) {
1830 IsConditional = true;
1831 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1832 RetOpcode == PPC::TCRETURNai8) {
1833 break;
1834 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1835 IsConditional = false;
1836 } else {
1837 EmitToStreamer(*OutStreamer, RetInst);
1838 break;
1839 }
1840
1841 MCSymbol *FallthroughLabel;
1842 if (IsConditional) {
1843 // Before:
1844 // bgtlr cr0
1845 //
1846 // After:
1847 // ble cr0, .end
1848 // .p2align 3
1849 // .begin:
1850 // blr # lis 0, FuncId[16..32]
1851 // nop # li 0, FuncId[0..15]
1852 // std 0, -8(1)
1853 // mflr 0
1854 // bl __xray_FunctionExit
1855 // mtlr 0
1856 // blr
1857 // .end:
1858 //
1859 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1860 // of instructions change.
1861 FallthroughLabel = OutContext.createTempSymbol();
1862 EmitToStreamer(
1863 *OutStreamer,
1864 MCInstBuilder(PPC::BCC)
1865 .addImm(PPC::InvertPredicate(
1866 static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1867 .addReg(MI->getOperand(2).getReg())
1868 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1869 RetInst = MCInst();
1870 RetInst.setOpcode(PPC::BLR8);
1871 }
1872 // .p2align 3
1873 // .begin:
1874 // b(lr)? # lis 0, FuncId[16..32]
1875 // nop # li 0, FuncId[0..15]
1876 // std 0, -8(1)
1877 // mflr 0
1878 // bl __xray_FunctionExit
1879 // mtlr 0
1880 // b(lr)?
1881 //
1882 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1883 // of instructions change.
1884 OutStreamer->emitCodeAlignment(Align(8), &getSubtargetInfo());
1885 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1886 OutStreamer->emitLabel(BeginOfSled);
1887 EmitToStreamer(*OutStreamer, RetInst);
1888 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1889 EmitToStreamer(
1890 *OutStreamer,
1891 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1892 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1893 EmitToStreamer(*OutStreamer,
1894 MCInstBuilder(PPC::BL8_NOP)
1895 .addExpr(MCSymbolRefExpr::create(
1896 OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1897 OutContext)));
1898 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1899 EmitToStreamer(*OutStreamer, RetInst);
1900 if (IsConditional)
1901 OutStreamer->emitLabel(FallthroughLabel);
1902 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1903 break;
1904 }
1905 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1906 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1907 case TargetOpcode::PATCHABLE_TAIL_CALL:
1908 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1909 // normal function exit from a tail exit.
1910 llvm_unreachable("Tail call is handled in the normal case. See comments "
1911 "around this assert.");
1912 }
1913}
1914
1915void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1916 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1917 PPCTargetStreamer *TS =
1918 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1919 TS->emitAbiVersion(2);
1920 }
1921
1922 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1923 !isPositionIndependent())
1925
1926 if (M.getPICLevel() == PICLevel::SmallPIC)
1928
1929 OutStreamer->switchSection(OutContext.getELFSection(
1931
1932 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1933 MCSymbol *CurrentPos = OutContext.createTempSymbol();
1934
1935 OutStreamer->emitLabel(CurrentPos);
1936
1937 // The GOT pointer points to the middle of the GOT, in order to reference the
1938 // entire 64kB range. 0x8000 is the midpoint.
1939 const MCExpr *tocExpr =
1940 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1941 MCConstantExpr::create(0x8000, OutContext),
1942 OutContext);
1943
1944 OutStreamer->emitAssignment(TOCSym, tocExpr);
1945
1946 OutStreamer->switchSection(getObjFileLowering().getTextSection());
1947}
1948
1949void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1950 // linux/ppc32 - Normal entry label.
1951 if (!Subtarget->isPPC64() &&
1952 (!isPositionIndependent() ||
1953 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1955
1956 if (!Subtarget->isPPC64()) {
1957 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1958 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1959 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1960 MCSymbol *PICBase = MF->getPICBaseSymbol();
1961 OutStreamer->emitLabel(RelocSymbol);
1962
1963 const MCExpr *OffsExpr =
1965 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1966 OutContext),
1967 MCSymbolRefExpr::create(PICBase, OutContext),
1968 OutContext);
1969 OutStreamer->emitValue(OffsExpr, 4);
1970 OutStreamer->emitLabel(CurrentFnSym);
1971 return;
1972 } else
1974 }
1975
1976 // ELFv2 ABI - Normal entry label.
1977 if (Subtarget->isELFv2ABI()) {
1978 // In the Large code model, we allow arbitrary displacements between
1979 // the text section and its associated TOC section. We place the
1980 // full 8-byte offset to the TOC in memory immediately preceding
1981 // the function global entry point.
1982 if (TM.getCodeModel() == CodeModel::Large
1983 && !MF->getRegInfo().use_empty(PPC::X2)) {
1984 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1985
1986 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1987 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1988 const MCExpr *TOCDeltaExpr =
1989 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1990 MCSymbolRefExpr::create(GlobalEPSymbol,
1991 OutContext),
1992 OutContext);
1993
1994 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1995 OutStreamer->emitValue(TOCDeltaExpr, 8);
1996 }
1998 }
1999
2000 // Emit an official procedure descriptor.
2001 MCSectionSubPair Current = OutStreamer->getCurrentSection();
2002 MCSectionELF *Section = OutStreamer->getContext().getELFSection(
2004 OutStreamer->switchSection(Section);
2005 OutStreamer->emitLabel(CurrentFnSym);
2006 OutStreamer->emitValueToAlignment(Align(8));
2007 MCSymbol *Symbol1 = CurrentFnSymForSize;
2008 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
2009 // entry point.
2010 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
2011 8 /*size*/);
2012 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
2013 // Generates a R_PPC64_TOC relocation for TOC base insertion.
2014 OutStreamer->emitValue(
2016 8/*size*/);
2017 // Emit a null environment pointer.
2018 OutStreamer->emitIntValue(0, 8 /* size */);
2019 OutStreamer->switchSection(Current.first, Current.second);
2020}
2021
2022void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
2023 const DataLayout &DL = getDataLayout();
2024
2025 bool isPPC64 = DL.getPointerSizeInBits() == 64;
2026
2027 PPCTargetStreamer *TS =
2028 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2029
2030 // If we are using any values provided by Glibc at fixed addresses,
2031 // we need to ensure that the Glibc used at link time actually provides
2032 // those values. All versions of Glibc that do will define the symbol
2033 // named "__parse_hwcap_and_convert_at_platform".
2034 if (static_cast<const PPCTargetMachine &>(TM).hasGlibcHWCAPAccess())
2035 OutStreamer->emitSymbolValue(
2036 GetExternalSymbolSymbol("__parse_hwcap_and_convert_at_platform"),
2037 MAI->getCodePointerSize());
2038 emitGNUAttributes(M);
2039
2040 if (!TOC.empty()) {
2041 const char *Name = isPPC64 ? ".toc" : ".got2";
2042 MCSectionELF *Section = OutContext.getELFSection(
2044 OutStreamer->switchSection(Section);
2045 if (!isPPC64)
2046 OutStreamer->emitValueToAlignment(Align(4));
2047
2048 for (const auto &TOCMapPair : TOC) {
2049 const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first;
2050 MCSymbol *const TOCEntryLabel = TOCMapPair.second;
2051
2052 OutStreamer->emitLabel(TOCEntryLabel);
2053 if (isPPC64)
2054 TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second);
2055 else
2056 OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
2057 }
2058 }
2059
2060 PPCAsmPrinter::emitEndOfAsmFile(M);
2061}
2062
2063/// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
2064void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
2065 // In the ELFv2 ABI, in functions that use the TOC register, we need to
2066 // provide two entry points. The ABI guarantees that when calling the
2067 // local entry point, r2 is set up by the caller to contain the TOC base
2068 // for this function, and when calling the global entry point, r12 is set
2069 // up by the caller to hold the address of the global entry point. We
2070 // thus emit a prefix sequence along the following lines:
2071 //
2072 // func:
2073 // .Lfunc_gepNN:
2074 // # global entry point
2075 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
2076 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l
2077 // .Lfunc_lepNN:
2078 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
2079 // # local entry point, followed by function body
2080 //
2081 // For the Large code model, we create
2082 //
2083 // .Lfunc_tocNN:
2084 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel
2085 // func:
2086 // .Lfunc_gepNN:
2087 // # global entry point
2088 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
2089 // add r2,r2,r12
2090 // .Lfunc_lepNN:
2091 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
2092 // # local entry point, followed by function body
2093 //
2094 // This ensures we have r2 set up correctly while executing the function
2095 // body, no matter which entry point is called.
2096 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
2097 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
2098 !MF->getRegInfo().use_empty(PPC::R2);
2099 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
2100 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
2101 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
2102 Subtarget->isELFv2ABI() && UsesX2OrR2;
2103
2104 // Only do all that if the function uses R2 as the TOC pointer
2105 // in the first place. We don't need the global entry point if the
2106 // function uses R2 as an allocatable register.
2107 if (NonPCrelGEPRequired || PCrelGEPRequired) {
2108 // Note: The logic here must be synchronized with the code in the
2109 // branch-selection pass which sets the offset of the first block in the
2110 // function. This matters because it affects the alignment.
2111 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
2112 OutStreamer->emitLabel(GlobalEntryLabel);
2113 const MCSymbolRefExpr *GlobalEntryLabelExp =
2114 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
2115
2116 if (TM.getCodeModel() != CodeModel::Large) {
2117 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
2118 const MCExpr *TOCDeltaExpr =
2119 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
2120 GlobalEntryLabelExp, OutContext);
2121
2122 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
2123 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
2124 .addReg(PPC::X2)
2125 .addReg(PPC::X12)
2126 .addExpr(TOCDeltaHi));
2127
2128 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
2129 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
2130 .addReg(PPC::X2)
2131 .addReg(PPC::X2)
2132 .addExpr(TOCDeltaLo));
2133 } else {
2134 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
2135 const MCExpr *TOCOffsetDeltaExpr =
2136 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
2137 GlobalEntryLabelExp, OutContext);
2138
2139 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
2140 .addReg(PPC::X2)
2141 .addExpr(TOCOffsetDeltaExpr)
2142 .addReg(PPC::X12));
2143 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
2144 .addReg(PPC::X2)
2145 .addReg(PPC::X2)
2146 .addReg(PPC::X12));
2147 }
2148
2149 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
2150 OutStreamer->emitLabel(LocalEntryLabel);
2151 const MCSymbolRefExpr *LocalEntryLabelExp =
2152 MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
2153 const MCExpr *LocalOffsetExp =
2154 MCBinaryExpr::createSub(LocalEntryLabelExp,
2155 GlobalEntryLabelExp, OutContext);
2156
2157 PPCTargetStreamer *TS =
2158 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2159 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
2160 } else if (Subtarget->isUsingPCRelativeCalls()) {
2161 // When generating the entry point for a function we have a few scenarios
2162 // based on whether or not that function uses R2 and whether or not that
2163 // function makes calls (or is a leaf function).
2164 // 1) A leaf function that does not use R2 (or treats it as callee-saved
2165 // and preserves it). In this case st_other=0 and both
2166 // the local and global entry points for the function are the same.
2167 // No special entry point code is required.
2168 // 2) A function uses the TOC pointer R2. This function may or may not have
2169 // calls. In this case st_other=[2,6] and the global and local entry
2170 // points are different. Code to correctly setup the TOC pointer in R2
2171 // is put between the global and local entry points. This case is
2172 // covered by the if statatement above.
2173 // 3) A function does not use the TOC pointer R2 but does have calls.
2174 // In this case st_other=1 since we do not know whether or not any
2175 // of the callees clobber R2. This case is dealt with in this else if
2176 // block. Tail calls are considered calls and the st_other should also
2177 // be set to 1 in that case as well.
2178 // 4) The function does not use the TOC pointer but R2 is used inside
2179 // the function. In this case st_other=1 once again.
2180 // 5) This function uses inline asm. We mark R2 as reserved if the function
2181 // has inline asm as we have to assume that it may be used.
2182 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
2183 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
2184 PPCTargetStreamer *TS =
2185 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2186 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
2187 MCConstantExpr::create(1, OutContext));
2188 }
2189 }
2190}
2191
2192/// EmitFunctionBodyEnd - Print the traceback table before the .size
2193/// directive.
2194///
2195void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
2196 // Only the 64-bit target requires a traceback table. For now,
2197 // we only emit the word of zeroes that GDB requires to find
2198 // the end of the function, and zeroes for the eight-byte
2199 // mandatory fields.
2200 // FIXME: We should fill in the eight-byte mandatory fields as described in
2201 // the PPC64 ELF ABI (this is a low-priority item because GDB does not
2202 // currently make use of these fields).
2203 if (Subtarget->isPPC64()) {
2204 OutStreamer->emitIntValue(0, 4/*size*/);
2205 OutStreamer->emitIntValue(0, 8/*size*/);
2206 }
2207}
2208
2209void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
2210 MCSymbol *GVSym) const {
2211
2212 assert(MAI->hasVisibilityOnlyWithLinkage() &&
2213 "AIX's linkage directives take a visibility setting.");
2214
2215 MCSymbolAttr LinkageAttr = MCSA_Invalid;
2216 switch (GV->getLinkage()) {
2218 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
2219 break;
2225 LinkageAttr = MCSA_Weak;
2226 break;
2228 LinkageAttr = MCSA_Extern;
2229 break;
2231 return;
2234 "InternalLinkage should not have other visibility setting.");
2235 LinkageAttr = MCSA_LGlobal;
2236 break;
2238 llvm_unreachable("Should never emit this");
2240 llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
2241 }
2242
2243 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
2244
2245 MCSymbolAttr VisibilityAttr = MCSA_Invalid;
2246 if (!TM.getIgnoreXCOFFVisibility()) {
2249 "Cannot not be both dllexport and non-default visibility");
2250 switch (GV->getVisibility()) {
2251
2252 // TODO: "internal" Visibility needs to go here.
2254 if (GV->hasDLLExportStorageClass())
2255 VisibilityAttr = MAI->getExportedVisibilityAttr();
2256 break;
2258 VisibilityAttr = MAI->getHiddenVisibilityAttr();
2259 break;
2261 VisibilityAttr = MAI->getProtectedVisibilityAttr();
2262 break;
2263 }
2264 }
2265
2266 // Do not emit the _$TLSML symbol.
2267 if (GV->getThreadLocalMode() == GlobalVariable::LocalDynamicTLSModel &&
2268 GV->hasName() && GV->getName() == "_$TLSML")
2269 return;
2270
2271 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
2272 VisibilityAttr);
2273}
2274
2275void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
2276 // Setup CurrentFnDescSym and its containing csect.
2277 MCSectionXCOFF *FnDescSec =
2278 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
2279 &MF.getFunction(), TM));
2280 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
2281
2282 CurrentFnDescSym = FnDescSec->getQualNameSymbol();
2283
2285}
2286
2287uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() {
2288 // Calculate the number of VRs be saved.
2289 // Vector registers 20 through 31 are marked as reserved and cannot be used
2290 // in the default ABI.
2291 const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
2292 if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
2293 TM.getAIXExtendedAltivecABI()) {
2294 const MachineRegisterInfo &MRI = MF->getRegInfo();
2295 for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg)
2296 if (MRI.isPhysRegModified(Reg))
2297 // Number of VRs saved.
2298 return PPC::V31 - Reg + 1;
2299 }
2300 return 0;
2301}
2302
2303void PPCAIXAsmPrinter::emitFunctionBodyEnd() {
2304
2305 if (!TM.getXCOFFTracebackTable())
2306 return;
2307
2308 emitTracebackTable();
2309
2310 // If ShouldEmitEHBlock returns true, then the eh info table
2311 // will be emitted via `AIXException::endFunction`. Otherwise, we
2312 // need to emit a dumy eh info table when VRs are saved. We could not
2313 // consolidate these two places into one because there is no easy way
2314 // to access register information in `AIXException` class.
2316 (getNumberOfVRSaved() > 0)) {
2317 // Emit dummy EH Info Table.
2318 OutStreamer->switchSection(getObjFileLowering().getCompactUnwindSection());
2319 MCSymbol *EHInfoLabel =
2321 OutStreamer->emitLabel(EHInfoLabel);
2322
2323 // Version number.
2324 OutStreamer->emitInt32(0);
2325
2326 const DataLayout &DL = MMI->getModule()->getDataLayout();
2327 const unsigned PointerSize = DL.getPointerSize();
2328 // Add necessary paddings in 64 bit mode.
2329 OutStreamer->emitValueToAlignment(Align(PointerSize));
2330
2331 OutStreamer->emitIntValue(0, PointerSize);
2332 OutStreamer->emitIntValue(0, PointerSize);
2333 OutStreamer->switchSection(MF->getSection());
2334 }
2335}
2336
2337void PPCAIXAsmPrinter::emitTracebackTable() {
2338
2339 // Create a symbol for the end of function.
2340 MCSymbol *FuncEnd = createTempSymbol(MF->getName());
2341 OutStreamer->emitLabel(FuncEnd);
2342
2343 OutStreamer->AddComment("Traceback table begin");
2344 // Begin with a fullword of zero.
2345 OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/);
2346
2347 SmallString<128> CommentString;
2348 raw_svector_ostream CommentOS(CommentString);
2349
2350 auto EmitComment = [&]() {
2351 OutStreamer->AddComment(CommentOS.str());
2352 CommentString.clear();
2353 };
2354
2355 auto EmitCommentAndValue = [&](uint64_t Value, int Size) {
2356 EmitComment();
2357 OutStreamer->emitIntValueInHexWithPadding(Value, Size);
2358 };
2359
2360 unsigned int Version = 0;
2361 CommentOS << "Version = " << Version;
2362 EmitCommentAndValue(Version, 1);
2363
2364 // There is a lack of information in the IR to assist with determining the
2365 // source language. AIX exception handling mechanism would only search for
2366 // personality routine and LSDA area when such language supports exception
2367 // handling. So to be conservatively correct and allow runtime to do its job,
2368 // we need to set it to C++ for now.
2369 TracebackTable::LanguageID LanguageIdentifier =
2371
2372 CommentOS << "Language = "
2373 << getNameForTracebackTableLanguageId(LanguageIdentifier);
2374 EmitCommentAndValue(LanguageIdentifier, 1);
2375
2376 // This is only populated for the third and fourth bytes.
2377 uint32_t FirstHalfOfMandatoryField = 0;
2378
2379 // Emit the 3rd byte of the mandatory field.
2380
2381 // We always set traceback offset bit to true.
2382 FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask;
2383
2384 const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2385 const MachineRegisterInfo &MRI = MF->getRegInfo();
2386
2387 // Check the function uses floating-point processor instructions or not
2388 for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) {
2389 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2390 FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask;
2391 break;
2392 }
2393 }
2394
2395#define GENBOOLCOMMENT(Prefix, V, Field) \
2396 CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-") \
2397 << #Field
2398
2399#define GENVALUECOMMENT(PrefixAndName, V, Field) \
2400 CommentOS << (PrefixAndName) << " = " \
2401 << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >> \
2402 (TracebackTable::Field##Shift))
2403
2404 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage);
2405 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue);
2406 EmitComment();
2407
2408 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset);
2409 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure);
2410 EmitComment();
2411
2412 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage);
2413 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless);
2414 EmitComment();
2415
2416 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent);
2417 EmitComment();
2418 GENBOOLCOMMENT("", FirstHalfOfMandatoryField,
2419 IsFloatingPointOperationLogOrAbortEnabled);
2420 EmitComment();
2421
2422 OutStreamer->emitIntValueInHexWithPadding(
2423 (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2424
2425 // Set the 4th byte of the mandatory field.
2426 FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask;
2427
2428 const PPCRegisterInfo *RegInfo =
2429 static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo());
2430 Register FrameReg = RegInfo->getFrameRegister(*MF);
2431 if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31))
2432 FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask;
2433
2434 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
2435 if (!MustSaveCRs.empty())
2436 FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask;
2437
2438 if (FI->mustSaveLR())
2439 FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask;
2440
2441 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler);
2442 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent);
2443 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed);
2444 EmitComment();
2445 GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField,
2446 OnConditionDirective);
2447 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved);
2448 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved);
2449 EmitComment();
2450 OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff),
2451 1);
2452
2453 // Set the 5th byte of mandatory field.
2454 uint32_t SecondHalfOfMandatoryField = 0;
2455
2456 SecondHalfOfMandatoryField |= MF->getFrameInfo().getStackSize()
2458 : 0;
2459
2460 uint32_t FPRSaved = 0;
2461 for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) {
2462 if (MRI.isPhysRegModified(Reg)) {
2463 FPRSaved = PPC::F31 - Reg + 1;
2464 break;
2465 }
2466 }
2467 SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) &
2469 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored);
2470 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup);
2471 GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved);
2472 EmitComment();
2473 OutStreamer->emitIntValueInHexWithPadding(
2474 (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1);
2475
2476 // Set the 6th byte of mandatory field.
2477
2478 // Check whether has Vector Instruction,We only treat instructions uses vector
2479 // register as vector instructions.
2480 bool HasVectorInst = false;
2481 for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg)
2482 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2483 // Has VMX instruction.
2484 HasVectorInst = true;
2485 break;
2486 }
2487
2488 if (FI->hasVectorParms() || HasVectorInst)
2489 SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask;
2490
2491 uint16_t NumOfVRSaved = getNumberOfVRSaved();
2492 bool ShouldEmitEHBlock =
2494
2495 if (ShouldEmitEHBlock)
2496 SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask;
2497
2498 uint32_t GPRSaved = 0;
2499
2500 // X13 is reserved under 64-bit environment.
2501 unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13;
2502 unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31;
2503
2504 for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) {
2505 if (MRI.isPhysRegModified(Reg)) {
2506 GPRSaved = GPREnd - Reg + 1;
2507 break;
2508 }
2509 }
2510
2511 SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) &
2513
2514 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable);
2515 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo);
2516 GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved);
2517 EmitComment();
2518 OutStreamer->emitIntValueInHexWithPadding(
2519 (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1);
2520
2521 // Set the 7th byte of mandatory field.
2522 uint32_t NumberOfFixedParms = FI->getFixedParmsNum();
2523 SecondHalfOfMandatoryField |=
2524 (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) &
2526 GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField,
2527 NumberOfFixedParms);
2528 EmitComment();
2529 OutStreamer->emitIntValueInHexWithPadding(
2530 (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2531
2532 // Set the 8th byte of mandatory field.
2533
2534 // Always set parameter on stack.
2535 SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask;
2536
2537 uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum();
2538 SecondHalfOfMandatoryField |=
2541
2542 GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField,
2543 NumberOfFloatingPointParms);
2544 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack);
2545 EmitComment();
2546 OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff,
2547 1);
2548
2549 // Generate the optional fields of traceback table.
2550
2551 // Parameter type.
2552 if (NumberOfFixedParms || NumberOfFPParms) {
2553 uint32_t ParmsTypeValue = FI->getParmsType();
2554
2555 Expected<SmallString<32>> ParmsType =
2556 FI->hasVectorParms()
2558 ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms,
2559 FI->getVectorParmsNum())
2560 : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms,
2561 NumberOfFPParms);
2562
2563 assert(ParmsType && toString(ParmsType.takeError()).c_str());
2564 if (ParmsType) {
2565 CommentOS << "Parameter type = " << ParmsType.get();
2566 EmitComment();
2567 }
2568 OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue,
2569 sizeof(ParmsTypeValue));
2570 }
2571 // Traceback table offset.
2572 OutStreamer->AddComment("Function size");
2573 if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) {
2574 MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol(
2575 &(MF->getFunction()), TM);
2576 OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4);
2577 }
2578
2579 // Since we unset the Int_Handler.
2580 if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask)
2581 report_fatal_error("Hand_Mask not implement yet");
2582
2583 if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask)
2584 report_fatal_error("Ctl_Info not implement yet");
2585
2586 if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) {
2587 StringRef Name = MF->getName().substr(0, INT16_MAX);
2588 int16_t NameLength = Name.size();
2589 CommentOS << "Function name len = "
2590 << static_cast<unsigned int>(NameLength);
2591 EmitCommentAndValue(NameLength, 2);
2592 OutStreamer->AddComment("Function Name");
2593 OutStreamer->emitBytes(Name);
2594 }
2595
2596 if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) {
2597 uint8_t AllocReg = XCOFF::AllocRegNo;
2598 OutStreamer->AddComment("AllocaUsed");
2599 OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg));
2600 }
2601
2602 if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) {
2603 uint16_t VRData = 0;
2604 if (NumOfVRSaved) {
2605 // Number of VRs saved.
2606 VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) &
2608 // This bit is supposed to set only when the special register
2609 // VRSAVE is saved on stack.
2610 // However, IBM XL compiler sets the bit when any vector registers
2611 // are saved on the stack. We will follow XL's behavior on AIX
2612 // so that we don't get surprise behavior change for C code.
2614 }
2615
2616 // Set has_varargs.
2617 if (FI->getVarArgsFrameIndex())
2619
2620 // Vector parameters number.
2621 unsigned VectorParmsNum = FI->getVectorParmsNum();
2622 VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) &
2624
2625 if (HasVectorInst)
2627
2628 GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved);
2629 GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack);
2630 GENBOOLCOMMENT(", ", VRData, HasVarArgs);
2631 EmitComment();
2632 OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1);
2633
2634 GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms);
2635 GENBOOLCOMMENT(", ", VRData, HasVMXInstruction);
2636 EmitComment();
2637 OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1);
2638
2639 uint32_t VecParmTypeValue = FI->getVecExtParmsType();
2640
2641 Expected<SmallString<32>> VecParmsType =
2642 XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum);
2643 assert(VecParmsType && toString(VecParmsType.takeError()).c_str());
2644 if (VecParmsType) {
2645 CommentOS << "Vector Parameter type = " << VecParmsType.get();
2646 EmitComment();
2647 }
2648 OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue,
2649 sizeof(VecParmTypeValue));
2650 // Padding 2 bytes.
2651 CommentOS << "Padding";
2652 EmitCommentAndValue(0, 2);
2653 }
2654
2655 uint8_t ExtensionTableFlag = 0;
2656 if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) {
2657 if (ShouldEmitEHBlock)
2658 ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO;
2661 ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY;
2662
2663 CommentOS << "ExtensionTableFlag = "
2664 << getExtendedTBTableFlagString(ExtensionTableFlag);
2665 EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag));
2666 }
2667
2668 if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) {
2669 auto &Ctx = OutStreamer->getContext();
2670 MCSymbol *EHInfoSym =
2672 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym, TOCType_EHBlock);
2673 const MCSymbol *TOCBaseSym =
2674 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2675 ->getQualNameSymbol();
2676 const MCExpr *Exp =
2678 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2679
2680 const DataLayout &DL = getDataLayout();
2681 OutStreamer->emitValueToAlignment(Align(4));
2682 OutStreamer->AddComment("EHInfo Table");
2683 OutStreamer->emitValue(Exp, DL.getPointerSize());
2684 }
2685#undef GENBOOLCOMMENT
2686#undef GENVALUECOMMENT
2687}
2688
2690 return GV->hasAppendingLinkage() &&
2692 // TODO: Linker could still eliminate the GV if we just skip
2693 // handling llvm.used array. Skipping them for now until we or the
2694 // AIX OS team come up with a good solution.
2695 .Case("llvm.used", true)
2696 // It's correct to just skip llvm.compiler.used array here.
2697 .Case("llvm.compiler.used", true)
2698 .Default(false);
2699}
2700
2702 return StringSwitch<bool>(GV->getName())
2703 .Cases("llvm.global_ctors", "llvm.global_dtors", true)
2704 .Default(false);
2705}
2706
2707uint64_t PPCAIXAsmPrinter::getAliasOffset(const Constant *C) {
2708 if (auto *GA = dyn_cast<GlobalAlias>(C))
2709 return getAliasOffset(GA->getAliasee());
2710 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2711 const MCExpr *LowC = lowerConstant(CE);
2712 const MCBinaryExpr *CBE = dyn_cast<MCBinaryExpr>(LowC);
2713 if (!CBE)
2714 return 0;
2715 if (CBE->getOpcode() != MCBinaryExpr::Add)
2716 report_fatal_error("Only adding an offset is supported now.");
2717 auto *RHS = dyn_cast<MCConstantExpr>(CBE->getRHS());
2718 if (!RHS)
2719 report_fatal_error("Unable to get the offset of alias.");
2720 return RHS->getValue();
2721 }
2722 return 0;
2723}
2724
2725static void tocDataChecks(unsigned PointerSize, const GlobalVariable *GV) {
2726 // TODO: These asserts should be updated as more support for the toc data
2727 // transformation is added (struct support, etc.).
2728 assert(
2729 PointerSize >= GV->getAlign().valueOrOne().value() &&
2730 "GlobalVariables with an alignment requirement stricter than TOC entry "
2731 "size not supported by the toc data transformation.");
2732
2733 Type *GVType = GV->getValueType();
2734 assert(GVType->isSized() && "A GlobalVariable's size must be known to be "
2735 "supported by the toc data transformation.");
2736 if (GV->getParent()->getDataLayout().getTypeSizeInBits(GVType) >
2737 PointerSize * 8)
2739 "A GlobalVariable with size larger than a TOC entry is not currently "
2740 "supported by the toc data transformation.");
2741 if (GV->hasPrivateLinkage())
2742 report_fatal_error("A GlobalVariable with private linkage is not "
2743 "currently supported by the toc data transformation.");
2744}
2745
2746void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
2747 // Special LLVM global arrays have been handled at the initialization.
2749 return;
2750
2751 // If the Global Variable has the toc-data attribute, it needs to be emitted
2752 // when we emit the .toc section.
2753 if (GV->hasAttribute("toc-data")) {
2754 unsigned PointerSize = GV->getParent()->getDataLayout().getPointerSize();
2755 tocDataChecks(PointerSize, GV);
2756 TOCDataGlobalVars.push_back(GV);
2757 return;
2758 }
2759
2760 emitGlobalVariableHelper(GV);
2761}
2762
2763void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) {
2764 assert(!GV->getName().starts_with("llvm.") &&
2765 "Unhandled intrinsic global variable.");
2766
2767 if (GV->hasComdat())
2768 report_fatal_error("COMDAT not yet supported by AIX.");
2769
2770 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
2771
2772 if (GV->isDeclarationForLinker()) {
2773 emitLinkage(GV, GVSym);
2774 return;
2775 }
2776
2777 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
2778 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() &&
2779 !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS.
2780 report_fatal_error("Encountered a global variable kind that is "
2781 "not supported yet.");
2782
2783 // Print GV in verbose mode
2784 if (isVerbose()) {
2785 if (GV->hasInitializer()) {
2786 GV->printAsOperand(OutStreamer->getCommentOS(),
2787 /*PrintType=*/false, GV->getParent());
2788 OutStreamer->getCommentOS() << '\n';
2789 }
2790 }
2791
2792 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2793 getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
2794
2795 // Switch to the containing csect.
2796 OutStreamer->switchSection(Csect);
2797
2798 const DataLayout &DL = GV->getParent()->getDataLayout();
2799
2800 // Handle common and zero-initialized local symbols.
2801 if (GV->hasCommonLinkage() || GVKind.isBSSLocal() ||
2802 GVKind.isThreadBSSLocal()) {
2803 Align Alignment = GV->getAlign().value_or(DL.getPreferredAlign(GV));
2804 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
2805 GVSym->setStorageClass(
2807
2808 if (GVKind.isBSSLocal() && Csect->getMappingClass() == XCOFF::XMC_TD) {
2809 OutStreamer->emitZeros(Size);
2810 } else if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal()) {
2811 assert(Csect->getMappingClass() != XCOFF::XMC_TD &&
2812 "BSS local toc-data already handled and TLS variables "
2813 "incompatible with XMC_TD");
2814 OutStreamer->emitXCOFFLocalCommonSymbol(
2815 OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
2816 GVSym, Alignment);
2817 } else {
2818 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
2819 }
2820 return;
2821 }
2822
2823 MCSymbol *EmittedInitSym = GVSym;
2824
2825 // Emit linkage for the global variable and its aliases.
2826 emitLinkage(GV, EmittedInitSym);
2827 for (const GlobalAlias *GA : GOAliasMap[GV])
2828 emitLinkage(GA, getSymbol(GA));
2829
2830 emitAlignment(getGVAlignment(GV, DL), GV);
2831
2832 // When -fdata-sections is enabled, every GlobalVariable will
2833 // be put into its own csect; therefore, label is not necessary here.
2834 if (!TM.getDataSections() || GV->hasSection())
2835 OutStreamer->emitLabel(EmittedInitSym);
2836
2837 // No alias to emit.
2838 if (!GOAliasMap[GV].size()) {
2839 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
2840 return;
2841 }
2842
2843 // Aliases with the same offset should be aligned. Record the list of aliases
2844 // associated with the offset.
2845 AliasMapTy AliasList;
2846 for (const GlobalAlias *GA : GOAliasMap[GV])
2847 AliasList[getAliasOffset(GA->getAliasee())].push_back(GA);
2848
2849 // Emit alias label and element value for global variable.
2850 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer(),
2851 &AliasList);
2852}
2853
2854void PPCAIXAsmPrinter::emitFunctionDescriptor() {
2855 const DataLayout &DL = getDataLayout();
2856 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
2857
2858 MCSectionSubPair Current = OutStreamer->getCurrentSection();
2859 // Emit function descriptor.
2860 OutStreamer->switchSection(
2861 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
2862
2863 // Emit aliasing label for function descriptor csect.
2864 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2865 OutStreamer->emitLabel(getSymbol(Alias));
2866
2867 // Emit function entry point address.
2868 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
2869 PointerSize);
2870 // Emit TOC base address.
2871 const MCSymbol *TOCBaseSym =
2872 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2873 ->getQualNameSymbol();
2874 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
2875 PointerSize);
2876 // Emit a null environment pointer.
2877 OutStreamer->emitIntValue(0, PointerSize);
2878
2879 OutStreamer->switchSection(Current.first, Current.second);
2880}
2881
2882void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
2883 // For functions without user defined section, it's not necessary to emit the
2884 // label when we have individual function in its own csect.
2885 if (!TM.getFunctionSections() || MF->getFunction().hasSection())
2886 PPCAsmPrinter::emitFunctionEntryLabel();
2887
2888 // Emit aliasing label for function entry point label.
2889 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2890 OutStreamer->emitLabel(
2891 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
2892}
2893
2894void PPCAIXAsmPrinter::emitPGORefs(Module &M) {
2895 if (!OutContext.hasXCOFFSection(
2896 "__llvm_prf_cnts",
2898 return;
2899
2900 // When inside a csect `foo`, a .ref directive referring to a csect `bar`
2901 // translates into a relocation entry from `foo` to` bar`. The referring
2902 // csect, `foo`, is identified by its address. If multiple csects have the
2903 // same address (because one or more of them are zero-length), the referring
2904 // csect cannot be determined. Hence, we don't generate the .ref directives
2905 // if `__llvm_prf_cnts` is an empty section.
2906 bool HasNonZeroLengthPrfCntsSection = false;
2907 const DataLayout &DL = M.getDataLayout();
2908 for (GlobalVariable &GV : M.globals())
2909 if (GV.hasSection() && GV.getSection() == "__llvm_prf_cnts" &&
2910 DL.getTypeAllocSize(GV.getValueType()) > 0) {
2911 HasNonZeroLengthPrfCntsSection = true;
2912 break;
2913 }
2914
2915 if (HasNonZeroLengthPrfCntsSection) {
2916 MCSection *CntsSection = OutContext.getXCOFFSection(
2917 "__llvm_prf_cnts", SectionKind::getData(),
2919 /*MultiSymbolsAllowed*/ true);
2920
2921 OutStreamer->switchSection(CntsSection);
2922 if (OutContext.hasXCOFFSection(
2923 "__llvm_prf_data",
2925 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_data[RW]");
2926 OutStreamer->emitXCOFFRefDirective(S);
2927 }
2928 if (OutContext.hasXCOFFSection(
2929 "__llvm_prf_names",
2931 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_names[RO]");
2932 OutStreamer->emitXCOFFRefDirective(S);
2933 }
2934 if (OutContext.hasXCOFFSection(
2935 "__llvm_prf_vnds",
2937 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_vnds[RW]");
2938 OutStreamer->emitXCOFFRefDirective(S);
2939 }
2940 }
2941}
2942
2943void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
2944 // If there are no functions and there are no toc-data definitions in this
2945 // module, we will never need to reference the TOC base.
2946 if (M.empty() && TOCDataGlobalVars.empty())
2947 return;
2948
2949 emitPGORefs(M);
2950
2951 // Switch to section to emit TOC base.
2952 OutStreamer->switchSection(getObjFileLowering().getTOCBaseSection());
2953
2954 PPCTargetStreamer *TS =
2955 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2956
2957 for (auto &I : TOC) {
2958 MCSectionXCOFF *TCEntry;
2959 // Setup the csect for the current TC entry. If the variant kind is
2960 // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a
2961 // new symbol to prefix the name with a dot.
2962 // If TLS model opt is turned on, create a new symbol to prefix the name
2963 // with a dot.
2964 if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM ||
2965 (Subtarget->hasAIXShLibTLSModelOpt() &&
2966 I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLD)) {
2968 StringRef Prefix = ".";
2969 Name += Prefix;
2970 Name += cast<MCSymbolXCOFF>(I.first.first)->getSymbolTableName();
2971 MCSymbol *S = OutContext.getOrCreateSymbol(Name);
2972 TCEntry = cast<MCSectionXCOFF>(
2973 getObjFileLowering().getSectionForTOCEntry(S, TM));
2974 } else {
2975 TCEntry = cast<MCSectionXCOFF>(
2976 getObjFileLowering().getSectionForTOCEntry(I.first.first, TM));
2977 }
2978 OutStreamer->switchSection(TCEntry);
2979
2980 OutStreamer->emitLabel(I.second);
2981 TS->emitTCEntry(*I.first.first, I.first.second);
2982 }
2983
2984 // Traverse the list of global variables twice, emitting all of the
2985 // non-common global variables before the common ones, as emitting a
2986 // .comm directive changes the scope from .toc to the common symbol.
2987 for (const auto *GV : TOCDataGlobalVars) {
2988 if (!GV->hasCommonLinkage())
2989 emitGlobalVariableHelper(GV);
2990 }
2991 for (const auto *GV : TOCDataGlobalVars) {
2992 if (GV->hasCommonLinkage())
2993 emitGlobalVariableHelper(GV);
2994 }
2995}
2996
2997bool PPCAIXAsmPrinter::doInitialization(Module &M) {
2998 const bool Result = PPCAsmPrinter::doInitialization(M);
2999
3000 auto setCsectAlignment = [this](const GlobalObject *GO) {
3001 // Declarations have 0 alignment which is set by default.
3002 if (GO->isDeclarationForLinker())
3003 return;
3004
3005 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
3006 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
3007 getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
3008
3009 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
3010 Csect->ensureMinAlignment(GOAlign);
3011 };
3012
3013 // For all TLS variables, calculate their corresponding addresses and store
3014 // them into TLSVarsToAddressMapping, which will be used to determine whether
3015 // or not local-exec TLS variables require special assembly printing.
3016 uint64_t TLSVarAddress = 0;
3017 auto DL = M.getDataLayout();
3018 for (const auto &G : M.globals()) {
3019 if (G.isThreadLocal() && !G.isDeclaration()) {
3020 TLSVarAddress = alignTo(TLSVarAddress, getGVAlignment(&G, DL));
3021 TLSVarsToAddressMapping[&G] = TLSVarAddress;
3022 TLSVarAddress += DL.getTypeAllocSize(G.getValueType());
3023 }
3024 }
3025
3026 // We need to know, up front, the alignment of csects for the assembly path,
3027 // because once a .csect directive gets emitted, we could not change the
3028 // alignment value on it.
3029 for (const auto &G : M.globals()) {
3031 continue;
3032
3034 // Generate a format indicator and a unique module id to be a part of
3035 // the sinit and sterm function names.
3036 if (FormatIndicatorAndUniqueModId.empty()) {
3037 std::string UniqueModuleId = getUniqueModuleId(&M);
3038 if (UniqueModuleId != "")
3039 // TODO: Use source file full path to generate the unique module id
3040 // and add a format indicator as a part of function name in case we
3041 // will support more than one format.
3042 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
3043 else {
3044 // Use threadId, Pid, and current time as the unique module id when we
3045 // cannot generate one based on a module's strong external symbols.
3046 auto CurTime =
3047 std::chrono::duration_cast<std::chrono::nanoseconds>(
3048 std::chrono::steady_clock::now().time_since_epoch())
3049 .count();
3050 FormatIndicatorAndUniqueModId =
3051 "clangPidTidTime_" + llvm::itostr(sys::Process::getProcessId()) +
3052 "_" + llvm::itostr(llvm::get_threadid()) + "_" +
3053 llvm::itostr(CurTime);
3054 }
3055 }
3056
3057 emitSpecialLLVMGlobal(&G);
3058 continue;
3059 }
3060
3061 setCsectAlignment(&G);
3062 std::optional<CodeModel::Model> OptionalCodeModel = G.getCodeModel();
3063 if (OptionalCodeModel)
3064 setOptionalCodeModel(cast<MCSymbolXCOFF>(getSymbol(&G)),
3065 *OptionalCodeModel);
3066 }
3067
3068 for (const auto &F : M)
3069 setCsectAlignment(&F);
3070
3071 // Construct an aliasing list for each GlobalObject.
3072 for (const auto &Alias : M.aliases()) {
3073 const GlobalObject *Aliasee = Alias.getAliaseeObject();
3074 if (!Aliasee)
3076 "alias without a base object is not yet supported on AIX");
3077
3078 if (Aliasee->hasCommonLinkage()) {
3079 report_fatal_error("Aliases to common variables are not allowed on AIX:"
3080 "\n\tAlias attribute for " +
3081 Alias.getGlobalIdentifier() +
3082 " is invalid because " + Aliasee->getName() +
3083 " is common.",
3084 false);
3085 }
3086
3087 const GlobalVariable *GVar =
3088 dyn_cast_or_null<GlobalVariable>(Alias.getAliaseeObject());
3089 if (GVar) {
3090 std::optional<CodeModel::Model> OptionalCodeModel = GVar->getCodeModel();
3091 if (OptionalCodeModel)
3092 setOptionalCodeModel(cast<MCSymbolXCOFF>(getSymbol(&Alias)),
3093 *OptionalCodeModel);
3094 }
3095
3096 GOAliasMap[Aliasee].push_back(&Alias);
3097 }
3098
3099 return Result;
3100}
3101
3102void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
3103 switch (MI->getOpcode()) {
3104 default:
3105 break;
3106 case PPC::TW:
3107 case PPC::TWI:
3108 case PPC::TD:
3109 case PPC::TDI: {
3110 if (MI->getNumOperands() < 5)
3111 break;
3112 const MachineOperand &LangMO = MI->getOperand(3);
3113 const MachineOperand &ReasonMO = MI->getOperand(4);
3114 if (!LangMO.isImm() || !ReasonMO.isImm())
3115 break;
3116 MCSymbol *TempSym = OutContext.createNamedTempSymbol();
3117 OutStreamer->emitLabel(TempSym);
3118 OutStreamer->emitXCOFFExceptDirective(CurrentFnSym, TempSym,
3119 LangMO.getImm(), ReasonMO.getImm(),
3120 Subtarget->isPPC64() ? MI->getMF()->getInstructionCount() * 8 :
3121 MI->getMF()->getInstructionCount() * 4,
3122 MMI->hasDebugInfo());
3123 break;
3124 }
3125 case PPC::GETtlsMOD32AIX:
3126 case PPC::GETtlsMOD64AIX:
3127 case PPC::GETtlsTpointer32AIX:
3128 case PPC::GETtlsADDR64AIX:
3129 case PPC::GETtlsADDR32AIX: {
3130 // A reference to .__tls_get_mod/.__tls_get_addr/.__get_tpointer is unknown
3131 // to the assembler so we need to emit an external symbol reference.
3132 MCSymbol *TlsGetAddr =
3133 createMCSymbolForTlsGetAddr(OutContext, MI->getOpcode());
3134 ExtSymSDNodeSymbols.insert(TlsGetAddr);
3135 break;
3136 }
3137 case PPC::BL8:
3138 case PPC::BL:
3139 case PPC::BL8_NOP:
3140 case PPC::BL_NOP: {
3141 const MachineOperand &MO = MI->getOperand(0);
3142 if (MO.isSymbol()) {
3143 MCSymbolXCOFF *S =
3144 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
3145 ExtSymSDNodeSymbols.insert(S);
3146 }
3147 } break;
3148 case PPC::BL_TLS:
3149 case PPC::BL8_TLS:
3150 case PPC::BL8_TLS_:
3151 case PPC::BL8_NOP_TLS:
3152 report_fatal_error("TLS call not yet implemented");
3153 case PPC::TAILB:
3154 case PPC::TAILB8:
3155 case PPC::TAILBA:
3156 case PPC::TAILBA8:
3157 case PPC::TAILBCTR:
3158 case PPC::TAILBCTR8:
3159 if (MI->getOperand(0).isSymbol())
3160 report_fatal_error("Tail call for extern symbol not yet supported.");
3161 break;
3162 case PPC::DST:
3163 case PPC::DST64:
3164 case PPC::DSTT:
3165 case PPC::DSTT64:
3166 case PPC::DSTST:
3167 case PPC::DSTST64:
3168 case PPC::DSTSTT:
3169 case PPC::DSTSTT64:
3170 EmitToStreamer(
3171 *OutStreamer,
3172 MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0));
3173 return;
3174 }
3175 return PPCAsmPrinter::emitInstruction(MI);
3176}
3177
3178bool PPCAIXAsmPrinter::doFinalization(Module &M) {
3179 // Do streamer related finalization for DWARF.
3180 if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo())
3181 OutStreamer->doFinalizationAtSectionEnd(
3182 OutStreamer->getContext().getObjectFileInfo()->getTextSection());
3183
3184 for (MCSymbol *Sym : ExtSymSDNodeSymbols)
3185 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
3186 return PPCAsmPrinter::doFinalization(M);
3187}
3188
3189static unsigned mapToSinitPriority(int P) {
3190 if (P < 0 || P > 65535)
3191 report_fatal_error("invalid init priority");
3192
3193 if (P <= 20)
3194 return P;
3195
3196 if (P < 81)
3197 return 20 + (P - 20) * 16;
3198
3199 if (P <= 1124)
3200 return 1004 + (P - 81);
3201
3202 if (P < 64512)
3203 return 2047 + (P - 1124) * 33878;
3204
3205 return 2147482625u + (P - 64512);
3206}
3207
3208static std::string convertToSinitPriority(int Priority) {
3209 // This helper function converts clang init priority to values used in sinit
3210 // and sterm functions.
3211 //
3212 // The conversion strategies are:
3213 // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
3214 // reserved priority range [0, 1023] by
3215 // - directly mapping the first 21 and the last 20 elements of the ranges
3216 // - linear interpolating the intermediate values with a step size of 16.
3217 //
3218 // We map the non reserved clang/gnu priority range of [101, 65535] into the
3219 // sinit/sterm priority range [1024, 2147483648] by:
3220 // - directly mapping the first and the last 1024 elements of the ranges
3221 // - linear interpolating the intermediate values with a step size of 33878.
3222 unsigned int P = mapToSinitPriority(Priority);
3223
3224 std::string PrioritySuffix;
3225 llvm::raw_string_ostream os(PrioritySuffix);
3226 os << llvm::format_hex_no_prefix(P, 8);
3227 os.flush();
3228 return PrioritySuffix;
3229}
3230
3231void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
3232 const Constant *List, bool IsCtor) {
3233 SmallVector<Structor, 8> Structors;
3234 preprocessXXStructorList(DL, List, Structors);
3235 if (Structors.empty())
3236 return;
3237
3238 unsigned Index = 0;
3239 for (Structor &S : Structors) {
3240 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
3241 S.Func = CE->getOperand(0);
3242
3245 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
3246 llvm::Twine(convertToSinitPriority(S.Priority)) +
3247 llvm::Twine("_", FormatIndicatorAndUniqueModId) +
3248 llvm::Twine("_", llvm::utostr(Index++)),
3249 cast<Function>(S.Func));
3250 }
3251}
3252
3253void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV,
3254 unsigned Encoding) {
3255 if (GV) {
3256 TOCEntryType GlobalType = TOCType_GlobalInternal;
3258 if (Linkage == GlobalValue::ExternalLinkage ||
3261 GlobalType = TOCType_GlobalExternal;
3262 MCSymbol *TypeInfoSym = TM.getSymbol(GV);
3263 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym, GlobalType);
3264 const MCSymbol *TOCBaseSym =
3265 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
3266 ->getQualNameSymbol();
3267 auto &Ctx = OutStreamer->getContext();
3268 const MCExpr *Exp =
3270 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
3271 OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding));
3272 } else
3273 OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding));
3274}
3275
3276// Return a pass that prints the PPC assembly code for a MachineFunction to the
3277// given output stream.
3278static AsmPrinter *
3280 std::unique_ptr<MCStreamer> &&Streamer) {
3281 if (tm.getTargetTriple().isOSAIX())
3282 return new PPCAIXAsmPrinter(tm, std::move(Streamer));
3283
3284 return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
3285}
3286
3287void PPCAIXAsmPrinter::emitModuleCommandLines(Module &M) {
3288 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3289 if (!NMD || !NMD->getNumOperands())
3290 return;
3291
3292 std::string S;
3293 raw_string_ostream RSOS(S);
3294 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3295 const MDNode *N = NMD->getOperand(i);
3296 assert(N->getNumOperands() == 1 &&
3297 "llvm.commandline metadata entry can have only one operand");
3298 const MDString *MDS = cast<MDString>(N->getOperand(0));
3299 // Add "@(#)" to support retrieving the command line information with the
3300 // AIX "what" command
3301 RSOS << "@(#)opt " << MDS->getString() << "\n";
3302 RSOS.write('\0');
3303 }
3304 OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
3305}
3306
3307// Force static initialization.
3317}
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)
if(VerifyEach)
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 implements a set that has insertion order iteration characteristics.
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:704
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:450
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:1017
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an Operation in the Expression.
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:525
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:80
bool hasComdat() const
Definition: GlobalObject.h:128
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:110
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:281
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasDefaultVisibility() const
Definition: GlobalValue.h:249
bool hasPrivateLinkage() const
Definition: GlobalValue.h:527
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
bool hasDLLExportStorageClass() const
Definition: GlobalValue.h:281
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:375
@ 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:532
bool hasAppendingLinkage() const
Definition: GlobalValue.h:525
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:81
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:784
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:610
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:293
A tuple of MDNodes.
Definition: Metadata.h:1729
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1381
unsigned getNumOperands() const
Definition: Metadata.cpp:1377
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:315
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
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
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:563
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:710
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:4996
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:5079
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:1157
@ SHF_WRITE
Definition: ELF.h:1154
@ SHT_PROGBITS
Definition: ELF.h:1063
const uint64_t Version
Definition: InstrProf.h:1177
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:1680
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)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:1849
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