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/Support/Mangler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetAsmInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
49 STATISTIC(EmittedInsts, "Number of machine instrs printed");
52 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
53 std::set<std::string> FnStubs, GVStubs;
54 const PPCSubtarget &Subtarget;
56 PPCAsmPrinter(raw_ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
57 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
60 virtual const char *getPassName() const {
61 return "PowerPC Assembly Printer";
64 PPCTargetMachine &getTM() {
65 return static_cast<PPCTargetMachine&>(TM);
68 unsigned enumRegToMachineReg(unsigned enumReg) {
70 default: assert(0 && "Unhandled register!"); break;
71 case PPC::CR0: return 0;
72 case PPC::CR1: return 1;
73 case PPC::CR2: return 2;
74 case PPC::CR3: return 3;
75 case PPC::CR4: return 4;
76 case PPC::CR5: return 5;
77 case PPC::CR6: return 6;
78 case PPC::CR7: return 7;
83 /// printInstruction - This method is automatically generated by tablegen
84 /// from the instruction set description. This method returns true if the
85 /// machine instruction was sufficiently described to print it, otherwise it
87 bool printInstruction(const MachineInstr *MI);
89 void printMachineInstruction(const MachineInstr *MI);
90 void printOp(const MachineOperand &MO);
92 /// stripRegisterPrefix - This method strips the character prefix from a
93 /// register name so that only the number is left. Used by for linux asm.
94 const char *stripRegisterPrefix(const char *RegName) {
98 case 'v': return RegName + 1;
99 case 'c': if (RegName[1] == 'r') return RegName + 2;
105 /// printRegister - Print register according to target requirements.
107 void printRegister(const MachineOperand &MO, bool R0AsZero) {
108 unsigned RegNo = MO.getReg();
109 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
111 // If we should use 0 for R0.
112 if (R0AsZero && RegNo == PPC::R0) {
117 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
118 // Linux assembler (Others?) does not take register mnemonics.
119 // FIXME - What about special registers used in mfspr/mtspr?
120 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
124 void printOperand(const MachineInstr *MI, unsigned OpNo) {
125 const MachineOperand &MO = MI->getOperand(OpNo);
126 if (MO.isRegister()) {
127 printRegister(MO, false);
128 } else if (MO.isImmediate()) {
135 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
136 unsigned AsmVariant, const char *ExtraCode);
137 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
138 unsigned AsmVariant, const char *ExtraCode);
141 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
142 char value = MI->getOperand(OpNo).getImm();
143 value = (value << (32-5)) >> (32-5);
146 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
147 unsigned char value = MI->getOperand(OpNo).getImm();
148 assert(value <= 31 && "Invalid u5imm argument!");
149 O << (unsigned int)value;
151 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
152 unsigned char value = MI->getOperand(OpNo).getImm();
153 assert(value <= 63 && "Invalid u6imm argument!");
154 O << (unsigned int)value;
156 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
157 O << (short)MI->getOperand(OpNo).getImm();
159 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
160 O << (unsigned short)MI->getOperand(OpNo).getImm();
162 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
163 if (MI->getOperand(OpNo).isImmediate()) {
164 O << (short)(MI->getOperand(OpNo).getImm()*4);
167 printOp(MI->getOperand(OpNo));
168 if (TM.getRelocationModel() == Reloc::PIC_)
169 O << "-\"L" << getFunctionNumber() << "$pb\")";
174 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
175 // Branches can take an immediate operand. This is used by the branch
176 // selection pass to print $+8, an eight byte displacement from the PC.
177 if (MI->getOperand(OpNo).isImmediate()) {
178 O << "$+" << MI->getOperand(OpNo).getImm()*4;
180 printOp(MI->getOperand(OpNo));
183 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
184 const MachineOperand &MO = MI->getOperand(OpNo);
185 if (TM.getRelocationModel() != Reloc::Static) {
186 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
187 GlobalValue *GV = MO.getGlobal();
188 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
189 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
190 // Dynamically-resolved functions need a stub for the function.
191 std::string Name = Mang->getValueName(GV);
192 FnStubs.insert(Name);
193 printSuffixedName(Name, "$stub");
194 if (GV->hasExternalWeakLinkage())
195 ExtWeakSymbols.insert(GV);
199 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
200 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
201 FnStubs.insert(Name);
202 printSuffixedName(Name, "$stub");
207 printOp(MI->getOperand(OpNo));
209 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
210 O << (int)MI->getOperand(OpNo).getImm()*4;
212 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
213 O << "\"L" << getFunctionNumber() << "$pb\"\n";
214 O << "\"L" << getFunctionNumber() << "$pb\":";
216 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
217 if (MI->getOperand(OpNo).isImmediate()) {
218 printS16ImmOperand(MI, OpNo);
220 if (Subtarget.isDarwin()) O << "ha16(";
221 printOp(MI->getOperand(OpNo));
222 if (TM.getRelocationModel() == Reloc::PIC_)
223 O << "-\"L" << getFunctionNumber() << "$pb\"";
224 if (Subtarget.isDarwin())
230 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
231 if (MI->getOperand(OpNo).isImmediate()) {
232 printS16ImmOperand(MI, OpNo);
234 if (Subtarget.isDarwin()) O << "lo16(";
235 printOp(MI->getOperand(OpNo));
236 if (TM.getRelocationModel() == Reloc::PIC_)
237 O << "-\"L" << getFunctionNumber() << "$pb\"";
238 if (Subtarget.isDarwin())
244 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
245 unsigned CCReg = MI->getOperand(OpNo).getReg();
246 unsigned RegNo = enumRegToMachineReg(CCReg);
247 O << (0x80 >> RegNo);
249 // The new addressing mode printers.
250 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
251 printSymbolLo(MI, OpNo);
253 if (MI->getOperand(OpNo+1).isRegister() &&
254 MI->getOperand(OpNo+1).getReg() == PPC::R0)
257 printOperand(MI, OpNo+1);
260 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
261 if (MI->getOperand(OpNo).isImmediate())
262 printS16X4ImmOperand(MI, OpNo);
264 printSymbolLo(MI, OpNo);
266 if (MI->getOperand(OpNo+1).isRegister() &&
267 MI->getOperand(OpNo+1).getReg() == PPC::R0)
270 printOperand(MI, OpNo+1);
274 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
275 // When used as the base register, r0 reads constant zero rather than
276 // the value contained in the register. For this reason, the darwin
277 // assembler requires that we print r0 as 0 (no r) when used as the base.
278 const MachineOperand &MO = MI->getOperand(OpNo);
279 printRegister(MO, true);
281 printOperand(MI, OpNo+1);
284 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
285 const char *Modifier);
287 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
288 virtual bool doFinalization(Module &M) = 0;
290 virtual void EmitExternalGlobal(const GlobalVariable *GV);
293 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
294 struct VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
297 MachineModuleInfo *MMI;
299 PPCLinuxAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
300 const TargetAsmInfo *T)
301 : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
304 virtual const char *getPassName() const {
305 return "Linux PPC Assembly Printer";
308 bool runOnMachineFunction(MachineFunction &F);
309 bool doInitialization(Module &M);
310 bool doFinalization(Module &M);
312 void getAnalysisUsage(AnalysisUsage &AU) const {
313 AU.setPreservesAll();
314 AU.addRequired<MachineModuleInfo>();
315 PPCAsmPrinter::getAnalysisUsage(AU);
318 /// getSectionForFunction - Return the section that we should emit the
319 /// specified function body into.
320 virtual std::string getSectionForFunction(const Function &F) const;
321 void printModuleLevelGV(const GlobalVariable* GVar);
324 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
326 struct VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
329 MachineModuleInfo *MMI;
331 PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
332 const TargetAsmInfo *T)
333 : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
336 virtual const char *getPassName() const {
337 return "Darwin PPC Assembly Printer";
340 bool runOnMachineFunction(MachineFunction &F);
341 bool doInitialization(Module &M);
342 bool doFinalization(Module &M);
344 void getAnalysisUsage(AnalysisUsage &AU) const {
345 AU.setPreservesAll();
346 AU.addRequired<MachineModuleInfo>();
347 PPCAsmPrinter::getAnalysisUsage(AU);
350 /// getSectionForFunction - Return the section that we should emit the
351 /// specified function body into.
352 virtual std::string getSectionForFunction(const Function &F) const;
353 void printModuleLevelGV(const GlobalVariable* GVar);
355 } // end of anonymous namespace
357 // Include the auto-generated portion of the assembly writer
358 #include "PPCGenAsmWriter.inc"
360 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
361 switch (MO.getType()) {
362 case MachineOperand::MO_Immediate:
363 cerr << "printOp() does not handle immediate values\n";
367 case MachineOperand::MO_MachineBasicBlock:
368 printBasicBlockLabel(MO.getMBB());
370 case MachineOperand::MO_JumpTableIndex:
371 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
372 << '_' << MO.getIndex();
373 // FIXME: PIC relocation model
375 case MachineOperand::MO_ConstantPoolIndex:
376 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
377 << '_' << MO.getIndex();
379 case MachineOperand::MO_ExternalSymbol:
380 // Computing the address of an external symbol, not calling it.
381 if (TM.getRelocationModel() != Reloc::Static) {
382 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
383 GVStubs.insert(Name);
384 printSuffixedName(Name, "$non_lazy_ptr");
387 O << TAI->getGlobalPrefix() << MO.getSymbolName();
389 case MachineOperand::MO_GlobalAddress: {
390 // Computing the address of a global symbol, not calling it.
391 GlobalValue *GV = MO.getGlobal();
392 std::string Name = Mang->getValueName(GV);
394 // External or weakly linked global variables need non-lazily-resolved stubs
395 if (TM.getRelocationModel() != Reloc::Static) {
396 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
397 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
398 GVStubs.insert(Name);
399 printSuffixedName(Name, "$non_lazy_ptr");
400 if (GV->hasExternalWeakLinkage())
401 ExtWeakSymbols.insert(GV);
407 if (MO.getOffset() > 0)
408 O << "+" << MO.getOffset();
409 else if (MO.getOffset() < 0)
412 if (GV->hasExternalWeakLinkage())
413 ExtWeakSymbols.insert(GV);
418 O << "<unknown operand type: " << MO.getType() << ">";
423 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
425 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
426 std::string Name = getGlobalLinkName(GV);
427 if (TM.getRelocationModel() != Reloc::Static) {
428 GVStubs.insert(Name);
429 printSuffixedName(Name, "$non_lazy_ptr");
435 /// PrintAsmOperand - Print out an operand for an inline asm expression.
437 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
439 const char *ExtraCode) {
440 // Does this asm operand have a single letter operand modifier?
441 if (ExtraCode && ExtraCode[0]) {
442 if (ExtraCode[1] != 0) return true; // Unknown modifier.
444 switch (ExtraCode[0]) {
445 default: return true; // Unknown modifier.
446 case 'c': // Don't print "$" before a global var name or constant.
447 // PPC never has a prefix.
448 printOperand(MI, OpNo);
450 case 'L': // Write second word of DImode reference.
451 // Verify that this operand has two consecutive registers.
452 if (!MI->getOperand(OpNo).isRegister() ||
453 OpNo+1 == MI->getNumOperands() ||
454 !MI->getOperand(OpNo+1).isRegister())
456 ++OpNo; // Return the high-part.
459 // Write 'i' if an integer constant, otherwise nothing. Used to print
461 if (MI->getOperand(OpNo).isImmediate())
467 printOperand(MI, OpNo);
471 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
473 const char *ExtraCode) {
474 if (ExtraCode && ExtraCode[0])
475 return true; // Unknown modifier.
476 if (MI->getOperand(OpNo).isRegister())
477 printMemRegReg(MI, OpNo);
479 printMemRegImm(MI, OpNo);
483 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
484 const char *Modifier) {
485 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
486 unsigned Code = MI->getOperand(OpNo).getImm();
487 if (!strcmp(Modifier, "cc")) {
488 switch ((PPC::Predicate)Code) {
489 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
490 case PPC::PRED_LT: O << "lt"; return;
491 case PPC::PRED_LE: O << "le"; return;
492 case PPC::PRED_EQ: O << "eq"; return;
493 case PPC::PRED_GE: O << "ge"; return;
494 case PPC::PRED_GT: O << "gt"; return;
495 case PPC::PRED_NE: O << "ne"; return;
496 case PPC::PRED_UN: O << "un"; return;
497 case PPC::PRED_NU: O << "nu"; return;
501 assert(!strcmp(Modifier, "reg") &&
502 "Need to specify 'cc' or 'reg' as predicate op modifier!");
503 // Don't print the register for 'always'.
504 if (Code == PPC::PRED_ALWAYS) return;
505 printOperand(MI, OpNo+1);
510 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
511 /// the current output stream.
513 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
516 // Check for slwi/srwi mnemonics.
517 if (MI->getOpcode() == PPC::RLWINM) {
518 bool FoundMnemonic = false;
519 unsigned char SH = MI->getOperand(2).getImm();
520 unsigned char MB = MI->getOperand(3).getImm();
521 unsigned char ME = MI->getOperand(4).getImm();
522 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
523 O << "\tslwi "; FoundMnemonic = true;
525 if (SH <= 31 && MB == (32-SH) && ME == 31) {
526 O << "\tsrwi "; FoundMnemonic = true;
533 O << ", " << (unsigned int)SH << '\n';
536 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
537 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
545 } else if (MI->getOpcode() == PPC::RLDICR) {
546 unsigned char SH = MI->getOperand(2).getImm();
547 unsigned char ME = MI->getOperand(3).getImm();
548 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
554 O << ", " << (unsigned int)SH << '\n';
559 if (printInstruction(MI))
560 return; // Printer was automatically generated
562 assert(0 && "Unhandled instruction in asm writer!");
567 /// runOnMachineFunction - This uses the printMachineInstruction()
568 /// method to print assembly for each instruction.
570 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
572 SetupMachineFunction(MF);
575 // Print out constants referenced by the function
576 EmitConstantPool(MF.getConstantPool());
578 // Print out labels for the function.
579 const Function *F = MF.getFunction();
580 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
582 switch (F->getLinkage()) {
583 default: assert(0 && "Unknown linkage type!");
584 case Function::InternalLinkage: // Symbols default to internal.
586 case Function::ExternalLinkage:
587 O << "\t.global\t" << CurrentFnName << '\n'
588 << "\t.type\t" << CurrentFnName << ", @function\n";
590 case Function::WeakLinkage:
591 case Function::LinkOnceLinkage:
592 O << "\t.global\t" << CurrentFnName << '\n';
593 O << "\t.weak\t" << CurrentFnName << '\n';
597 printVisibility(CurrentFnName, F->getVisibility());
600 O << CurrentFnName << ":\n";
602 // Emit pre-function debug information.
603 DW.BeginFunction(&MF);
605 // Print out code for the function.
606 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
608 // Print a label for the basic block.
609 if (I != MF.begin()) {
610 printBasicBlockLabel(I, true, true);
613 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
615 // Print the assembly for the instruction.
616 printMachineInstruction(II);
620 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
622 // Print out jump tables referenced by the function.
623 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
625 // Emit post-function debug information.
628 // We didn't modify anything.
632 bool PPCLinuxAsmPrinter::doInitialization(Module &M) {
633 bool Result = AsmPrinter::doInitialization(M);
635 // Emit initial debug information.
638 // AsmPrinter::doInitialization should have done this analysis.
639 MMI = getAnalysisToUpdate<MachineModuleInfo>();
641 DW.SetModuleInfo(MMI);
643 // GNU as handles section names wrapped in quotes
644 Mang->setUseQuotes(true);
646 SwitchToTextSection(TAI->getTextSection());
651 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
652 /// Don't print things like \n or \0.
653 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
654 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
660 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
661 const TargetData *TD = TM.getTargetData();
663 if (!GVar->hasInitializer())
664 return; // External global require no code
666 // Check to see if this is a special global used by LLVM, if so, emit it.
667 if (EmitSpecialLLVMGlobal(GVar))
670 std::string name = Mang->getValueName(GVar);
671 std::string SectionName = TAI->SectionForGlobal(GVar);
673 printVisibility(name, GVar->getVisibility());
675 Constant *C = GVar->getInitializer();
676 const Type *Type = C->getType();
677 unsigned Size = TD->getABITypeSize(Type);
678 unsigned Align = TD->getPreferredAlignmentLog(GVar);
680 SwitchToDataSection(SectionName.c_str());
682 if (C->isNullValue() && /* FIXME: Verify correct */
683 !GVar->hasSection() &&
684 (GVar->hasInternalLinkage() || GVar->hasExternalLinkage() ||
685 GVar->isWeakForLinker())) {
686 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
688 if (GVar->hasExternalLinkage()) {
689 O << "\t.global " << name << '\n';
690 O << "\t.type " << name << ", @object\n";
692 O << "\t.zero " << Size << '\n';
693 } else if (GVar->hasInternalLinkage()) {
694 O << TAI->getLCOMMDirective() << name << ',' << Size;
696 O << ".comm " << name << ',' << Size;
698 O << "\t\t" << TAI->getCommentString() << " '";
699 PrintUnmangledNameSafely(GVar, O);
704 switch (GVar->getLinkage()) {
705 case GlobalValue::LinkOnceLinkage:
706 case GlobalValue::WeakLinkage:
707 case GlobalValue::CommonLinkage:
708 O << "\t.global " << name << '\n'
709 << "\t.type " << name << ", @object\n"
710 << "\t.weak " << name << '\n';
712 case GlobalValue::AppendingLinkage:
713 // FIXME: appending linkage variables should go into a section of
714 // their name or something. For now, just emit them as external.
715 case GlobalValue::ExternalLinkage:
716 // If external or appending, declare as a global symbol
717 O << "\t.global " << name << '\n'
718 << "\t.type " << name << ", @object\n";
720 case GlobalValue::InternalLinkage:
723 cerr << "Unknown linkage type!";
727 EmitAlignment(Align, GVar);
728 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
729 PrintUnmangledNameSafely(GVar, O);
732 // If the initializer is a extern weak symbol, remember to emit the weak
734 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
735 if (GV->hasExternalWeakLinkage())
736 ExtWeakSymbols.insert(GV);
738 EmitGlobalConstant(C);
742 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
743 // Print out module-level global variables here.
744 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
746 printModuleLevelGV(I);
750 // Emit initial debug information.
753 return AsmPrinter::doFinalization(M);
756 std::string PPCLinuxAsmPrinter::getSectionForFunction(const Function &F) const {
757 return TAI->SectionForGlobal(&F);
760 std::string PPCDarwinAsmPrinter::getSectionForFunction(const Function &F) const {
761 return TAI->SectionForGlobal(&F);
764 /// runOnMachineFunction - This uses the printMachineInstruction()
765 /// method to print assembly for each instruction.
767 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
768 SetupMachineFunction(MF);
771 // Print out constants referenced by the function
772 EmitConstantPool(MF.getConstantPool());
774 // Print out labels for the function.
775 const Function *F = MF.getFunction();
776 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
778 switch (F->getLinkage()) {
779 default: assert(0 && "Unknown linkage type!");
780 case Function::InternalLinkage: // Symbols default to internal.
782 case Function::ExternalLinkage:
783 O << "\t.globl\t" << CurrentFnName << '\n';
785 case Function::WeakLinkage:
786 case Function::LinkOnceLinkage:
787 O << "\t.globl\t" << CurrentFnName << '\n';
788 O << "\t.weak_definition\t" << CurrentFnName << '\n';
792 printVisibility(CurrentFnName, F->getVisibility());
794 EmitAlignment(OptimizeForSize ? 2 : 4, F);
795 O << CurrentFnName << ":\n";
797 // Emit pre-function debug information.
798 DW.BeginFunction(&MF);
800 // If the function is empty, then we need to emit *something*. Otherwise, the
801 // function's label might be associated with something that it wasn't meant to
802 // be associated with. We emit a noop in this situation.
803 MachineFunction::iterator I = MF.begin();
805 if (++I == MF.end() && MF.front().empty())
808 // Print out code for the function.
809 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
811 // Print a label for the basic block.
812 if (I != MF.begin()) {
813 printBasicBlockLabel(I, true, true);
816 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
818 // Print the assembly for the instruction.
819 printMachineInstruction(II);
823 // Print out jump tables referenced by the function.
824 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
826 // Emit post-function debug information.
829 // We didn't modify anything.
834 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
835 static const char *const CPUDirectives[] = {
847 unsigned Directive = Subtarget.getDarwinDirective();
848 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
849 Directive = PPC::DIR_970;
850 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
851 Directive = PPC::DIR_7400;
852 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
853 Directive = PPC::DIR_64;
854 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
855 O << "\t.machine " << CPUDirectives[Directive] << '\n';
857 bool Result = AsmPrinter::doInitialization(M);
859 // Emit initial debug information.
862 // We need this for Personality functions.
863 // AsmPrinter::doInitialization should have done this analysis.
864 MMI = getAnalysisToUpdate<MachineModuleInfo>();
866 DW.SetModuleInfo(MMI);
868 // Darwin wants symbols to be quoted if they have complex names.
869 Mang->setUseQuotes(true);
871 // Prime text sections so they are adjacent. This reduces the likelihood a
872 // large data or debug section causes a branch to exceed 16M limit.
873 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
874 "pure_instructions");
875 if (TM.getRelocationModel() == Reloc::PIC_) {
876 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
877 "pure_instructions,32");
878 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
879 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
880 "pure_instructions,16");
882 SwitchToTextSection(TAI->getTextSection());
887 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
888 const TargetData *TD = TM.getTargetData();
890 if (!GVar->hasInitializer())
891 return; // External global require no code
893 // Check to see if this is a special global used by LLVM, if so, emit it.
894 if (EmitSpecialLLVMGlobal(GVar)) {
895 if (TM.getRelocationModel() == Reloc::Static) {
896 if (GVar->getName() == "llvm.global_ctors")
897 O << ".reference .constructors_used\n";
898 else if (GVar->getName() == "llvm.global_dtors")
899 O << ".reference .destructors_used\n";
904 std::string name = Mang->getValueName(GVar);
905 std::string SectionName = TAI->SectionForGlobal(GVar);
907 printVisibility(name, GVar->getVisibility());
909 Constant *C = GVar->getInitializer();
910 const Type *Type = C->getType();
911 unsigned Size = TD->getABITypeSize(Type);
912 unsigned Align = TD->getPreferredAlignmentLog(GVar);
914 SwitchToDataSection(SectionName.c_str());
916 if (C->isNullValue() && /* FIXME: Verify correct */
917 !GVar->hasSection() &&
918 (GVar->hasInternalLinkage() || GVar->hasExternalLinkage() ||
919 GVar->isWeakForLinker())) {
920 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
922 if (GVar->hasExternalLinkage()) {
923 O << "\t.globl " << name << '\n';
924 O << "\t.zerofill __DATA, __common, " << name << ", "
925 << Size << ", " << Align;
926 } else if (GVar->hasInternalLinkage()) {
927 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
928 } else if (!GVar->hasCommonLinkage()) {
929 O << "\t.globl " << name << '\n'
930 << TAI->getWeakDefDirective() << name << '\n';
931 EmitAlignment(Align, GVar);
932 O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
933 PrintUnmangledNameSafely(GVar, O);
935 EmitGlobalConstant(C);
938 O << ".comm " << name << ',' << Size;
939 // Darwin 9 and above support aligned common data.
940 if (Subtarget.isDarwin9())
943 O << "\t\t" << TAI->getCommentString() << " '";
944 PrintUnmangledNameSafely(GVar, O);
949 switch (GVar->getLinkage()) {
950 case GlobalValue::LinkOnceLinkage:
951 case GlobalValue::WeakLinkage:
952 case GlobalValue::CommonLinkage:
953 O << "\t.globl " << name << '\n'
954 << "\t.weak_definition " << name << '\n';
956 case GlobalValue::AppendingLinkage:
957 // FIXME: appending linkage variables should go into a section of
958 // their name or something. For now, just emit them as external.
959 case GlobalValue::ExternalLinkage:
960 // If external or appending, declare as a global symbol
961 O << "\t.globl " << name << '\n';
963 case GlobalValue::InternalLinkage:
966 cerr << "Unknown linkage type!";
970 EmitAlignment(Align, GVar);
971 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
972 PrintUnmangledNameSafely(GVar, O);
975 // If the initializer is a extern weak symbol, remember to emit the weak
977 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
978 if (GV->hasExternalWeakLinkage())
979 ExtWeakSymbols.insert(GV);
981 EmitGlobalConstant(C);
985 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
986 const TargetData *TD = TM.getTargetData();
988 // Print out module-level global variables here.
989 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
991 printModuleLevelGV(I);
993 bool isPPC64 = TD->getPointerSizeInBits() == 64;
995 // Output stubs for dynamically-linked functions
996 if (TM.getRelocationModel() == Reloc::PIC_) {
997 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
999 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1000 "pure_instructions,32");
1003 std::string L0p = (p[0]=='\"') ? "\"L0$" + p.substr(1) : "L0$" + p ;
1004 printSuffixedName(p, "$stub");
1006 O << "\t.indirect_symbol " << *i << '\n';
1008 O << "\tbcl 20,31," << L0p << '\n';
1010 O << "\tmflr r11\n";
1011 O << "\taddis r11,r11,ha16(";
1012 printSuffixedName(p, "$lazy_ptr");
1013 O << "-" << L0p << ")\n";
1016 O << "\tldu r12,lo16(";
1018 O << "\tlwzu r12,lo16(";
1019 printSuffixedName(p, "$lazy_ptr");
1020 O << "-" << L0p << ")(r11)\n";
1021 O << "\tmtctr r12\n";
1023 SwitchToDataSection(".lazy_symbol_pointer");
1024 printSuffixedName(p, "$lazy_ptr");
1026 O << "\t.indirect_symbol " << *i << '\n';
1028 O << "\t.quad dyld_stub_binding_helper\n";
1030 O << "\t.long dyld_stub_binding_helper\n";
1033 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1035 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1036 "pure_instructions,16");
1039 printSuffixedName(p, "$stub");
1041 O << "\t.indirect_symbol " << *i << '\n';
1042 O << "\tlis r11,ha16(";
1043 printSuffixedName(p, "$lazy_ptr");
1046 O << "\tldu r12,lo16(";
1048 O << "\tlwzu r12,lo16(";
1049 printSuffixedName(p, "$lazy_ptr");
1051 O << "\tmtctr r12\n";
1053 SwitchToDataSection(".lazy_symbol_pointer");
1054 printSuffixedName(p, "$lazy_ptr");
1056 O << "\t.indirect_symbol " << *i << '\n';
1058 O << "\t.quad dyld_stub_binding_helper\n";
1060 O << "\t.long dyld_stub_binding_helper\n";
1066 if (TAI->doesSupportExceptionHandling() && MMI) {
1067 // Add the (possibly multiple) personalities to the set of global values.
1068 // Only referenced functions get into the Personalities list.
1069 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1071 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1072 E = Personalities.end(); I != E; ++I)
1073 if (*I) GVStubs.insert("_" + (*I)->getName());
1076 // Output stubs for external and common global variables.
1077 if (!GVStubs.empty()) {
1078 SwitchToDataSection(".non_lazy_symbol_pointer");
1079 for (std::set<std::string>::iterator I = GVStubs.begin(),
1080 E = GVStubs.end(); I != E; ++I) {
1082 printSuffixedName(p, "$non_lazy_ptr");
1084 O << "\t.indirect_symbol " << *I << '\n';
1086 O << "\t.quad\t0\n";
1088 O << "\t.long\t0\n";
1092 // Emit initial debug information.
1095 // Funny Darwin hack: This flag tells the linker that no global symbols
1096 // contain code that falls through to other global symbols (e.g. the obvious
1097 // implementation of multiple entry points). If this doesn't occur, the
1098 // linker can safely perform dead code stripping. Since LLVM never generates
1099 // code that does this, it is always safe to set.
1100 O << "\t.subsections_via_symbols\n";
1102 return AsmPrinter::doFinalization(M);
1107 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1108 /// for a MachineFunction to the given output stream, in a format that the
1109 /// Darwin assembler can deal with.
1111 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1112 PPCTargetMachine &tm) {
1113 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1115 if (Subtarget->isDarwin()) {
1116 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1118 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1123 static struct Register {
1125 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);