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/MCStreamer.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Mangler.h"
37 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
40 const TargetData *TD) {
41 X86MachineFunctionInfo Info;
44 switch (F->getCallingConv()) {
45 case CallingConv::X86_StdCall:
46 Info.setDecorationStyle(StdCall);
48 case CallingConv::X86_FastCall:
49 Info.setDecorationStyle(FastCall);
56 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
57 AI != AE; ++AI, ++argNum) {
58 const Type* Ty = AI->getType();
60 // 'Dereference' type in case of byval parameter attribute
61 if (F->paramHasAttr(argNum, Attribute::ByVal))
62 Ty = cast<PointerType>(Ty)->getElementType();
64 // Size should be aligned to DWORD boundary
65 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
68 // We're not supporting tooooo huge arguments :)
69 Info.setBytesToPopOnReturn((unsigned int)Size);
74 /// decorateName - Query FunctionInfoMap and use this information for various
76 void X86IntelAsmPrinter::decorateName(std::string &Name,
77 const GlobalValue *GV) {
78 const Function *F = dyn_cast<Function>(GV);
81 // We don't want to decorate non-stdcall or non-fastcall functions right now
82 unsigned CC = F->getCallingConv();
83 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
86 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
88 const X86MachineFunctionInfo *Info;
89 if (info_item == FunctionInfoMap.end()) {
90 // Calculate apropriate function info and populate map
91 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
92 Info = &FunctionInfoMap[F];
94 Info = &info_item->second;
97 const FunctionType *FT = F->getFunctionType();
98 switch (Info->getDecorationStyle()) {
102 // "Pure" variadic functions do not receive @0 suffix.
103 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
104 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
105 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
108 // "Pure" variadic functions do not receive @0 suffix.
109 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
110 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
111 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
120 llvm_unreachable("Unsupported DecorationStyle");
124 /// runOnMachineFunction - This uses the printMachineInstruction()
125 /// method to print assembly for each instruction.
127 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
129 SetupMachineFunction(MF);
132 // Print out constants referenced by the function
133 EmitConstantPool(MF.getConstantPool());
135 // Print out labels for the function.
136 const Function *F = MF.getFunction();
137 unsigned CC = F->getCallingConv();
138 unsigned FnAlign = MF.getAlignment();
140 // Populate function information map. Actually, We don't want to populate
141 // non-stdcall or non-fastcall functions' information right now.
142 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
143 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
145 decorateName(CurrentFnName, F);
147 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
149 switch (F->getLinkage()) {
150 default: llvm_unreachable("Unsupported linkage type!");
151 case Function::PrivateLinkage:
152 case Function::LinkerPrivateLinkage:
153 case Function::InternalLinkage:
154 EmitAlignment(FnAlign);
156 case Function::DLLExportLinkage:
157 DLLExportedFns.insert(CurrentFnName);
159 case Function::ExternalLinkage:
160 O << "\tpublic " << CurrentFnName << "\n";
161 EmitAlignment(FnAlign);
165 O << CurrentFnName << "\tproc near\n";
167 // Print out code for the function.
168 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
170 // Print a label for the basic block if there are any predecessors.
171 if (!I->pred_empty()) {
172 printBasicBlockLabel(I, true, true);
175 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
177 // Print the assembly for the instruction.
178 printMachineInstruction(II);
182 // Print out jump tables referenced by the function.
183 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
185 O << CurrentFnName << "\tendp\n";
187 // We didn't modify anything.
191 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
192 unsigned char value = MI->getOperand(Op).getImm();
193 assert(value <= 7 && "Invalid ssecc argument!");
195 case 0: O << "eq"; break;
196 case 1: O << "lt"; break;
197 case 2: O << "le"; break;
198 case 3: O << "unord"; break;
199 case 4: O << "neq"; break;
200 case 5: O << "nlt"; break;
201 case 6: O << "nle"; break;
202 case 7: O << "ord"; break;
206 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
207 const char *Modifier) {
208 switch (MO.getType()) {
209 case MachineOperand::MO_Register: {
210 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
211 unsigned Reg = MO.getReg();
212 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
213 EVT VT = (strcmp(Modifier,"subreg64") == 0) ?
214 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
215 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
216 Reg = getX86SubSuperRegister(Reg, VT);
218 O << TRI->getName(Reg);
220 O << "reg" << MO.getReg();
223 case MachineOperand::MO_Immediate:
226 case MachineOperand::MO_JumpTableIndex: {
227 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
228 if (!isMemOp) O << "OFFSET ";
229 O << MAI->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 << "[" << MAI->getPrivateGlobalPrefix() << "CPI"
237 << getFunctionNumber() << "_" << MO.getIndex();
238 printOffset(MO.getOffset());
242 case MachineOperand::MO_GlobalAddress: {
243 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
244 GlobalValue *GV = MO.getGlobal();
245 std::string Name = Mang->getMangledName(GV);
246 decorateName(Name, GV);
248 if (!isMemOp) O << "OFFSET ";
250 // Handle dllimport linkage.
251 // FIXME: This should be fixed with full support of stdcall & fastcall
253 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
257 printOffset(MO.getOffset());
260 case MachineOperand::MO_ExternalSymbol: {
261 O << MAI->getGlobalPrefix() << MO.getSymbolName();
265 O << "<unknown operand type>"; return;
269 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
270 const MachineOperand &MO = MI->getOperand(OpNo);
271 switch (MO.getType()) {
272 default: llvm_unreachable("Unknown pcrel immediate operand");
273 case MachineOperand::MO_Immediate:
276 case MachineOperand::MO_MachineBasicBlock:
277 printBasicBlockLabel(MO.getMBB(), false, false, false);
280 case MachineOperand::MO_GlobalAddress: {
281 GlobalValue *GV = MO.getGlobal();
282 std::string Name = Mang->getMangledName(GV);
283 decorateName(Name, GV);
285 // Handle dllimport linkage.
286 // FIXME: This should be fixed with full support of stdcall & fastcall
288 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
291 printOffset(MO.getOffset());
295 case MachineOperand::MO_ExternalSymbol:
296 O << MAI->getGlobalPrefix() << MO.getSymbolName();
302 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
304 const char *Modifier) {
305 const MachineOperand &BaseReg = MI->getOperand(Op);
306 int ScaleVal = MI->getOperand(Op+1).getImm();
307 const MachineOperand &IndexReg = MI->getOperand(Op+2);
308 const MachineOperand &DispSpec = MI->getOperand(Op+3);
311 bool NeedPlus = false;
312 if (BaseReg.getReg()) {
313 printOp(BaseReg, Modifier);
317 if (IndexReg.getReg()) {
318 if (NeedPlus) O << " + ";
320 O << ScaleVal << "*";
321 printOp(IndexReg, Modifier);
325 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
329 printOp(DispSpec, "mem");
331 int DispVal = DispSpec.getImm();
332 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
347 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
348 const char *Modifier) {
349 assert(isMem(MI, Op) && "Invalid memory reference!");
350 MachineOperand Segment = MI->getOperand(Op+4);
351 if (Segment.getReg()) {
352 printOperand(MI, Op+4, Modifier);
355 printLeaMemReference(MI, Op, Modifier);
358 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
359 const MachineBasicBlock *MBB) const {
360 if (!MAI->getSetDirective())
363 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
364 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
365 printBasicBlockLabel(MBB, false, false, false);
366 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
369 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
370 O << "L" << getFunctionNumber() << "$pb\n";
371 O << "L" << getFunctionNumber() << "$pb:";
374 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
376 unsigned Reg = MO.getReg();
378 default: return true; // Unknown mode.
379 case 'b': // Print QImode register
380 Reg = getX86SubSuperRegister(Reg, MVT::i8);
382 case 'h': // Print QImode high register
383 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
385 case 'w': // Print HImode register
386 Reg = getX86SubSuperRegister(Reg, MVT::i16);
388 case 'k': // Print SImode register
389 Reg = getX86SubSuperRegister(Reg, MVT::i32);
393 O << TRI->getName(Reg);
397 /// PrintAsmOperand - Print out an operand for an inline asm expression.
399 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
401 const char *ExtraCode) {
402 // Does this asm operand have a single letter operand modifier?
403 if (ExtraCode && ExtraCode[0]) {
404 if (ExtraCode[1] != 0) return true; // Unknown modifier.
406 switch (ExtraCode[0]) {
407 default: return true; // Unknown modifier.
408 case 'b': // Print QImode register
409 case 'h': // Print QImode high register
410 case 'w': // Print HImode register
411 case 'k': // Print SImode register
412 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
416 printOperand(MI, OpNo);
420 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
423 const char *ExtraCode) {
424 if (ExtraCode && ExtraCode[0])
425 return true; // Unknown modifier.
426 printMemReference(MI, OpNo);
430 /// printMachineInstruction -- Print out a single X86 LLVM instruction
431 /// MI in Intel syntax to the current output stream.
433 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
436 // Call the autogenerated instruction printer routines.
437 printInstruction(MI);
440 bool X86IntelAsmPrinter::doInitialization(Module &M) {
441 bool Result = AsmPrinter::doInitialization(M);
443 Mang->markCharUnacceptable('.');
445 O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
447 // Emit declarations for external functions.
448 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
449 if (I->isDeclaration()) {
450 std::string Name = Mang->getMangledName(I);
451 decorateName(Name, I);
454 if (I->hasDLLImportLinkage()) {
457 O << Name << ":near\n";
460 // Emit declarations for external globals. Note that VC++ always declares
461 // external globals to have type byte, and if that's good enough for VC++...
462 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
464 if (I->isDeclaration()) {
465 std::string Name = Mang->getMangledName(I);
468 if (I->hasDLLImportLinkage()) {
471 O << Name << ":byte\n";
478 void X86IntelAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
479 // Check to see if this is a special global used by LLVM, if so, emit it.
480 if (GV->isDeclaration() ||
481 EmitSpecialLLVMGlobal(GV))
484 const TargetData *TD = TM.getTargetData();
486 std::string name = Mang->getMangledName(GV);
487 Constant *C = GV->getInitializer();
488 unsigned Align = TD->getPreferredAlignmentLog(GV);
489 bool bCustomSegment = false;
491 switch (GV->getLinkage()) {
492 case GlobalValue::CommonLinkage:
493 case GlobalValue::LinkOnceAnyLinkage:
494 case GlobalValue::LinkOnceODRLinkage:
495 case GlobalValue::WeakAnyLinkage:
496 case GlobalValue::WeakODRLinkage:
497 // FIXME: make a MCSection.
498 O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
499 bCustomSegment = true;
500 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
501 // are also available.
503 case GlobalValue::AppendingLinkage:
504 // FIXME: make a MCSection.
505 O << name << "?\tSEGMENT PARA public 'DATA'\n";
506 bCustomSegment = true;
507 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
508 // are also available.
510 case GlobalValue::DLLExportLinkage:
511 DLLExportedGVs.insert(name);
513 case GlobalValue::ExternalLinkage:
514 O << "\tpublic " << name << "\n";
516 case GlobalValue::InternalLinkage:
517 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
520 llvm_unreachable("Unknown linkage type!");
524 EmitAlignment(Align, GV);
528 O.PadToColumn(MAI->getCommentColumn());
529 O << MAI->getCommentString()
530 << " " << GV->getName();
533 EmitGlobalConstant(C);
536 O << name << "?\tends\n";
539 bool X86IntelAsmPrinter::doFinalization(Module &M) {
540 // Output linker support code for dllexported globals
541 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
542 O << "; WARNING: The following code is valid only with MASM v8.x"
543 << "and (possible) higher\n"
544 << "; This version of MASM is usually shipped with Microsoft "
545 << "Visual Studio 2005\n"
546 << "; or (possible) further versions. Unfortunately, there is no "
547 << "way to support\n"
548 << "; dllexported symbols in the earlier versions of MASM in fully "
549 << "automatic way\n\n";
550 O << "_drectve\t segment info alias('.drectve')\n";
552 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
553 e = DLLExportedGVs.end();
555 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
557 for (StringSet<>::iterator i = DLLExportedFns.begin(),
558 e = DLLExportedFns.end();
560 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
562 O << "_drectve\t ends\n";
565 // Bypass X86SharedAsmPrinter::doFinalization().
566 bool Result = AsmPrinter::doFinalization(M);
571 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
572 unsigned NumElts = CVA->getNumOperands();
574 // ML does not have escape sequences except '' for '. It also has a maximum
575 // string length of 255.
577 bool inString = false;
578 for (unsigned i = 0; i < NumElts; i++) {
579 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
583 if (n >= 32 && n <= 127) {
610 len += 1 + (n > 9) + (n > 99);
631 // Include the auto-generated portion of the assembly writer.
632 #include "X86GenAsmWriter1.inc"