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 //===----------------------------------------------------------------------===//
20 #include "PowerPCInstrInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Mangler.h"
30 #include "Support/Statistic.h"
31 #include "Support/StringExtras.h"
32 #include "Support/CommandLine.h"
37 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39 struct Printer : public MachineFunctionPass {
40 /// Output stream on which we're printing assembly code.
44 /// Target machine description which we query for reg. names, data
49 /// Name-mangler for global names.
52 std::set< std::string > Stubs;
53 std::set<std::string> Strings;
55 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
57 /// We name each basic block in a Function with a unique number, so
58 /// that we can consistently refer to them later. This is cleared
59 /// at the beginning of each call to runOnMachineFunction().
61 typedef std::map<const Value *, unsigned> ValueMapTy;
62 ValueMapTy NumberForBB;
64 /// Cache of mangled name for current function. This is
65 /// recalculated at the beginning of each call to
66 /// runOnMachineFunction().
68 std::string CurrentFnName;
70 virtual const char *getPassName() const {
71 return "PowerPC Assembly Printer";
74 void printMachineInstruction(const MachineInstr *MI);
75 void printOp(const MachineOperand &MO,
76 bool elideOffsetKeyword = false);
77 void printConstantPool(MachineConstantPool *MCP);
78 bool runOnMachineFunction(MachineFunction &F);
79 bool doInitialization(Module &M);
80 bool doFinalization(Module &M);
81 void emitGlobalConstant(const Constant* CV);
82 void emitConstantValueOnly(const Constant *CV);
84 } // end of anonymous namespace
86 /// createPPCCodePrinterPass - Returns a pass that prints the X86
87 /// assembly code for a MachineFunction to the given output stream,
88 /// using the given target machine description. This should work
89 /// regardless of whether the function is in SSA form.
91 FunctionPass *createPPCCodePrinterPass(std::ostream &o,TargetMachine &tm){
92 return new Printer(o, tm);
95 /// isStringCompatible - Can we treat the specified array as a string?
96 /// Only if it is an array of ubytes or non-negative sbytes.
98 static bool isStringCompatible(const ConstantArray *CVA) {
99 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
100 if (ETy == Type::UByteTy) return true;
101 if (ETy != Type::SByteTy) return false;
103 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
104 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
110 /// toOctal - Convert the low order bits of X into an octal digit.
112 static inline char toOctal(int X) {
116 /// getAsCString - Return the specified array as a C compatible
117 /// string, only if the predicate isStringCompatible is true.
119 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
120 assert(isStringCompatible(CVA) && "Array is not string compatible!");
123 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
124 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
128 } else if (C == '\\') {
130 } else if (isprint(C)) {
134 case '\b': O << "\\b"; break;
135 case '\f': O << "\\f"; break;
136 case '\n': O << "\\n"; break;
137 case '\r': O << "\\r"; break;
138 case '\t': O << "\\t"; break;
141 O << toOctal(C >> 6);
142 O << toOctal(C >> 3);
143 O << toOctal(C >> 0);
151 // Print out the specified constant, without a storage class. Only the
152 // constants valid in constant expressions can occur here.
153 void Printer::emitConstantValueOnly(const Constant *CV) {
154 if (CV->isNullValue())
156 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
157 assert(CB == ConstantBool::True);
159 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
161 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
163 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
164 // This is a constant address for a global variable or function. Use the
165 // name of the variable or function as the address value.
166 O << Mang->getValueName(CPR->getValue());
167 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
168 const TargetData &TD = TM.getTargetData();
169 switch(CE->getOpcode()) {
170 case Instruction::GetElementPtr: {
171 // generate a symbolic expression for the byte address
172 const Constant *ptrVal = CE->getOperand(0);
173 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
174 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
176 emitConstantValueOnly(ptrVal);
177 O << ") + " << Offset;
179 emitConstantValueOnly(ptrVal);
183 case Instruction::Cast: {
184 // Support only non-converting or widening casts for now, that is, ones
185 // that do not involve a change in value. This assertion is really gross,
186 // and may not even be a complete check.
187 Constant *Op = CE->getOperand(0);
188 const Type *OpTy = Op->getType(), *Ty = CE->getType();
190 // Remember, kids, pointers on x86 can be losslessly converted back and
191 // forth into 32-bit or wider integers, regardless of signedness. :-P
192 assert(((isa<PointerType>(OpTy)
193 && (Ty == Type::LongTy || Ty == Type::ULongTy
194 || Ty == Type::IntTy || Ty == Type::UIntTy))
195 || (isa<PointerType>(Ty)
196 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
197 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
198 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
199 && OpTy->isLosslesslyConvertibleTo(Ty))))
200 && "FIXME: Don't yet support this kind of constant cast expr");
202 emitConstantValueOnly(Op);
206 case Instruction::Add:
208 emitConstantValueOnly(CE->getOperand(0));
210 emitConstantValueOnly(CE->getOperand(1));
214 assert(0 && "Unsupported operator!");
217 assert(0 && "Unknown constant value!");
221 // Print a constant value or values, with the appropriate storage class as a
223 void Printer::emitGlobalConstant(const Constant *CV) {
224 const TargetData &TD = TM.getTargetData();
226 if (CV->isNullValue()) {
227 O << "\t.space\t " << TD.getTypeSize(CV->getType()) << "\n";
229 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
230 if (isStringCompatible(CVA)) {
232 printAsCString(O, CVA);
234 } else { // Not a string. Print the values in successive locations
235 const std::vector<Use> &constValues = CVA->getValues();
236 for (unsigned i=0; i < constValues.size(); i++)
237 emitGlobalConstant(cast<Constant>(constValues[i].get()));
240 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
241 // Print the fields in successive locations. Pad to align if needed!
242 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
243 const std::vector<Use>& constValues = CVS->getValues();
244 unsigned sizeSoFar = 0;
245 for (unsigned i=0, N = constValues.size(); i < N; i++) {
246 const Constant* field = cast<Constant>(constValues[i].get());
248 // Check if padding is needed and insert one or more 0s.
249 unsigned fieldSize = TD.getTypeSize(field->getType());
250 unsigned padSize = ((i == N-1? cvsLayout->StructSize
251 : cvsLayout->MemberOffsets[i+1])
252 - cvsLayout->MemberOffsets[i]) - fieldSize;
253 sizeSoFar += fieldSize + padSize;
255 // Now print the actual field value
256 emitGlobalConstant(field);
258 // Insert the field padding unless it's zero bytes...
260 O << "\t.space\t " << padSize << "\n";
262 assert(sizeSoFar == cvsLayout->StructSize &&
263 "Layout of constant struct may be incorrect!");
265 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
266 // FP Constants are printed as integer constants to avoid losing
268 double Val = CFP->getValue();
269 switch (CFP->getType()->getPrimitiveID()) {
270 default: assert(0 && "Unknown floating point type!");
271 case Type::FloatTyID: {
272 union FU { // Abide by C TBAA rules
277 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
280 case Type::DoubleTyID: {
281 union DU { // Abide by C TBAA rules
291 O << ".long\t" << U.T.MSWord << "\t# double most significant word " << Val << "\n";
292 O << ".long\t" << U.T.LSWord << "\t# double least significant word" << Val << "\n";
296 } else if (CV->getType()->getPrimitiveSize() == 64) {
297 const ConstantInt *CI = dyn_cast<ConstantInt>(CV);
299 union DU { // Abide by C TBAA rules
306 U.UVal = CI->getRawValue();
308 O << ".long\t" << U.T.MSWord << "\t# Double-word most significant word " << U.UVal << "\n";
309 O << ".long\t" << U.T.LSWord << "\t# Double-word least significant word" << U.UVal << "\n";
314 const Type *type = CV->getType();
316 switch (type->getPrimitiveID()) {
317 case Type::UByteTyID: case Type::SByteTyID:
320 case Type::UShortTyID: case Type::ShortTyID:
324 case Type::PointerTyID:
325 case Type::UIntTyID: case Type::IntTyID:
328 case Type::ULongTyID: case Type::LongTyID:
329 assert (0 && "Should have already output double-word constant.");
330 case Type::FloatTyID: case Type::DoubleTyID:
331 assert (0 && "Should have already output floating point constant.");
333 assert (0 && "Can't handle printing this type of thing");
337 emitConstantValueOnly(CV);
341 /// printConstantPool - Print to the current output stream assembly
342 /// representations of the constants in the constant pool MCP. This is
343 /// used to print out constants which have been "spilled to memory" by
344 /// the code generator.
346 void Printer::printConstantPool(MachineConstantPool *MCP) {
347 const std::vector<Constant*> &CP = MCP->getConstants();
348 const TargetData &TD = TM.getTargetData();
350 if (CP.empty()) return;
352 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
354 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
356 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
358 emitGlobalConstant(CP[i]);
362 /// runOnMachineFunction - This uses the printMachineInstruction()
363 /// method to print assembly for each instruction.
365 bool Printer::runOnMachineFunction(MachineFunction &MF) {
366 // BBNumber is used here so that a given Printer will never give two
367 // BBs the same name. (If you have a better way, please let me know!)
368 static unsigned BBNumber = 0;
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 // Number each basic block so that we can consistently refer to them
384 // in PC-relative references.
386 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
388 NumberForBB[I->getBasicBlock()] = BBNumber++;
391 // Print out code for the function.
392 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
394 // Print a label for the basic block.
395 O << "L" << NumberForBB[I->getBasicBlock()] << ":\t# "
396 << I->getBasicBlock()->getName() << "\n";
397 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
399 // Print the assembly for the instruction.
401 printMachineInstruction(II);
405 // We didn't modify anything.
411 void Printer::printOp(const MachineOperand &MO,
412 bool elideOffsetKeyword /* = false */) {
413 const MRegisterInfo &RI = *TM.getRegisterInfo();
416 switch (MO.getType()) {
417 case MachineOperand::MO_VirtualRegister:
418 if (Value *V = MO.getVRegValueOrNull()) {
419 O << "<" << V->getName() << ">";
423 case MachineOperand::MO_MachineRegister:
424 O << RI.get(MO.getReg()).Name;
427 case MachineOperand::MO_SignExtendedImmed:
428 case MachineOperand::MO_UnextendedImmed:
429 O << (int)MO.getImmedValue();
431 case MachineOperand::MO_MachineBasicBlock: {
432 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
433 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
434 << "_" << MBBOp->getNumber () << "\t# "
435 << MBBOp->getBasicBlock ()->getName ();
438 case MachineOperand::MO_PCRelativeDisp:
439 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
442 case MachineOperand::MO_GlobalAddress:
443 if (!elideOffsetKeyword) {
444 if(isa<Function>(MO.getGlobal())) {
445 Stubs.insert(Mang->getValueName(MO.getGlobal()));
446 O << "L" << Mang->getValueName(MO.getGlobal()) << "$stub";
448 O << Mang->getValueName(MO.getGlobal());
452 case MachineOperand::MO_ExternalSymbol:
453 O << MO.getSymbolName();
456 O << "<unknown operand type>"; return;
462 unsigned int ValidOpcodes(const MachineInstr *MI, unsigned int ArgType[5]) {
464 unsigned int retval = 1;
466 for(i = 0; i<5; i++) {
497 /// printMachineInstruction -- Print out a single PPC32 LLVM instruction
498 /// MI in Darwin syntax to the current output stream.
500 void Printer::printMachineInstruction(const MachineInstr *MI) {
501 unsigned Opcode = MI->getOpcode();
502 const TargetInstrInfo &TII = *TM.getInstrInfo();
503 const TargetInstrDescriptor &Desc = TII.get(Opcode);
506 unsigned int ArgCount = Desc.TSFlags & PPC32II::ArgCountMask;
507 unsigned int ArgType[5];
510 ArgType[0] = (Desc.TSFlags>>PPC32II::Arg0TypeShift) & PPC32II::ArgTypeMask;
511 ArgType[1] = (Desc.TSFlags>>PPC32II::Arg1TypeShift) & PPC32II::ArgTypeMask;
512 ArgType[2] = (Desc.TSFlags>>PPC32II::Arg2TypeShift) & PPC32II::ArgTypeMask;
513 ArgType[3] = (Desc.TSFlags>>PPC32II::Arg3TypeShift) & PPC32II::ArgTypeMask;
514 ArgType[4] = (Desc.TSFlags>>PPC32II::Arg4TypeShift) & PPC32II::ArgTypeMask;
516 assert ( ((Desc.TSFlags & PPC32II::VMX) == 0) && "Instruction requires VMX support");
517 assert ( ((Desc.TSFlags & PPC32II::PPC64) == 0) && "Instruction requires 64 bit support");
518 //assert ( ValidOpcodes(MI, ArgType) && "Instruction has invalid inputs");
521 if(Opcode == PPC32::MovePCtoLR) {
523 O << "bcl 20,31,L" << CurrentFnName << "$pb\n";
524 O << "L" << CurrentFnName << "$pb:\n";
528 O << TII.getName(MI->getOpcode()) << " ";
529 std::cout << TII.getName(MI->getOpcode()) << " expects " << ArgCount << " args\n";
531 if(Opcode == PPC32::LOADLoAddr) {
532 printOp(MI->getOperand(0));
534 printOp(MI->getOperand(1));
536 printOp(MI->getOperand(2));
537 O << "-L" << CurrentFnName << "$pb)\n";
541 if(Opcode == PPC32::LOADHiAddr) {
542 printOp(MI->getOperand(0));
544 printOp(MI->getOperand(1));
546 printOp(MI->getOperand(2));
547 O << "-L" << CurrentFnName << "$pb)\n";
551 if( (ArgCount == 3) && (ArgType[1] == PPC32II::Disimm16) ) {
552 printOp(MI->getOperand(0));
554 printOp(MI->getOperand(1));
556 if((ArgType[2] == PPC32II::Gpr0) && (MI->getOperand(2).getReg() == PPC32::R0)) {
559 printOp(MI->getOperand(2));
563 for(i = 0; i< ArgCount; i++) {
564 if( (ArgType[i] == PPC32II::Gpr0) && ((MI->getOperand(i).getReg()) == PPC32::R0)) {
567 //std::cout << "DEBUG " << (*(TM.getRegisterInfo())).get(MI->getOperand(i).getReg()).Name << "\n";
568 printOp(MI->getOperand(i));
570 if( ArgCount - 1 == i) {
581 bool Printer::doInitialization(Module &M) {
582 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
584 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
585 // instruction as a reference to the register named sp, and if you try to
586 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
587 // before being looked up in the symbol table. This creates spurious
588 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
589 // mode, and decorate all register names with percent signs.
590 // O << "\t.intel_syntax\n";
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.local " << name << "\n";
627 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
628 << "," << (unsigned)TD.getTypeAlignment(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 if (C->isNullValue())
651 SwitchSection(O, CurSection, ".bss");
653 SwitchSection(O, CurSection, ".data");
657 O << "\t.align " << Align << "\n";
658 O << name << ":\t\t\t\t# ";
659 WriteAsOperand(O, I, true, true, &M);
661 WriteAsOperand(O, C, false, false, &M);
663 emitGlobalConstant(C);
667 for(std::set<std::string>::iterator i = Stubs.begin(); i != Stubs.end(); ++i) {
669 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
671 O << "L" << *i << "$stub:\n";
672 O << "\t.indirect_symbol " << *i << "\n";
674 O << "\tbcl 20,31,L0$" << *i << "\n";
675 O << "L0$" << *i << ":\n";
677 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
679 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
680 O << "\tmtctr r12\n";
683 O << ".lazy_symbol_pointer\n";
684 O << "L" << *i << "$lazy_ptr:\n";
685 O << ".indirect_symbol " << *i << "\n";
686 O << ".long dyld_stub_binding_helper\n";
691 return false; // success
694 } // End llvm namespace