blob: c656765a4bfb649a1e774dbdc0d98a031a3469ba [file] [log] [blame]
Chris Lattnerbf4b6a82009-09-20 07:41:30 +00001//===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerbf4b6a82009-09-20 07:41:30 +000010// This file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to AT&T format assembly
12// language. This printer is the output mechanism used by `llc'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattnerbf4b6a82009-09-20 07:41:30 +000016#define DEBUG_TYPE "asm-printer"
17#include "X86AsmPrinter.h"
18#include "X86ATTInstPrinter.h"
19#include "X86IntelInstPrinter.h"
20#include "X86MCInstLower.h"
21#include "X86.h"
22#include "X86COFF.h"
23#include "X86COFFMachineModuleInfo.h"
24#include "X86MachineFunctionInfo.h"
25#include "X86TargetMachine.h"
26#include "llvm/CallingConv.h"
27#include "llvm/DerivedTypes.h"
28#include "llvm/Module.h"
29#include "llvm/Type.h"
30#include "llvm/Assembly/Writer.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCSectionMachO.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfoImpls.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/Support/Mangler.h"
40#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/Target/TargetLoweringObjectFile.h"
42#include "llvm/Target/TargetOptions.h"
43#include "llvm/Target/TargetRegistry.h"
44#include "llvm/ADT/SmallString.h"
45#include "llvm/ADT/Statistic.h"
46using namespace llvm;
47
48STATISTIC(EmittedInsts, "Number of machine instrs printed");
49
50//===----------------------------------------------------------------------===//
51// Primitive Helper Functions.
52//===----------------------------------------------------------------------===//
53
54void X86AsmPrinter::printMCInst(const MCInst *MI) {
55 if (MAI->getAssemblerDialect() == 0)
56 X86ATTInstPrinter(O, *MAI).printInstruction(MI);
57 else
58 X86IntelInstPrinter(O, *MAI).printInstruction(MI);
59}
60
61void X86AsmPrinter::PrintPICBaseSymbol() const {
62 // FIXME: Gross const cast hack.
63 X86AsmPrinter *AP = const_cast<X86AsmPrinter*>(this);
64 X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
65}
66
67void X86AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
68 unsigned FnAlign = MF.getAlignment();
69 const Function *F = MF.getFunction();
70
71 if (Subtarget->isTargetCygMing()) {
72 X86COFFMachineModuleInfo &COFFMMI =
73 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
Chris Lattnerc53c24c2010-01-16 00:51:39 +000074 COFFMMI.DecorateCygMingName(CurrentFnSym, OutContext, F,
75 *TM.getTargetData());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +000076 }
77
78 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
79 EmitAlignment(FnAlign, F);
80
81 switch (F->getLinkage()) {
82 default: llvm_unreachable("Unknown linkage type!");
83 case Function::InternalLinkage: // Symbols default to internal.
84 case Function::PrivateLinkage:
85 break;
86 case Function::DLLExportLinkage:
87 case Function::ExternalLinkage:
Chris Lattner86ec9712010-01-16 00:32:38 +000088 O << "\t.globl\t";
89 CurrentFnSym->print(O, MAI);
90 O << '\n';
Chris Lattnerbf4b6a82009-09-20 07:41:30 +000091 break;
92 case Function::LinkerPrivateLinkage:
93 case Function::LinkOnceAnyLinkage:
94 case Function::LinkOnceODRLinkage:
95 case Function::WeakAnyLinkage:
96 case Function::WeakODRLinkage:
97 if (Subtarget->isTargetDarwin()) {
Chris Lattner86ec9712010-01-16 00:32:38 +000098 O << "\t.globl\t";
99 CurrentFnSym->print(O, MAI);
100 O << '\n';
101 O << MAI->getWeakDefDirective();
102 CurrentFnSym->print(O, MAI);
103 O << '\n';
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000104 } else if (Subtarget->isTargetCygMing()) {
Chris Lattner86ec9712010-01-16 00:32:38 +0000105 O << "\t.globl\t";
106 CurrentFnSym->print(O, MAI);
107 O << "\n\t.linkonce discard\n";
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000108 } else {
Chris Lattner86ec9712010-01-16 00:32:38 +0000109 O << "\t.weak\t";
110 CurrentFnSym->print(O, MAI);
111 O << '\n';
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000112 }
113 break;
114 }
115
Chris Lattner86ec9712010-01-16 00:32:38 +0000116 printVisibility(CurrentFnSym, F->getVisibility());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000117
Chris Lattner86ec9712010-01-16 00:32:38 +0000118 if (Subtarget->isTargetELF()) {
119 O << "\t.type\t";
120 CurrentFnSym->print(O, MAI);
121 O << ",@function\n";
122 } else if (Subtarget->isTargetCygMing()) {
123 O << "\t.def\t ";
124 CurrentFnSym->print(O, MAI);
125 O << ";\t.scl\t" <<
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000126 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
127 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
128 << ";\t.endef\n";
129 }
130
Chris Lattner86ec9712010-01-16 00:32:38 +0000131 CurrentFnSym->print(O, MAI);
132 O << ':';
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000133 if (VerboseAsm) {
134 O.PadToColumn(MAI->getCommentColumn());
135 O << MAI->getCommentString() << ' ';
136 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
137 }
138 O << '\n';
139
140 // Add some workaround for linkonce linkage on Cygwin\MinGW
141 if (Subtarget->isTargetCygMing() &&
Chris Lattner86ec9712010-01-16 00:32:38 +0000142 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
143 O << "Lllvm$workaround$fake$stub$";
144 CurrentFnSym->print(O, MAI);
145 O << ":\n";
146 }
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000147}
148
149/// runOnMachineFunction - This uses the printMachineInstruction()
150/// method to print assembly for each instruction.
151///
152bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
153 const Function *F = MF.getFunction();
154 this->MF = &MF;
155 CallingConv::ID CC = F->getCallingConv();
156
157 SetupMachineFunction(MF);
158 O << "\n\n";
159
160 if (Subtarget->isTargetCOFF()) {
161 X86COFFMachineModuleInfo &COFFMMI =
162 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
163
164 // Populate function information map. Don't want to populate
165 // non-stdcall or non-fastcall functions' information right now.
166 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
167 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
168 }
169
170 // Print out constants referenced by the function
171 EmitConstantPool(MF.getConstantPool());
172
173 // Print the 'header' of function
174 emitFunctionHeader(MF);
175
176 // Emit pre-function debug and/or EH information.
177 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
178 DW->BeginFunction(&MF);
179
180 // Print out code for the function.
181 bool hasAnyRealCode = false;
182 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
183 I != E; ++I) {
184 // Print a label for the basic block.
Dan Gohman5fda4342009-10-06 17:38:38 +0000185 EmitBasicBlockStart(I);
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000186 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
187 II != IE; ++II) {
188 // Print the assembly for the instruction.
189 if (!II->isLabel())
190 hasAnyRealCode = true;
191 printMachineInstruction(II);
192 }
193 }
194
195 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
196 // If the function is empty, then we need to emit *something*. Otherwise,
197 // the function's label might be associated with something that it wasn't
198 // meant to be associated with. We emit a noop in this situation.
199 // We are assuming inline asms are code.
200 O << "\tnop\n";
201 }
202
Chris Lattner86ec9712010-01-16 00:32:38 +0000203 if (MAI->hasDotTypeDotSizeDirective()) {
204 O << "\t.size\t";
205 CurrentFnSym->print(O, MAI);
206 O << ", .-";
207 CurrentFnSym->print(O, MAI);
208 O << '\n';
209 }
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000210
211 // Emit post-function debug information.
212 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
213 DW->EndFunction(&MF);
214
215 // Print out jump tables referenced by the function.
216 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
217
218 // We didn't modify anything.
219 return false;
220}
221
222/// printSymbolOperand - Print a raw symbol reference operand. This handles
223/// jump tables, constant pools, global address and external symbols, all of
224/// which print to a label with various suffixes for relocation types etc.
225void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000226 SmallString<128> TempNameStr;
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000227 switch (MO.getType()) {
228 default: llvm_unreachable("unknown symbol type!");
229 case MachineOperand::MO_JumpTableIndex:
230 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
231 << MO.getIndex();
232 break;
233 case MachineOperand::MO_ConstantPoolIndex:
234 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
235 << MO.getIndex();
236 printOffset(MO.getOffset());
237 break;
238 case MachineOperand::MO_GlobalAddress: {
239 const GlobalValue *GV = MO.getGlobal();
240
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000241 const MCSymbol *GVSym;
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000242 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000243 GVSym = GetPrivateGlobalValueSymbolStub(GV, "$stub");
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000244 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
245 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
246 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000247 GVSym = GetPrivateGlobalValueSymbolStub(GV, "$non_lazy_ptr");
248 else
249 GVSym = GetGlobalValueSymbol(GV);
250
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000251 if (Subtarget->isTargetCygMing()) {
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000252 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000253 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000254 COFFMMI.DecorateCygMingName(GVSym, OutContext, GV, *TM.getTargetData());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000255 }
256
257 // Handle dllimport linkage.
258 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000259 GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000260
261 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
262 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000263 Mang->getNameWithPrefix(TempNameStr, GV, true);
264 TempNameStr += "$non_lazy_ptr";
265 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000266
267 const MCSymbol *&StubSym =
268 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
269 if (StubSym == 0) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000270 TempNameStr.clear();
271 Mang->getNameWithPrefix(TempNameStr, GV, false);
272 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000273 }
274 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
Chris Lattnera38b2872010-01-13 06:38:18 +0000275 Mang->getNameWithPrefix(TempNameStr, GV, true);
276 TempNameStr += "$non_lazy_ptr";
277 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000278 const MCSymbol *&StubSym =
279 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
280 if (StubSym == 0) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000281 TempNameStr.clear();
282 Mang->getNameWithPrefix(TempNameStr, GV, false);
283 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000284 }
285 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000286 Mang->getNameWithPrefix(TempNameStr, GV, true);
287 TempNameStr += "$stub";
288 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000289 const MCSymbol *&StubSym =
290 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
291 if (StubSym == 0) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000292 TempNameStr.clear();
293 Mang->getNameWithPrefix(TempNameStr, GV, false);
294 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000295 }
296 }
297
298 // If the name begins with a dollar-sign, enclose it in parens. We do this
299 // to avoid having it look like an integer immediate to the assembler.
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000300 if (GVSym->getName()[0] != '$')
301 GVSym->print(O, MAI);
302 else {
303 O << '(';
304 GVSym->print(O, MAI);
305 O << ')';
306 }
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000307 printOffset(MO.getOffset());
308 break;
309 }
310 case MachineOperand::MO_ExternalSymbol: {
Chris Lattnerf80743e2010-01-13 07:56:59 +0000311 const MCSymbol *SymToPrint;
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000312 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattnerf80743e2010-01-13 07:56:59 +0000313 Mang->getNameWithPrefix(TempNameStr,
314 StringRef(MO.getSymbolName())+"$stub");
315 const MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000316 const MCSymbol *&StubSym =
317 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
318 if (StubSym == 0) {
Chris Lattnera38b2872010-01-13 06:38:18 +0000319 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
320 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000321 }
Chris Lattnerf80743e2010-01-13 07:56:59 +0000322 SymToPrint = StubSym;
323 } else {
324 Mang->getNameWithPrefix(TempNameStr, MO.getSymbolName());
325 SymToPrint = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000326 }
327
328 // If the name begins with a dollar-sign, enclose it in parens. We do this
329 // to avoid having it look like an integer immediate to the assembler.
Chris Lattnerf80743e2010-01-13 07:56:59 +0000330 if (SymToPrint->getName()[0] != '$')
331 SymToPrint->print(O, MAI);
332 else {
333 O << '(';
334 SymToPrint->print(O, MAI);
335 O << '(';
336 }
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000337 break;
338 }
339 }
340
341 switch (MO.getTargetFlags()) {
342 default:
343 llvm_unreachable("Unknown target flag on GV operand");
344 case X86II::MO_NO_FLAG: // No flag.
345 break;
346 case X86II::MO_DARWIN_NONLAZY:
347 case X86II::MO_DLLIMPORT:
348 case X86II::MO_DARWIN_STUB:
349 // These affect the name of the symbol, not any suffix.
350 break;
351 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
352 O << " + [.-";
353 PrintPICBaseSymbol();
354 O << ']';
355 break;
356 case X86II::MO_PIC_BASE_OFFSET:
357 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
358 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
359 O << '-';
360 PrintPICBaseSymbol();
361 break;
362 case X86II::MO_TLSGD: O << "@TLSGD"; break;
363 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
364 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
365 case X86II::MO_TPOFF: O << "@TPOFF"; break;
366 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
367 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
368 case X86II::MO_GOT: O << "@GOT"; break;
369 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
370 case X86II::MO_PLT: O << "@PLT"; break;
371 }
372}
373
374/// print_pcrel_imm - This is used to print an immediate value that ends up
375/// being encoded as a pc-relative value. These print slightly differently, for
376/// example, a $ is not emitted.
377void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
378 const MachineOperand &MO = MI->getOperand(OpNo);
379 switch (MO.getType()) {
380 default: llvm_unreachable("Unknown pcrel immediate operand");
381 case MachineOperand::MO_Immediate:
382 O << MO.getImm();
383 return;
384 case MachineOperand::MO_MachineBasicBlock:
385 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
386 return;
387 case MachineOperand::MO_GlobalAddress:
388 case MachineOperand::MO_ExternalSymbol:
389 printSymbolOperand(MO);
390 return;
391 }
392}
393
394
395void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
396 const char *Modifier) {
397 const MachineOperand &MO = MI->getOperand(OpNo);
398 switch (MO.getType()) {
399 default: llvm_unreachable("unknown operand type!");
400 case MachineOperand::MO_Register: {
401 O << '%';
402 unsigned Reg = MO.getReg();
403 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
404 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
405 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
406 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
407 Reg = getX86SubSuperRegister(Reg, VT);
408 }
409 O << X86ATTInstPrinter::getRegisterName(Reg);
410 return;
411 }
412
413 case MachineOperand::MO_Immediate:
414 O << '$' << MO.getImm();
415 return;
416
417 case MachineOperand::MO_JumpTableIndex:
418 case MachineOperand::MO_ConstantPoolIndex:
419 case MachineOperand::MO_GlobalAddress:
420 case MachineOperand::MO_ExternalSymbol: {
421 O << '$';
422 printSymbolOperand(MO);
423 break;
424 }
425 }
426}
427
428void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
429 unsigned char value = MI->getOperand(Op).getImm();
430 assert(value <= 7 && "Invalid ssecc argument!");
431 switch (value) {
432 case 0: O << "eq"; break;
433 case 1: O << "lt"; break;
434 case 2: O << "le"; break;
435 case 3: O << "unord"; break;
436 case 4: O << "neq"; break;
437 case 5: O << "nlt"; break;
438 case 6: O << "nle"; break;
439 case 7: O << "ord"; break;
440 }
441}
442
443void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
444 const char *Modifier) {
445 const MachineOperand &BaseReg = MI->getOperand(Op);
446 const MachineOperand &IndexReg = MI->getOperand(Op+2);
447 const MachineOperand &DispSpec = MI->getOperand(Op+3);
448
449 // If we really don't want to print out (rip), don't.
450 bool HasBaseReg = BaseReg.getReg() != 0;
451 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
452 BaseReg.getReg() == X86::RIP)
453 HasBaseReg = false;
454
455 // HasParenPart - True if we will print out the () part of the mem ref.
456 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
457
458 if (DispSpec.isImm()) {
459 int DispVal = DispSpec.getImm();
460 if (DispVal || !HasParenPart)
461 O << DispVal;
462 } else {
463 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
464 DispSpec.isJTI() || DispSpec.isSymbol());
465 printSymbolOperand(MI->getOperand(Op+3));
466 }
467
468 if (HasParenPart) {
469 assert(IndexReg.getReg() != X86::ESP &&
470 "X86 doesn't allow scaling by ESP");
471
472 O << '(';
473 if (HasBaseReg)
474 printOperand(MI, Op, Modifier);
475
476 if (IndexReg.getReg()) {
477 O << ',';
478 printOperand(MI, Op+2, Modifier);
479 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
480 if (ScaleVal != 1)
481 O << ',' << ScaleVal;
482 }
483 O << ')';
484 }
485}
486
487void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
488 const char *Modifier) {
489 assert(isMem(MI, Op) && "Invalid memory reference!");
490 const MachineOperand &Segment = MI->getOperand(Op+4);
491 if (Segment.getReg()) {
492 printOperand(MI, Op+4, Modifier);
493 O << ':';
494 }
495 printLeaMemReference(MI, Op, Modifier);
496}
497
498void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
499 const MachineBasicBlock *MBB) const {
500 if (!MAI->getSetDirective())
501 return;
502
503 // We don't need .set machinery if we have GOT-style relocations
504 if (Subtarget->isPICStyleGOT())
505 return;
506
507 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
508 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
509
510 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
511
512 if (Subtarget->isPICStyleRIPRel())
513 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
514 << '_' << uid << '\n';
515 else {
516 O << '-';
517 PrintPICBaseSymbol();
518 O << '\n';
519 }
520}
521
522
523void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
524 PrintPICBaseSymbol();
525 O << '\n';
526 PrintPICBaseSymbol();
527 O << ':';
528}
529
530void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
531 const MachineBasicBlock *MBB,
532 unsigned uid) const {
533 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
534 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
535
536 O << JTEntryDirective << ' ';
537
538 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
539 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
540 << '_' << uid << "_set_" << MBB->getNumber();
541 } else if (Subtarget->isPICStyleGOT()) {
542 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
543 O << "@GOTOFF";
544 } else
545 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
546}
547
548bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
549 unsigned Reg = MO.getReg();
550 switch (Mode) {
551 default: return true; // Unknown mode.
552 case 'b': // Print QImode register
553 Reg = getX86SubSuperRegister(Reg, MVT::i8);
554 break;
555 case 'h': // Print QImode high register
556 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
557 break;
558 case 'w': // Print HImode register
559 Reg = getX86SubSuperRegister(Reg, MVT::i16);
560 break;
561 case 'k': // Print SImode register
562 Reg = getX86SubSuperRegister(Reg, MVT::i32);
563 break;
564 case 'q': // Print DImode register
565 Reg = getX86SubSuperRegister(Reg, MVT::i64);
566 break;
567 }
568
569 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
570 return false;
571}
572
573/// PrintAsmOperand - Print out an operand for an inline asm expression.
574///
575bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
576 unsigned AsmVariant,
577 const char *ExtraCode) {
578 // Does this asm operand have a single letter operand modifier?
579 if (ExtraCode && ExtraCode[0]) {
580 if (ExtraCode[1] != 0) return true; // Unknown modifier.
581
582 const MachineOperand &MO = MI->getOperand(OpNo);
583
584 switch (ExtraCode[0]) {
585 default: return true; // Unknown modifier.
586 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
587 if (MO.isImm()) {
588 O << MO.getImm();
589 return false;
590 }
591 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
592 printSymbolOperand(MO);
593 return false;
594 }
595 if (MO.isReg()) {
596 O << '(';
597 printOperand(MI, OpNo);
598 O << ')';
599 return false;
600 }
601 return true;
602
603 case 'c': // Don't print "$" before a global var name or constant.
604 if (MO.isImm())
605 O << MO.getImm();
606 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
607 printSymbolOperand(MO);
608 else
609 printOperand(MI, OpNo);
610 return false;
611
612 case 'A': // Print '*' before a register (it must be a register)
613 if (MO.isReg()) {
614 O << '*';
615 printOperand(MI, OpNo);
616 return false;
617 }
618 return true;
619
620 case 'b': // Print QImode register
621 case 'h': // Print QImode high register
622 case 'w': // Print HImode register
623 case 'k': // Print SImode register
624 case 'q': // Print DImode register
625 if (MO.isReg())
626 return printAsmMRegister(MO, ExtraCode[0]);
627 printOperand(MI, OpNo);
628 return false;
629
630 case 'P': // This is the operand of a call, treat specially.
631 print_pcrel_imm(MI, OpNo);
632 return false;
633
634 case 'n': // Negate the immediate or print a '-' before the operand.
635 // Note: this is a temporary solution. It should be handled target
636 // independently as part of the 'MC' work.
637 if (MO.isImm()) {
638 O << -MO.getImm();
639 return false;
640 }
641 O << '-';
642 }
643 }
644
645 printOperand(MI, OpNo);
646 return false;
647}
648
649bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
650 unsigned OpNo, unsigned AsmVariant,
651 const char *ExtraCode) {
652 if (ExtraCode && ExtraCode[0]) {
653 if (ExtraCode[1] != 0) return true; // Unknown modifier.
654
655 switch (ExtraCode[0]) {
656 default: return true; // Unknown modifier.
657 case 'b': // Print QImode register
658 case 'h': // Print QImode high register
659 case 'w': // Print HImode register
660 case 'k': // Print SImode register
661 case 'q': // Print SImode register
662 // These only apply to registers, ignore on mem.
663 break;
664 case 'P': // Don't print @PLT, but do print as memory.
665 printMemReference(MI, OpNo, "no-rip");
666 return false;
667 }
668 }
669 printMemReference(MI, OpNo);
670 return false;
671}
672
673
674
675/// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
676/// AT&T syntax to the current output stream.
677///
678void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
679 ++EmittedInsts;
680
Devang Patel5450fc12009-10-06 02:19:11 +0000681 processDebugLoc(MI, true);
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000682
683 printInstructionThroughMCStreamer(MI);
684
David Greeneca9b04b2009-11-13 21:34:57 +0000685 if (VerboseAsm)
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000686 EmitComments(*MI);
687 O << '\n';
Devang Patel5450fc12009-10-06 02:19:11 +0000688
689 processDebugLoc(MI, false);
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000690}
691
692void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
693 if (!GVar->hasInitializer())
694 return; // External global require no code
695
696 // Check to see if this is a special global used by LLVM, if so, emit it.
697 if (EmitSpecialLLVMGlobal(GVar)) {
698 if (Subtarget->isTargetDarwin() &&
699 TM.getRelocationModel() == Reloc::Static) {
700 if (GVar->getName() == "llvm.global_ctors")
701 O << ".reference .constructors_used\n";
702 else if (GVar->getName() == "llvm.global_dtors")
703 O << ".reference .destructors_used\n";
704 }
705 return;
706 }
707
708 const TargetData *TD = TM.getTargetData();
709
710 std::string name = Mang->getMangledName(GVar);
711 Constant *C = GVar->getInitializer();
712 const Type *Type = C->getType();
713 unsigned Size = TD->getTypeAllocSize(Type);
714 unsigned Align = TD->getPreferredAlignmentLog(GVar);
715
716 printVisibility(name, GVar->getVisibility());
717
718 if (Subtarget->isTargetELF())
719 O << "\t.type\t" << name << ",@object\n";
720
721
722 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
723 const MCSection *TheSection =
724 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
725 OutStreamer.SwitchSection(TheSection);
726
727 // FIXME: get this stuff from section kind flags.
728 if (C->isNullValue() && !GVar->hasSection() &&
729 // Don't put things that should go in the cstring section into "comm".
730 !TheSection->getKind().isMergeableCString()) {
731 if (GVar->hasExternalLinkage()) {
732 if (const char *Directive = MAI->getZeroFillDirective()) {
733 O << "\t.globl " << name << '\n';
734 O << Directive << "__DATA, __common, " << name << ", "
735 << Size << ", " << Align << '\n';
736 return;
737 }
738 }
739
740 if (!GVar->isThreadLocal() &&
741 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
742 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
743
744 if (MAI->getLCOMMDirective() != NULL) {
745 if (GVar->hasLocalLinkage()) {
746 O << MAI->getLCOMMDirective() << name << ',' << Size;
747 if (Subtarget->isTargetDarwin())
748 O << ',' << Align;
749 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
750 O << "\t.globl " << name << '\n'
751 << MAI->getWeakDefDirective() << name << '\n';
752 EmitAlignment(Align, GVar);
753 O << name << ":";
754 if (VerboseAsm) {
755 O.PadToColumn(MAI->getCommentColumn());
756 O << MAI->getCommentString() << ' ';
757 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
758 }
759 O << '\n';
760 EmitGlobalConstant(C);
761 return;
762 } else {
763 O << MAI->getCOMMDirective() << name << ',' << Size;
764 if (MAI->getCOMMDirectiveTakesAlignment())
765 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
766 }
767 } else {
768 if (!Subtarget->isTargetCygMing()) {
769 if (GVar->hasLocalLinkage())
770 O << "\t.local\t" << name << '\n';
771 }
772 O << MAI->getCOMMDirective() << name << ',' << Size;
773 if (MAI->getCOMMDirectiveTakesAlignment())
774 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
775 }
776 if (VerboseAsm) {
777 O.PadToColumn(MAI->getCommentColumn());
778 O << MAI->getCommentString() << ' ';
779 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
780 }
781 O << '\n';
782 return;
783 }
784 }
785
786 switch (GVar->getLinkage()) {
787 case GlobalValue::CommonLinkage:
788 case GlobalValue::LinkOnceAnyLinkage:
789 case GlobalValue::LinkOnceODRLinkage:
790 case GlobalValue::WeakAnyLinkage:
791 case GlobalValue::WeakODRLinkage:
792 case GlobalValue::LinkerPrivateLinkage:
793 if (Subtarget->isTargetDarwin()) {
794 O << "\t.globl " << name << '\n'
795 << MAI->getWeakDefDirective() << name << '\n';
796 } else if (Subtarget->isTargetCygMing()) {
797 O << "\t.globl\t" << name << "\n"
798 "\t.linkonce same_size\n";
799 } else {
800 O << "\t.weak\t" << name << '\n';
801 }
802 break;
803 case GlobalValue::DLLExportLinkage:
804 case GlobalValue::AppendingLinkage:
805 // FIXME: appending linkage variables should go into a section of
806 // their name or something. For now, just emit them as external.
807 case GlobalValue::ExternalLinkage:
808 // If external or appending, declare as a global symbol
809 O << "\t.globl " << name << '\n';
810 // FALL THROUGH
811 case GlobalValue::PrivateLinkage:
812 case GlobalValue::InternalLinkage:
813 break;
814 default:
815 llvm_unreachable("Unknown linkage type!");
816 }
817
818 EmitAlignment(Align, GVar);
819 O << name << ":";
820 if (VerboseAsm){
821 O.PadToColumn(MAI->getCommentColumn());
822 O << MAI->getCommentString() << ' ';
823 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
824 }
825 O << '\n';
826
827 EmitGlobalConstant(C);
828
829 if (MAI->hasDotTypeDotSizeDirective())
830 O << "\t.size\t" << name << ", " << Size << '\n';
831}
832
833void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
834 if (Subtarget->isTargetDarwin()) {
835 // All darwin targets use mach-o.
836 TargetLoweringObjectFileMachO &TLOFMacho =
837 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
838
839 MachineModuleInfoMachO &MMIMacho =
840 MMI->getObjFileInfo<MachineModuleInfoMachO>();
841
842 // Output stubs for dynamically-linked functions.
843 MachineModuleInfoMachO::SymbolListTy Stubs;
844
845 Stubs = MMIMacho.GetFnStubList();
846 if (!Stubs.empty()) {
847 const MCSection *TheSection =
848 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
849 MCSectionMachO::S_SYMBOL_STUBS |
850 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
851 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
852 5, SectionKind::getMetadata());
853 OutStreamer.SwitchSection(TheSection);
854
855 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
856 Stubs[i].first->print(O, MAI);
857 O << ":\n" << "\t.indirect_symbol ";
858 // Get the MCSymbol without the $stub suffix.
859 Stubs[i].second->print(O, MAI);
860 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
861 }
862 O << '\n';
863
864 Stubs.clear();
865 }
866
867 // Output stubs for external and common global variables.
868 Stubs = MMIMacho.GetGVStubList();
869 if (!Stubs.empty()) {
870 const MCSection *TheSection =
871 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
872 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
873 SectionKind::getMetadata());
874 OutStreamer.SwitchSection(TheSection);
875
876 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
877 Stubs[i].first->print(O, MAI);
878 O << ":\n\t.indirect_symbol ";
879 Stubs[i].second->print(O, MAI);
880 O << "\n\t.long\t0\n";
881 }
882 Stubs.clear();
883 }
884
885 Stubs = MMIMacho.GetHiddenGVStubList();
886 if (!Stubs.empty()) {
887 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
888 EmitAlignment(2);
889
890 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
891 Stubs[i].first->print(O, MAI);
892 O << ":\n" << MAI->getData32bitsDirective();
893 Stubs[i].second->print(O, MAI);
894 O << '\n';
895 }
896 Stubs.clear();
897 }
898
899 // Funny Darwin hack: This flag tells the linker that no global symbols
900 // contain code that falls through to other global symbols (e.g. the obvious
901 // implementation of multiple entry points). If this doesn't occur, the
902 // linker can safely perform dead code stripping. Since LLVM never
903 // generates code that does this, it is always safe to set.
Chris Lattnerfe284f72009-10-19 18:03:08 +0000904 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000905 }
906
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000907 if (Subtarget->isTargetCOFF()) {
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000908 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000909 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000910
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000911 // Emit type information for external functions
912 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000913 E = COFFMMI.stub_end(); I != E; ++I) {
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000914 O << "\t.def\t " << I->getKeyData()
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000915 << ";\t.scl\t" << COFF::C_EXT
916 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
917 << ";\t.endef\n";
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000918 }
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000919
920 if (Subtarget->isTargetCygMing()) {
921 // Necessary for dllexport support
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000922 std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000923
924 TargetLoweringObjectFileCOFF &TLOFCOFF =
925 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
926
927 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
928 if (I->hasDLLExportLinkage()) {
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000929 const MCSymbol *Sym = GetGlobalValueSymbol(I);
930 COFFMMI.DecorateCygMingName(Sym, OutContext, I, *TM.getTargetData());
931 DLLExportedFns.push_back(Sym);
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000932 }
933
934 for (Module::const_global_iterator I = M.global_begin(),
935 E = M.global_end(); I != E; ++I)
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000936 if (I->hasDLLExportLinkage())
937 DLLExportedGlobals.push_back(GetGlobalValueSymbol(I));
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000938
939 // Output linker support code for dllexported globals on windows.
940 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
941 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
942 true,
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000943 SectionKind::getMetadata()));
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000944 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i) {
945 O << "\t.ascii \" -export:";
946 DLLExportedGlobals[i]->print(O, MAI);
947 O << ",data\"\n";
948 }
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000949
Chris Lattnerc53c24c2010-01-16 00:51:39 +0000950 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i) {
951 O << "\t.ascii \" -export:";
952 DLLExportedFns[i]->print(O, MAI);
953 O << "\"\n";
954 }
Anton Korobeynikovd5fcb1d2009-10-15 22:36:18 +0000955 }
Chris Lattnerbf4b6a82009-09-20 07:41:30 +0000956 }
957 }
958}
959
960
961//===----------------------------------------------------------------------===//
962// Target Registry Stuff
963//===----------------------------------------------------------------------===//
964
965static MCInstPrinter *createX86MCInstPrinter(const Target &T,
966 unsigned SyntaxVariant,
967 const MCAsmInfo &MAI,
968 raw_ostream &O) {
969 if (SyntaxVariant == 0)
970 return new X86ATTInstPrinter(O, MAI);
971 if (SyntaxVariant == 1)
972 return new X86IntelInstPrinter(O, MAI);
973 return 0;
974}
975
976// Force static initialization.
977extern "C" void LLVMInitializeX86AsmPrinter() {
978 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
979 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
980
981 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
982 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);
983}