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 void printModuleLevelGV(const GlobalVariable* GVar);
321 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
323 struct VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
326 MachineModuleInfo *MMI;
328 PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
329 const TargetAsmInfo *T)
330 : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
333 virtual const char *getPassName() const {
334 return "Darwin PPC Assembly Printer";
337 bool runOnMachineFunction(MachineFunction &F);
338 bool doInitialization(Module &M);
339 bool doFinalization(Module &M);
341 void getAnalysisUsage(AnalysisUsage &AU) const {
342 AU.setPreservesAll();
343 AU.addRequired<MachineModuleInfo>();
344 PPCAsmPrinter::getAnalysisUsage(AU);
347 void printModuleLevelGV(const GlobalVariable* GVar);
349 } // end of anonymous namespace
351 // Include the auto-generated portion of the assembly writer
352 #include "PPCGenAsmWriter.inc"
354 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
355 switch (MO.getType()) {
356 case MachineOperand::MO_Immediate:
357 cerr << "printOp() does not handle immediate values\n";
361 case MachineOperand::MO_MachineBasicBlock:
362 printBasicBlockLabel(MO.getMBB());
364 case MachineOperand::MO_JumpTableIndex:
365 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
366 << '_' << MO.getIndex();
367 // FIXME: PIC relocation model
369 case MachineOperand::MO_ConstantPoolIndex:
370 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
371 << '_' << MO.getIndex();
373 case MachineOperand::MO_ExternalSymbol:
374 // Computing the address of an external symbol, not calling it.
375 if (TM.getRelocationModel() != Reloc::Static) {
376 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
377 GVStubs.insert(Name);
378 printSuffixedName(Name, "$non_lazy_ptr");
381 O << TAI->getGlobalPrefix() << MO.getSymbolName();
383 case MachineOperand::MO_GlobalAddress: {
384 // Computing the address of a global symbol, not calling it.
385 GlobalValue *GV = MO.getGlobal();
386 std::string Name = Mang->getValueName(GV);
388 // External or weakly linked global variables need non-lazily-resolved stubs
389 if (TM.getRelocationModel() != Reloc::Static) {
390 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
391 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
392 GVStubs.insert(Name);
393 printSuffixedName(Name, "$non_lazy_ptr");
394 if (GV->hasExternalWeakLinkage())
395 ExtWeakSymbols.insert(GV);
401 if (MO.getOffset() > 0)
402 O << "+" << MO.getOffset();
403 else if (MO.getOffset() < 0)
406 if (GV->hasExternalWeakLinkage())
407 ExtWeakSymbols.insert(GV);
412 O << "<unknown operand type: " << MO.getType() << ">";
417 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
419 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
420 std::string Name = getGlobalLinkName(GV);
421 if (TM.getRelocationModel() != Reloc::Static) {
422 GVStubs.insert(Name);
423 printSuffixedName(Name, "$non_lazy_ptr");
429 /// PrintAsmOperand - Print out an operand for an inline asm expression.
431 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
433 const char *ExtraCode) {
434 // Does this asm operand have a single letter operand modifier?
435 if (ExtraCode && ExtraCode[0]) {
436 if (ExtraCode[1] != 0) return true; // Unknown modifier.
438 switch (ExtraCode[0]) {
439 default: return true; // Unknown modifier.
440 case 'c': // Don't print "$" before a global var name or constant.
441 // PPC never has a prefix.
442 printOperand(MI, OpNo);
444 case 'L': // Write second word of DImode reference.
445 // Verify that this operand has two consecutive registers.
446 if (!MI->getOperand(OpNo).isRegister() ||
447 OpNo+1 == MI->getNumOperands() ||
448 !MI->getOperand(OpNo+1).isRegister())
450 ++OpNo; // Return the high-part.
453 // Write 'i' if an integer constant, otherwise nothing. Used to print
455 if (MI->getOperand(OpNo).isImmediate())
461 printOperand(MI, OpNo);
465 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
467 const char *ExtraCode) {
468 if (ExtraCode && ExtraCode[0])
469 return true; // Unknown modifier.
470 if (MI->getOperand(OpNo).isRegister())
471 printMemRegReg(MI, OpNo);
473 printMemRegImm(MI, OpNo);
477 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
478 const char *Modifier) {
479 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
480 unsigned Code = MI->getOperand(OpNo).getImm();
481 if (!strcmp(Modifier, "cc")) {
482 switch ((PPC::Predicate)Code) {
483 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
484 case PPC::PRED_LT: O << "lt"; return;
485 case PPC::PRED_LE: O << "le"; return;
486 case PPC::PRED_EQ: O << "eq"; return;
487 case PPC::PRED_GE: O << "ge"; return;
488 case PPC::PRED_GT: O << "gt"; return;
489 case PPC::PRED_NE: O << "ne"; return;
490 case PPC::PRED_UN: O << "un"; return;
491 case PPC::PRED_NU: O << "nu"; return;
495 assert(!strcmp(Modifier, "reg") &&
496 "Need to specify 'cc' or 'reg' as predicate op modifier!");
497 // Don't print the register for 'always'.
498 if (Code == PPC::PRED_ALWAYS) return;
499 printOperand(MI, OpNo+1);
504 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
505 /// the current output stream.
507 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
510 // Check for slwi/srwi mnemonics.
511 if (MI->getOpcode() == PPC::RLWINM) {
512 bool FoundMnemonic = false;
513 unsigned char SH = MI->getOperand(2).getImm();
514 unsigned char MB = MI->getOperand(3).getImm();
515 unsigned char ME = MI->getOperand(4).getImm();
516 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
517 O << "\tslwi "; FoundMnemonic = true;
519 if (SH <= 31 && MB == (32-SH) && ME == 31) {
520 O << "\tsrwi "; FoundMnemonic = true;
527 O << ", " << (unsigned int)SH << '\n';
530 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
531 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
539 } else if (MI->getOpcode() == PPC::RLDICR) {
540 unsigned char SH = MI->getOperand(2).getImm();
541 unsigned char ME = MI->getOperand(3).getImm();
542 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
548 O << ", " << (unsigned int)SH << '\n';
553 if (printInstruction(MI))
554 return; // Printer was automatically generated
556 assert(0 && "Unhandled instruction in asm writer!");
561 /// runOnMachineFunction - This uses the printMachineInstruction()
562 /// method to print assembly for each instruction.
564 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
566 SetupMachineFunction(MF);
569 // Print out constants referenced by the function
570 EmitConstantPool(MF.getConstantPool());
572 // Print out labels for the function.
573 const Function *F = MF.getFunction();
574 SwitchToSection(TAI->SectionForGlobal(F));
576 switch (F->getLinkage()) {
577 default: assert(0 && "Unknown linkage type!");
578 case Function::InternalLinkage: // Symbols default to internal.
580 case Function::ExternalLinkage:
581 O << "\t.global\t" << CurrentFnName << '\n'
582 << "\t.type\t" << CurrentFnName << ", @function\n";
584 case Function::WeakLinkage:
585 case Function::LinkOnceLinkage:
586 O << "\t.global\t" << CurrentFnName << '\n';
587 O << "\t.weak\t" << CurrentFnName << '\n';
591 printVisibility(CurrentFnName, F->getVisibility());
594 O << CurrentFnName << ":\n";
596 // Emit pre-function debug information.
597 DW.BeginFunction(&MF);
599 // Print out code for the function.
600 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
602 // Print a label for the basic block.
603 if (I != MF.begin()) {
604 printBasicBlockLabel(I, true, true);
607 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
609 // Print the assembly for the instruction.
610 printMachineInstruction(II);
614 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
616 // Print out jump tables referenced by the function.
617 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
619 // Emit post-function debug information.
622 // We didn't modify anything.
626 bool PPCLinuxAsmPrinter::doInitialization(Module &M) {
627 bool Result = AsmPrinter::doInitialization(M);
629 // Emit initial debug information.
632 // AsmPrinter::doInitialization should have done this analysis.
633 MMI = getAnalysisToUpdate<MachineModuleInfo>();
635 DW.SetModuleInfo(MMI);
637 // GNU as handles section names wrapped in quotes
638 Mang->setUseQuotes(true);
640 SwitchToSection(TAI->getTextSection());
645 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
646 /// Don't print things like \n or \0.
647 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
648 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
654 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
655 const TargetData *TD = TM.getTargetData();
657 if (!GVar->hasInitializer())
658 return; // External global require no code
660 // Check to see if this is a special global used by LLVM, if so, emit it.
661 if (EmitSpecialLLVMGlobal(GVar))
664 std::string name = Mang->getValueName(GVar);
666 printVisibility(name, GVar->getVisibility());
668 Constant *C = GVar->getInitializer();
669 const Type *Type = C->getType();
670 unsigned Size = TD->getABITypeSize(Type);
671 unsigned Align = TD->getPreferredAlignmentLog(GVar);
673 SwitchToSection(TAI->SectionForGlobal(GVar));
675 if (C->isNullValue() && /* FIXME: Verify correct */
676 !GVar->hasSection() &&
677 (GVar->hasInternalLinkage() || GVar->hasExternalLinkage() ||
678 GVar->isWeakForLinker())) {
679 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
681 if (GVar->hasExternalLinkage()) {
682 O << "\t.global " << name << '\n';
683 O << "\t.type " << name << ", @object\n";
685 O << "\t.zero " << Size << '\n';
686 } else if (GVar->hasInternalLinkage()) {
687 O << TAI->getLCOMMDirective() << name << ',' << Size;
689 O << ".comm " << name << ',' << Size;
691 O << "\t\t" << TAI->getCommentString() << " '";
692 PrintUnmangledNameSafely(GVar, O);
697 switch (GVar->getLinkage()) {
698 case GlobalValue::LinkOnceLinkage:
699 case GlobalValue::WeakLinkage:
700 case GlobalValue::CommonLinkage:
701 O << "\t.global " << name << '\n'
702 << "\t.type " << name << ", @object\n"
703 << "\t.weak " << name << '\n';
705 case GlobalValue::AppendingLinkage:
706 // FIXME: appending linkage variables should go into a section of
707 // their name or something. For now, just emit them as external.
708 case GlobalValue::ExternalLinkage:
709 // If external or appending, declare as a global symbol
710 O << "\t.global " << name << '\n'
711 << "\t.type " << name << ", @object\n";
713 case GlobalValue::InternalLinkage:
716 cerr << "Unknown linkage type!";
720 EmitAlignment(Align, GVar);
721 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
722 PrintUnmangledNameSafely(GVar, O);
725 // If the initializer is a extern weak symbol, remember to emit the weak
727 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
728 if (GV->hasExternalWeakLinkage())
729 ExtWeakSymbols.insert(GV);
731 EmitGlobalConstant(C);
735 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
736 // Print out module-level global variables here.
737 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
739 printModuleLevelGV(I);
743 // Emit initial debug information.
746 return AsmPrinter::doFinalization(M);
749 /// runOnMachineFunction - This uses the printMachineInstruction()
750 /// method to print assembly for each instruction.
752 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
753 SetupMachineFunction(MF);
756 // Print out constants referenced by the function
757 EmitConstantPool(MF.getConstantPool());
759 // Print out labels for the function.
760 const Function *F = MF.getFunction();
761 SwitchToSection(TAI->SectionForGlobal(F));
763 switch (F->getLinkage()) {
764 default: assert(0 && "Unknown linkage type!");
765 case Function::InternalLinkage: // Symbols default to internal.
767 case Function::ExternalLinkage:
768 O << "\t.globl\t" << CurrentFnName << '\n';
770 case Function::WeakLinkage:
771 case Function::LinkOnceLinkage:
772 O << "\t.globl\t" << CurrentFnName << '\n';
773 O << "\t.weak_definition\t" << CurrentFnName << '\n';
777 printVisibility(CurrentFnName, F->getVisibility());
779 EmitAlignment(OptimizeForSize ? 2 : 4, F);
780 O << CurrentFnName << ":\n";
782 // Emit pre-function debug information.
783 DW.BeginFunction(&MF);
785 // If the function is empty, then we need to emit *something*. Otherwise, the
786 // function's label might be associated with something that it wasn't meant to
787 // be associated with. We emit a noop in this situation.
788 MachineFunction::iterator I = MF.begin();
790 if (++I == MF.end() && MF.front().empty())
793 // Print out code for the function.
794 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
796 // Print a label for the basic block.
797 if (I != MF.begin()) {
798 printBasicBlockLabel(I, true, true);
801 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
803 // Print the assembly for the instruction.
804 printMachineInstruction(II);
808 // Print out jump tables referenced by the function.
809 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
811 // Emit post-function debug information.
814 // We didn't modify anything.
819 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
820 static const char *const CPUDirectives[] = {
832 unsigned Directive = Subtarget.getDarwinDirective();
833 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
834 Directive = PPC::DIR_970;
835 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
836 Directive = PPC::DIR_7400;
837 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
838 Directive = PPC::DIR_64;
839 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
840 O << "\t.machine " << CPUDirectives[Directive] << '\n';
842 bool Result = AsmPrinter::doInitialization(M);
844 // Emit initial debug information.
847 // We need this for Personality functions.
848 // AsmPrinter::doInitialization should have done this analysis.
849 MMI = getAnalysisToUpdate<MachineModuleInfo>();
851 DW.SetModuleInfo(MMI);
853 // Darwin wants symbols to be quoted if they have complex names.
854 Mang->setUseQuotes(true);
856 // Prime text sections so they are adjacent. This reduces the likelihood a
857 // large data or debug section causes a branch to exceed 16M limit.
858 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
859 "pure_instructions");
860 if (TM.getRelocationModel() == Reloc::PIC_) {
861 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
862 "pure_instructions,32");
863 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
864 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
865 "pure_instructions,16");
867 SwitchToSection(TAI->getTextSection());
872 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
873 const TargetData *TD = TM.getTargetData();
875 if (!GVar->hasInitializer())
876 return; // External global require no code
878 // Check to see if this is a special global used by LLVM, if so, emit it.
879 if (EmitSpecialLLVMGlobal(GVar)) {
880 if (TM.getRelocationModel() == Reloc::Static) {
881 if (GVar->getName() == "llvm.global_ctors")
882 O << ".reference .constructors_used\n";
883 else if (GVar->getName() == "llvm.global_dtors")
884 O << ".reference .destructors_used\n";
889 std::string name = Mang->getValueName(GVar);
891 printVisibility(name, GVar->getVisibility());
893 Constant *C = GVar->getInitializer();
894 const Type *Type = C->getType();
895 unsigned Size = TD->getABITypeSize(Type);
896 unsigned Align = TD->getPreferredAlignmentLog(GVar);
898 SwitchToSection(TAI->SectionForGlobal(GVar));
900 if (C->isNullValue() && /* FIXME: Verify correct */
901 !GVar->hasSection() &&
902 (GVar->hasInternalLinkage() || GVar->hasExternalLinkage() ||
903 GVar->isWeakForLinker())) {
904 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
906 if (GVar->hasExternalLinkage()) {
907 O << "\t.globl " << name << '\n';
908 O << "\t.zerofill __DATA, __common, " << name << ", "
909 << Size << ", " << Align;
910 } else if (GVar->hasInternalLinkage()) {
911 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
912 } else if (!GVar->hasCommonLinkage()) {
913 O << "\t.globl " << name << '\n'
914 << TAI->getWeakDefDirective() << name << '\n';
915 EmitAlignment(Align, GVar);
916 O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
917 PrintUnmangledNameSafely(GVar, O);
919 EmitGlobalConstant(C);
922 O << ".comm " << name << ',' << Size;
923 // Darwin 9 and above support aligned common data.
924 if (Subtarget.isDarwin9())
927 O << "\t\t" << TAI->getCommentString() << " '";
928 PrintUnmangledNameSafely(GVar, O);
933 switch (GVar->getLinkage()) {
934 case GlobalValue::LinkOnceLinkage:
935 case GlobalValue::WeakLinkage:
936 case GlobalValue::CommonLinkage:
937 O << "\t.globl " << name << '\n'
938 << "\t.weak_definition " << name << '\n';
940 case GlobalValue::AppendingLinkage:
941 // FIXME: appending linkage variables should go into a section of
942 // their name or something. For now, just emit them as external.
943 case GlobalValue::ExternalLinkage:
944 // If external or appending, declare as a global symbol
945 O << "\t.globl " << name << '\n';
947 case GlobalValue::InternalLinkage:
950 cerr << "Unknown linkage type!";
954 EmitAlignment(Align, GVar);
955 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
956 PrintUnmangledNameSafely(GVar, O);
959 // If the initializer is a extern weak symbol, remember to emit the weak
961 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
962 if (GV->hasExternalWeakLinkage())
963 ExtWeakSymbols.insert(GV);
965 EmitGlobalConstant(C);
969 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
970 const TargetData *TD = TM.getTargetData();
972 // Print out module-level global variables here.
973 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
975 printModuleLevelGV(I);
977 bool isPPC64 = TD->getPointerSizeInBits() == 64;
979 // Output stubs for dynamically-linked functions
980 if (TM.getRelocationModel() == Reloc::PIC_) {
981 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
983 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
984 "pure_instructions,32");
987 std::string L0p = (p[0]=='\"') ? "\"L0$" + p.substr(1) : "L0$" + p ;
988 printSuffixedName(p, "$stub");
990 O << "\t.indirect_symbol " << *i << '\n';
992 O << "\tbcl 20,31," << L0p << '\n';
995 O << "\taddis r11,r11,ha16(";
996 printSuffixedName(p, "$lazy_ptr");
997 O << "-" << L0p << ")\n";
1000 O << "\tldu r12,lo16(";
1002 O << "\tlwzu r12,lo16(";
1003 printSuffixedName(p, "$lazy_ptr");
1004 O << "-" << L0p << ")(r11)\n";
1005 O << "\tmtctr r12\n";
1007 SwitchToDataSection(".lazy_symbol_pointer");
1008 printSuffixedName(p, "$lazy_ptr");
1010 O << "\t.indirect_symbol " << *i << '\n';
1012 O << "\t.quad dyld_stub_binding_helper\n";
1014 O << "\t.long dyld_stub_binding_helper\n";
1017 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1019 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1020 "pure_instructions,16");
1023 printSuffixedName(p, "$stub");
1025 O << "\t.indirect_symbol " << *i << '\n';
1026 O << "\tlis r11,ha16(";
1027 printSuffixedName(p, "$lazy_ptr");
1030 O << "\tldu r12,lo16(";
1032 O << "\tlwzu r12,lo16(";
1033 printSuffixedName(p, "$lazy_ptr");
1035 O << "\tmtctr r12\n";
1037 SwitchToDataSection(".lazy_symbol_pointer");
1038 printSuffixedName(p, "$lazy_ptr");
1040 O << "\t.indirect_symbol " << *i << '\n';
1042 O << "\t.quad dyld_stub_binding_helper\n";
1044 O << "\t.long dyld_stub_binding_helper\n";
1050 if (TAI->doesSupportExceptionHandling() && MMI) {
1051 // Add the (possibly multiple) personalities to the set of global values.
1052 // Only referenced functions get into the Personalities list.
1053 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1055 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1056 E = Personalities.end(); I != E; ++I)
1057 if (*I) GVStubs.insert("_" + (*I)->getName());
1060 // Output stubs for external and common global variables.
1061 if (!GVStubs.empty()) {
1062 SwitchToDataSection(".non_lazy_symbol_pointer");
1063 for (std::set<std::string>::iterator I = GVStubs.begin(),
1064 E = GVStubs.end(); I != E; ++I) {
1066 printSuffixedName(p, "$non_lazy_ptr");
1068 O << "\t.indirect_symbol " << *I << '\n';
1070 O << "\t.quad\t0\n";
1072 O << "\t.long\t0\n";
1076 // Emit initial debug information.
1079 // Funny Darwin hack: This flag tells the linker that no global symbols
1080 // contain code that falls through to other global symbols (e.g. the obvious
1081 // implementation of multiple entry points). If this doesn't occur, the
1082 // linker can safely perform dead code stripping. Since LLVM never generates
1083 // code that does this, it is always safe to set.
1084 O << "\t.subsections_via_symbols\n";
1086 return AsmPrinter::doFinalization(M);
1091 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1092 /// for a MachineFunction to the given output stream, in a format that the
1093 /// Darwin assembler can deal with.
1095 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1096 PPCTargetMachine &tm) {
1097 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1099 if (Subtarget->isDarwin()) {
1100 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1102 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1107 static struct Register {
1109 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);