1 //===-- PowerPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "PowerPCTargetMachine.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringExtras.h"
40 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
42 struct PPC32AsmPrinter : public AsmPrinter {
43 std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
44 std::set<std::string> Strings;
46 PPC32AsmPrinter(std::ostream &O, TargetMachine &TM)
47 : AsmPrinter(O, TM), LabelNumber(0) {}
49 /// Unique incrementer for label values for referencing Global values.
53 virtual const char *getPassName() const {
54 return "PowerPC Assembly Printer";
57 PowerPCTargetMachine &getTM() {
58 return static_cast<PowerPCTargetMachine&>(TM);
61 /// printInstruction - This method is automatically generated by tablegen
62 /// from the instruction set description. This method returns true if the
63 /// machine instruction was sufficiently described to print it, otherwise it
65 bool printInstruction(const MachineInstr *MI);
67 void printMachineInstruction(const MachineInstr *MI);
68 void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
70 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
71 const MachineOperand &MO = MI->getOperand(OpNo);
72 if (MO.getType() == MachineOperand::MO_MachineRegister) {
73 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
74 O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
75 } else if (MO.isImmediate()) {
76 O << MO.getImmedValue();
82 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
84 unsigned char value = MI->getOperand(OpNo).getImmedValue();
85 assert(value <= 31 && "Invalid u5imm argument!");
86 O << (unsigned int)value;
88 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
90 unsigned char value = MI->getOperand(OpNo).getImmedValue();
91 assert(value <= 63 && "Invalid u6imm argument!");
92 O << (unsigned int)value;
94 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
96 O << (short)MI->getOperand(OpNo).getImmedValue();
98 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
100 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
102 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
105 // Branches can take an immediate operand. This is used by the branch
106 // selection pass to print $+8, an eight byte displacement from the PC.
107 if (MI->getOperand(OpNo).isImmediate()) {
108 O << "$+" << MI->getOperand(OpNo).getImmedValue() << '\n';
110 printOp(MI->getOperand(OpNo));
113 void printPICLabel(const MachineInstr *MI, unsigned OpNo,
115 // FIXME: should probably be converted to cout.width and cout.fill
116 O << "\"L0000" << LabelNumber << "$pb\"\n";
117 O << "\"L0000" << LabelNumber << "$pb\":";
119 void printSymbolHi(const MachineInstr *MI, unsigned OpNo,
122 printOp(MI->getOperand(OpNo), true /* LoadAddrOp */);
123 O << "-\"L0000" << LabelNumber << "$pb\")";
125 void printSymbolLo(const MachineInstr *MI, unsigned OpNo,
127 // FIXME: Because LFS, LFD, and LWZ can be used either with a s16imm or
128 // a lo16 of a global or constant pool operand, we must handle both here.
129 // this isn't a great design, but it works for now.
130 if (MI->getOperand(OpNo).isImmediate()) {
131 O << (short)MI->getOperand(OpNo).getImmedValue();
134 printOp(MI->getOperand(OpNo), true /* LoadAddrOp */);
135 O << "-\"L0000" << LabelNumber << "$pb\")";
139 virtual void printConstantPool(MachineConstantPool *MCP) = 0;
140 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
141 virtual bool doFinalization(Module &M) = 0;
146 struct DarwinAsmPrinter : public PPC32AsmPrinter {
148 DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
149 : PPC32AsmPrinter(O, TM) {
152 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
153 Data64bitsDirective = 0; // we can't emit a 64-bit unit
154 AlignmentIsInBytes = false; // Alignment is by power of 2.
157 virtual const char *getPassName() const {
158 return "Darwin PPC Assembly Printer";
161 void printConstantPool(MachineConstantPool *MCP);
162 bool runOnMachineFunction(MachineFunction &F);
163 bool doFinalization(Module &M);
168 struct AIXAsmPrinter : public PPC32AsmPrinter {
169 /// Map for labels corresponding to global variables
171 std::map<const GlobalVariable*,std::string> GVToLabelMap;
173 AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
174 : PPC32AsmPrinter(O, TM) {
177 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
178 Data64bitsDirective = 0; // we can't emit a 64-bit unit
179 AlignmentIsInBytes = false; // Alignment is by power of 2.
182 virtual const char *getPassName() const {
183 return "AIX PPC Assembly Printer";
186 void printConstantPool(MachineConstantPool *MCP);
187 bool runOnMachineFunction(MachineFunction &F);
188 bool doInitialization(Module &M);
189 bool doFinalization(Module &M);
191 } // end of anonymous namespace
193 // SwitchSection - Switch to the specified section of the executable if we are
194 // not already in it!
196 static void SwitchSection(std::ostream &OS, std::string &CurSection,
197 const char *NewSection) {
198 if (CurSection != NewSection) {
199 CurSection = NewSection;
200 if (!CurSection.empty())
201 OS << "\t" << NewSection << "\n";
205 /// isStringCompatible - Can we treat the specified array as a string?
206 /// Only if it is an array of ubytes or non-negative sbytes.
208 static bool isStringCompatible(const ConstantArray *CVA) {
209 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
210 if (ETy == Type::UByteTy) return true;
211 if (ETy != Type::SByteTy) return false;
213 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
214 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
220 /// toOctal - Convert the low order bits of X into an octal digit.
222 static inline char toOctal(int X) {
226 // Possible states while outputting ASCII strings
235 /// SwitchStringSection - manage the changes required to output bytes as
236 /// characters in a string vs. numeric decimal values
238 static inline void SwitchStringSection(std::ostream &O, StringSection NewSect,
239 StringSection &Current) {
240 if (Current == None) {
241 if (NewSect == Alpha)
243 else if (NewSect == Numeric)
245 } else if (Current == Alpha) {
248 else if (NewSect == Numeric)
251 } else if (Current == Numeric) {
252 if (NewSect == Alpha)
255 else if (NewSect == Numeric)
262 /// getAsCString - Return the specified array as a C compatible
263 /// string, only if the predicate isStringCompatible is true.
265 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
266 assert(isStringCompatible(CVA) && "Array is not string compatible!");
268 if (CVA->getNumOperands() == 0)
271 StringSection Current = None;
272 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) {
273 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
275 SwitchStringSection(O, Alpha, Current);
277 } else if (isprint(C)) {
278 SwitchStringSection(O, Alpha, Current);
281 SwitchStringSection(O, Numeric, Current);
282 O << utostr((unsigned)C);
285 SwitchStringSection(O, None, Current);
289 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
290 /// code for a MachineFunction to the given output stream, in a format that the
291 /// Darwin assembler can deal with.
293 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
294 return new DarwinAsmPrinter(o, tm);
297 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
298 /// for a MachineFunction to the given output stream, in a format that the
299 /// AIX 5L assembler can deal with.
301 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
302 return new AIXAsmPrinter(o, tm);
305 // Include the auto-generated portion of the assembly writer
306 #include "PowerPCGenAsmWriter.inc"
308 void PPC32AsmPrinter::printOp(const MachineOperand &MO,
309 bool LoadAddrOp /* = false */) {
310 const MRegisterInfo &RI = *TM.getRegisterInfo();
313 switch (MO.getType()) {
314 case MachineOperand::MO_VirtualRegister:
315 if (Value *V = MO.getVRegValueOrNull()) {
316 O << "<" << V->getName() << ">";
320 case MachineOperand::MO_MachineRegister:
321 case MachineOperand::MO_CCRegister:
322 O << LowercaseString(RI.get(MO.getReg()).Name);
325 case MachineOperand::MO_SignExtendedImmed:
326 case MachineOperand::MO_UnextendedImmed:
327 std::cerr << "printOp() does not handle immediate values\n";
331 case MachineOperand::MO_PCRelativeDisp:
332 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
336 case MachineOperand::MO_MachineBasicBlock: {
337 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
338 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
339 << "_" << MBBOp->getNumber() << "\t; "
340 << MBBOp->getBasicBlock()->getName();
344 case MachineOperand::MO_ConstantPoolIndex:
345 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
348 case MachineOperand::MO_ExternalSymbol:
349 O << MO.getSymbolName();
352 case MachineOperand::MO_GlobalAddress: {
353 GlobalValue *GV = MO.getGlobal();
354 std::string Name = Mang->getValueName(GV);
356 // Dynamically-resolved functions need a stub for the function. Be
357 // wary however not to output $stub for external functions whose addresses
358 // are taken. Those should be emitted as $non_lazy_ptr below.
359 Function *F = dyn_cast<Function>(GV);
360 if (F && F->isExternal() && !LoadAddrOp &&
361 getTM().CalledFunctions.count(F)) {
362 FnStubs.insert(Name);
363 O << "L" << Name << "$stub";
367 // External global variables need a non-lazily-resolved stub
368 if (GV->isExternal() && getTM().AddressTaken.count(GV)) {
369 GVStubs.insert(Name);
370 O << "L" << Name << "$non_lazy_ptr";
374 if (F && LoadAddrOp && getTM().AddressTaken.count(GV)) {
375 LinkOnceStubs.insert(Name);
376 O << "L" << Name << "$non_lazy_ptr";
380 O << Mang->getValueName(GV);
385 O << "<unknown operand type: " << MO.getType() << ">";
390 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
391 /// the current output stream.
393 void PPC32AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
395 if (printInstruction(MI))
396 return; // Printer was automatically generated
398 assert(0 && "Unhandled instruction in asm writer!");
403 /// runOnMachineFunction - This uses the printMachineInstruction()
404 /// method to print assembly for each instruction.
406 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
407 setupMachineFunction(MF);
410 // Print out constants referenced by the function
411 printConstantPool(MF.getConstantPool());
413 // Print out labels for the function.
416 O << "\t.globl\t" << CurrentFnName << "\n";
417 O << CurrentFnName << ":\n";
419 // Print out code for the function.
420 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
422 // Print a label for the basic block.
423 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
424 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
425 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
427 // Print the assembly for the instruction.
429 printMachineInstruction(II);
434 // We didn't modify anything.
438 /// printConstantPool - Print to the current output stream assembly
439 /// representations of the constants in the constant pool MCP. This is
440 /// used to print out constants which have been "spilled to memory" by
441 /// the code generator.
443 void DarwinAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
444 const std::vector<Constant*> &CP = MCP->getConstants();
445 const TargetData &TD = TM.getTargetData();
447 if (CP.empty()) return;
449 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
451 emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
452 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
454 emitGlobalConstant(CP[i]);
458 bool DarwinAsmPrinter::doFinalization(Module &M) {
459 const TargetData &TD = TM.getTargetData();
460 std::string CurSection;
462 // Print out module-level global variables here.
463 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
464 if (I->hasInitializer()) { // External global require no code
466 std::string name = Mang->getValueName(I);
467 Constant *C = I->getInitializer();
468 unsigned Size = TD.getTypeSize(C->getType());
469 unsigned Align = TD.getTypeAlignmentShift(C->getType());
471 if (C->isNullValue() && /* FIXME: Verify correct */
472 (I->hasInternalLinkage() || I->hasWeakLinkage())) {
473 SwitchSection(O, CurSection, ".data");
474 if (I->hasInternalLinkage())
475 O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
478 O << ".comm " << name << "," << TD.getTypeSize(C->getType());
480 WriteAsOperand(O, I, true, true, &M);
483 switch (I->getLinkage()) {
484 case GlobalValue::LinkOnceLinkage:
485 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
486 << ".weak_definition " << name << '\n'
487 << ".private_extern " << name << '\n'
488 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
489 LinkOnceStubs.insert(name);
491 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
492 // Nonnull linkonce -> weak
493 O << "\t.weak " << name << "\n";
494 SwitchSection(O, CurSection, "");
495 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
497 case GlobalValue::AppendingLinkage:
498 // FIXME: appending linkage variables should go into a section of
499 // their name or something. For now, just emit them as external.
500 case GlobalValue::ExternalLinkage:
501 // If external or appending, declare as a global symbol
502 O << "\t.globl " << name << "\n";
504 case GlobalValue::InternalLinkage:
505 SwitchSection(O, CurSection, ".data");
509 emitAlignment(Align);
510 O << name << ":\t\t\t\t; ";
511 WriteAsOperand(O, I, true, true, &M);
513 WriteAsOperand(O, C, false, false, &M);
515 emitGlobalConstant(C);
519 // Output stubs for dynamically-linked functions
520 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
524 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
526 O << "L" << *i << "$stub:\n";
527 O << "\t.indirect_symbol " << *i << "\n";
529 O << "\tbcl 20,31,L0$" << *i << "\n";
530 O << "L0$" << *i << ":\n";
532 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
534 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
535 O << "\tmtctr r12\n";
538 O << ".lazy_symbol_pointer\n";
539 O << "L" << *i << "$lazy_ptr:\n";
540 O << "\t.indirect_symbol " << *i << "\n";
541 O << "\t.long dyld_stub_binding_helper\n";
546 // Output stubs for external global variables
547 if (GVStubs.begin() != GVStubs.end())
548 O << ".data\n.non_lazy_symbol_pointer\n";
549 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
551 O << "L" << *i << "$non_lazy_ptr:\n";
552 O << "\t.indirect_symbol " << *i << "\n";
556 // Output stubs for link-once variables
557 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
558 O << ".data\n.align 2\n";
559 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
560 e = LinkOnceStubs.end(); i != e; ++i) {
561 O << "L" << *i << "$non_lazy_ptr:\n"
562 << "\t.long\t" << *i << '\n';
565 AsmPrinter::doFinalization(M);
566 return false; // success
569 /// runOnMachineFunction - This uses the printMachineInstruction()
570 /// method to print assembly for each instruction.
572 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
573 CurrentFnName = MF.getFunction()->getName();
575 // Print out constants referenced by the function
576 printConstantPool(MF.getConstantPool());
578 // Print out header for the function.
579 O << "\t.csect .text[PR]\n"
581 << "\t.globl " << CurrentFnName << '\n'
582 << "\t.globl ." << CurrentFnName << '\n'
583 << "\t.csect " << CurrentFnName << "[DS],3\n"
584 << CurrentFnName << ":\n"
585 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
586 << "\t.csect .text[PR]\n"
587 << '.' << CurrentFnName << ":\n";
589 // Print out code for the function.
590 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
592 // Print a label for the basic block.
593 O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
594 << I->getBasicBlock()->getName() << "\n";
595 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
597 // Print the assembly for the instruction.
599 printMachineInstruction(II);
604 O << "LT.." << CurrentFnName << ":\n"
606 << "\t.byte 0,0,32,65,128,0,0,0\n"
607 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
609 << "\t.byte \"" << CurrentFnName << "\"\n"
612 // We didn't modify anything.
616 /// printConstantPool - Print to the current output stream assembly
617 /// representations of the constants in the constant pool MCP. This is
618 /// used to print out constants which have been "spilled to memory" by
619 /// the code generator.
621 void AIXAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
622 const std::vector<Constant*> &CP = MCP->getConstants();
623 const TargetData &TD = TM.getTargetData();
625 if (CP.empty()) return;
627 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
629 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
631 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
633 emitGlobalConstant(CP[i]);
637 bool AIXAsmPrinter::doInitialization(Module &M) {
638 const TargetData &TD = TM.getTargetData();
639 std::string CurSection;
641 O << "\t.machine \"ppc64\"\n"
643 << "\t.csect .text[PR]\n";
645 // Print out module-level global variables
646 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
647 if (!I->hasInitializer())
650 std::string Name = I->getName();
651 Constant *C = I->getInitializer();
652 // N.B.: We are defaulting to writable strings
653 if (I->hasExternalLinkage()) {
654 O << "\t.globl " << Name << '\n'
655 << "\t.csect .data[RW],3\n";
657 O << "\t.csect _global.rw_c[RW],3\n";
660 emitGlobalConstant(C);
663 // Output labels for globals
664 if (M.gbegin() != M.gend()) O << "\t.toc\n";
665 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
666 const GlobalVariable *GV = I;
667 // Do not output labels for unused variables
668 if (GV->isExternal() && GV->use_begin() == GV->use_end())
671 std::string Name = GV->getName();
672 std::string Label = "LC.." + utostr(LabelNumber++);
673 GVToLabelMap[GV] = Label;
675 << "\t.tc " << Name << "[TC]," << Name;
676 if (GV->isExternal()) O << "[RW]";
680 Mang = new Mangler(M, ".");
681 return false; // success
684 bool AIXAsmPrinter::doFinalization(Module &M) {
685 const TargetData &TD = TM.getTargetData();
686 // Print out module-level global variables
687 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
688 if (I->hasInitializer() || I->hasExternalLinkage())
691 std::string Name = I->getName();
692 if (I->hasInternalLinkage()) {
693 O << "\t.lcomm " << Name << ",16,_global.bss_c";
695 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
696 << "," << log2((unsigned)TD.getTypeAlignment(I->getType()));
699 WriteAsOperand(O, I, true, true, &M);
703 O << "_section_.text:\n"
704 << "\t.csect .data[RW],3\n"
705 << "\t.llong _section_.text\n";
708 return false; // success