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 "X86TargetAsmInfo.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/Support/ErrorHandling.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetOptions.h"
35 STATISTIC(EmittedInsts, "Number of machine instrs printed");
37 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
38 const TargetData *TD) {
39 X86MachineFunctionInfo Info;
42 switch (F->getCallingConv()) {
43 case CallingConv::X86_StdCall:
44 Info.setDecorationStyle(StdCall);
46 case CallingConv::X86_FastCall:
47 Info.setDecorationStyle(FastCall);
54 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
55 AI != AE; ++AI, ++argNum) {
56 const Type* Ty = AI->getType();
58 // 'Dereference' type in case of byval parameter attribute
59 if (F->paramHasAttr(argNum, Attribute::ByVal))
60 Ty = cast<PointerType>(Ty)->getElementType();
62 // Size should be aligned to DWORD boundary
63 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
66 // We're not supporting tooooo huge arguments :)
67 Info.setBytesToPopOnReturn((unsigned int)Size);
72 /// decorateName - Query FunctionInfoMap and use this information for various
74 void X86IntelAsmPrinter::decorateName(std::string &Name,
75 const GlobalValue *GV) {
76 const Function *F = dyn_cast<Function>(GV);
79 // We don't want to decorate non-stdcall or non-fastcall functions right now
80 unsigned CC = F->getCallingConv();
81 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
84 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
86 const X86MachineFunctionInfo *Info;
87 if (info_item == FunctionInfoMap.end()) {
88 // Calculate apropriate function info and populate map
89 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
90 Info = &FunctionInfoMap[F];
92 Info = &info_item->second;
95 const FunctionType *FT = F->getFunctionType();
96 switch (Info->getDecorationStyle()) {
100 // "Pure" variadic functions do not receive @0 suffix.
101 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
102 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
103 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
106 // "Pure" variadic functions do not receive @0 suffix.
107 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
108 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
109 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
118 LLVM_UNREACHABLE( "Unsupported DecorationStyle");
122 /// runOnMachineFunction - This uses the printMachineInstruction()
123 /// method to print assembly for each instruction.
125 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
127 SetupMachineFunction(MF);
130 // Print out constants referenced by the function
131 EmitConstantPool(MF.getConstantPool());
133 // Print out labels for the function.
134 const Function *F = MF.getFunction();
135 unsigned CC = F->getCallingConv();
136 unsigned FnAlign = MF.getAlignment();
138 // Populate function information map. Actually, We don't want to populate
139 // non-stdcall or non-fastcall functions' information right now.
140 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
141 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
143 decorateName(CurrentFnName, F);
145 SwitchToTextSection("_text", F);
146 switch (F->getLinkage()) {
147 default: LLVM_UNREACHABLE( "Unsupported linkage type!");
148 case Function::PrivateLinkage:
149 case Function::InternalLinkage:
150 EmitAlignment(FnAlign);
152 case Function::DLLExportLinkage:
153 DLLExportedFns.insert(CurrentFnName);
155 case Function::ExternalLinkage:
156 O << "\tpublic " << CurrentFnName << "\n";
157 EmitAlignment(FnAlign);
161 O << CurrentFnName << "\tproc near\n";
163 // Print out code for the function.
164 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
166 // Print a label for the basic block if there are any predecessors.
167 if (!I->pred_empty()) {
168 printBasicBlockLabel(I, true, true);
171 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
173 // Print the assembly for the instruction.
174 printMachineInstruction(II);
178 // Print out jump tables referenced by the function.
179 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
181 O << CurrentFnName << "\tendp\n";
185 // We didn't modify anything.
189 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
190 unsigned char value = MI->getOperand(Op).getImm();
191 assert(value <= 7 && "Invalid ssecc argument!");
193 case 0: O << "eq"; break;
194 case 1: O << "lt"; break;
195 case 2: O << "le"; break;
196 case 3: O << "unord"; break;
197 case 4: O << "neq"; break;
198 case 5: O << "nlt"; break;
199 case 6: O << "nle"; break;
200 case 7: O << "ord"; break;
204 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
205 const char *Modifier) {
206 switch (MO.getType()) {
207 case MachineOperand::MO_Register: {
208 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
209 unsigned Reg = MO.getReg();
210 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
211 MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
212 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
213 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
214 Reg = getX86SubSuperRegister(Reg, VT);
216 O << TRI->getName(Reg);
218 O << "reg" << MO.getReg();
221 case MachineOperand::MO_Immediate:
224 case MachineOperand::MO_JumpTableIndex: {
225 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
226 if (!isMemOp) O << "OFFSET ";
227 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
228 << "_" << MO.getIndex();
231 case MachineOperand::MO_ConstantPoolIndex: {
232 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
233 if (!isMemOp) O << "OFFSET ";
234 O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
235 << getFunctionNumber() << "_" << MO.getIndex();
236 printOffset(MO.getOffset());
240 case MachineOperand::MO_GlobalAddress: {
241 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
242 GlobalValue *GV = MO.getGlobal();
243 std::string Name = Mang->getValueName(GV);
245 decorateName(Name, GV);
247 if (!isMemOp) O << "OFFSET ";
249 // Handle dllimport linkage.
250 // FIXME: This should be fixed with full support of stdcall & fastcall
252 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
256 printOffset(MO.getOffset());
259 case MachineOperand::MO_ExternalSymbol: {
260 O << TAI->getGlobalPrefix() << MO.getSymbolName();
264 O << "<unknown operand type>"; return;
268 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
269 const MachineOperand &MO = MI->getOperand(OpNo);
270 switch (MO.getType()) {
271 default: LLVM_UNREACHABLE( "Unknown pcrel immediate operand");
272 case MachineOperand::MO_Immediate:
275 case MachineOperand::MO_MachineBasicBlock:
276 printBasicBlockLabel(MO.getMBB());
279 case MachineOperand::MO_GlobalAddress: {
280 GlobalValue *GV = MO.getGlobal();
281 std::string Name = Mang->getValueName(GV);
282 decorateName(Name, GV);
284 // Handle dllimport linkage.
285 // FIXME: This should be fixed with full support of stdcall & fastcall
287 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
290 printOffset(MO.getOffset());
294 case MachineOperand::MO_ExternalSymbol:
295 O << TAI->getGlobalPrefix() << MO.getSymbolName();
301 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
303 const char *Modifier) {
304 const MachineOperand &BaseReg = MI->getOperand(Op);
305 int ScaleVal = MI->getOperand(Op+1).getImm();
306 const MachineOperand &IndexReg = MI->getOperand(Op+2);
307 const MachineOperand &DispSpec = MI->getOperand(Op+3);
310 bool NeedPlus = false;
311 if (BaseReg.getReg()) {
312 printOp(BaseReg, Modifier);
316 if (IndexReg.getReg()) {
317 if (NeedPlus) O << " + ";
319 O << ScaleVal << "*";
320 printOp(IndexReg, Modifier);
324 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
328 printOp(DispSpec, "mem");
330 int DispVal = DispSpec.getImm();
331 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
346 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
347 const char *Modifier) {
348 assert(isMem(MI, Op) && "Invalid memory reference!");
349 MachineOperand Segment = MI->getOperand(Op+4);
350 if (Segment.getReg()) {
351 printOperand(MI, Op+4, Modifier);
354 printLeaMemReference(MI, Op, Modifier);
357 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
358 const MachineBasicBlock *MBB) const {
359 if (!TAI->getSetDirective())
362 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
363 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
364 printBasicBlockLabel(MBB, false, false, false);
365 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
368 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
369 O << "L" << getFunctionNumber() << "$pb\n";
370 O << "L" << getFunctionNumber() << "$pb:";
373 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
375 unsigned Reg = MO.getReg();
377 default: return true; // Unknown mode.
378 case 'b': // Print QImode register
379 Reg = getX86SubSuperRegister(Reg, MVT::i8);
381 case 'h': // Print QImode high register
382 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
384 case 'w': // Print HImode register
385 Reg = getX86SubSuperRegister(Reg, MVT::i16);
387 case 'k': // Print SImode register
388 Reg = getX86SubSuperRegister(Reg, MVT::i32);
392 O << TRI->getName(Reg);
396 /// PrintAsmOperand - Print out an operand for an inline asm expression.
398 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
400 const char *ExtraCode) {
401 // Does this asm operand have a single letter operand modifier?
402 if (ExtraCode && ExtraCode[0]) {
403 if (ExtraCode[1] != 0) return true; // Unknown modifier.
405 switch (ExtraCode[0]) {
406 default: return true; // Unknown modifier.
407 case 'b': // Print QImode register
408 case 'h': // Print QImode high register
409 case 'w': // Print HImode register
410 case 'k': // Print SImode register
411 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
415 printOperand(MI, OpNo);
419 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
422 const char *ExtraCode) {
423 if (ExtraCode && ExtraCode[0])
424 return true; // Unknown modifier.
425 printMemReference(MI, OpNo);
429 /// printMachineInstruction -- Print out a single X86 LLVM instruction
430 /// MI in Intel syntax to the current output stream.
432 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
435 // Call the autogenerated instruction printer routines.
436 printInstruction(MI);
439 bool X86IntelAsmPrinter::doInitialization(Module &M) {
440 bool Result = AsmPrinter::doInitialization(M);
442 Mang->markCharUnacceptable('.');
444 O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
446 // Emit declarations for external functions.
447 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
448 if (I->isDeclaration()) {
449 std::string Name = Mang->getValueName(I);
450 decorateName(Name, I);
453 if (I->hasDLLImportLinkage()) {
456 O << Name << ":near\n";
459 // Emit declarations for external globals. Note that VC++ always declares
460 // external globals to have type byte, and if that's good enough for VC++...
461 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
463 if (I->isDeclaration()) {
464 std::string Name = Mang->getValueName(I);
467 if (I->hasDLLImportLinkage()) {
470 O << Name << ":byte\n";
477 bool X86IntelAsmPrinter::doFinalization(Module &M) {
478 const TargetData *TD = TM.getTargetData();
480 // Print out module-level global variables here.
481 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
483 if (I->isDeclaration()) continue; // External global require no code
485 // Check to see if this is a special global used by LLVM, if so, emit it.
486 if (EmitSpecialLLVMGlobal(I))
489 std::string name = Mang->getValueName(I);
490 Constant *C = I->getInitializer();
491 unsigned Align = TD->getPreferredAlignmentLog(I);
492 bool bCustomSegment = false;
494 switch (I->getLinkage()) {
495 case GlobalValue::CommonLinkage:
496 case GlobalValue::LinkOnceAnyLinkage:
497 case GlobalValue::LinkOnceODRLinkage:
498 case GlobalValue::WeakAnyLinkage:
499 case GlobalValue::WeakODRLinkage:
500 SwitchToDataSection("");
501 O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
502 bCustomSegment = true;
503 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
504 // are also available.
506 case GlobalValue::AppendingLinkage:
507 SwitchToDataSection("");
508 O << name << "?\tSEGMENT PARA public 'DATA'\n";
509 bCustomSegment = true;
510 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
511 // are also available.
513 case GlobalValue::DLLExportLinkage:
514 DLLExportedGVs.insert(name);
516 case GlobalValue::ExternalLinkage:
517 O << "\tpublic " << name << "\n";
519 case GlobalValue::InternalLinkage:
520 SwitchToSection(TAI->getDataSection());
523 LLVM_UNREACHABLE( "Unknown linkage type!");
527 EmitAlignment(Align, I);
531 O << "\t\t\t\t" << TAI->getCommentString()
532 << " " << I->getName();
535 EmitGlobalConstant(C);
538 O << name << "?\tends\n";
541 // Output linker support code for dllexported globals
542 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
543 SwitchToDataSection("");
544 O << "; WARNING: The following code is valid only with MASM v8.x"
545 << "and (possible) higher\n"
546 << "; This version of MASM is usually shipped with Microsoft "
547 << "Visual Studio 2005\n"
548 << "; or (possible) further versions. Unfortunately, there is no "
549 << "way to support\n"
550 << "; dllexported symbols in the earlier versions of MASM in fully "
551 << "automatic way\n\n";
552 O << "_drectve\t segment info alias('.drectve')\n";
555 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
556 e = DLLExportedGVs.end();
558 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
560 for (StringSet<>::iterator i = DLLExportedFns.begin(),
561 e = DLLExportedFns.end();
563 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
565 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
566 O << "_drectve\t ends\n";
568 // Bypass X86SharedAsmPrinter::doFinalization().
569 bool Result = AsmPrinter::doFinalization(M);
570 SwitchToDataSection("");
575 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
576 unsigned NumElts = CVA->getNumOperands();
578 // ML does not have escape sequences except '' for '. It also has a maximum
579 // string length of 255.
581 bool inString = false;
582 for (unsigned i = 0; i < NumElts; i++) {
583 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
587 if (n >= 32 && n <= 127) {
614 len += 1 + (n > 9) + (n > 99);
635 // Include the auto-generated portion of the assembly writer.
636 #include "X86GenAsmWriter1.inc"