1 //===-- PPC32/Printer.cpp - Convert X86 LLVM code to Intel 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
11 // representation of machine-dependent LLVM code to Intel-format
12 // assembly language. This printer is the output mechanism used
13 // by `llc' and `lli -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "asmprinter"
19 #include "PowerPCInstrInfo.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "Support/CommandLine.h"
30 #include "Support/Debug.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
38 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
40 struct Printer : public MachineFunctionPass {
41 /// Output stream on which we're printing assembly code.
45 /// Target machine description which we query for reg. names, data
50 /// Name-mangler for global names.
53 std::set<std::string> Stubs;
54 std::set<std::string> Strings;
56 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
58 /// Cache of mangled name for current function. This is
59 /// recalculated at the beginning of each call to
60 /// runOnMachineFunction().
62 std::string CurrentFnName;
64 virtual const char *getPassName() const {
65 return "PowerPC Assembly Printer";
68 void printMachineInstruction(const MachineInstr *MI);
69 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
70 void printConstantPool(MachineConstantPool *MCP);
71 bool runOnMachineFunction(MachineFunction &F);
72 bool doInitialization(Module &M);
73 bool doFinalization(Module &M);
74 void emitGlobalConstant(const Constant* CV);
75 void emitConstantValueOnly(const Constant *CV);
77 } // end of anonymous namespace
79 /// createPPCCodePrinterPass - Returns a pass that prints the X86
80 /// assembly code for a MachineFunction to the given output stream,
81 /// using the given target machine description. This should work
82 /// regardless of whether the function is in SSA form.
84 FunctionPass *createPPCCodePrinterPass(std::ostream &o,TargetMachine &tm) {
85 return new Printer(o, tm);
88 /// isStringCompatible - Can we treat the specified array as a string?
89 /// Only if it is an array of ubytes or non-negative sbytes.
91 static bool isStringCompatible(const ConstantArray *CVA) {
92 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
93 if (ETy == Type::UByteTy) return true;
94 if (ETy != Type::SByteTy) return false;
96 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
97 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
103 /// toOctal - Convert the low order bits of X into an octal digit.
105 static inline char toOctal(int X) {
109 /// getAsCString - Return the specified array as a C compatible
110 /// string, only if the predicate isStringCompatible is true.
112 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
113 assert(isStringCompatible(CVA) && "Array is not string compatible!");
116 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
117 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
121 } else if (C == '\\') {
123 } else if (isprint(C)) {
127 case '\b': O << "\\b"; break;
128 case '\f': O << "\\f"; break;
129 case '\n': O << "\\n"; break;
130 case '\r': O << "\\r"; break;
131 case '\t': O << "\\t"; break;
134 O << toOctal(C >> 6);
135 O << toOctal(C >> 3);
136 O << toOctal(C >> 0);
144 // Print out the specified constant, without a storage class. Only the
145 // constants valid in constant expressions can occur here.
146 void Printer::emitConstantValueOnly(const Constant *CV) {
147 if (CV->isNullValue())
149 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
150 assert(CB == ConstantBool::True);
152 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
154 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
156 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
157 // This is a constant address for a global variable or function. Use the
158 // name of the variable or function as the address value.
159 O << Mang->getValueName(CPR->getValue());
160 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
161 const TargetData &TD = TM.getTargetData();
162 switch(CE->getOpcode()) {
163 case Instruction::GetElementPtr: {
164 // generate a symbolic expression for the byte address
165 const Constant *ptrVal = CE->getOperand(0);
166 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
167 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
169 emitConstantValueOnly(ptrVal);
170 O << ") + " << Offset;
172 emitConstantValueOnly(ptrVal);
176 case Instruction::Cast: {
177 // Support only non-converting or widening casts for now, that is, ones
178 // that do not involve a change in value. This assertion is really gross,
179 // and may not even be a complete check.
180 Constant *Op = CE->getOperand(0);
181 const Type *OpTy = Op->getType(), *Ty = CE->getType();
183 // Remember, kids, pointers on x86 can be losslessly converted back and
184 // forth into 32-bit or wider integers, regardless of signedness. :-P
185 assert(((isa<PointerType>(OpTy)
186 && (Ty == Type::LongTy || Ty == Type::ULongTy
187 || Ty == Type::IntTy || Ty == Type::UIntTy))
188 || (isa<PointerType>(Ty)
189 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
190 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
191 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
192 && OpTy->isLosslesslyConvertibleTo(Ty))))
193 && "FIXME: Don't yet support this kind of constant cast expr");
195 emitConstantValueOnly(Op);
199 case Instruction::Add:
201 emitConstantValueOnly(CE->getOperand(0));
203 emitConstantValueOnly(CE->getOperand(1));
207 assert(0 && "Unsupported operator!");
210 assert(0 && "Unknown constant value!");
214 // Print a constant value or values, with the appropriate storage class as a
216 void Printer::emitGlobalConstant(const Constant *CV) {
217 const TargetData &TD = TM.getTargetData();
219 if (CV->isNullValue()) {
220 O << "\t.space\t " << TD.getTypeSize(CV->getType()) << "\n";
222 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
223 if (isStringCompatible(CVA)) {
225 printAsCString(O, CVA);
227 } else { // Not a string. Print the values in successive locations
228 const std::vector<Use> &constValues = CVA->getValues();
229 for (unsigned i=0; i < constValues.size(); i++)
230 emitGlobalConstant(cast<Constant>(constValues[i].get()));
233 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
234 // Print the fields in successive locations. Pad to align if needed!
235 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
236 const std::vector<Use>& constValues = CVS->getValues();
237 unsigned sizeSoFar = 0;
238 for (unsigned i=0, N = constValues.size(); i < N; i++) {
239 const Constant* field = cast<Constant>(constValues[i].get());
241 // Check if padding is needed and insert one or more 0s.
242 unsigned fieldSize = TD.getTypeSize(field->getType());
243 unsigned padSize = ((i == N-1? cvsLayout->StructSize
244 : cvsLayout->MemberOffsets[i+1])
245 - cvsLayout->MemberOffsets[i]) - fieldSize;
246 sizeSoFar += fieldSize + padSize;
248 // Now print the actual field value
249 emitGlobalConstant(field);
251 // Insert the field padding unless it's zero bytes...
253 O << "\t.space\t " << padSize << "\n";
255 assert(sizeSoFar == cvsLayout->StructSize &&
256 "Layout of constant struct may be incorrect!");
258 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
259 // FP Constants are printed as integer constants to avoid losing
261 double Val = CFP->getValue();
262 switch (CFP->getType()->getTypeID()) {
263 default: assert(0 && "Unknown floating point type!");
264 case Type::FloatTyID: {
265 union FU { // Abide by C TBAA rules
270 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
273 case Type::DoubleTyID: {
274 union DU { // Abide by C TBAA rules
284 O << ".long\t" << U.T.MSWord << "\t# double most significant word "
286 O << ".long\t" << U.T.LSWord << "\t# double least significant word"
291 } else if (CV->getType()->getPrimitiveSize() == 64) {
292 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
293 union DU { // Abide by C TBAA rules
300 U.UVal = CI->getRawValue();
302 O << ".long\t" << U.T.MSWord << "\t# Double-word most significant word "
304 O << ".long\t" << U.T.LSWord << "\t# Double-word least significant word"
310 const Type *type = CV->getType();
312 switch (type->getTypeID()) {
313 case Type::UByteTyID: case Type::SByteTyID:
316 case Type::UShortTyID: case Type::ShortTyID:
320 case Type::PointerTyID:
321 case Type::UIntTyID: case Type::IntTyID:
324 case Type::ULongTyID: case Type::LongTyID:
325 assert (0 && "Should have already output double-word constant.");
326 case Type::FloatTyID: case Type::DoubleTyID:
327 assert (0 && "Should have already output floating point constant.");
329 assert (0 && "Can't handle printing this type of thing");
333 emitConstantValueOnly(CV);
337 /// printConstantPool - Print to the current output stream assembly
338 /// representations of the constants in the constant pool MCP. This is
339 /// used to print out constants which have been "spilled to memory" by
340 /// the code generator.
342 void Printer::printConstantPool(MachineConstantPool *MCP) {
343 const std::vector<Constant*> &CP = MCP->getConstants();
344 const TargetData &TD = TM.getTargetData();
346 if (CP.empty()) return;
348 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
350 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
352 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
354 emitGlobalConstant(CP[i]);
358 /// runOnMachineFunction - This uses the printMachineInstruction()
359 /// method to print assembly for each instruction.
361 bool Printer::runOnMachineFunction(MachineFunction &MF) {
362 // BBNumber is used here so that a given Printer will never give two
363 // BBs the same name. (If you have a better way, please let me know!)
364 static unsigned BBNumber = 0;
367 // What's my mangled name?
368 CurrentFnName = Mang->getValueName(MF.getFunction());
370 // Print out constants referenced by the function
371 printConstantPool(MF.getConstantPool());
373 // Print out labels for the function.
375 O << "\t.globl\t" << CurrentFnName << "\n";
377 O << CurrentFnName << ":\n";
379 // Print out code for the function.
380 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
382 // Print a label for the basic block.
383 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
384 << I->getBasicBlock()->getName() << "\n";
385 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
387 // Print the assembly for the instruction.
389 printMachineInstruction(II);
393 // We didn't modify anything.
397 void Printer::printOp(const MachineOperand &MO,
398 bool elideOffsetKeyword /* = false */) {
399 const MRegisterInfo &RI = *TM.getRegisterInfo();
402 switch (MO.getType()) {
403 case MachineOperand::MO_VirtualRegister:
404 if (Value *V = MO.getVRegValueOrNull()) {
405 O << "<" << V->getName() << ">";
409 case MachineOperand::MO_MachineRegister:
410 O << LowercaseString(RI.get(MO.getReg()).Name);
413 case MachineOperand::MO_SignExtendedImmed:
414 case MachineOperand::MO_UnextendedImmed:
415 O << (int)MO.getImmedValue();
417 case MachineOperand::MO_MachineBasicBlock: {
418 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
419 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
420 << "_" << MBBOp->getNumber() << "\t# "
421 << MBBOp->getBasicBlock()->getName();
424 case MachineOperand::MO_PCRelativeDisp:
425 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
428 case MachineOperand::MO_GlobalAddress:
429 if (!elideOffsetKeyword) {
430 if (isa<Function>(MO.getGlobal())) {
431 Stubs.insert(Mang->getValueName(MO.getGlobal()));
432 O << "L" << Mang->getValueName(MO.getGlobal()) << "$stub";
434 O << Mang->getValueName(MO.getGlobal());
438 case MachineOperand::MO_ExternalSymbol:
439 O << MO.getSymbolName();
442 O << "<unknown operand type>";
449 unsigned int ValidOpcodes(const MachineInstr *MI, unsigned int ArgType[5]) {
451 unsigned int retval = 1;
453 for(i = 0; i<5; i++) {
484 /// printMachineInstruction -- Print out a single PPC32 LLVM instruction
485 /// MI in Darwin syntax to the current output stream.
487 void Printer::printMachineInstruction(const MachineInstr *MI) {
488 unsigned Opcode = MI->getOpcode();
489 const TargetInstrInfo &TII = *TM.getInstrInfo();
490 const TargetInstrDescriptor &Desc = TII.get(Opcode);
493 unsigned int ArgCount = Desc.TSFlags & PPC32II::ArgCountMask;
494 unsigned int ArgType[] = {
495 (Desc.TSFlags >> PPC32II::Arg0TypeShift) & PPC32II::ArgTypeMask,
496 (Desc.TSFlags >> PPC32II::Arg1TypeShift) & PPC32II::ArgTypeMask,
497 (Desc.TSFlags >> PPC32II::Arg2TypeShift) & PPC32II::ArgTypeMask,
498 (Desc.TSFlags >> PPC32II::Arg3TypeShift) & PPC32II::ArgTypeMask,
499 (Desc.TSFlags >> PPC32II::Arg4TypeShift) & PPC32II::ArgTypeMask
501 assert(((Desc.TSFlags & PPC32II::VMX) == 0) &&
502 "Instruction requires VMX support");
503 assert(((Desc.TSFlags & PPC32II::PPC64) == 0) &&
504 "Instruction requires 64 bit support");
505 //assert ( ValidOpcodes(MI, ArgType) && "Instruction has invalid inputs");
508 if (Opcode == PPC32::MovePCtoLR) {
510 O << "\tbc 20,31,L" << CurrentFnName << "$pb\n";
511 O << "L" << CurrentFnName << "$pb:\n";
515 O << TII.getName(MI->getOpcode()) << " ";
516 DEBUG(std::cerr << TII.getName(MI->getOpcode()) << " expects "
517 << ArgCount << " args\n");
519 if (Opcode == PPC32::LOADLoAddr) {
520 printOp(MI->getOperand(0));
522 printOp(MI->getOperand(1));
524 printOp(MI->getOperand(2));
525 O << "-L" << CurrentFnName << "$pb)\n";
526 } else if (Opcode == PPC32::LOADHiAddr) {
527 printOp(MI->getOperand(0));
529 printOp(MI->getOperand(1));
531 printOp(MI->getOperand(2));
532 O << "-L" << CurrentFnName << "$pb)\n";
533 } else if (ArgCount == 3 && ArgType[1] == PPC32II::Disimm16) {
534 printOp(MI->getOperand(0));
536 printOp(MI->getOperand(1));
538 if (ArgType[2] == PPC32II::Gpr0 && MI->getOperand(2).getReg() == PPC32::R0)
541 printOp(MI->getOperand(2));
544 for (i = 0; i < ArgCount; ++i) {
545 if (ArgType[i] == PPC32II::Gpr0 &&
546 MI->getOperand(i).getReg() == PPC32::R0)
549 //std::cout << "DEBUG " << (*(TM.getRegisterInfo())).get(MI->getOperand(i).getReg()).Name << "\n";
550 printOp(MI->getOperand(i));
552 if (ArgCount - 1 == i)
560 bool Printer::doInitialization(Module &M) {
561 Mang = new Mangler(M, true);
562 return false; // success
565 // SwitchSection - Switch to the specified section of the executable if we are
566 // not already in it!
568 static void SwitchSection(std::ostream &OS, std::string &CurSection,
569 const char *NewSection) {
570 if (CurSection != NewSection) {
571 CurSection = NewSection;
572 if (!CurSection.empty())
573 OS << "\t" << NewSection << "\n";
577 bool Printer::doFinalization(Module &M) {
578 const TargetData &TD = TM.getTargetData();
579 std::string CurSection;
581 // Print out module-level global variables here.
582 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
583 if (I->hasInitializer()) { // External global require no code
585 std::string name = Mang->getValueName(I);
586 Constant *C = I->getInitializer();
587 unsigned Size = TD.getTypeSize(C->getType());
588 unsigned Align = TD.getTypeAlignment(C->getType());
590 if (C->isNullValue() &&
591 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
592 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
593 SwitchSection(O, CurSection, ".data");
594 if (I->hasInternalLinkage())
595 O << "\t.local " << name << "\n";
597 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
598 << "," << (unsigned)TD.getTypeAlignment(C->getType());
600 WriteAsOperand(O, I, true, true, &M);
603 switch (I->getLinkage()) {
604 case GlobalValue::LinkOnceLinkage:
605 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
606 // Nonnull linkonce -> weak
607 O << "\t.weak " << name << "\n";
608 SwitchSection(O, CurSection, "");
609 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
612 case GlobalValue::AppendingLinkage:
613 // FIXME: appending linkage variables should go into a section of
614 // their name or something. For now, just emit them as external.
615 case GlobalValue::ExternalLinkage:
616 // If external or appending, declare as a global symbol
617 O << "\t.globl " << name << "\n";
619 case GlobalValue::InternalLinkage:
620 if (C->isNullValue())
621 SwitchSection(O, CurSection, ".bss");
623 SwitchSection(O, CurSection, ".data");
627 O << "\t.align " << Align << "\n";
628 O << name << ":\t\t\t\t# ";
629 WriteAsOperand(O, I, true, true, &M);
631 WriteAsOperand(O, C, false, false, &M);
633 emitGlobalConstant(C);
637 for(std::set<std::string>::iterator i = Stubs.begin(); i != Stubs.end(); ++i)
640 O<<".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
642 O << "L" << *i << "$stub:\n";
643 O << "\t.indirect_symbol " << *i << "\n";
645 O << "\tbcl 20,31,L0$" << *i << "\n";
646 O << "L0$" << *i << ":\n";
648 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
650 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
651 O << "\tmtctr r12\n";
654 O << ".lazy_symbol_pointer\n";
655 O << "L" << *i << "$lazy_ptr:\n";
656 O << ".indirect_symbol " << *i << "\n";
657 O << ".long dyld_stub_binding_helper\n";
661 return false; // success
664 } // End llvm namespace