blob: 70c6dd03eb19d623942755cea4eec60d5d6d5fbf [file] [log] [blame]
Chris Lattner0dc32ea2009-09-20 07:41:30 +00001//===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
Misha Brukman0e0a7a452005-04-21 23:38:14 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman0e0a7a452005-04-21 23:38:14 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner72614082002-10-25 22:55:53 +00009//
Chris Lattner0dc32ea2009-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'.
Chris Lattner72614082002-10-25 22:55:53 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner0dc32ea2009-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>();
74 COFFMMI.DecorateCygMingName(CurrentFnName, F, *TM.getTargetData());
75 }
76
77 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
78 EmitAlignment(FnAlign, F);
79
80 switch (F->getLinkage()) {
81 default: llvm_unreachable("Unknown linkage type!");
82 case Function::InternalLinkage: // Symbols default to internal.
83 case Function::PrivateLinkage:
84 break;
85 case Function::DLLExportLinkage:
86 case Function::ExternalLinkage:
87 O << "\t.globl\t" << CurrentFnName << '\n';
88 break;
89 case Function::LinkerPrivateLinkage:
90 case Function::LinkOnceAnyLinkage:
91 case Function::LinkOnceODRLinkage:
92 case Function::WeakAnyLinkage:
93 case Function::WeakODRLinkage:
94 if (Subtarget->isTargetDarwin()) {
95 O << "\t.globl\t" << CurrentFnName << '\n';
96 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
97 } else if (Subtarget->isTargetCygMing()) {
98 O << "\t.globl\t" << CurrentFnName << "\n"
99 "\t.linkonce discard\n";
100 } else {
101 O << "\t.weak\t" << CurrentFnName << '\n';
102 }
103 break;
104 }
105
106 printVisibility(CurrentFnName, F->getVisibility());
107
108 if (Subtarget->isTargetELF())
109 O << "\t.type\t" << CurrentFnName << ",@function\n";
110 else if (Subtarget->isTargetCygMing()) {
111 O << "\t.def\t " << CurrentFnName
112 << ";\t.scl\t" <<
113 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
114 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
115 << ";\t.endef\n";
116 }
117
118 O << CurrentFnName << ':';
119 if (VerboseAsm) {
120 O.PadToColumn(MAI->getCommentColumn());
121 O << MAI->getCommentString() << ' ';
122 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
123 }
124 O << '\n';
125
126 // Add some workaround for linkonce linkage on Cygwin\MinGW
127 if (Subtarget->isTargetCygMing() &&
128 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
129 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
130}
131
132/// runOnMachineFunction - This uses the printMachineInstruction()
133/// method to print assembly for each instruction.
134///
135bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
136 const Function *F = MF.getFunction();
137 this->MF = &MF;
138 CallingConv::ID CC = F->getCallingConv();
139
140 SetupMachineFunction(MF);
141 O << "\n\n";
142
143 if (Subtarget->isTargetCOFF()) {
144 X86COFFMachineModuleInfo &COFFMMI =
145 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
146
147 // Populate function information map. Don't want to populate
148 // non-stdcall or non-fastcall functions' information right now.
149 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
150 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
151 }
152
153 // Print out constants referenced by the function
154 EmitConstantPool(MF.getConstantPool());
155
156 // Print the 'header' of function
157 emitFunctionHeader(MF);
158
159 // Emit pre-function debug and/or EH information.
160 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
161 DW->BeginFunction(&MF);
162
163 // Print out code for the function.
164 bool hasAnyRealCode = false;
165 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
166 I != E; ++I) {
167 // Print a label for the basic block.
Dan Gohmane3cc3f32009-10-06 17:38:38 +0000168 EmitBasicBlockStart(I);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000169 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
170 II != IE; ++II) {
171 // Print the assembly for the instruction.
172 if (!II->isLabel())
173 hasAnyRealCode = true;
174 printMachineInstruction(II);
175 }
176 }
177
178 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
179 // If the function is empty, then we need to emit *something*. Otherwise,
180 // the function's label might be associated with something that it wasn't
181 // meant to be associated with. We emit a noop in this situation.
182 // We are assuming inline asms are code.
183 O << "\tnop\n";
184 }
185
186 if (MAI->hasDotTypeDotSizeDirective())
187 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
188
189 // Emit post-function debug information.
190 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
191 DW->EndFunction(&MF);
192
193 // Print out jump tables referenced by the function.
194 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
195
196 // We didn't modify anything.
197 return false;
198}
199
200/// printSymbolOperand - Print a raw symbol reference operand. This handles
201/// jump tables, constant pools, global address and external symbols, all of
202/// which print to a label with various suffixes for relocation types etc.
203void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
Chris Lattner48130352010-01-13 06:38:18 +0000204 SmallString<128> TempNameStr;
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000205 switch (MO.getType()) {
206 default: llvm_unreachable("unknown symbol type!");
207 case MachineOperand::MO_JumpTableIndex:
208 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
209 << MO.getIndex();
210 break;
211 case MachineOperand::MO_ConstantPoolIndex:
212 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
213 << MO.getIndex();
214 printOffset(MO.getOffset());
215 break;
216 case MachineOperand::MO_GlobalAddress: {
217 const GlobalValue *GV = MO.getGlobal();
218
219 const char *Suffix = "";
220 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
221 Suffix = "$stub";
222 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
223 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
224 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
225 Suffix = "$non_lazy_ptr";
226
227 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
228 if (Subtarget->isTargetCygMing()) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000229 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000230 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
231 COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
232 }
233
234 // Handle dllimport linkage.
235 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
236 Name = "__imp_" + Name;
237
238 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
239 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
Chris Lattner48130352010-01-13 06:38:18 +0000240 Mang->getNameWithPrefix(TempNameStr, GV, true);
241 TempNameStr += "$non_lazy_ptr";
242 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000243
244 const MCSymbol *&StubSym =
245 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
246 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000247 TempNameStr.clear();
248 Mang->getNameWithPrefix(TempNameStr, GV, false);
249 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000250 }
251 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
Chris Lattner48130352010-01-13 06:38:18 +0000252 Mang->getNameWithPrefix(TempNameStr, GV, true);
253 TempNameStr += "$non_lazy_ptr";
254 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000255 const MCSymbol *&StubSym =
256 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
257 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000258 TempNameStr.clear();
259 Mang->getNameWithPrefix(TempNameStr, GV, false);
260 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000261 }
262 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattner48130352010-01-13 06:38:18 +0000263 Mang->getNameWithPrefix(TempNameStr, GV, true);
264 TempNameStr += "$stub";
265 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000266 const MCSymbol *&StubSym =
267 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
268 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000269 TempNameStr.clear();
270 Mang->getNameWithPrefix(TempNameStr, GV, false);
271 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000272 }
273 }
274
275 // If the name begins with a dollar-sign, enclose it in parens. We do this
276 // to avoid having it look like an integer immediate to the assembler.
277 if (Name[0] == '$')
278 O << '(' << Name << ')';
279 else
280 O << Name;
281
282 printOffset(MO.getOffset());
283 break;
284 }
285 case MachineOperand::MO_ExternalSymbol: {
Chris Lattneree9250b2010-01-13 07:56:59 +0000286 const MCSymbol *SymToPrint;
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000287 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattneree9250b2010-01-13 07:56:59 +0000288 Mang->getNameWithPrefix(TempNameStr,
289 StringRef(MO.getSymbolName())+"$stub");
290 const MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000291 const MCSymbol *&StubSym =
292 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
293 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000294 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
295 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000296 }
Chris Lattneree9250b2010-01-13 07:56:59 +0000297 SymToPrint = StubSym;
298 } else {
299 Mang->getNameWithPrefix(TempNameStr, MO.getSymbolName());
300 SymToPrint = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000301 }
302
303 // If the name begins with a dollar-sign, enclose it in parens. We do this
304 // to avoid having it look like an integer immediate to the assembler.
Chris Lattneree9250b2010-01-13 07:56:59 +0000305 if (SymToPrint->getName()[0] != '$')
306 SymToPrint->print(O, MAI);
307 else {
308 O << '(';
309 SymToPrint->print(O, MAI);
310 O << '(';
311 }
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000312 break;
313 }
314 }
315
316 switch (MO.getTargetFlags()) {
317 default:
318 llvm_unreachable("Unknown target flag on GV operand");
319 case X86II::MO_NO_FLAG: // No flag.
320 break;
321 case X86II::MO_DARWIN_NONLAZY:
322 case X86II::MO_DLLIMPORT:
323 case X86II::MO_DARWIN_STUB:
324 // These affect the name of the symbol, not any suffix.
325 break;
326 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
327 O << " + [.-";
328 PrintPICBaseSymbol();
329 O << ']';
330 break;
331 case X86II::MO_PIC_BASE_OFFSET:
332 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
333 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
334 O << '-';
335 PrintPICBaseSymbol();
336 break;
337 case X86II::MO_TLSGD: O << "@TLSGD"; break;
338 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
339 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
340 case X86II::MO_TPOFF: O << "@TPOFF"; break;
341 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
342 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
343 case X86II::MO_GOT: O << "@GOT"; break;
344 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
345 case X86II::MO_PLT: O << "@PLT"; break;
346 }
347}
348
349/// print_pcrel_imm - This is used to print an immediate value that ends up
350/// being encoded as a pc-relative value. These print slightly differently, for
351/// example, a $ is not emitted.
352void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
353 const MachineOperand &MO = MI->getOperand(OpNo);
354 switch (MO.getType()) {
355 default: llvm_unreachable("Unknown pcrel immediate operand");
356 case MachineOperand::MO_Immediate:
357 O << MO.getImm();
358 return;
359 case MachineOperand::MO_MachineBasicBlock:
360 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
361 return;
362 case MachineOperand::MO_GlobalAddress:
363 case MachineOperand::MO_ExternalSymbol:
364 printSymbolOperand(MO);
365 return;
366 }
367}
368
369
370void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
371 const char *Modifier) {
372 const MachineOperand &MO = MI->getOperand(OpNo);
373 switch (MO.getType()) {
374 default: llvm_unreachable("unknown operand type!");
375 case MachineOperand::MO_Register: {
376 O << '%';
377 unsigned Reg = MO.getReg();
378 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
379 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
380 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
381 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
382 Reg = getX86SubSuperRegister(Reg, VT);
383 }
384 O << X86ATTInstPrinter::getRegisterName(Reg);
385 return;
386 }
387
388 case MachineOperand::MO_Immediate:
389 O << '$' << MO.getImm();
390 return;
391
392 case MachineOperand::MO_JumpTableIndex:
393 case MachineOperand::MO_ConstantPoolIndex:
394 case MachineOperand::MO_GlobalAddress:
395 case MachineOperand::MO_ExternalSymbol: {
396 O << '$';
397 printSymbolOperand(MO);
398 break;
399 }
400 }
401}
402
403void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
404 unsigned char value = MI->getOperand(Op).getImm();
405 assert(value <= 7 && "Invalid ssecc argument!");
406 switch (value) {
407 case 0: O << "eq"; break;
408 case 1: O << "lt"; break;
409 case 2: O << "le"; break;
410 case 3: O << "unord"; break;
411 case 4: O << "neq"; break;
412 case 5: O << "nlt"; break;
413 case 6: O << "nle"; break;
414 case 7: O << "ord"; break;
415 }
416}
417
418void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
419 const char *Modifier) {
420 const MachineOperand &BaseReg = MI->getOperand(Op);
421 const MachineOperand &IndexReg = MI->getOperand(Op+2);
422 const MachineOperand &DispSpec = MI->getOperand(Op+3);
423
424 // If we really don't want to print out (rip), don't.
425 bool HasBaseReg = BaseReg.getReg() != 0;
426 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
427 BaseReg.getReg() == X86::RIP)
428 HasBaseReg = false;
429
430 // HasParenPart - True if we will print out the () part of the mem ref.
431 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
432
433 if (DispSpec.isImm()) {
434 int DispVal = DispSpec.getImm();
435 if (DispVal || !HasParenPart)
436 O << DispVal;
437 } else {
438 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
439 DispSpec.isJTI() || DispSpec.isSymbol());
440 printSymbolOperand(MI->getOperand(Op+3));
441 }
442
443 if (HasParenPart) {
444 assert(IndexReg.getReg() != X86::ESP &&
445 "X86 doesn't allow scaling by ESP");
446
447 O << '(';
448 if (HasBaseReg)
449 printOperand(MI, Op, Modifier);
450
451 if (IndexReg.getReg()) {
452 O << ',';
453 printOperand(MI, Op+2, Modifier);
454 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
455 if (ScaleVal != 1)
456 O << ',' << ScaleVal;
457 }
458 O << ')';
459 }
460}
461
462void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
463 const char *Modifier) {
464 assert(isMem(MI, Op) && "Invalid memory reference!");
465 const MachineOperand &Segment = MI->getOperand(Op+4);
466 if (Segment.getReg()) {
467 printOperand(MI, Op+4, Modifier);
468 O << ':';
469 }
470 printLeaMemReference(MI, Op, Modifier);
471}
472
473void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
474 const MachineBasicBlock *MBB) const {
475 if (!MAI->getSetDirective())
476 return;
477
478 // We don't need .set machinery if we have GOT-style relocations
479 if (Subtarget->isPICStyleGOT())
480 return;
481
482 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
483 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
484
485 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
486
487 if (Subtarget->isPICStyleRIPRel())
488 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
489 << '_' << uid << '\n';
490 else {
491 O << '-';
492 PrintPICBaseSymbol();
493 O << '\n';
494 }
495}
496
497
498void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
499 PrintPICBaseSymbol();
500 O << '\n';
501 PrintPICBaseSymbol();
502 O << ':';
503}
504
505void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
506 const MachineBasicBlock *MBB,
507 unsigned uid) const {
508 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
509 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
510
511 O << JTEntryDirective << ' ';
512
513 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
514 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
515 << '_' << uid << "_set_" << MBB->getNumber();
516 } else if (Subtarget->isPICStyleGOT()) {
517 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
518 O << "@GOTOFF";
519 } else
520 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
521}
522
523bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
524 unsigned Reg = MO.getReg();
525 switch (Mode) {
526 default: return true; // Unknown mode.
527 case 'b': // Print QImode register
528 Reg = getX86SubSuperRegister(Reg, MVT::i8);
529 break;
530 case 'h': // Print QImode high register
531 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
532 break;
533 case 'w': // Print HImode register
534 Reg = getX86SubSuperRegister(Reg, MVT::i16);
535 break;
536 case 'k': // Print SImode register
537 Reg = getX86SubSuperRegister(Reg, MVT::i32);
538 break;
539 case 'q': // Print DImode register
540 Reg = getX86SubSuperRegister(Reg, MVT::i64);
541 break;
542 }
543
544 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
545 return false;
546}
547
548/// PrintAsmOperand - Print out an operand for an inline asm expression.
549///
550bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
551 unsigned AsmVariant,
552 const char *ExtraCode) {
553 // Does this asm operand have a single letter operand modifier?
554 if (ExtraCode && ExtraCode[0]) {
555 if (ExtraCode[1] != 0) return true; // Unknown modifier.
556
557 const MachineOperand &MO = MI->getOperand(OpNo);
558
559 switch (ExtraCode[0]) {
560 default: return true; // Unknown modifier.
561 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
562 if (MO.isImm()) {
563 O << MO.getImm();
564 return false;
565 }
566 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
567 printSymbolOperand(MO);
568 return false;
569 }
570 if (MO.isReg()) {
571 O << '(';
572 printOperand(MI, OpNo);
573 O << ')';
574 return false;
575 }
576 return true;
577
578 case 'c': // Don't print "$" before a global var name or constant.
579 if (MO.isImm())
580 O << MO.getImm();
581 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
582 printSymbolOperand(MO);
583 else
584 printOperand(MI, OpNo);
585 return false;
586
587 case 'A': // Print '*' before a register (it must be a register)
588 if (MO.isReg()) {
589 O << '*';
590 printOperand(MI, OpNo);
591 return false;
592 }
593 return true;
594
595 case 'b': // Print QImode register
596 case 'h': // Print QImode high register
597 case 'w': // Print HImode register
598 case 'k': // Print SImode register
599 case 'q': // Print DImode register
600 if (MO.isReg())
601 return printAsmMRegister(MO, ExtraCode[0]);
602 printOperand(MI, OpNo);
603 return false;
604
605 case 'P': // This is the operand of a call, treat specially.
606 print_pcrel_imm(MI, OpNo);
607 return false;
608
609 case 'n': // Negate the immediate or print a '-' before the operand.
610 // Note: this is a temporary solution. It should be handled target
611 // independently as part of the 'MC' work.
612 if (MO.isImm()) {
613 O << -MO.getImm();
614 return false;
615 }
616 O << '-';
617 }
618 }
619
620 printOperand(MI, OpNo);
621 return false;
622}
623
624bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
625 unsigned OpNo, unsigned AsmVariant,
626 const char *ExtraCode) {
627 if (ExtraCode && ExtraCode[0]) {
628 if (ExtraCode[1] != 0) return true; // Unknown modifier.
629
630 switch (ExtraCode[0]) {
631 default: return true; // Unknown modifier.
632 case 'b': // Print QImode register
633 case 'h': // Print QImode high register
634 case 'w': // Print HImode register
635 case 'k': // Print SImode register
636 case 'q': // Print SImode register
637 // These only apply to registers, ignore on mem.
638 break;
639 case 'P': // Don't print @PLT, but do print as memory.
640 printMemReference(MI, OpNo, "no-rip");
641 return false;
642 }
643 }
644 printMemReference(MI, OpNo);
645 return false;
646}
647
648
649
650/// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
651/// AT&T syntax to the current output stream.
652///
653void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
654 ++EmittedInsts;
655
Devang Patelaf0e2722009-10-06 02:19:11 +0000656 processDebugLoc(MI, true);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000657
658 printInstructionThroughMCStreamer(MI);
659
David Greene1924aab2009-11-13 21:34:57 +0000660 if (VerboseAsm)
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000661 EmitComments(*MI);
662 O << '\n';
Devang Patelaf0e2722009-10-06 02:19:11 +0000663
664 processDebugLoc(MI, false);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000665}
666
667void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
668 if (!GVar->hasInitializer())
669 return; // External global require no code
670
671 // Check to see if this is a special global used by LLVM, if so, emit it.
672 if (EmitSpecialLLVMGlobal(GVar)) {
673 if (Subtarget->isTargetDarwin() &&
674 TM.getRelocationModel() == Reloc::Static) {
675 if (GVar->getName() == "llvm.global_ctors")
676 O << ".reference .constructors_used\n";
677 else if (GVar->getName() == "llvm.global_dtors")
678 O << ".reference .destructors_used\n";
679 }
680 return;
681 }
682
683 const TargetData *TD = TM.getTargetData();
684
685 std::string name = Mang->getMangledName(GVar);
686 Constant *C = GVar->getInitializer();
687 const Type *Type = C->getType();
688 unsigned Size = TD->getTypeAllocSize(Type);
689 unsigned Align = TD->getPreferredAlignmentLog(GVar);
690
691 printVisibility(name, GVar->getVisibility());
692
693 if (Subtarget->isTargetELF())
694 O << "\t.type\t" << name << ",@object\n";
695
696
697 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
698 const MCSection *TheSection =
699 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
700 OutStreamer.SwitchSection(TheSection);
701
702 // FIXME: get this stuff from section kind flags.
703 if (C->isNullValue() && !GVar->hasSection() &&
704 // Don't put things that should go in the cstring section into "comm".
705 !TheSection->getKind().isMergeableCString()) {
706 if (GVar->hasExternalLinkage()) {
707 if (const char *Directive = MAI->getZeroFillDirective()) {
708 O << "\t.globl " << name << '\n';
709 O << Directive << "__DATA, __common, " << name << ", "
710 << Size << ", " << Align << '\n';
711 return;
712 }
713 }
714
715 if (!GVar->isThreadLocal() &&
716 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
717 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
718
719 if (MAI->getLCOMMDirective() != NULL) {
720 if (GVar->hasLocalLinkage()) {
721 O << MAI->getLCOMMDirective() << name << ',' << Size;
722 if (Subtarget->isTargetDarwin())
723 O << ',' << Align;
724 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
725 O << "\t.globl " << name << '\n'
726 << MAI->getWeakDefDirective() << name << '\n';
727 EmitAlignment(Align, GVar);
728 O << name << ":";
729 if (VerboseAsm) {
730 O.PadToColumn(MAI->getCommentColumn());
731 O << MAI->getCommentString() << ' ';
732 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
733 }
734 O << '\n';
735 EmitGlobalConstant(C);
736 return;
737 } else {
738 O << MAI->getCOMMDirective() << name << ',' << Size;
739 if (MAI->getCOMMDirectiveTakesAlignment())
740 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
741 }
742 } else {
743 if (!Subtarget->isTargetCygMing()) {
744 if (GVar->hasLocalLinkage())
745 O << "\t.local\t" << name << '\n';
746 }
747 O << MAI->getCOMMDirective() << name << ',' << Size;
748 if (MAI->getCOMMDirectiveTakesAlignment())
749 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
750 }
751 if (VerboseAsm) {
752 O.PadToColumn(MAI->getCommentColumn());
753 O << MAI->getCommentString() << ' ';
754 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
755 }
756 O << '\n';
757 return;
758 }
759 }
760
761 switch (GVar->getLinkage()) {
762 case GlobalValue::CommonLinkage:
763 case GlobalValue::LinkOnceAnyLinkage:
764 case GlobalValue::LinkOnceODRLinkage:
765 case GlobalValue::WeakAnyLinkage:
766 case GlobalValue::WeakODRLinkage:
767 case GlobalValue::LinkerPrivateLinkage:
768 if (Subtarget->isTargetDarwin()) {
769 O << "\t.globl " << name << '\n'
770 << MAI->getWeakDefDirective() << name << '\n';
771 } else if (Subtarget->isTargetCygMing()) {
772 O << "\t.globl\t" << name << "\n"
773 "\t.linkonce same_size\n";
774 } else {
775 O << "\t.weak\t" << name << '\n';
776 }
777 break;
778 case GlobalValue::DLLExportLinkage:
779 case GlobalValue::AppendingLinkage:
780 // FIXME: appending linkage variables should go into a section of
781 // their name or something. For now, just emit them as external.
782 case GlobalValue::ExternalLinkage:
783 // If external or appending, declare as a global symbol
784 O << "\t.globl " << name << '\n';
785 // FALL THROUGH
786 case GlobalValue::PrivateLinkage:
787 case GlobalValue::InternalLinkage:
788 break;
789 default:
790 llvm_unreachable("Unknown linkage type!");
791 }
792
793 EmitAlignment(Align, GVar);
794 O << name << ":";
795 if (VerboseAsm){
796 O.PadToColumn(MAI->getCommentColumn());
797 O << MAI->getCommentString() << ' ';
798 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
799 }
800 O << '\n';
801
802 EmitGlobalConstant(C);
803
804 if (MAI->hasDotTypeDotSizeDirective())
805 O << "\t.size\t" << name << ", " << Size << '\n';
806}
807
808void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
809 if (Subtarget->isTargetDarwin()) {
810 // All darwin targets use mach-o.
811 TargetLoweringObjectFileMachO &TLOFMacho =
812 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
813
814 MachineModuleInfoMachO &MMIMacho =
815 MMI->getObjFileInfo<MachineModuleInfoMachO>();
816
817 // Output stubs for dynamically-linked functions.
818 MachineModuleInfoMachO::SymbolListTy Stubs;
819
820 Stubs = MMIMacho.GetFnStubList();
821 if (!Stubs.empty()) {
822 const MCSection *TheSection =
823 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
824 MCSectionMachO::S_SYMBOL_STUBS |
825 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
826 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
827 5, SectionKind::getMetadata());
828 OutStreamer.SwitchSection(TheSection);
829
830 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
831 Stubs[i].first->print(O, MAI);
832 O << ":\n" << "\t.indirect_symbol ";
833 // Get the MCSymbol without the $stub suffix.
834 Stubs[i].second->print(O, MAI);
835 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
836 }
837 O << '\n';
838
839 Stubs.clear();
840 }
841
842 // Output stubs for external and common global variables.
843 Stubs = MMIMacho.GetGVStubList();
844 if (!Stubs.empty()) {
845 const MCSection *TheSection =
846 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
847 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
848 SectionKind::getMetadata());
849 OutStreamer.SwitchSection(TheSection);
850
851 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
852 Stubs[i].first->print(O, MAI);
853 O << ":\n\t.indirect_symbol ";
854 Stubs[i].second->print(O, MAI);
855 O << "\n\t.long\t0\n";
856 }
857 Stubs.clear();
858 }
859
860 Stubs = MMIMacho.GetHiddenGVStubList();
861 if (!Stubs.empty()) {
862 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
863 EmitAlignment(2);
864
865 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
866 Stubs[i].first->print(O, MAI);
867 O << ":\n" << MAI->getData32bitsDirective();
868 Stubs[i].second->print(O, MAI);
869 O << '\n';
870 }
871 Stubs.clear();
872 }
873
874 // Funny Darwin hack: This flag tells the linker that no global symbols
875 // contain code that falls through to other global symbols (e.g. the obvious
876 // implementation of multiple entry points). If this doesn't occur, the
877 // linker can safely perform dead code stripping. Since LLVM never
878 // generates code that does this, it is always safe to set.
Chris Lattner74cd3b72009-10-19 18:03:08 +0000879 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000880 }
881
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000882 if (Subtarget->isTargetCOFF()) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000883 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000884 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000885
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000886 // Emit type information for external functions
887 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000888 E = COFFMMI.stub_end(); I != E; ++I) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000889 O << "\t.def\t " << I->getKeyData()
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000890 << ";\t.scl\t" << COFF::C_EXT
891 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
892 << ";\t.endef\n";
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000893 }
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000894
895 if (Subtarget->isTargetCygMing()) {
896 // Necessary for dllexport support
897 std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
898
899 TargetLoweringObjectFileCOFF &TLOFCOFF =
900 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
901
902 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
903 if (I->hasDLLExportLinkage()) {
904 std::string Name = Mang->getMangledName(I);
905 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
906 DLLExportedFns.push_back(Name);
907 }
908
909 for (Module::const_global_iterator I = M.global_begin(),
910 E = M.global_end(); I != E; ++I)
911 if (I->hasDLLExportLinkage()) {
912 std::string Name = Mang->getMangledName(I);
913 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
914 DLLExportedGlobals.push_back(Mang->getMangledName(I));
915 }
916
917 // Output linker support code for dllexported globals on windows.
918 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
919 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
920 true,
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000921 SectionKind::getMetadata()));
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000922 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
923 O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
924
925 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
926 O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";
927 }
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000928 }
929 }
930}
931
932
933//===----------------------------------------------------------------------===//
934// Target Registry Stuff
935//===----------------------------------------------------------------------===//
936
937static MCInstPrinter *createX86MCInstPrinter(const Target &T,
938 unsigned SyntaxVariant,
939 const MCAsmInfo &MAI,
940 raw_ostream &O) {
941 if (SyntaxVariant == 0)
942 return new X86ATTInstPrinter(O, MAI);
943 if (SyntaxVariant == 1)
944 return new X86IntelInstPrinter(O, MAI);
945 return 0;
946}
947
948// Force static initialization.
949extern "C" void LLVMInitializeX86AsmPrinter() {
950 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
951 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
952
953 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
954 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);
955}