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 "X86TargetAsmInfo.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/ADT/Statistic.h"
30 STATISTIC(EmittedInsts, "Number of machine instrs printed");
32 std::string X86IntelAsmPrinter::getSectionForFunction(const Function &F) const {
33 // Intel asm always emits functions to _text.
37 /// runOnMachineFunction - This uses the printMachineInstruction()
38 /// method to print assembly for each instruction.
40 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
41 SetupMachineFunction(MF);
44 // Print out constants referenced by the function
45 EmitConstantPool(MF.getConstantPool());
47 // Print out labels for the function.
48 const Function *F = MF.getFunction();
49 unsigned CC = F->getCallingConv();
51 // Populate function information map. Actually, We don't want to populate
52 // non-stdcall or non-fastcall functions' information right now.
53 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
54 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
56 X86SharedAsmPrinter::decorateName(CurrentFnName, F);
58 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
60 switch (F->getLinkage()) {
61 default: assert(0 && "Unsupported linkage type!");
62 case Function::InternalLinkage:
65 case Function::DLLExportLinkage:
66 DLLExportedFns.insert(CurrentFnName);
68 case Function::ExternalLinkage:
69 O << "\tpublic " << CurrentFnName << "\n";
74 O << CurrentFnName << "\tproc near\n";
76 // Print out code for the function.
77 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
79 // Print a label for the basic block if there are any predecessors.
80 if (!I->pred_empty()) {
81 printBasicBlockLabel(I, true);
84 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
86 // Print the assembly for the instruction.
87 printMachineInstruction(II);
91 // Print out jump tables referenced by the function.
92 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
94 O << CurrentFnName << "\tendp\n";
96 // We didn't modify anything.
100 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
101 unsigned char value = MI->getOperand(Op).getImm();
102 assert(value <= 7 && "Invalid ssecc argument!");
104 case 0: O << "eq"; break;
105 case 1: O << "lt"; break;
106 case 2: O << "le"; break;
107 case 3: O << "unord"; break;
108 case 4: O << "neq"; break;
109 case 5: O << "nlt"; break;
110 case 6: O << "nle"; break;
111 case 7: O << "ord"; break;
115 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
116 const char *Modifier) {
117 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
118 switch (MO.getType()) {
119 case MachineOperand::MO_Register: {
120 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
121 unsigned Reg = MO.getReg();
122 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
123 MVT::ValueType VT = (strcmp(Modifier,"subreg64") == 0) ?
124 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
125 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
126 Reg = getX86SubSuperRegister(Reg, VT);
128 O << RI.get(Reg).Name;
130 O << "reg" << MO.getReg();
133 case MachineOperand::MO_Immediate:
136 case MachineOperand::MO_MachineBasicBlock:
137 printBasicBlockLabel(MO.getMBB());
139 case MachineOperand::MO_JumpTableIndex: {
140 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
141 if (!isMemOp) O << "OFFSET ";
142 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
143 << "_" << MO.getIndex();
146 case MachineOperand::MO_ConstantPoolIndex: {
147 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
148 if (!isMemOp) O << "OFFSET ";
149 O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
150 << getFunctionNumber() << "_" << MO.getIndex();
151 int Offset = MO.getOffset();
153 O << " + " << Offset;
159 case MachineOperand::MO_GlobalAddress: {
160 bool isCallOp = Modifier && !strcmp(Modifier, "call");
161 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
162 GlobalValue *GV = MO.getGlobal();
163 std::string Name = Mang->getValueName(GV);
165 X86SharedAsmPrinter::decorateName(Name, GV);
167 if (!isMemOp && !isCallOp) O << "OFFSET ";
168 if (GV->hasDLLImportLinkage()) {
169 // FIXME: This should be fixed with full support of stdcall & fastcall
174 int Offset = MO.getOffset();
176 O << " + " << Offset;
181 case MachineOperand::MO_ExternalSymbol: {
182 bool isCallOp = Modifier && !strcmp(Modifier, "call");
183 if (!isCallOp) O << "OFFSET ";
184 O << TAI->getGlobalPrefix() << MO.getSymbolName();
188 O << "<unknown operand type>"; return;
192 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
193 const char *Modifier) {
194 assert(isMem(MI, Op) && "Invalid memory reference!");
196 const MachineOperand &BaseReg = MI->getOperand(Op);
197 int ScaleVal = MI->getOperand(Op+1).getImm();
198 const MachineOperand &IndexReg = MI->getOperand(Op+2);
199 const MachineOperand &DispSpec = MI->getOperand(Op+3);
202 bool NeedPlus = false;
203 if (BaseReg.getReg()) {
204 printOp(BaseReg, Modifier);
208 if (IndexReg.getReg()) {
209 if (NeedPlus) O << " + ";
211 O << ScaleVal << "*";
212 printOp(IndexReg, Modifier);
216 if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex() ||
217 DispSpec.isJumpTableIndex()) {
220 printOp(DispSpec, "mem");
222 int DispVal = DispSpec.getImm();
223 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
237 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
238 const MachineBasicBlock *MBB) const {
239 if (!TAI->getSetDirective())
242 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
243 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
244 printBasicBlockLabel(MBB, false, false);
245 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
248 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
249 O << "\"L" << getFunctionNumber() << "$pb\"\n";
250 O << "\"L" << getFunctionNumber() << "$pb\":";
253 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
255 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
256 unsigned Reg = MO.getReg();
258 default: return true; // Unknown mode.
259 case 'b': // Print QImode register
260 Reg = getX86SubSuperRegister(Reg, MVT::i8);
262 case 'h': // Print QImode high register
263 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
265 case 'w': // Print HImode register
266 Reg = getX86SubSuperRegister(Reg, MVT::i16);
268 case 'k': // Print SImode register
269 Reg = getX86SubSuperRegister(Reg, MVT::i32);
273 O << '%' << RI.get(Reg).Name;
277 /// PrintAsmOperand - Print out an operand for an inline asm expression.
279 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
281 const char *ExtraCode) {
282 // Does this asm operand have a single letter operand modifier?
283 if (ExtraCode && ExtraCode[0]) {
284 if (ExtraCode[1] != 0) return true; // Unknown modifier.
286 switch (ExtraCode[0]) {
287 default: return true; // Unknown modifier.
288 case 'b': // Print QImode register
289 case 'h': // Print QImode high register
290 case 'w': // Print HImode register
291 case 'k': // Print SImode register
292 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
296 printOperand(MI, OpNo);
300 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
303 const char *ExtraCode) {
304 if (ExtraCode && ExtraCode[0])
305 return true; // Unknown modifier.
306 printMemReference(MI, OpNo);
310 /// printMachineInstruction -- Print out a single X86 LLVM instruction
311 /// MI in Intel syntax to the current output stream.
313 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
316 // See if a truncate instruction can be turned into a nop.
317 switch (MI->getOpcode()) {
319 case X86::PsMOVZX64rr32:
320 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
324 // Call the autogenerated instruction printer routines.
325 printInstruction(MI);
328 bool X86IntelAsmPrinter::doInitialization(Module &M) {
329 bool Result = X86SharedAsmPrinter::doInitialization(M);
331 Mang->markCharUnacceptable('.');
333 O << "\t.686\n\t.model flat\n\n";
335 // Emit declarations for external functions.
336 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
337 if (I->isDeclaration()) {
338 std::string Name = Mang->getValueName(I);
339 X86SharedAsmPrinter::decorateName(Name, I);
342 if (I->hasDLLImportLinkage()) {
345 O << Name << ":near\n";
348 // Emit declarations for external globals. Note that VC++ always declares
349 // external globals to have type byte, and if that's good enough for VC++...
350 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
352 if (I->isDeclaration()) {
353 std::string Name = Mang->getValueName(I);
356 if (I->hasDLLImportLinkage()) {
359 O << Name << ":byte\n";
366 bool X86IntelAsmPrinter::doFinalization(Module &M) {
367 const TargetData *TD = TM.getTargetData();
369 // Print out module-level global variables here.
370 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
372 if (I->isDeclaration()) continue; // External global require no code
374 // Check to see if this is a special global used by LLVM, if so, emit it.
375 if (EmitSpecialLLVMGlobal(I))
378 std::string name = Mang->getValueName(I);
379 Constant *C = I->getInitializer();
380 unsigned Align = TD->getPreferredAlignmentLog(I);
381 bool bCustomSegment = false;
383 switch (I->getLinkage()) {
384 case GlobalValue::LinkOnceLinkage:
385 case GlobalValue::WeakLinkage:
386 SwitchToDataSection("");
387 O << name << "?\tsegment common 'COMMON'\n";
388 bCustomSegment = true;
389 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
390 // are also available.
392 case GlobalValue::AppendingLinkage:
393 SwitchToDataSection("");
394 O << name << "?\tsegment public 'DATA'\n";
395 bCustomSegment = true;
396 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
397 // are also available.
399 case GlobalValue::DLLExportLinkage:
400 DLLExportedGVs.insert(name);
402 case GlobalValue::ExternalLinkage:
403 O << "\tpublic " << name << "\n";
405 case GlobalValue::InternalLinkage:
406 SwitchToDataSection(TAI->getDataSection(), I);
409 assert(0 && "Unknown linkage type!");
413 EmitAlignment(Align, I);
415 O << name << ":\t\t\t\t" << TAI->getCommentString()
416 << " " << I->getName() << '\n';
418 EmitGlobalConstant(C);
421 O << name << "?\tends\n";
424 // Output linker support code for dllexported globals
425 if (!DLLExportedGVs.empty() ||
426 !DLLExportedFns.empty()) {
427 SwitchToDataSection("");
428 O << "; WARNING: The following code is valid only with MASM v8.x and (possible) higher\n"
429 << "; This version of MASM is usually shipped with Microsoft Visual Studio 2005\n"
430 << "; or (possible) further versions. Unfortunately, there is no way to support\n"
431 << "; dllexported symbols in the earlier versions of MASM in fully automatic way\n\n";
432 O << "_drectve\t segment info alias('.drectve')\n";
435 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
436 e = DLLExportedGVs.end();
438 O << "\t db ' /EXPORT:" << *i << ",data'\n";
441 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
442 e = DLLExportedFns.end();
444 O << "\t db ' /EXPORT:" << *i << "'\n";
447 if (!DLLExportedGVs.empty() ||
448 !DLLExportedFns.empty()) {
449 O << "_drectve\t ends\n";
452 // Bypass X86SharedAsmPrinter::doFinalization().
453 bool Result = AsmPrinter::doFinalization(M);
454 SwitchToDataSection("");
459 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
460 unsigned NumElts = CVA->getNumOperands();
462 // ML does not have escape sequences except '' for '. It also has a maximum
463 // string length of 255.
465 bool inString = false;
466 for (unsigned i = 0; i < NumElts; i++) {
467 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
471 if (n >= 32 && n <= 127) {
498 len += 1 + (n > 9) + (n > 99);
519 // Include the auto-generated portion of the assembly writer.
520 #include "X86GenAsmWriter1.inc"