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/Support/Mangler.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetOptions.h"
33 STATISTIC(EmittedInsts, "Number of machine instrs printed");
35 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
36 const TargetData *TD) {
37 X86MachineFunctionInfo Info;
40 switch (F->getCallingConv()) {
41 case CallingConv::X86_StdCall:
42 Info.setDecorationStyle(StdCall);
44 case CallingConv::X86_FastCall:
45 Info.setDecorationStyle(FastCall);
52 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
53 AI != AE; ++AI, ++argNum) {
54 const Type* Ty = AI->getType();
56 // 'Dereference' type in case of byval parameter attribute
57 if (F->paramHasAttr(argNum, Attribute::ByVal))
58 Ty = cast<PointerType>(Ty)->getElementType();
60 // Size should be aligned to DWORD boundary
61 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
64 // We're not supporting tooooo huge arguments :)
65 Info.setBytesToPopOnReturn((unsigned int)Size);
70 /// decorateName - Query FunctionInfoMap and use this information for various
72 void X86IntelAsmPrinter::decorateName(std::string &Name,
73 const GlobalValue *GV) {
74 const Function *F = dyn_cast<Function>(GV);
77 // We don't want to decorate non-stdcall or non-fastcall functions right now
78 unsigned CC = F->getCallingConv();
79 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
82 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
84 const X86MachineFunctionInfo *Info;
85 if (info_item == FunctionInfoMap.end()) {
86 // Calculate apropriate function info and populate map
87 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
88 Info = &FunctionInfoMap[F];
90 Info = &info_item->second;
93 const FunctionType *FT = F->getFunctionType();
94 switch (Info->getDecorationStyle()) {
98 // "Pure" variadic functions do not receive @0 suffix.
99 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
100 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
101 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
104 // "Pure" variadic functions do not receive @0 suffix.
105 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
106 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
107 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
116 assert(0 && "Unsupported DecorationStyle");
120 /// runOnMachineFunction - This uses the printMachineInstruction()
121 /// method to print assembly for each instruction.
123 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
124 SetupMachineFunction(MF);
127 // Print out constants referenced by the function
128 EmitConstantPool(MF.getConstantPool());
130 // Print out labels for the function.
131 const Function *F = MF.getFunction();
132 unsigned CC = F->getCallingConv();
134 // Populate function information map. Actually, We don't want to populate
135 // non-stdcall or non-fastcall functions' information right now.
136 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
137 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
139 decorateName(CurrentFnName, F);
141 SwitchToTextSection("_text", F);
143 unsigned FnAlign = 4;
144 if (F->hasFnAttr(Attribute::OptimizeForSize))
146 switch (F->getLinkage()) {
147 default: assert(0 && "Unsupported linkage type!");
148 case Function::InternalLinkage:
149 EmitAlignment(FnAlign);
151 case Function::DLLExportLinkage:
152 DLLExportedFns.insert(CurrentFnName);
154 case Function::ExternalLinkage:
155 O << "\tpublic " << CurrentFnName << "\n";
156 EmitAlignment(FnAlign);
160 O << CurrentFnName << "\tproc near\n";
162 // Print out code for the function.
163 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
165 // Print a label for the basic block if there are any predecessors.
166 if (!I->pred_empty()) {
167 printBasicBlockLabel(I, true, true);
170 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
172 // Print the assembly for the instruction.
173 printMachineInstruction(II);
177 // Print out jump tables referenced by the function.
178 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
180 O << CurrentFnName << "\tendp\n";
184 // We didn't modify anything.
188 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
189 unsigned char value = MI->getOperand(Op).getImm();
190 assert(value <= 7 && "Invalid ssecc argument!");
192 case 0: O << "eq"; break;
193 case 1: O << "lt"; break;
194 case 2: O << "le"; break;
195 case 3: O << "unord"; break;
196 case 4: O << "neq"; break;
197 case 5: O << "nlt"; break;
198 case 6: O << "nle"; break;
199 case 7: O << "ord"; break;
203 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
204 const char *Modifier) {
205 switch (MO.getType()) {
206 case MachineOperand::MO_Register: {
207 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
208 unsigned Reg = MO.getReg();
209 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
210 MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
211 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
212 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
213 Reg = getX86SubSuperRegister(Reg, VT);
215 O << TRI->getName(Reg);
217 O << "reg" << MO.getReg();
220 case MachineOperand::MO_Immediate:
223 case MachineOperand::MO_MachineBasicBlock:
224 printBasicBlockLabel(MO.getMBB());
226 case MachineOperand::MO_JumpTableIndex: {
227 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
228 if (!isMemOp) O << "OFFSET ";
229 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
230 << "_" << MO.getIndex();
233 case MachineOperand::MO_ConstantPoolIndex: {
234 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
235 if (!isMemOp) O << "OFFSET ";
236 O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
237 << getFunctionNumber() << "_" << MO.getIndex();
238 int Offset = MO.getOffset();
240 O << " + " << Offset;
246 case MachineOperand::MO_GlobalAddress: {
247 bool isCallOp = Modifier && !strcmp(Modifier, "call");
248 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
249 GlobalValue *GV = MO.getGlobal();
250 std::string Name = Mang->getValueName(GV);
252 decorateName(Name, GV);
254 if (!isMemOp && !isCallOp) O << "OFFSET ";
255 if (GV->hasDLLImportLinkage()) {
256 // FIXME: This should be fixed with full support of stdcall & fastcall
261 int Offset = MO.getOffset();
263 O << " + " << Offset;
268 case MachineOperand::MO_ExternalSymbol: {
269 bool isCallOp = Modifier && !strcmp(Modifier, "call");
270 if (!isCallOp) O << "OFFSET ";
271 O << TAI->getGlobalPrefix() << MO.getSymbolName();
275 O << "<unknown operand type>"; return;
279 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
280 const char *Modifier) {
281 assert(isMem(MI, Op) && "Invalid memory reference!");
283 const MachineOperand &BaseReg = MI->getOperand(Op);
284 int ScaleVal = MI->getOperand(Op+1).getImm();
285 const MachineOperand &IndexReg = MI->getOperand(Op+2);
286 const MachineOperand &DispSpec = MI->getOperand(Op+3);
289 bool NeedPlus = false;
290 if (BaseReg.getReg()) {
291 printOp(BaseReg, Modifier);
295 if (IndexReg.getReg()) {
296 if (NeedPlus) O << " + ";
298 O << ScaleVal << "*";
299 printOp(IndexReg, Modifier);
303 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
307 printOp(DispSpec, "mem");
309 int DispVal = DispSpec.getImm();
310 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
325 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
326 const MachineBasicBlock *MBB) const {
327 if (!TAI->getSetDirective())
330 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
331 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
332 printBasicBlockLabel(MBB, false, false, false);
333 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
336 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
337 O << "\"L" << getFunctionNumber() << "$pb\"\n";
338 O << "\"L" << getFunctionNumber() << "$pb\":";
341 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
343 unsigned Reg = MO.getReg();
345 default: return true; // Unknown mode.
346 case 'b': // Print QImode register
347 Reg = getX86SubSuperRegister(Reg, MVT::i8);
349 case 'h': // Print QImode high register
350 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
352 case 'w': // Print HImode register
353 Reg = getX86SubSuperRegister(Reg, MVT::i16);
355 case 'k': // Print SImode register
356 Reg = getX86SubSuperRegister(Reg, MVT::i32);
360 O << '%' << TRI->getName(Reg);
364 /// PrintAsmOperand - Print out an operand for an inline asm expression.
366 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
368 const char *ExtraCode) {
369 // Does this asm operand have a single letter operand modifier?
370 if (ExtraCode && ExtraCode[0]) {
371 if (ExtraCode[1] != 0) return true; // Unknown modifier.
373 switch (ExtraCode[0]) {
374 default: return true; // Unknown modifier.
375 case 'b': // Print QImode register
376 case 'h': // Print QImode high register
377 case 'w': // Print HImode register
378 case 'k': // Print SImode register
379 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
383 printOperand(MI, OpNo);
387 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
390 const char *ExtraCode) {
391 if (ExtraCode && ExtraCode[0])
392 return true; // Unknown modifier.
393 printMemReference(MI, OpNo);
397 /// printMachineInstruction -- Print out a single X86 LLVM instruction
398 /// MI in Intel syntax to the current output stream.
400 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
403 // Call the autogenerated instruction printer routines.
404 printInstruction(MI);
407 bool X86IntelAsmPrinter::doInitialization(Module &M) {
408 bool Result = AsmPrinter::doInitialization(M);
410 Mang->markCharUnacceptable('.');
412 O << "\t.686\n\t.model flat\n\n";
414 // Emit declarations for external functions.
415 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
416 if (I->isDeclaration()) {
417 std::string Name = Mang->getValueName(I);
418 decorateName(Name, I);
421 if (I->hasDLLImportLinkage()) {
424 O << Name << ":near\n";
427 // Emit declarations for external globals. Note that VC++ always declares
428 // external globals to have type byte, and if that's good enough for VC++...
429 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
431 if (I->isDeclaration()) {
432 std::string Name = Mang->getValueName(I);
435 if (I->hasDLLImportLinkage()) {
438 O << Name << ":byte\n";
445 bool X86IntelAsmPrinter::doFinalization(Module &M) {
446 const TargetData *TD = TM.getTargetData();
448 // Print out module-level global variables here.
449 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
451 if (I->isDeclaration()) continue; // External global require no code
453 // Check to see if this is a special global used by LLVM, if so, emit it.
454 if (EmitSpecialLLVMGlobal(I))
457 std::string name = Mang->getValueName(I);
458 Constant *C = I->getInitializer();
459 unsigned Align = TD->getPreferredAlignmentLog(I);
460 bool bCustomSegment = false;
462 switch (I->getLinkage()) {
463 case GlobalValue::CommonLinkage:
464 case GlobalValue::LinkOnceLinkage:
465 case GlobalValue::WeakLinkage:
466 SwitchToDataSection("");
467 O << name << "?\tsegment common 'COMMON'\n";
468 bCustomSegment = true;
469 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
470 // are also available.
472 case GlobalValue::AppendingLinkage:
473 SwitchToDataSection("");
474 O << name << "?\tsegment public 'DATA'\n";
475 bCustomSegment = true;
476 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
477 // are also available.
479 case GlobalValue::DLLExportLinkage:
480 DLLExportedGVs.insert(name);
482 case GlobalValue::ExternalLinkage:
483 O << "\tpublic " << name << "\n";
485 case GlobalValue::InternalLinkage:
486 SwitchToSection(TAI->getDataSection());
489 assert(0 && "Unknown linkage type!");
493 EmitAlignment(Align, I);
495 O << name << ":\t\t\t\t" << TAI->getCommentString()
496 << " " << I->getName() << '\n';
498 EmitGlobalConstant(C);
501 O << name << "?\tends\n";
504 // Output linker support code for dllexported globals
505 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
506 SwitchToDataSection("");
507 O << "; WARNING: The following code is valid only with MASM v8.x"
508 << "and (possible) higher\n"
509 << "; This version of MASM is usually shipped with Microsoft "
510 << "Visual Studio 2005\n"
511 << "; or (possible) further versions. Unfortunately, there is no "
512 << "way to support\n"
513 << "; dllexported symbols in the earlier versions of MASM in fully "
514 << "automatic way\n\n";
515 O << "_drectve\t segment info alias('.drectve')\n";
518 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
519 e = DLLExportedGVs.end();
521 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
523 for (StringSet<>::iterator i = DLLExportedFns.begin(),
524 e = DLLExportedFns.end();
526 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
528 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
529 O << "_drectve\t ends\n";
531 // Bypass X86SharedAsmPrinter::doFinalization().
532 bool Result = AsmPrinter::doFinalization(M);
533 SwitchToDataSection("");
538 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
539 unsigned NumElts = CVA->getNumOperands();
541 // ML does not have escape sequences except '' for '. It also has a maximum
542 // string length of 255.
544 bool inString = false;
545 for (unsigned i = 0; i < NumElts; i++) {
546 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
550 if (n >= 32 && n <= 127) {
577 len += 1 + (n > 9) + (n > 99);
598 // Include the auto-generated portion of the assembly writer.
599 #include "X86GenAsmWriter1.inc"