1 //===-- Printer.cpp - Convert LLVM code 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' and `lli -print-machineinstrs'.
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 "PowerPCInstrInfo.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/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/CommandLine.h"
32 #include "Support/Debug.h"
33 #include "Support/Statistic.h"
34 #include "Support/StringExtras.h"
40 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
42 struct Printer : public MachineFunctionPass {
43 /// Output stream on which we're printing assembly code.
47 /// Target machine description which we query for reg. names, data
52 /// Name-mangler for global names.
55 std::set<std::string> Stubs;
56 std::set<std::string> Strings;
58 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm), labelNumber(0)
61 /// Cache of mangled name for current function. This is
62 /// recalculated at the beginning of each call to
63 /// runOnMachineFunction().
65 std::string CurrentFnName;
67 /// Unique incrementer for label values for referencing
70 unsigned int labelNumber;
72 virtual const char *getPassName() const {
73 return "PowerPC Assembly Printer";
76 void printMachineInstruction(const MachineInstr *MI);
77 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
78 void printConstantPool(MachineConstantPool *MCP);
79 bool runOnMachineFunction(MachineFunction &F);
80 bool doInitialization(Module &M);
81 bool doFinalization(Module &M);
82 void emitGlobalConstant(const Constant* CV);
83 void emitConstantValueOnly(const Constant *CV);
85 } // end of anonymous namespace
87 /// createPPCCodePrinterPass - Returns a pass that prints the PPC
88 /// assembly code for a MachineFunction to the given output stream,
89 /// using the given target machine description. This should work
90 /// regardless of whether the function is in SSA form.
92 FunctionPass *createPPCCodePrinterPass(std::ostream &o,TargetMachine &tm) {
93 return new Printer(o, tm);
96 /// isStringCompatible - Can we treat the specified array as a string?
97 /// Only if it is an array of ubytes or non-negative sbytes.
99 static bool isStringCompatible(const ConstantArray *CVA) {
100 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
101 if (ETy == Type::UByteTy) return true;
102 if (ETy != Type::SByteTy) return false;
104 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
105 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
111 /// toOctal - Convert the low order bits of X into an octal digit.
113 static inline char toOctal(int X) {
117 /// getAsCString - Return the specified array as a C compatible
118 /// string, only if the predicate isStringCompatible is true.
120 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
121 assert(isStringCompatible(CVA) && "Array is not string compatible!");
124 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
125 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
129 } else if (C == '\\') {
131 } else if (isprint(C)) {
135 case '\b': O << "\\b"; break;
136 case '\f': O << "\\f"; break;
137 case '\n': O << "\\n"; break;
138 case '\r': O << "\\r"; break;
139 case '\t': O << "\\t"; break;
142 O << toOctal(C >> 6);
143 O << toOctal(C >> 3);
144 O << toOctal(C >> 0);
152 // Print out the specified constant, without a storage class. Only the
153 // constants valid in constant expressions can occur here.
154 void Printer::emitConstantValueOnly(const Constant *CV) {
155 if (CV->isNullValue())
157 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
158 assert(CB == ConstantBool::True);
160 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
162 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
164 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
165 // This is a constant address for a global variable or function. Use the
166 // name of the variable or function as the address value.
167 O << Mang->getValueName(CPR->getValue());
168 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
169 const TargetData &TD = TM.getTargetData();
170 switch(CE->getOpcode()) {
171 case Instruction::GetElementPtr: {
172 // generate a symbolic expression for the byte address
173 const Constant *ptrVal = CE->getOperand(0);
174 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
175 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
177 emitConstantValueOnly(ptrVal);
178 O << ") + " << Offset;
180 emitConstantValueOnly(ptrVal);
184 case Instruction::Cast: {
185 // Support only non-converting or widening casts for now, that is, ones
186 // that do not involve a change in value. This assertion is really gross,
187 // and may not even be a complete check.
188 Constant *Op = CE->getOperand(0);
189 const Type *OpTy = Op->getType(), *Ty = CE->getType();
191 // Remember, kids, pointers on x86 can be losslessly converted back and
192 // forth into 32-bit or wider integers, regardless of signedness. :-P
193 assert(((isa<PointerType>(OpTy)
194 && (Ty == Type::LongTy || Ty == Type::ULongTy
195 || Ty == Type::IntTy || Ty == Type::UIntTy))
196 || (isa<PointerType>(Ty)
197 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
198 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
199 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
200 && OpTy->isLosslesslyConvertibleTo(Ty))))
201 && "FIXME: Don't yet support this kind of constant cast expr");
203 emitConstantValueOnly(Op);
207 case Instruction::Add:
209 emitConstantValueOnly(CE->getOperand(0));
211 emitConstantValueOnly(CE->getOperand(1));
215 assert(0 && "Unsupported operator!");
218 assert(0 && "Unknown constant value!");
222 // Print a constant value or values, with the appropriate storage class as a
224 void Printer::emitGlobalConstant(const Constant *CV) {
225 const TargetData &TD = TM.getTargetData();
227 if (CV->isNullValue()) {
228 O << "\t.space\t " << TD.getTypeSize(CV->getType()) << "\n";
230 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
231 if (isStringCompatible(CVA)) {
233 printAsCString(O, CVA);
235 } else { // Not a string. Print the values in successive locations
236 const std::vector<Use> &constValues = CVA->getValues();
237 for (unsigned i=0; i < constValues.size(); i++)
238 emitGlobalConstant(cast<Constant>(constValues[i].get()));
241 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
242 // Print the fields in successive locations. Pad to align if needed!
243 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
244 const std::vector<Use>& constValues = CVS->getValues();
245 unsigned sizeSoFar = 0;
246 for (unsigned i=0, N = constValues.size(); i < N; i++) {
247 const Constant* field = cast<Constant>(constValues[i].get());
249 // Check if padding is needed and insert one or more 0s.
250 unsigned fieldSize = TD.getTypeSize(field->getType());
251 unsigned padSize = ((i == N-1? cvsLayout->StructSize
252 : cvsLayout->MemberOffsets[i+1])
253 - cvsLayout->MemberOffsets[i]) - fieldSize;
254 sizeSoFar += fieldSize + padSize;
256 // Now print the actual field value
257 emitGlobalConstant(field);
259 // Insert the field padding unless it's zero bytes...
261 O << "\t.space\t " << padSize << "\n";
263 assert(sizeSoFar == cvsLayout->StructSize &&
264 "Layout of constant struct may be incorrect!");
266 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
267 // FP Constants are printed as integer constants to avoid losing
269 double Val = CFP->getValue();
270 switch (CFP->getType()->getTypeID()) {
271 default: assert(0 && "Unknown floating point type!");
272 case Type::FloatTyID: {
273 union FU { // Abide by C TBAA rules
278 O << ".long\t" << U.UVal << "\t; float " << Val << "\n";
281 case Type::DoubleTyID: {
282 union DU { // Abide by C TBAA rules
292 O << ".long\t" << U.T.MSWord << "\t; double most significant word "
294 O << ".long\t" << U.T.LSWord << "\t; double least significant word"
299 } else if (CV->getType()->getPrimitiveSize() == 64) {
300 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
301 union DU { // Abide by C TBAA rules
308 U.UVal = CI->getRawValue();
310 O << ".long\t" << U.T.MSWord << "\t; Double-word most significant word "
312 O << ".long\t" << U.T.LSWord << "\t; Double-word least significant word"
318 const Type *type = CV->getType();
320 switch (type->getTypeID()) {
321 case Type::UByteTyID: case Type::SByteTyID:
324 case Type::UShortTyID: case Type::ShortTyID:
328 case Type::PointerTyID:
329 case Type::UIntTyID: case Type::IntTyID:
332 case Type::ULongTyID: case Type::LongTyID:
333 assert (0 && "Should have already output double-word constant.");
334 case Type::FloatTyID: case Type::DoubleTyID:
335 assert (0 && "Should have already output floating point constant.");
337 assert (0 && "Can't handle printing this type of thing");
341 emitConstantValueOnly(CV);
345 /// printConstantPool - Print to the current output stream assembly
346 /// representations of the constants in the constant pool MCP. This is
347 /// used to print out constants which have been "spilled to memory" by
348 /// the code generator.
350 void Printer::printConstantPool(MachineConstantPool *MCP) {
351 const std::vector<Constant*> &CP = MCP->getConstants();
352 const TargetData &TD = TM.getTargetData();
354 if (CP.empty()) return;
356 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
358 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
360 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
362 emitGlobalConstant(CP[i]);
366 /// runOnMachineFunction - This uses the printMachineInstruction()
367 /// method to print assembly for each instruction.
369 bool Printer::runOnMachineFunction(MachineFunction &MF) {
371 // What's my mangled name?
372 CurrentFnName = Mang->getValueName(MF.getFunction());
374 // Print out constants referenced by the function
375 printConstantPool(MF.getConstantPool());
377 // Print out labels for the function.
379 O << "\t.globl\t" << CurrentFnName << "\n";
381 O << CurrentFnName << ":\n";
383 // Print out code for the function.
384 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
386 // Print a label for the basic block.
387 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
388 << I->getBasicBlock()->getName() << "\n";
389 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
391 // Print the assembly for the instruction.
393 printMachineInstruction(II);
397 // We didn't modify anything.
401 void Printer::printOp(const MachineOperand &MO,
402 bool elideOffsetKeyword /* = false */) {
403 const MRegisterInfo &RI = *TM.getRegisterInfo();
406 switch (MO.getType()) {
407 case MachineOperand::MO_VirtualRegister:
408 if (Value *V = MO.getVRegValueOrNull()) {
409 O << "<" << V->getName() << ">";
413 case MachineOperand::MO_MachineRegister:
414 case MachineOperand::MO_CCRegister:
415 O << LowercaseString(RI.get(MO.getReg()).Name);
418 case MachineOperand::MO_SignExtendedImmed:
419 case MachineOperand::MO_UnextendedImmed:
420 O << (int)MO.getImmedValue();
423 case MachineOperand::MO_PCRelativeDisp:
424 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
428 case MachineOperand::MO_MachineBasicBlock: {
429 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
430 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
431 << "_" << MBBOp->getNumber() << "\t; "
432 << MBBOp->getBasicBlock()->getName();
436 case MachineOperand::MO_ConstantPoolIndex:
437 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
440 case MachineOperand::MO_ExternalSymbol:
441 O << MO.getSymbolName();
444 case MachineOperand::MO_GlobalAddress:
445 if (!elideOffsetKeyword) {
446 // Dynamically-resolved functions need a stub for the function
447 Function *F = dyn_cast<Function>(MO.getGlobal());
448 if (F && F->isExternal()) {
449 Stubs.insert(Mang->getValueName(MO.getGlobal()));
450 O << "L" << Mang->getValueName(MO.getGlobal()) << "$stub";
452 O << Mang->getValueName(MO.getGlobal());
458 O << "<unknown operand type: " << MO.getType() << ">";
465 unsigned int ValidOpcodes(const MachineInstr *MI, unsigned int ArgType[5]) {
467 unsigned int retval = 1;
469 for(i = 0; i<5; i++) {
500 /// printMachineInstruction -- Print out a single PPC32 LLVM instruction
501 /// MI in Darwin syntax to the current output stream.
503 void Printer::printMachineInstruction(const MachineInstr *MI) {
504 unsigned Opcode = MI->getOpcode();
505 const TargetInstrInfo &TII = *TM.getInstrInfo();
506 const TargetInstrDescriptor &Desc = TII.get(Opcode);
509 unsigned int ArgCount = MI->getNumOperands();
510 //Desc.TSFlags & PPC32II::ArgCountMask;
511 unsigned int ArgType[] = {
512 (Desc.TSFlags >> PPC32II::Arg0TypeShift) & PPC32II::ArgTypeMask,
513 (Desc.TSFlags >> PPC32II::Arg1TypeShift) & PPC32II::ArgTypeMask,
514 (Desc.TSFlags >> PPC32II::Arg2TypeShift) & PPC32II::ArgTypeMask,
515 (Desc.TSFlags >> PPC32II::Arg3TypeShift) & PPC32II::ArgTypeMask,
516 (Desc.TSFlags >> PPC32II::Arg4TypeShift) & PPC32II::ArgTypeMask
518 assert(((Desc.TSFlags & PPC32II::VMX) == 0) &&
519 "Instruction requires VMX support");
520 assert(((Desc.TSFlags & PPC32II::PPC64) == 0) &&
521 "Instruction requires 64 bit support");
522 //assert ( ValidOpcodes(MI, ArgType) && "Instruction has invalid inputs");
525 // FIXME: should probably be converted to cout.width and cout.fill
526 if (Opcode == PPC32::MovePCtoLR) {
527 O << "bl \"L0000" << labelNumber << "$pb\"\n";
528 O << "\"L0000" << labelNumber << "$pb\":\n";
530 printOp(MI->getOperand(0));
535 O << TII.getName(MI->getOpcode()) << " ";
536 DEBUG(std::cerr << TII.getName(MI->getOpcode()) << " expects "
537 << ArgCount << " args\n");
539 if (Opcode == PPC32::LOADLoAddr) {
540 printOp(MI->getOperand(0));
542 printOp(MI->getOperand(2));
543 O << "-\"L0000" << labelNumber << "$pb\")";
546 if (MI->getOperand(1).getReg() == PPC32::R0)
549 printOp(MI->getOperand(1));
551 } else if (Opcode == PPC32::LOADHiAddr) {
552 printOp(MI->getOperand(0));
554 if (MI->getOperand(1).getReg() == PPC32::R0)
557 printOp(MI->getOperand(1));
559 printOp(MI->getOperand(2));
560 O << "-\"L0000" << labelNumber << "$pb\")\n";
561 } else if (ArgCount == 3 && ArgType[1] == PPC32II::Disimm16) {
562 printOp(MI->getOperand(0));
564 printOp(MI->getOperand(1));
566 if (MI->getOperand(2).hasAllocatedReg() &&
567 MI->getOperand(2).getReg() == PPC32::R0)
570 printOp(MI->getOperand(2));
573 for (i = 0; i < ArgCount; ++i) {
574 if (i == 1 && ArgCount == 3 && ArgType[2] == PPC32II::Simm16 &&
575 MI->getOperand(1).hasAllocatedReg() &&
576 MI->getOperand(1).getReg() == PPC32::R0) {
579 //std::cout << "DEBUG " << (*(TM.getRegisterInfo())).get(MI->getOperand(i).getReg()).Name << "\n";
580 printOp(MI->getOperand(i));
582 if (ArgCount - 1 == i)
590 bool Printer::doInitialization(Module &M) {
591 Mang = new Mangler(M, true);
592 return false; // success
595 // SwitchSection - Switch to the specified section of the executable if we are
596 // not already in it!
598 static void SwitchSection(std::ostream &OS, std::string &CurSection,
599 const char *NewSection) {
600 if (CurSection != NewSection) {
601 CurSection = NewSection;
602 if (!CurSection.empty())
603 OS << "\t" << NewSection << "\n";
607 bool Printer::doFinalization(Module &M) {
608 const TargetData &TD = TM.getTargetData();
609 std::string CurSection;
611 // Print out module-level global variables here.
612 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
613 if (I->hasInitializer()) { // External global require no code
615 std::string name = Mang->getValueName(I);
616 Constant *C = I->getInitializer();
617 unsigned Size = TD.getTypeSize(C->getType());
618 unsigned Align = TD.getTypeAlignment(C->getType());
620 if (C->isNullValue() &&
621 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
622 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
623 SwitchSection(O, CurSection, ".data");
624 if (I->hasInternalLinkage())
625 O << "\t.lcomm " << name << "," << TD.getTypeSize(C->getType())
626 << "," << (unsigned)TD.getTypeAlignment(C->getType());
628 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType());
630 WriteAsOperand(O, I, true, true, &M);
633 switch (I->getLinkage()) {
634 case GlobalValue::LinkOnceLinkage:
635 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
636 // Nonnull linkonce -> weak
637 O << "\t.weak " << name << "\n";
638 SwitchSection(O, CurSection, "");
639 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
642 case GlobalValue::AppendingLinkage:
643 // FIXME: appending linkage variables should go into a section of
644 // their name or something. For now, just emit them as external.
645 case GlobalValue::ExternalLinkage:
646 // If external or appending, declare as a global symbol
647 O << "\t.globl " << name << "\n";
649 case GlobalValue::InternalLinkage:
650 SwitchSection(O, CurSection, ".data");
654 O << "\t.align " << Align << "\n";
655 O << name << ":\t\t\t\t; ";
656 WriteAsOperand(O, I, true, true, &M);
658 WriteAsOperand(O, C, false, false, &M);
660 emitGlobalConstant(C);
664 for(std::set<std::string>::iterator i = Stubs.begin(); i != Stubs.end(); ++i)
666 O << "\t.picsymbol_stub\n";
667 O << "L" << *i << "$stub:\n";
668 O << "\t.indirect_symbol " << *i << "\n";
670 O << "\tbl L0$" << *i << "\n";
671 O << "L0$" << *i << ":\n";
673 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
675 O << "\tlwz r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
676 O << "\tmtctr r12\n";
677 O << "\taddi r11,r11,lo16(L" << *i << "$lazy_ptr - L0$" << *i << ")\n";
680 O << ".lazy_symbol_pointer\n";
681 O << "L" << *i << "$lazy_ptr:\n";
682 O << ".indirect_symbol " << *i << "\n";
683 O << ".long dyld_stub_binding_helper\n";
687 return false; // success
690 } // End llvm namespace