1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel 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 Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86IntelAsmPrinter.h"
18 #include "X86InstrInfo.h"
19 #include "X86MCAsmInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Mangler.h"
38 STATISTIC(EmittedInsts, "Number of machine instrs printed");
40 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
41 const TargetData *TD) {
42 X86MachineFunctionInfo Info;
45 switch (F->getCallingConv()) {
46 case CallingConv::X86_StdCall:
47 Info.setDecorationStyle(StdCall);
49 case CallingConv::X86_FastCall:
50 Info.setDecorationStyle(FastCall);
57 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
58 AI != AE; ++AI, ++argNum) {
59 const Type* Ty = AI->getType();
61 // 'Dereference' type in case of byval parameter attribute
62 if (F->paramHasAttr(argNum, Attribute::ByVal))
63 Ty = cast<PointerType>(Ty)->getElementType();
65 // Size should be aligned to DWORD boundary
66 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
69 // We're not supporting tooooo huge arguments :)
70 Info.setBytesToPopOnReturn((unsigned int)Size);
75 /// decorateName - Query FunctionInfoMap and use this information for various
77 void X86IntelAsmPrinter::decorateName(std::string &Name,
78 const GlobalValue *GV) {
79 const Function *F = dyn_cast<Function>(GV);
82 // We don't want to decorate non-stdcall or non-fastcall functions right now
83 CallingConv::ID CC = F->getCallingConv();
84 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
87 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
89 const X86MachineFunctionInfo *Info;
90 if (info_item == FunctionInfoMap.end()) {
91 // Calculate apropriate function info and populate map
92 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
93 Info = &FunctionInfoMap[F];
95 Info = &info_item->second;
98 const FunctionType *FT = F->getFunctionType();
99 switch (Info->getDecorationStyle()) {
103 // "Pure" variadic functions do not receive @0 suffix.
104 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
105 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
106 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
109 // "Pure" variadic functions do not receive @0 suffix.
110 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
111 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
112 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
121 llvm_unreachable("Unsupported DecorationStyle");
125 /// runOnMachineFunction - This uses the printMachineInstruction()
126 /// method to print assembly for each instruction.
128 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
130 SetupMachineFunction(MF);
133 // Print out constants referenced by the function
134 EmitConstantPool(MF.getConstantPool());
136 // Print out labels for the function.
137 const Function *F = MF.getFunction();
138 CallingConv::ID CC = F->getCallingConv();
139 unsigned FnAlign = MF.getAlignment();
141 // Populate function information map. Actually, We don't want to populate
142 // non-stdcall or non-fastcall functions' information right now.
143 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
144 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
146 decorateName(CurrentFnName, F);
148 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
150 switch (F->getLinkage()) {
151 default: llvm_unreachable("Unsupported linkage type!");
152 case Function::PrivateLinkage:
153 case Function::LinkerPrivateLinkage:
154 case Function::InternalLinkage:
155 EmitAlignment(FnAlign);
157 case Function::DLLExportLinkage:
158 DLLExportedFns.insert(CurrentFnName);
160 case Function::ExternalLinkage:
161 O << "\tpublic " << CurrentFnName << "\n";
162 EmitAlignment(FnAlign);
166 O << CurrentFnName << "\tproc near\n";
168 // Print out code for the function.
169 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
171 // Print a label for the basic block if there are any predecessors.
172 if (!I->pred_empty()) {
173 printBasicBlockLabel(I, true, true);
176 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
178 // Print the assembly for the instruction.
179 printMachineInstruction(II);
183 // Print out jump tables referenced by the function.
184 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
186 O << CurrentFnName << "\tendp\n";
188 // We didn't modify anything.
192 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
193 unsigned char value = MI->getOperand(Op).getImm();
194 assert(value <= 7 && "Invalid ssecc argument!");
196 case 0: O << "eq"; break;
197 case 1: O << "lt"; break;
198 case 2: O << "le"; break;
199 case 3: O << "unord"; break;
200 case 4: O << "neq"; break;
201 case 5: O << "nlt"; break;
202 case 6: O << "nle"; break;
203 case 7: O << "ord"; break;
207 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
208 const char *Modifier) {
209 switch (MO.getType()) {
210 case MachineOperand::MO_Register: {
211 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
212 unsigned Reg = MO.getReg();
213 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
214 EVT VT = (strcmp(Modifier,"subreg64") == 0) ?
215 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
216 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
217 Reg = getX86SubSuperRegister(Reg, VT);
219 O << TRI->getName(Reg);
221 O << "reg" << MO.getReg();
224 case MachineOperand::MO_Immediate:
227 case MachineOperand::MO_JumpTableIndex: {
228 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
229 if (!isMemOp) O << "OFFSET ";
230 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
231 << "_" << MO.getIndex();
234 case MachineOperand::MO_ConstantPoolIndex: {
235 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
236 if (!isMemOp) O << "OFFSET ";
237 O << "[" << MAI->getPrivateGlobalPrefix() << "CPI"
238 << getFunctionNumber() << "_" << MO.getIndex();
239 printOffset(MO.getOffset());
243 case MachineOperand::MO_GlobalAddress: {
244 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
245 GlobalValue *GV = MO.getGlobal();
246 std::string Name = Mang->getMangledName(GV);
247 decorateName(Name, GV);
249 if (!isMemOp) O << "OFFSET ";
251 // Handle dllimport linkage.
252 // FIXME: This should be fixed with full support of stdcall & fastcall
254 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
258 printOffset(MO.getOffset());
261 case MachineOperand::MO_ExternalSymbol: {
262 O << MAI->getGlobalPrefix() << MO.getSymbolName();
266 O << "<unknown operand type>"; return;
270 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
271 const MachineOperand &MO = MI->getOperand(OpNo);
272 switch (MO.getType()) {
273 default: llvm_unreachable("Unknown pcrel immediate operand");
274 case MachineOperand::MO_Immediate:
277 case MachineOperand::MO_MachineBasicBlock:
278 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
281 case MachineOperand::MO_GlobalAddress: {
282 GlobalValue *GV = MO.getGlobal();
283 std::string Name = Mang->getMangledName(GV);
284 decorateName(Name, GV);
286 // Handle dllimport linkage.
287 // FIXME: This should be fixed with full support of stdcall & fastcall
289 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
292 printOffset(MO.getOffset());
296 case MachineOperand::MO_ExternalSymbol:
297 O << MAI->getGlobalPrefix() << MO.getSymbolName();
303 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
305 const char *Modifier) {
306 const MachineOperand &BaseReg = MI->getOperand(Op);
307 int ScaleVal = MI->getOperand(Op+1).getImm();
308 const MachineOperand &IndexReg = MI->getOperand(Op+2);
309 const MachineOperand &DispSpec = MI->getOperand(Op+3);
312 bool NeedPlus = false;
313 if (BaseReg.getReg()) {
314 printOp(BaseReg, Modifier);
318 if (IndexReg.getReg()) {
319 if (NeedPlus) O << " + ";
321 O << ScaleVal << "*";
322 printOp(IndexReg, Modifier);
326 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
330 printOp(DispSpec, "mem");
332 int DispVal = DispSpec.getImm();
333 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
348 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
349 const char *Modifier) {
350 assert(isMem(MI, Op) && "Invalid memory reference!");
351 MachineOperand Segment = MI->getOperand(Op+4);
352 if (Segment.getReg()) {
353 printOperand(MI, Op+4, Modifier);
356 printLeaMemReference(MI, Op, Modifier);
359 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
360 const MachineBasicBlock *MBB) const {
361 if (!MAI->getSetDirective())
364 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
365 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
366 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
367 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
370 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
371 O << "L" << getFunctionNumber() << "$pb\n";
372 O << "L" << getFunctionNumber() << "$pb:";
375 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
377 unsigned Reg = MO.getReg();
379 default: return true; // Unknown mode.
380 case 'b': // Print QImode register
381 Reg = getX86SubSuperRegister(Reg, MVT::i8);
383 case 'h': // Print QImode high register
384 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
386 case 'w': // Print HImode register
387 Reg = getX86SubSuperRegister(Reg, MVT::i16);
389 case 'k': // Print SImode register
390 Reg = getX86SubSuperRegister(Reg, MVT::i32);
394 O << TRI->getName(Reg);
398 /// PrintAsmOperand - Print out an operand for an inline asm expression.
400 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
402 const char *ExtraCode) {
403 // Does this asm operand have a single letter operand modifier?
404 if (ExtraCode && ExtraCode[0]) {
405 if (ExtraCode[1] != 0) return true; // Unknown modifier.
407 switch (ExtraCode[0]) {
408 default: return true; // Unknown modifier.
409 case 'b': // Print QImode register
410 case 'h': // Print QImode high register
411 case 'w': // Print HImode register
412 case 'k': // Print SImode register
413 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
417 printOperand(MI, OpNo);
421 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
424 const char *ExtraCode) {
425 if (ExtraCode && ExtraCode[0])
426 return true; // Unknown modifier.
427 printMemReference(MI, OpNo);
431 /// printMachineInstruction -- Print out a single X86 LLVM instruction
432 /// MI in Intel syntax to the current output stream.
434 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
437 processDebugLoc(MI->getDebugLoc());
439 // Call the autogenerated instruction printer routines.
440 printInstruction(MI);
442 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
447 bool X86IntelAsmPrinter::doInitialization(Module &M) {
448 bool Result = AsmPrinter::doInitialization(M);
450 O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
452 // Emit declarations for external functions.
453 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
454 if (I->isDeclaration()) {
455 std::string Name = Mang->getMangledName(I);
456 decorateName(Name, I);
459 if (I->hasDLLImportLinkage()) {
462 O << Name << ":near\n";
465 // Emit declarations for external globals. Note that VC++ always declares
466 // external globals to have type byte, and if that's good enough for VC++...
467 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
469 if (I->isDeclaration()) {
470 std::string Name = Mang->getMangledName(I);
473 if (I->hasDLLImportLinkage()) {
476 O << Name << ":byte\n";
483 void X86IntelAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
484 // Check to see if this is a special global used by LLVM, if so, emit it.
485 if (GV->isDeclaration() ||
486 EmitSpecialLLVMGlobal(GV))
489 const TargetData *TD = TM.getTargetData();
491 std::string name = Mang->getMangledName(GV);
492 Constant *C = GV->getInitializer();
493 unsigned Align = TD->getPreferredAlignmentLog(GV);
494 bool bCustomSegment = false;
496 switch (GV->getLinkage()) {
497 case GlobalValue::CommonLinkage:
498 case GlobalValue::LinkOnceAnyLinkage:
499 case GlobalValue::LinkOnceODRLinkage:
500 case GlobalValue::WeakAnyLinkage:
501 case GlobalValue::WeakODRLinkage:
502 // FIXME: make a MCSection.
503 O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
504 bCustomSegment = true;
505 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
506 // are also available.
508 case GlobalValue::AppendingLinkage:
509 // FIXME: make a MCSection.
510 O << name << "?\tSEGMENT PARA public 'DATA'\n";
511 bCustomSegment = true;
512 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
513 // are also available.
515 case GlobalValue::DLLExportLinkage:
516 DLLExportedGVs.insert(name);
518 case GlobalValue::ExternalLinkage:
519 O << "\tpublic " << name << "\n";
521 case GlobalValue::InternalLinkage:
522 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
525 llvm_unreachable("Unknown linkage type!");
529 EmitAlignment(Align, GV);
533 O.PadToColumn(MAI->getCommentColumn());
534 O << MAI->getCommentString()
535 << " " << GV->getName();
538 EmitGlobalConstant(C);
541 O << name << "?\tends\n";
544 bool X86IntelAsmPrinter::doFinalization(Module &M) {
545 // Output linker support code for dllexported globals
546 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
547 O << "; WARNING: The following code is valid only with MASM v8.x"
548 << "and (possible) higher\n"
549 << "; This version of MASM is usually shipped with Microsoft "
550 << "Visual Studio 2005\n"
551 << "; or (possible) further versions. Unfortunately, there is no "
552 << "way to support\n"
553 << "; dllexported symbols in the earlier versions of MASM in fully "
554 << "automatic way\n\n";
555 O << "_drectve\t segment info alias('.drectve')\n";
557 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
558 e = DLLExportedGVs.end();
560 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
562 for (StringSet<>::iterator i = DLLExportedFns.begin(),
563 e = DLLExportedFns.end();
565 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
567 O << "_drectve\t ends\n";
570 // Bypass X86SharedAsmPrinter::doFinalization().
571 bool Result = AsmPrinter::doFinalization(M);
576 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
577 unsigned NumElts = CVA->getNumOperands();
579 // ML does not have escape sequences except '' for '. It also has a maximum
580 // string length of 255.
582 bool inString = false;
583 for (unsigned i = 0; i < NumElts; i++) {
584 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
588 if (n >= 32 && n <= 127) {
615 len += 1 + (n > 9) + (n > 99);
636 // Include the auto-generated portion of the assembly writer.
637 #include "X86GenAsmWriter1.inc"