1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 class PPCAsmPrinter : public AsmPrinter {
62 MCSymbol *Stub, *LazyPtr, *AnonSymbol;
65 Stub = LazyPtr = AnonSymbol = 0;
68 void Init(const GlobalValue *GV, AsmPrinter *Printer) {
69 // Already initialized.
70 if (Stub != 0) return;
73 Stub = Printer->GetSymbolWithGlobalValueBase(GV, "$stub");
74 LazyPtr = Printer->GetSymbolWithGlobalValueBase(GV, "$lazy_ptr");
75 AnonSymbol = Printer->GetSymbolWithGlobalValueBase(GV, "$stub$tmp");
78 void Init(StringRef GVName, Mangler *Mang, MCContext &Ctx) {
79 assert(!GVName.empty() && "external symbol name shouldn't be empty");
80 if (Stub != 0) return; // Already initialized.
81 // Get the names for the external symbol name.
82 SmallString<128> TmpStr;
83 Mang->getNameWithPrefix(TmpStr, GVName, Mangler::Private);
85 Stub = Ctx.GetOrCreateSymbol(TmpStr.str());
86 TmpStr.erase(TmpStr.end()-5, TmpStr.end()); // Remove $stub
88 TmpStr += "$lazy_ptr";
89 LazyPtr = Ctx.GetOrCreateSymbol(TmpStr.str());
90 TmpStr.erase(TmpStr.end()-9, TmpStr.end()); // Remove $lazy_ptr
92 TmpStr += "$stub$tmp";
93 AnonSymbol = Ctx.GetOrCreateSymbol(TmpStr.str());
97 DenseMap<const MCSymbol*, FnStubInfo> FnStubs;
98 DenseMap<const MCSymbol*, const MCSymbol*> GVStubs, HiddenGVStubs, TOC;
99 const PPCSubtarget &Subtarget;
102 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
103 const MCAsmInfo *T, bool V)
104 : AsmPrinter(O, TM, T, V),
105 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
107 virtual const char *getPassName() const {
108 return "PowerPC Assembly Printer";
111 PPCTargetMachine &getTM() {
112 return static_cast<PPCTargetMachine&>(TM);
115 unsigned enumRegToMachineReg(unsigned enumReg) {
117 default: llvm_unreachable("Unhandled register!");
118 case PPC::CR0: return 0;
119 case PPC::CR1: return 1;
120 case PPC::CR2: return 2;
121 case PPC::CR3: return 3;
122 case PPC::CR4: return 4;
123 case PPC::CR5: return 5;
124 case PPC::CR6: return 6;
125 case PPC::CR7: return 7;
130 /// printInstruction - This method is automatically generated by tablegen
131 /// from the instruction set description. This method returns true if the
132 /// machine instruction was sufficiently described to print it, otherwise it
134 void printInstruction(const MachineInstr *MI);
135 static const char *getRegisterName(unsigned RegNo);
138 void printMachineInstruction(const MachineInstr *MI);
139 void printOp(const MachineOperand &MO);
141 /// stripRegisterPrefix - This method strips the character prefix from a
142 /// register name so that only the number is left. Used by for linux asm.
143 const char *stripRegisterPrefix(const char *RegName) {
144 switch (RegName[0]) {
147 case 'v': return RegName + 1;
148 case 'c': if (RegName[1] == 'r') return RegName + 2;
154 /// printRegister - Print register according to target requirements.
156 void printRegister(const MachineOperand &MO, bool R0AsZero) {
157 unsigned RegNo = MO.getReg();
158 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
160 // If we should use 0 for R0.
161 if (R0AsZero && RegNo == PPC::R0) {
166 const char *RegName = getRegisterName(RegNo);
167 // Linux assembler (Others?) does not take register mnemonics.
168 // FIXME - What about special registers used in mfspr/mtspr?
169 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
173 void printOperand(const MachineInstr *MI, unsigned OpNo) {
174 const MachineOperand &MO = MI->getOperand(OpNo);
176 printRegister(MO, false);
177 } else if (MO.isImm()) {
184 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
185 unsigned AsmVariant, const char *ExtraCode);
186 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
187 unsigned AsmVariant, const char *ExtraCode);
190 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
191 char value = MI->getOperand(OpNo).getImm();
192 value = (value << (32-5)) >> (32-5);
195 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
196 unsigned char value = MI->getOperand(OpNo).getImm();
197 assert(value <= 31 && "Invalid u5imm argument!");
198 O << (unsigned int)value;
200 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
201 unsigned char value = MI->getOperand(OpNo).getImm();
202 assert(value <= 63 && "Invalid u6imm argument!");
203 O << (unsigned int)value;
205 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
206 O << (short)MI->getOperand(OpNo).getImm();
208 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
209 O << (unsigned short)MI->getOperand(OpNo).getImm();
211 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
212 if (MI->getOperand(OpNo).isImm()) {
213 O << (short)(MI->getOperand(OpNo).getImm()*4);
216 printOp(MI->getOperand(OpNo));
217 if (TM.getRelocationModel() == Reloc::PIC_)
218 O << "-\"L" << getFunctionNumber() << "$pb\")";
223 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
224 // Branches can take an immediate operand. This is used by the branch
225 // selection pass to print $+8, an eight byte displacement from the PC.
226 if (MI->getOperand(OpNo).isImm()) {
227 O << "$+" << MI->getOperand(OpNo).getImm()*4;
229 printOp(MI->getOperand(OpNo));
232 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
233 const MachineOperand &MO = MI->getOperand(OpNo);
234 if (TM.getRelocationModel() != Reloc::Static) {
235 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
236 GlobalValue *GV = MO.getGlobal();
237 if (GV->isDeclaration() || GV->isWeakForLinker()) {
238 // Dynamically-resolved functions need a stub for the function.
239 FnStubInfo &FnInfo = FnStubs[GetGlobalValueSymbol(GV)];
240 FnInfo.Init(GV, this);
245 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
247 FnStubs[GetExternalSymbolSymbol(MO.getSymbolName())];
248 FnInfo.Init(MO.getSymbolName(), Mang, OutContext);
254 printOp(MI->getOperand(OpNo));
256 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
257 O << (int)MI->getOperand(OpNo).getImm()*4;
259 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
260 O << "\"L" << getFunctionNumber() << "$pb\"\n";
261 O << "\"L" << getFunctionNumber() << "$pb\":";
263 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
264 if (MI->getOperand(OpNo).isImm()) {
265 printS16ImmOperand(MI, OpNo);
267 if (Subtarget.isDarwin()) O << "ha16(";
268 printOp(MI->getOperand(OpNo));
269 if (TM.getRelocationModel() == Reloc::PIC_)
270 O << "-\"L" << getFunctionNumber() << "$pb\"";
271 if (Subtarget.isDarwin())
277 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
278 if (MI->getOperand(OpNo).isImm()) {
279 printS16ImmOperand(MI, OpNo);
281 if (Subtarget.isDarwin()) O << "lo16(";
282 printOp(MI->getOperand(OpNo));
283 if (TM.getRelocationModel() == Reloc::PIC_)
284 O << "-\"L" << getFunctionNumber() << "$pb\"";
285 if (Subtarget.isDarwin())
291 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
292 unsigned CCReg = MI->getOperand(OpNo).getReg();
293 unsigned RegNo = enumRegToMachineReg(CCReg);
294 O << (0x80 >> RegNo);
296 // The new addressing mode printers.
297 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
298 printSymbolLo(MI, OpNo);
300 if (MI->getOperand(OpNo+1).isReg() &&
301 MI->getOperand(OpNo+1).getReg() == PPC::R0)
304 printOperand(MI, OpNo+1);
307 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
308 if (MI->getOperand(OpNo).isImm())
309 printS16X4ImmOperand(MI, OpNo);
311 printSymbolLo(MI, OpNo);
313 if (MI->getOperand(OpNo+1).isReg() &&
314 MI->getOperand(OpNo+1).getReg() == PPC::R0)
317 printOperand(MI, OpNo+1);
321 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
322 // When used as the base register, r0 reads constant zero rather than
323 // the value contained in the register. For this reason, the darwin
324 // assembler requires that we print r0 as 0 (no r) when used as the base.
325 const MachineOperand &MO = MI->getOperand(OpNo);
326 printRegister(MO, true);
328 printOperand(MI, OpNo+1);
331 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
332 const MachineOperand &MO = MI->getOperand(OpNo);
334 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
336 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
338 // Map symbol -> label of TOC entry.
339 const MCSymbol *&TOCEntry = TOC[Sym];
341 TOCEntry = OutContext.
342 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
345 O << *TOCEntry << "@toc";
348 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
349 const char *Modifier);
351 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
354 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
355 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
357 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
358 const MCAsmInfo *T, bool V)
359 : PPCAsmPrinter(O, TM, T, V){}
361 virtual const char *getPassName() const {
362 return "Linux PPC Assembly Printer";
365 bool runOnMachineFunction(MachineFunction &F);
366 bool doFinalization(Module &M);
368 void getAnalysisUsage(AnalysisUsage &AU) const {
369 AU.setPreservesAll();
370 AU.addRequired<MachineModuleInfo>();
371 AU.addRequired<DwarfWriter>();
372 PPCAsmPrinter::getAnalysisUsage(AU);
375 void PrintGlobalVariable(const GlobalVariable *GVar);
378 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
380 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
381 formatted_raw_ostream &OS;
383 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
384 const MCAsmInfo *T, bool V)
385 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
387 virtual const char *getPassName() const {
388 return "Darwin PPC Assembly Printer";
391 bool runOnMachineFunction(MachineFunction &F);
392 bool doFinalization(Module &M);
393 void EmitStartOfAsmFile(Module &M);
395 void getAnalysisUsage(AnalysisUsage &AU) const {
396 AU.setPreservesAll();
397 AU.addRequired<MachineModuleInfo>();
398 AU.addRequired<DwarfWriter>();
399 PPCAsmPrinter::getAnalysisUsage(AU);
402 void PrintGlobalVariable(const GlobalVariable *GVar);
404 } // end of anonymous namespace
406 // Include the auto-generated portion of the assembly writer
407 #include "PPCGenAsmWriter.inc"
409 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
410 switch (MO.getType()) {
411 case MachineOperand::MO_Immediate:
412 llvm_unreachable("printOp() does not handle immediate values");
414 case MachineOperand::MO_MachineBasicBlock:
415 O << *GetMBBSymbol(MO.getMBB()->getNumber());
417 case MachineOperand::MO_JumpTableIndex:
418 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
419 << '_' << MO.getIndex();
420 // FIXME: PIC relocation model
422 case MachineOperand::MO_ConstantPoolIndex:
423 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
424 << '_' << MO.getIndex();
426 case MachineOperand::MO_BlockAddress:
427 O << *GetBlockAddressSymbol(MO.getBlockAddress());
429 case MachineOperand::MO_ExternalSymbol: {
430 // Computing the address of an external symbol, not calling it.
431 const MCSymbol *SymName = GetExternalSymbolSymbol(MO.getSymbolName());
432 if (TM.getRelocationModel() == Reloc::Static) {
436 const MCSymbol *NLPSym =
437 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
438 MO.getSymbolName()+"$non_lazy_ptr");
439 GVStubs[SymName] = NLPSym;
443 case MachineOperand::MO_GlobalAddress: {
444 // Computing the address of a global symbol, not calling it.
445 GlobalValue *GV = MO.getGlobal();
446 MCSymbol *SymToPrint;
448 // External or weakly linked global variables need non-lazily-resolved stubs
449 if (TM.getRelocationModel() != Reloc::Static &&
450 (GV->isDeclaration() || GV->isWeakForLinker())) {
451 if (!GV->hasHiddenVisibility()) {
452 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
453 GVStubs[GetGlobalValueSymbol(GV)] = SymToPrint;
454 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
455 GV->hasAvailableExternallyLinkage()) {
456 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
457 HiddenGVStubs[GetGlobalValueSymbol(GV)] = SymToPrint;
459 SymToPrint = GetGlobalValueSymbol(GV);
462 SymToPrint = GetGlobalValueSymbol(GV);
467 printOffset(MO.getOffset());
472 O << "<unknown operand type: " << MO.getType() << ">";
477 /// PrintAsmOperand - Print out an operand for an inline asm expression.
479 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
481 const char *ExtraCode) {
482 // Does this asm operand have a single letter operand modifier?
483 if (ExtraCode && ExtraCode[0]) {
484 if (ExtraCode[1] != 0) return true; // Unknown modifier.
486 switch (ExtraCode[0]) {
487 default: return true; // Unknown modifier.
488 case 'c': // Don't print "$" before a global var name or constant.
489 // PPC never has a prefix.
490 printOperand(MI, OpNo);
492 case 'L': // Write second word of DImode reference.
493 // Verify that this operand has two consecutive registers.
494 if (!MI->getOperand(OpNo).isReg() ||
495 OpNo+1 == MI->getNumOperands() ||
496 !MI->getOperand(OpNo+1).isReg())
498 ++OpNo; // Return the high-part.
501 // Write 'i' if an integer constant, otherwise nothing. Used to print
503 if (MI->getOperand(OpNo).isImm())
509 printOperand(MI, OpNo);
513 // At the moment, all inline asm memory operands are a single register.
514 // In any case, the output of this routine should always be just one
515 // assembler operand.
517 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
519 const char *ExtraCode) {
520 if (ExtraCode && ExtraCode[0])
521 return true; // Unknown modifier.
522 assert (MI->getOperand(OpNo).isReg());
524 printOperand(MI, OpNo);
529 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
530 const char *Modifier) {
531 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
532 unsigned Code = MI->getOperand(OpNo).getImm();
533 if (!strcmp(Modifier, "cc")) {
534 switch ((PPC::Predicate)Code) {
535 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
536 case PPC::PRED_LT: O << "lt"; return;
537 case PPC::PRED_LE: O << "le"; return;
538 case PPC::PRED_EQ: O << "eq"; return;
539 case PPC::PRED_GE: O << "ge"; return;
540 case PPC::PRED_GT: O << "gt"; return;
541 case PPC::PRED_NE: O << "ne"; return;
542 case PPC::PRED_UN: O << "un"; return;
543 case PPC::PRED_NU: O << "nu"; return;
547 assert(!strcmp(Modifier, "reg") &&
548 "Need to specify 'cc' or 'reg' as predicate op modifier!");
549 // Don't print the register for 'always'.
550 if (Code == PPC::PRED_ALWAYS) return;
551 printOperand(MI, OpNo+1);
556 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
557 /// the current output stream.
559 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
562 processDebugLoc(MI, true);
564 // Check for slwi/srwi mnemonics.
565 bool useSubstituteMnemonic = false;
566 if (MI->getOpcode() == PPC::RLWINM) {
567 unsigned char SH = MI->getOperand(2).getImm();
568 unsigned char MB = MI->getOperand(3).getImm();
569 unsigned char ME = MI->getOperand(4).getImm();
570 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
571 O << "\tslwi "; useSubstituteMnemonic = true;
573 if (SH <= 31 && MB == (32-SH) && ME == 31) {
574 O << "\tsrwi "; useSubstituteMnemonic = true;
577 if (useSubstituteMnemonic) {
581 O << ", " << (unsigned int)SH;
583 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
584 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
585 useSubstituteMnemonic = true;
591 } else if (MI->getOpcode() == PPC::RLDICR) {
592 unsigned char SH = MI->getOperand(2).getImm();
593 unsigned char ME = MI->getOperand(3).getImm();
594 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
596 useSubstituteMnemonic = true;
601 O << ", " << (unsigned int)SH;
605 if (!useSubstituteMnemonic)
606 printInstruction(MI);
612 processDebugLoc(MI, false);
615 /// runOnMachineFunction - This uses the printMachineInstruction()
616 /// method to print assembly for each instruction.
618 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
621 SetupMachineFunction(MF);
624 // Print out constants referenced by the function
625 EmitConstantPool(MF.getConstantPool());
627 // Print out labels for the function.
628 const Function *F = MF.getFunction();
629 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
631 switch (F->getLinkage()) {
632 default: llvm_unreachable("Unknown linkage type!");
633 case Function::PrivateLinkage:
634 case Function::InternalLinkage: // Symbols default to internal.
636 case Function::ExternalLinkage:
637 O << "\t.global\t" << *CurrentFnSym << '\n' << "\t.type\t";
638 O << *CurrentFnSym << ", @function\n";
640 case Function::LinkerPrivateLinkage:
641 case Function::WeakAnyLinkage:
642 case Function::WeakODRLinkage:
643 case Function::LinkOnceAnyLinkage:
644 case Function::LinkOnceODRLinkage:
645 O << "\t.global\t" << *CurrentFnSym << '\n';
646 O << "\t.weak\t" << *CurrentFnSym << '\n';
650 printVisibility(CurrentFnSym, F->getVisibility());
652 EmitAlignment(MF.getAlignment(), F);
654 if (Subtarget.isPPC64()) {
655 // Emit an official procedure descriptor.
656 // FIXME 64-bit SVR4: Use MCSection here!
657 O << "\t.section\t\".opd\",\"aw\"\n";
659 O << *CurrentFnSym << ":\n";
660 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
661 O << "\t.previous\n";
662 O << ".L." << *CurrentFnSym << ":\n";
664 O << *CurrentFnSym << ":\n";
667 // Emit pre-function debug information.
668 DW->BeginFunction(&MF);
670 // Print out code for the function.
671 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
673 // Print a label for the basic block.
674 if (I != MF.begin()) {
675 EmitBasicBlockStart(I);
677 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
679 // Print the assembly for the instruction.
680 printMachineInstruction(II);
684 O << "\t.size\t" << *CurrentFnSym << ",.-" << *CurrentFnSym << '\n';
686 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
688 // Emit post-function debug information.
689 DW->EndFunction(&MF);
691 // Print out jump tables referenced by the function.
692 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
694 // We didn't modify anything.
698 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
699 const TargetData *TD = TM.getTargetData();
701 if (!GVar->hasInitializer())
702 return; // External global require no code
704 // Check to see if this is a special global used by LLVM, if so, emit it.
705 if (EmitSpecialLLVMGlobal(GVar))
708 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
710 printVisibility(GVarSym, GVar->getVisibility());
712 Constant *C = GVar->getInitializer();
713 const Type *Type = C->getType();
714 unsigned Size = TD->getTypeAllocSize(Type);
715 unsigned Align = TD->getPreferredAlignmentLog(GVar);
717 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
719 // Handle normal common symbols.
720 if (GVKind.isCommon()) {
721 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
723 O << ".comm " << *GVarSym << ',' << Size;
724 if (MAI->getCOMMDirectiveTakesAlignment())
728 O << "\t\t" << MAI->getCommentString() << " '";
729 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
736 OutStreamer.SwitchSection(getObjFileLowering().
737 SectionForGlobal(GVar, GVKind, Mang, TM));
739 if (C->isNullValue() && /* FIXME: Verify correct */
740 !GVar->hasSection() &&
741 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
742 GVar->isWeakForLinker())) {
743 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
745 if (GVar->hasExternalLinkage()) {
746 O << "\t.global " << *GVarSym << '\n';
747 O << "\t.type " << *GVarSym << ", @object\n";
748 O << *GVarSym << ":\n";
749 O << "\t.zero " << Size << '\n';
750 } else if (GVar->hasLocalLinkage()) {
751 O << MAI->getLCOMMDirective() << *GVarSym << ',' << Size;
753 O << ".comm " << *GVarSym << ',' << Size;
756 O << "\t\t" << MAI->getCommentString() << " '";
757 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
764 switch (GVar->getLinkage()) {
765 case GlobalValue::LinkOnceAnyLinkage:
766 case GlobalValue::LinkOnceODRLinkage:
767 case GlobalValue::WeakAnyLinkage:
768 case GlobalValue::WeakODRLinkage:
769 case GlobalValue::CommonLinkage:
770 case GlobalValue::LinkerPrivateLinkage:
771 O << "\t.global " << *GVarSym;
772 O << "\n\t.type " << *GVarSym << ", @object\n\t.weak " << *GVarSym << '\n';
774 case GlobalValue::AppendingLinkage:
775 // FIXME: appending linkage variables should go into a section of
776 // their name or something. For now, just emit them as external.
777 case GlobalValue::ExternalLinkage:
778 // If external or appending, declare as a global symbol
779 O << "\t.global " << *GVarSym;
780 O << "\n\t.type " << *GVarSym << ", @object\n";
782 case GlobalValue::InternalLinkage:
783 case GlobalValue::PrivateLinkage:
786 llvm_unreachable("Unknown linkage type!");
789 EmitAlignment(Align, GVar);
790 O << *GVarSym << ":";
792 O << "\t\t\t\t" << MAI->getCommentString() << " '";
793 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
798 EmitGlobalConstant(C);
802 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
803 const TargetData *TD = TM.getTargetData();
805 bool isPPC64 = TD->getPointerSizeInBits() == 64;
807 if (isPPC64 && !TOC.empty()) {
808 // FIXME 64-bit SVR4: Use MCSection here?
809 O << "\t.section\t\".toc\",\"aw\"\n";
811 // FIXME: This is nondeterminstic!
812 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
813 E = TOC.end(); I != E; ++I) {
814 O << *I->second << ":\n";
815 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
819 return AsmPrinter::doFinalization(M);
822 /// runOnMachineFunction - This uses the printMachineInstruction()
823 /// method to print assembly for each instruction.
825 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
828 SetupMachineFunction(MF);
831 // Print out constants referenced by the function
832 EmitConstantPool(MF.getConstantPool());
834 // Print out labels for the function.
835 const Function *F = MF.getFunction();
836 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
838 switch (F->getLinkage()) {
839 default: llvm_unreachable("Unknown linkage type!");
840 case Function::PrivateLinkage:
841 case Function::InternalLinkage: // Symbols default to internal.
843 case Function::ExternalLinkage:
844 O << "\t.globl\t" << *CurrentFnSym << '\n';
846 case Function::WeakAnyLinkage:
847 case Function::WeakODRLinkage:
848 case Function::LinkOnceAnyLinkage:
849 case Function::LinkOnceODRLinkage:
850 case Function::LinkerPrivateLinkage:
851 O << "\t.globl\t" << *CurrentFnSym << '\n';
852 O << "\t.weak_definition\t" << *CurrentFnSym << '\n';
856 printVisibility(CurrentFnSym, F->getVisibility());
858 EmitAlignment(MF.getAlignment(), F);
859 O << *CurrentFnSym << ":\n";
861 // Emit pre-function debug information.
862 DW->BeginFunction(&MF);
864 // If the function is empty, then we need to emit *something*. Otherwise, the
865 // function's label might be associated with something that it wasn't meant to
866 // be associated with. We emit a noop in this situation.
867 MachineFunction::iterator I = MF.begin();
869 if (++I == MF.end() && MF.front().empty())
872 // Print out code for the function.
873 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
875 // Print a label for the basic block.
876 if (I != MF.begin()) {
877 EmitBasicBlockStart(I);
879 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
881 // Print the assembly for the instruction.
882 printMachineInstruction(II);
886 // Emit post-function debug information.
887 DW->EndFunction(&MF);
889 // Print out jump tables referenced by the function.
890 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
892 // We didn't modify anything.
897 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
898 static const char *const CPUDirectives[] = {
910 unsigned Directive = Subtarget.getDarwinDirective();
911 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
912 Directive = PPC::DIR_970;
913 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
914 Directive = PPC::DIR_7400;
915 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
916 Directive = PPC::DIR_64;
917 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
918 O << "\t.machine " << CPUDirectives[Directive] << '\n';
920 // Prime text sections so they are adjacent. This reduces the likelihood a
921 // large data or debug section causes a branch to exceed 16M limit.
922 TargetLoweringObjectFileMachO &TLOFMacho =
923 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
924 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
925 if (TM.getRelocationModel() == Reloc::PIC_) {
926 OutStreamer.SwitchSection(
927 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
928 MCSectionMachO::S_SYMBOL_STUBS |
929 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
930 32, SectionKind::getText()));
931 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
932 OutStreamer.SwitchSection(
933 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
934 MCSectionMachO::S_SYMBOL_STUBS |
935 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
936 16, SectionKind::getText()));
938 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
941 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
942 const TargetData *TD = TM.getTargetData();
944 if (!GVar->hasInitializer())
945 return; // External global require no code
947 // Check to see if this is a special global used by LLVM, if so, emit it.
948 if (EmitSpecialLLVMGlobal(GVar)) {
949 if (TM.getRelocationModel() == Reloc::Static) {
950 if (GVar->getName() == "llvm.global_ctors")
951 O << ".reference .constructors_used\n";
952 else if (GVar->getName() == "llvm.global_dtors")
953 O << ".reference .destructors_used\n";
958 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
959 printVisibility(GVarSym, GVar->getVisibility());
961 Constant *C = GVar->getInitializer();
962 const Type *Type = C->getType();
963 unsigned Size = TD->getTypeAllocSize(Type);
964 unsigned Align = TD->getPreferredAlignmentLog(GVar);
966 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
968 // Handle normal common symbols.
969 if (GVKind.isCommon()) {
970 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
972 O << ".comm " << *GVarSym << ',' << Size;
973 if (MAI->getCOMMDirectiveTakesAlignment())
974 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
977 O << "\t\t" << MAI->getCommentString() << " '";
978 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
985 const MCSection *TheSection =
986 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
988 // Handle the zerofill directive on darwin, which is a special form of BSS
990 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective()) {
991 TargetLoweringObjectFileMachO &TLOFMacho =
992 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
993 if (TLOFMacho.isDataCommonSection(TheSection)) {
995 OutStreamer.EmitSymbolAttribute(GVarSym, MCStreamer::Global);
996 // .zerofill __DATA, __common, _foo, 400, 5
997 OutStreamer.EmitZerofill(TheSection, GVarSym, Size, 1 << Align);
1002 OutStreamer.SwitchSection(TheSection);
1004 /// FIXME: Drive this off the section!
1005 if (C->isNullValue() && /* FIXME: Verify correct */
1006 !GVar->hasSection() &&
1007 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
1008 GVar->isWeakForLinker()) &&
1009 // Don't put things that should go in the cstring section into "comm".
1010 !TheSection->getKind().isMergeableCString()) {
1011 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
1013 if (GVar->hasLocalLinkage()) {
1014 O << MAI->getLCOMMDirective() << *GVarSym << ',' << Size << ',' << Align;
1017 O << "\t\t" << MAI->getCommentString() << " '";
1018 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1023 O << "\t.globl " << *GVarSym << '\n' << MAI->getWeakDefDirective();
1024 O << *GVarSym << '\n';
1025 EmitAlignment(Align, GVar);
1026 O << *GVarSym << ":";
1028 O << "\t\t\t\t" << MAI->getCommentString() << " ";
1029 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1032 EmitGlobalConstant(C);
1037 switch (GVar->getLinkage()) {
1038 case GlobalValue::LinkOnceAnyLinkage:
1039 case GlobalValue::LinkOnceODRLinkage:
1040 case GlobalValue::WeakAnyLinkage:
1041 case GlobalValue::WeakODRLinkage:
1042 case GlobalValue::CommonLinkage:
1043 case GlobalValue::LinkerPrivateLinkage:
1044 O << "\t.globl " << *GVarSym << "\n\t.weak_definition " << *GVarSym << '\n';
1046 case GlobalValue::AppendingLinkage:
1047 // FIXME: appending linkage variables should go into a section of
1048 // their name or something. For now, just emit them as external.
1049 case GlobalValue::ExternalLinkage:
1050 // If external or appending, declare as a global symbol
1051 O << "\t.globl " << *GVarSym << '\n';
1053 case GlobalValue::InternalLinkage:
1054 case GlobalValue::PrivateLinkage:
1057 llvm_unreachable("Unknown linkage type!");
1060 EmitAlignment(Align, GVar);
1061 O << *GVarSym << ":";
1063 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1064 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1069 EmitGlobalConstant(C);
1073 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1074 const TargetData *TD = TM.getTargetData();
1076 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1078 // Darwin/PPC always uses mach-o.
1079 TargetLoweringObjectFileMachO &TLOFMacho =
1080 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1083 const MCSection *LSPSection = 0;
1084 if (!FnStubs.empty()) // .lazy_symbol_pointer
1085 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1088 // Output stubs for dynamically-linked functions
1089 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1090 const MCSection *StubSection =
1091 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1092 MCSectionMachO::S_SYMBOL_STUBS |
1093 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1094 32, SectionKind::getText());
1095 // FIXME: This is emitting in nondeterminstic order!
1096 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I =
1097 FnStubs.begin(), E = FnStubs.end(); I != E; ++I) {
1098 OutStreamer.SwitchSection(StubSection);
1100 const FnStubInfo &Info = I->second;
1101 O << *Info.Stub << ":\n";
1102 O << "\t.indirect_symbol " << *I->first << '\n';
1104 O << "\tbcl 20,31," << *Info.AnonSymbol << '\n';
1105 O << *Info.AnonSymbol << ":\n";
1106 O << "\tmflr r11\n";
1107 O << "\taddis r11,r11,ha16(" << *Info.LazyPtr << '-' << *Info.AnonSymbol
1110 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *Info.LazyPtr
1111 << '-' << *Info.AnonSymbol << ")(r11)\n";
1112 O << "\tmtctr r12\n";
1115 OutStreamer.SwitchSection(LSPSection);
1116 O << *Info.LazyPtr << ":\n";
1117 O << "\t.indirect_symbol " << *I->first << '\n';
1118 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1120 } else if (!FnStubs.empty()) {
1121 const MCSection *StubSection =
1122 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1123 MCSectionMachO::S_SYMBOL_STUBS |
1124 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1125 16, SectionKind::getText());
1127 // FIXME: This is emitting in nondeterminstic order!
1128 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I = FnStubs.begin(),
1129 E = FnStubs.end(); I != E; ++I) {
1130 OutStreamer.SwitchSection(StubSection);
1132 const FnStubInfo &Info = I->second;
1133 O << *Info.Stub << ":\n";
1134 O << "\t.indirect_symbol " << *I->first << '\n';
1135 O << "\tlis r11,ha16(" << *Info.LazyPtr << ")\n";
1136 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *Info.LazyPtr
1138 O << "\tmtctr r12\n";
1140 OutStreamer.SwitchSection(LSPSection);
1141 O << *Info.LazyPtr << ":\n";
1142 O << "\t.indirect_symbol " << *I->first << '\n';
1143 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1149 if (MAI->doesSupportExceptionHandling() && MMI) {
1150 // Add the (possibly multiple) personalities to the set of global values.
1151 // Only referenced functions get into the Personalities list.
1152 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1153 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1154 E = Personalities.end(); I != E; ++I) {
1156 GVStubs[GetGlobalValueSymbol(*I)] =
1157 GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
1161 // Output macho stubs for external and common global variables.
1162 if (!GVStubs.empty()) {
1163 // Switch with ".non_lazy_symbol_pointer" directive.
1164 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1165 EmitAlignment(isPPC64 ? 3 : 2);
1167 // FIXME: This is nondeterminstic.
1168 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1169 I = GVStubs.begin(), E = GVStubs.end(); I != E; ++I) {
1170 O << *I->second << ":\n";
1171 O << "\t.indirect_symbol " << *I->first << '\n';
1172 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1176 if (!HiddenGVStubs.empty()) {
1177 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1178 EmitAlignment(isPPC64 ? 3 : 2);
1179 // FIXME: This is nondeterminstic.
1180 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1181 I = HiddenGVStubs.begin(), E = HiddenGVStubs.end(); I != E; ++I) {
1182 O << *I->second << ":\n";
1183 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *I->first << '\n';
1187 // Funny Darwin hack: This flag tells the linker that no global symbols
1188 // contain code that falls through to other global symbols (e.g. the obvious
1189 // implementation of multiple entry points). If this doesn't occur, the
1190 // linker can safely perform dead code stripping. Since LLVM never generates
1191 // code that does this, it is always safe to set.
1192 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1194 return AsmPrinter::doFinalization(M);
1199 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1200 /// for a MachineFunction to the given output stream, in a format that the
1201 /// Darwin assembler can deal with.
1203 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1205 const MCAsmInfo *tai,
1207 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1209 if (Subtarget->isDarwin())
1210 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1211 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1214 // Force static initialization.
1215 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1216 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1217 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);