blob: 153a6344a0ebe1d1f19196e62a8751694b6a06e1 [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.
168 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
169 // This is an entry block or a block that's only reachable via a
170 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
171 } else {
172 EmitBasicBlockStart(I);
173 O << '\n';
174 }
175 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
176 II != IE; ++II) {
177 // Print the assembly for the instruction.
178 if (!II->isLabel())
179 hasAnyRealCode = true;
180 printMachineInstruction(II);
181 }
182 }
183
184 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
185 // If the function is empty, then we need to emit *something*. Otherwise,
186 // the function's label might be associated with something that it wasn't
187 // meant to be associated with. We emit a noop in this situation.
188 // We are assuming inline asms are code.
189 O << "\tnop\n";
190 }
191
192 if (MAI->hasDotTypeDotSizeDirective())
193 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
194
195 // Emit post-function debug information.
196 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
197 DW->EndFunction(&MF);
198
199 // Print out jump tables referenced by the function.
200 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
201
202 // We didn't modify anything.
203 return false;
204}
205
206/// printSymbolOperand - Print a raw symbol reference operand. This handles
207/// jump tables, constant pools, global address and external symbols, all of
208/// which print to a label with various suffixes for relocation types etc.
209void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
210 switch (MO.getType()) {
211 default: llvm_unreachable("unknown symbol type!");
212 case MachineOperand::MO_JumpTableIndex:
213 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
214 << MO.getIndex();
215 break;
216 case MachineOperand::MO_ConstantPoolIndex:
217 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
218 << MO.getIndex();
219 printOffset(MO.getOffset());
220 break;
221 case MachineOperand::MO_GlobalAddress: {
222 const GlobalValue *GV = MO.getGlobal();
223
224 const char *Suffix = "";
225 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
226 Suffix = "$stub";
227 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
228 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
229 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
230 Suffix = "$non_lazy_ptr";
231
232 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
233 if (Subtarget->isTargetCygMing()) {
234 X86COFFMachineModuleInfo &COFFMMI =
235 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
236 COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
237 }
238
239 // Handle dllimport linkage.
240 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
241 Name = "__imp_" + Name;
242
243 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
244 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
245 SmallString<128> NameStr;
246 Mang->getNameWithPrefix(NameStr, GV, true);
247 NameStr += "$non_lazy_ptr";
248 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
249
250 const MCSymbol *&StubSym =
251 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
252 if (StubSym == 0) {
253 NameStr.clear();
254 Mang->getNameWithPrefix(NameStr, GV, false);
255 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
256 }
257 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
258 SmallString<128> NameStr;
259 Mang->getNameWithPrefix(NameStr, GV, true);
260 NameStr += "$non_lazy_ptr";
261 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
262 const MCSymbol *&StubSym =
263 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
264 if (StubSym == 0) {
265 NameStr.clear();
266 Mang->getNameWithPrefix(NameStr, GV, false);
267 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
268 }
269 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
270 SmallString<128> NameStr;
271 Mang->getNameWithPrefix(NameStr, GV, true);
272 NameStr += "$stub";
273 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
274 const MCSymbol *&StubSym =
275 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
276 if (StubSym == 0) {
277 NameStr.clear();
278 Mang->getNameWithPrefix(NameStr, GV, false);
279 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
280 }
281 }
282
283 // If the name begins with a dollar-sign, enclose it in parens. We do this
284 // to avoid having it look like an integer immediate to the assembler.
285 if (Name[0] == '$')
286 O << '(' << Name << ')';
287 else
288 O << Name;
289
290 printOffset(MO.getOffset());
291 break;
292 }
293 case MachineOperand::MO_ExternalSymbol: {
294 std::string Name = Mang->makeNameProper(MO.getSymbolName());
295 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
296 Name += "$stub";
297 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
298 const MCSymbol *&StubSym =
299 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
300 if (StubSym == 0) {
301 Name.erase(Name.end()-5, Name.end());
302 StubSym = OutContext.GetOrCreateSymbol(Name);
303 }
304 }
305
306 // If the name begins with a dollar-sign, enclose it in parens. We do this
307 // to avoid having it look like an integer immediate to the assembler.
308 if (Name[0] == '$')
309 O << '(' << Name << ')';
310 else
311 O << Name;
312 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
656 processDebugLoc(MI->getDebugLoc());
657
658 printInstructionThroughMCStreamer(MI);
659
660 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
661 EmitComments(*MI);
662 O << '\n';
663}
664
665void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
666 if (!GVar->hasInitializer())
667 return; // External global require no code
668
669 // Check to see if this is a special global used by LLVM, if so, emit it.
670 if (EmitSpecialLLVMGlobal(GVar)) {
671 if (Subtarget->isTargetDarwin() &&
672 TM.getRelocationModel() == Reloc::Static) {
673 if (GVar->getName() == "llvm.global_ctors")
674 O << ".reference .constructors_used\n";
675 else if (GVar->getName() == "llvm.global_dtors")
676 O << ".reference .destructors_used\n";
677 }
678 return;
679 }
680
681 const TargetData *TD = TM.getTargetData();
682
683 std::string name = Mang->getMangledName(GVar);
684 Constant *C = GVar->getInitializer();
685 const Type *Type = C->getType();
686 unsigned Size = TD->getTypeAllocSize(Type);
687 unsigned Align = TD->getPreferredAlignmentLog(GVar);
688
689 printVisibility(name, GVar->getVisibility());
690
691 if (Subtarget->isTargetELF())
692 O << "\t.type\t" << name << ",@object\n";
693
694
695 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
696 const MCSection *TheSection =
697 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
698 OutStreamer.SwitchSection(TheSection);
699
700 // FIXME: get this stuff from section kind flags.
701 if (C->isNullValue() && !GVar->hasSection() &&
702 // Don't put things that should go in the cstring section into "comm".
703 !TheSection->getKind().isMergeableCString()) {
704 if (GVar->hasExternalLinkage()) {
705 if (const char *Directive = MAI->getZeroFillDirective()) {
706 O << "\t.globl " << name << '\n';
707 O << Directive << "__DATA, __common, " << name << ", "
708 << Size << ", " << Align << '\n';
709 return;
710 }
711 }
712
713 if (!GVar->isThreadLocal() &&
714 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
715 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
716
717 if (MAI->getLCOMMDirective() != NULL) {
718 if (GVar->hasLocalLinkage()) {
719 O << MAI->getLCOMMDirective() << name << ',' << Size;
720 if (Subtarget->isTargetDarwin())
721 O << ',' << Align;
722 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
723 O << "\t.globl " << name << '\n'
724 << MAI->getWeakDefDirective() << name << '\n';
725 EmitAlignment(Align, GVar);
726 O << name << ":";
727 if (VerboseAsm) {
728 O.PadToColumn(MAI->getCommentColumn());
729 O << MAI->getCommentString() << ' ';
730 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
731 }
732 O << '\n';
733 EmitGlobalConstant(C);
734 return;
735 } else {
736 O << MAI->getCOMMDirective() << name << ',' << Size;
737 if (MAI->getCOMMDirectiveTakesAlignment())
738 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
739 }
740 } else {
741 if (!Subtarget->isTargetCygMing()) {
742 if (GVar->hasLocalLinkage())
743 O << "\t.local\t" << name << '\n';
744 }
745 O << MAI->getCOMMDirective() << name << ',' << Size;
746 if (MAI->getCOMMDirectiveTakesAlignment())
747 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
748 }
749 if (VerboseAsm) {
750 O.PadToColumn(MAI->getCommentColumn());
751 O << MAI->getCommentString() << ' ';
752 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
753 }
754 O << '\n';
755 return;
756 }
757 }
758
759 switch (GVar->getLinkage()) {
760 case GlobalValue::CommonLinkage:
761 case GlobalValue::LinkOnceAnyLinkage:
762 case GlobalValue::LinkOnceODRLinkage:
763 case GlobalValue::WeakAnyLinkage:
764 case GlobalValue::WeakODRLinkage:
765 case GlobalValue::LinkerPrivateLinkage:
766 if (Subtarget->isTargetDarwin()) {
767 O << "\t.globl " << name << '\n'
768 << MAI->getWeakDefDirective() << name << '\n';
769 } else if (Subtarget->isTargetCygMing()) {
770 O << "\t.globl\t" << name << "\n"
771 "\t.linkonce same_size\n";
772 } else {
773 O << "\t.weak\t" << name << '\n';
774 }
775 break;
776 case GlobalValue::DLLExportLinkage:
777 case GlobalValue::AppendingLinkage:
778 // FIXME: appending linkage variables should go into a section of
779 // their name or something. For now, just emit them as external.
780 case GlobalValue::ExternalLinkage:
781 // If external or appending, declare as a global symbol
782 O << "\t.globl " << name << '\n';
783 // FALL THROUGH
784 case GlobalValue::PrivateLinkage:
785 case GlobalValue::InternalLinkage:
786 break;
787 default:
788 llvm_unreachable("Unknown linkage type!");
789 }
790
791 EmitAlignment(Align, GVar);
792 O << name << ":";
793 if (VerboseAsm){
794 O.PadToColumn(MAI->getCommentColumn());
795 O << MAI->getCommentString() << ' ';
796 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
797 }
798 O << '\n';
799
800 EmitGlobalConstant(C);
801
802 if (MAI->hasDotTypeDotSizeDirective())
803 O << "\t.size\t" << name << ", " << Size << '\n';
804}
805
806void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
807 if (Subtarget->isTargetDarwin()) {
808 // All darwin targets use mach-o.
809 TargetLoweringObjectFileMachO &TLOFMacho =
810 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
811
812 MachineModuleInfoMachO &MMIMacho =
813 MMI->getObjFileInfo<MachineModuleInfoMachO>();
814
815 // Output stubs for dynamically-linked functions.
816 MachineModuleInfoMachO::SymbolListTy Stubs;
817
818 Stubs = MMIMacho.GetFnStubList();
819 if (!Stubs.empty()) {
820 const MCSection *TheSection =
821 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
822 MCSectionMachO::S_SYMBOL_STUBS |
823 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
824 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
825 5, SectionKind::getMetadata());
826 OutStreamer.SwitchSection(TheSection);
827
828 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
829 Stubs[i].first->print(O, MAI);
830 O << ":\n" << "\t.indirect_symbol ";
831 // Get the MCSymbol without the $stub suffix.
832 Stubs[i].second->print(O, MAI);
833 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
834 }
835 O << '\n';
836
837 Stubs.clear();
838 }
839
840 // Output stubs for external and common global variables.
841 Stubs = MMIMacho.GetGVStubList();
842 if (!Stubs.empty()) {
843 const MCSection *TheSection =
844 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
845 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
846 SectionKind::getMetadata());
847 OutStreamer.SwitchSection(TheSection);
848
849 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
850 Stubs[i].first->print(O, MAI);
851 O << ":\n\t.indirect_symbol ";
852 Stubs[i].second->print(O, MAI);
853 O << "\n\t.long\t0\n";
854 }
855 Stubs.clear();
856 }
857
858 Stubs = MMIMacho.GetHiddenGVStubList();
859 if (!Stubs.empty()) {
860 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
861 EmitAlignment(2);
862
863 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
864 Stubs[i].first->print(O, MAI);
865 O << ":\n" << MAI->getData32bitsDirective();
866 Stubs[i].second->print(O, MAI);
867 O << '\n';
868 }
869 Stubs.clear();
870 }
871
872 // Funny Darwin hack: This flag tells the linker that no global symbols
873 // contain code that falls through to other global symbols (e.g. the obvious
874 // implementation of multiple entry points). If this doesn't occur, the
875 // linker can safely perform dead code stripping. Since LLVM never
876 // generates code that does this, it is always safe to set.
877 O << "\t.subsections_via_symbols\n";
878 }
879
880 if (Subtarget->isTargetCOFF()) {
881 // Necessary for dllexport support
882 std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
883
884 X86COFFMachineModuleInfo &COFFMMI =
885 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
886 TargetLoweringObjectFileCOFF &TLOFCOFF =
887 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
888
889 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
890 if (I->hasDLLExportLinkage())
891 DLLExportedFns.push_back(Mang->getMangledName(I));
892
893 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
894 I != E; ++I)
895 if (I->hasDLLExportLinkage())
896 DLLExportedGlobals.push_back(Mang->getMangledName(I));
897
898 if (Subtarget->isTargetCygMing()) {
899 // Emit type information for external functions
900 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
901 E = COFFMMI.stub_end(); I != E; ++I) {
902 O << "\t.def\t " << I->getKeyData()
903 << ";\t.scl\t" << COFF::C_EXT
904 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
905 << ";\t.endef\n";
906 }
907 }
908
909 // Output linker support code for dllexported globals on windows.
910 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
911 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
912 true,
913 SectionKind::getMetadata()));
914
915 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
916 O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
917
918 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
919 O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";
920 }
921 }
922}
923
924
925//===----------------------------------------------------------------------===//
926// Target Registry Stuff
927//===----------------------------------------------------------------------===//
928
929static MCInstPrinter *createX86MCInstPrinter(const Target &T,
930 unsigned SyntaxVariant,
931 const MCAsmInfo &MAI,
932 raw_ostream &O) {
933 if (SyntaxVariant == 0)
934 return new X86ATTInstPrinter(O, MAI);
935 if (SyntaxVariant == 1)
936 return new X86IntelInstPrinter(O, MAI);
937 return 0;
938}
939
940// Force static initialization.
941extern "C" void LLVMInitializeX86AsmPrinter() {
942 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
943 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
944
945 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
946 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);
947}