blob: 9545f233a3a8b72675a105a02990eb7aa40fc6cc [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());
Chris Lattner551cdd52010-01-16 00:32:38 +000075 CurrentFnSym = OutContext.GetOrCreateSymbol(StringRef(CurrentFnName));
Chris Lattner0dc32ea2009-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 Lattner551cdd52010-01-16 00:32:38 +000088 O << "\t.globl\t";
89 CurrentFnSym->print(O, MAI);
90 O << '\n';
Chris Lattner0dc32ea2009-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 Lattner551cdd52010-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 Lattner0dc32ea2009-09-20 07:41:30 +0000104 } else if (Subtarget->isTargetCygMing()) {
Chris Lattner551cdd52010-01-16 00:32:38 +0000105 O << "\t.globl\t";
106 CurrentFnSym->print(O, MAI);
107 O << "\n\t.linkonce discard\n";
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000108 } else {
Chris Lattner551cdd52010-01-16 00:32:38 +0000109 O << "\t.weak\t";
110 CurrentFnSym->print(O, MAI);
111 O << '\n';
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000112 }
113 break;
114 }
115
Chris Lattner551cdd52010-01-16 00:32:38 +0000116 printVisibility(CurrentFnSym, F->getVisibility());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000117
Chris Lattner551cdd52010-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 Lattner0dc32ea2009-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 Lattner551cdd52010-01-16 00:32:38 +0000131 CurrentFnSym->print(O, MAI);
132 O << ':';
Chris Lattner0dc32ea2009-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 Lattner551cdd52010-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 Lattner0dc32ea2009-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 Gohmane3cc3f32009-10-06 17:38:38 +0000185 EmitBasicBlockStart(I);
Chris Lattner0dc32ea2009-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 Lattner551cdd52010-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 Lattner0dc32ea2009-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 Lattner48130352010-01-13 06:38:18 +0000226 SmallString<128> TempNameStr;
Chris Lattner0dc32ea2009-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
241 const char *Suffix = "";
242 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
243 Suffix = "$stub";
244 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)
247 Suffix = "$non_lazy_ptr";
248
249 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
250 if (Subtarget->isTargetCygMing()) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000251 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000252 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
253 COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
254 }
255
256 // Handle dllimport linkage.
257 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
258 Name = "__imp_" + Name;
259
260 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
261 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
Chris Lattner48130352010-01-13 06:38:18 +0000262 Mang->getNameWithPrefix(TempNameStr, GV, true);
263 TempNameStr += "$non_lazy_ptr";
264 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000265
266 const MCSymbol *&StubSym =
267 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(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 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
Chris Lattner48130352010-01-13 06:38:18 +0000274 Mang->getNameWithPrefix(TempNameStr, GV, true);
275 TempNameStr += "$non_lazy_ptr";
276 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000277 const MCSymbol *&StubSym =
278 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
279 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000280 TempNameStr.clear();
281 Mang->getNameWithPrefix(TempNameStr, GV, false);
282 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000283 }
284 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattner48130352010-01-13 06:38:18 +0000285 Mang->getNameWithPrefix(TempNameStr, GV, true);
286 TempNameStr += "$stub";
287 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000288 const MCSymbol *&StubSym =
289 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
290 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000291 TempNameStr.clear();
292 Mang->getNameWithPrefix(TempNameStr, GV, false);
293 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000294 }
295 }
296
297 // If the name begins with a dollar-sign, enclose it in parens. We do this
298 // to avoid having it look like an integer immediate to the assembler.
299 if (Name[0] == '$')
300 O << '(' << Name << ')';
301 else
302 O << Name;
303
304 printOffset(MO.getOffset());
305 break;
306 }
307 case MachineOperand::MO_ExternalSymbol: {
Chris Lattneree9250b2010-01-13 07:56:59 +0000308 const MCSymbol *SymToPrint;
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000309 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattneree9250b2010-01-13 07:56:59 +0000310 Mang->getNameWithPrefix(TempNameStr,
311 StringRef(MO.getSymbolName())+"$stub");
312 const MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000313 const MCSymbol *&StubSym =
314 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
315 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000316 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
317 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000318 }
Chris Lattneree9250b2010-01-13 07:56:59 +0000319 SymToPrint = StubSym;
320 } else {
321 Mang->getNameWithPrefix(TempNameStr, MO.getSymbolName());
322 SymToPrint = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000323 }
324
325 // If the name begins with a dollar-sign, enclose it in parens. We do this
326 // to avoid having it look like an integer immediate to the assembler.
Chris Lattneree9250b2010-01-13 07:56:59 +0000327 if (SymToPrint->getName()[0] != '$')
328 SymToPrint->print(O, MAI);
329 else {
330 O << '(';
331 SymToPrint->print(O, MAI);
332 O << '(';
333 }
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000334 break;
335 }
336 }
337
338 switch (MO.getTargetFlags()) {
339 default:
340 llvm_unreachable("Unknown target flag on GV operand");
341 case X86II::MO_NO_FLAG: // No flag.
342 break;
343 case X86II::MO_DARWIN_NONLAZY:
344 case X86II::MO_DLLIMPORT:
345 case X86II::MO_DARWIN_STUB:
346 // These affect the name of the symbol, not any suffix.
347 break;
348 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
349 O << " + [.-";
350 PrintPICBaseSymbol();
351 O << ']';
352 break;
353 case X86II::MO_PIC_BASE_OFFSET:
354 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
355 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
356 O << '-';
357 PrintPICBaseSymbol();
358 break;
359 case X86II::MO_TLSGD: O << "@TLSGD"; break;
360 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
361 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
362 case X86II::MO_TPOFF: O << "@TPOFF"; break;
363 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
364 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
365 case X86II::MO_GOT: O << "@GOT"; break;
366 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
367 case X86II::MO_PLT: O << "@PLT"; break;
368 }
369}
370
371/// print_pcrel_imm - This is used to print an immediate value that ends up
372/// being encoded as a pc-relative value. These print slightly differently, for
373/// example, a $ is not emitted.
374void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
375 const MachineOperand &MO = MI->getOperand(OpNo);
376 switch (MO.getType()) {
377 default: llvm_unreachable("Unknown pcrel immediate operand");
378 case MachineOperand::MO_Immediate:
379 O << MO.getImm();
380 return;
381 case MachineOperand::MO_MachineBasicBlock:
382 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
383 return;
384 case MachineOperand::MO_GlobalAddress:
385 case MachineOperand::MO_ExternalSymbol:
386 printSymbolOperand(MO);
387 return;
388 }
389}
390
391
392void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
393 const char *Modifier) {
394 const MachineOperand &MO = MI->getOperand(OpNo);
395 switch (MO.getType()) {
396 default: llvm_unreachable("unknown operand type!");
397 case MachineOperand::MO_Register: {
398 O << '%';
399 unsigned Reg = MO.getReg();
400 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
401 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
402 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
403 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
404 Reg = getX86SubSuperRegister(Reg, VT);
405 }
406 O << X86ATTInstPrinter::getRegisterName(Reg);
407 return;
408 }
409
410 case MachineOperand::MO_Immediate:
411 O << '$' << MO.getImm();
412 return;
413
414 case MachineOperand::MO_JumpTableIndex:
415 case MachineOperand::MO_ConstantPoolIndex:
416 case MachineOperand::MO_GlobalAddress:
417 case MachineOperand::MO_ExternalSymbol: {
418 O << '$';
419 printSymbolOperand(MO);
420 break;
421 }
422 }
423}
424
425void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
426 unsigned char value = MI->getOperand(Op).getImm();
427 assert(value <= 7 && "Invalid ssecc argument!");
428 switch (value) {
429 case 0: O << "eq"; break;
430 case 1: O << "lt"; break;
431 case 2: O << "le"; break;
432 case 3: O << "unord"; break;
433 case 4: O << "neq"; break;
434 case 5: O << "nlt"; break;
435 case 6: O << "nle"; break;
436 case 7: O << "ord"; break;
437 }
438}
439
440void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
441 const char *Modifier) {
442 const MachineOperand &BaseReg = MI->getOperand(Op);
443 const MachineOperand &IndexReg = MI->getOperand(Op+2);
444 const MachineOperand &DispSpec = MI->getOperand(Op+3);
445
446 // If we really don't want to print out (rip), don't.
447 bool HasBaseReg = BaseReg.getReg() != 0;
448 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
449 BaseReg.getReg() == X86::RIP)
450 HasBaseReg = false;
451
452 // HasParenPart - True if we will print out the () part of the mem ref.
453 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
454
455 if (DispSpec.isImm()) {
456 int DispVal = DispSpec.getImm();
457 if (DispVal || !HasParenPart)
458 O << DispVal;
459 } else {
460 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
461 DispSpec.isJTI() || DispSpec.isSymbol());
462 printSymbolOperand(MI->getOperand(Op+3));
463 }
464
465 if (HasParenPart) {
466 assert(IndexReg.getReg() != X86::ESP &&
467 "X86 doesn't allow scaling by ESP");
468
469 O << '(';
470 if (HasBaseReg)
471 printOperand(MI, Op, Modifier);
472
473 if (IndexReg.getReg()) {
474 O << ',';
475 printOperand(MI, Op+2, Modifier);
476 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
477 if (ScaleVal != 1)
478 O << ',' << ScaleVal;
479 }
480 O << ')';
481 }
482}
483
484void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
485 const char *Modifier) {
486 assert(isMem(MI, Op) && "Invalid memory reference!");
487 const MachineOperand &Segment = MI->getOperand(Op+4);
488 if (Segment.getReg()) {
489 printOperand(MI, Op+4, Modifier);
490 O << ':';
491 }
492 printLeaMemReference(MI, Op, Modifier);
493}
494
495void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
496 const MachineBasicBlock *MBB) const {
497 if (!MAI->getSetDirective())
498 return;
499
500 // We don't need .set machinery if we have GOT-style relocations
501 if (Subtarget->isPICStyleGOT())
502 return;
503
504 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
505 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
506
507 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
508
509 if (Subtarget->isPICStyleRIPRel())
510 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
511 << '_' << uid << '\n';
512 else {
513 O << '-';
514 PrintPICBaseSymbol();
515 O << '\n';
516 }
517}
518
519
520void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
521 PrintPICBaseSymbol();
522 O << '\n';
523 PrintPICBaseSymbol();
524 O << ':';
525}
526
527void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
528 const MachineBasicBlock *MBB,
529 unsigned uid) const {
530 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
531 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
532
533 O << JTEntryDirective << ' ';
534
535 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
536 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
537 << '_' << uid << "_set_" << MBB->getNumber();
538 } else if (Subtarget->isPICStyleGOT()) {
539 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
540 O << "@GOTOFF";
541 } else
542 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
543}
544
545bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
546 unsigned Reg = MO.getReg();
547 switch (Mode) {
548 default: return true; // Unknown mode.
549 case 'b': // Print QImode register
550 Reg = getX86SubSuperRegister(Reg, MVT::i8);
551 break;
552 case 'h': // Print QImode high register
553 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
554 break;
555 case 'w': // Print HImode register
556 Reg = getX86SubSuperRegister(Reg, MVT::i16);
557 break;
558 case 'k': // Print SImode register
559 Reg = getX86SubSuperRegister(Reg, MVT::i32);
560 break;
561 case 'q': // Print DImode register
562 Reg = getX86SubSuperRegister(Reg, MVT::i64);
563 break;
564 }
565
566 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
567 return false;
568}
569
570/// PrintAsmOperand - Print out an operand for an inline asm expression.
571///
572bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
573 unsigned AsmVariant,
574 const char *ExtraCode) {
575 // Does this asm operand have a single letter operand modifier?
576 if (ExtraCode && ExtraCode[0]) {
577 if (ExtraCode[1] != 0) return true; // Unknown modifier.
578
579 const MachineOperand &MO = MI->getOperand(OpNo);
580
581 switch (ExtraCode[0]) {
582 default: return true; // Unknown modifier.
583 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
584 if (MO.isImm()) {
585 O << MO.getImm();
586 return false;
587 }
588 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
589 printSymbolOperand(MO);
590 return false;
591 }
592 if (MO.isReg()) {
593 O << '(';
594 printOperand(MI, OpNo);
595 O << ')';
596 return false;
597 }
598 return true;
599
600 case 'c': // Don't print "$" before a global var name or constant.
601 if (MO.isImm())
602 O << MO.getImm();
603 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
604 printSymbolOperand(MO);
605 else
606 printOperand(MI, OpNo);
607 return false;
608
609 case 'A': // Print '*' before a register (it must be a register)
610 if (MO.isReg()) {
611 O << '*';
612 printOperand(MI, OpNo);
613 return false;
614 }
615 return true;
616
617 case 'b': // Print QImode register
618 case 'h': // Print QImode high register
619 case 'w': // Print HImode register
620 case 'k': // Print SImode register
621 case 'q': // Print DImode register
622 if (MO.isReg())
623 return printAsmMRegister(MO, ExtraCode[0]);
624 printOperand(MI, OpNo);
625 return false;
626
627 case 'P': // This is the operand of a call, treat specially.
628 print_pcrel_imm(MI, OpNo);
629 return false;
630
631 case 'n': // Negate the immediate or print a '-' before the operand.
632 // Note: this is a temporary solution. It should be handled target
633 // independently as part of the 'MC' work.
634 if (MO.isImm()) {
635 O << -MO.getImm();
636 return false;
637 }
638 O << '-';
639 }
640 }
641
642 printOperand(MI, OpNo);
643 return false;
644}
645
646bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
647 unsigned OpNo, unsigned AsmVariant,
648 const char *ExtraCode) {
649 if (ExtraCode && ExtraCode[0]) {
650 if (ExtraCode[1] != 0) return true; // Unknown modifier.
651
652 switch (ExtraCode[0]) {
653 default: return true; // Unknown modifier.
654 case 'b': // Print QImode register
655 case 'h': // Print QImode high register
656 case 'w': // Print HImode register
657 case 'k': // Print SImode register
658 case 'q': // Print SImode register
659 // These only apply to registers, ignore on mem.
660 break;
661 case 'P': // Don't print @PLT, but do print as memory.
662 printMemReference(MI, OpNo, "no-rip");
663 return false;
664 }
665 }
666 printMemReference(MI, OpNo);
667 return false;
668}
669
670
671
672/// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
673/// AT&T syntax to the current output stream.
674///
675void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
676 ++EmittedInsts;
677
Devang Patelaf0e2722009-10-06 02:19:11 +0000678 processDebugLoc(MI, true);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000679
680 printInstructionThroughMCStreamer(MI);
681
David Greene1924aab2009-11-13 21:34:57 +0000682 if (VerboseAsm)
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000683 EmitComments(*MI);
684 O << '\n';
Devang Patelaf0e2722009-10-06 02:19:11 +0000685
686 processDebugLoc(MI, false);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000687}
688
689void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
690 if (!GVar->hasInitializer())
691 return; // External global require no code
692
693 // Check to see if this is a special global used by LLVM, if so, emit it.
694 if (EmitSpecialLLVMGlobal(GVar)) {
695 if (Subtarget->isTargetDarwin() &&
696 TM.getRelocationModel() == Reloc::Static) {
697 if (GVar->getName() == "llvm.global_ctors")
698 O << ".reference .constructors_used\n";
699 else if (GVar->getName() == "llvm.global_dtors")
700 O << ".reference .destructors_used\n";
701 }
702 return;
703 }
704
705 const TargetData *TD = TM.getTargetData();
706
707 std::string name = Mang->getMangledName(GVar);
708 Constant *C = GVar->getInitializer();
709 const Type *Type = C->getType();
710 unsigned Size = TD->getTypeAllocSize(Type);
711 unsigned Align = TD->getPreferredAlignmentLog(GVar);
712
713 printVisibility(name, GVar->getVisibility());
714
715 if (Subtarget->isTargetELF())
716 O << "\t.type\t" << name << ",@object\n";
717
718
719 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
720 const MCSection *TheSection =
721 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
722 OutStreamer.SwitchSection(TheSection);
723
724 // FIXME: get this stuff from section kind flags.
725 if (C->isNullValue() && !GVar->hasSection() &&
726 // Don't put things that should go in the cstring section into "comm".
727 !TheSection->getKind().isMergeableCString()) {
728 if (GVar->hasExternalLinkage()) {
729 if (const char *Directive = MAI->getZeroFillDirective()) {
730 O << "\t.globl " << name << '\n';
731 O << Directive << "__DATA, __common, " << name << ", "
732 << Size << ", " << Align << '\n';
733 return;
734 }
735 }
736
737 if (!GVar->isThreadLocal() &&
738 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
739 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
740
741 if (MAI->getLCOMMDirective() != NULL) {
742 if (GVar->hasLocalLinkage()) {
743 O << MAI->getLCOMMDirective() << name << ',' << Size;
744 if (Subtarget->isTargetDarwin())
745 O << ',' << Align;
746 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
747 O << "\t.globl " << name << '\n'
748 << MAI->getWeakDefDirective() << name << '\n';
749 EmitAlignment(Align, GVar);
750 O << name << ":";
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 EmitGlobalConstant(C);
758 return;
759 } else {
760 O << MAI->getCOMMDirective() << name << ',' << Size;
761 if (MAI->getCOMMDirectiveTakesAlignment())
762 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
763 }
764 } else {
765 if (!Subtarget->isTargetCygMing()) {
766 if (GVar->hasLocalLinkage())
767 O << "\t.local\t" << name << '\n';
768 }
769 O << MAI->getCOMMDirective() << name << ',' << Size;
770 if (MAI->getCOMMDirectiveTakesAlignment())
771 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
772 }
773 if (VerboseAsm) {
774 O.PadToColumn(MAI->getCommentColumn());
775 O << MAI->getCommentString() << ' ';
776 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
777 }
778 O << '\n';
779 return;
780 }
781 }
782
783 switch (GVar->getLinkage()) {
784 case GlobalValue::CommonLinkage:
785 case GlobalValue::LinkOnceAnyLinkage:
786 case GlobalValue::LinkOnceODRLinkage:
787 case GlobalValue::WeakAnyLinkage:
788 case GlobalValue::WeakODRLinkage:
789 case GlobalValue::LinkerPrivateLinkage:
790 if (Subtarget->isTargetDarwin()) {
791 O << "\t.globl " << name << '\n'
792 << MAI->getWeakDefDirective() << name << '\n';
793 } else if (Subtarget->isTargetCygMing()) {
794 O << "\t.globl\t" << name << "\n"
795 "\t.linkonce same_size\n";
796 } else {
797 O << "\t.weak\t" << name << '\n';
798 }
799 break;
800 case GlobalValue::DLLExportLinkage:
801 case GlobalValue::AppendingLinkage:
802 // FIXME: appending linkage variables should go into a section of
803 // their name or something. For now, just emit them as external.
804 case GlobalValue::ExternalLinkage:
805 // If external or appending, declare as a global symbol
806 O << "\t.globl " << name << '\n';
807 // FALL THROUGH
808 case GlobalValue::PrivateLinkage:
809 case GlobalValue::InternalLinkage:
810 break;
811 default:
812 llvm_unreachable("Unknown linkage type!");
813 }
814
815 EmitAlignment(Align, GVar);
816 O << name << ":";
817 if (VerboseAsm){
818 O.PadToColumn(MAI->getCommentColumn());
819 O << MAI->getCommentString() << ' ';
820 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
821 }
822 O << '\n';
823
824 EmitGlobalConstant(C);
825
826 if (MAI->hasDotTypeDotSizeDirective())
827 O << "\t.size\t" << name << ", " << Size << '\n';
828}
829
830void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
831 if (Subtarget->isTargetDarwin()) {
832 // All darwin targets use mach-o.
833 TargetLoweringObjectFileMachO &TLOFMacho =
834 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
835
836 MachineModuleInfoMachO &MMIMacho =
837 MMI->getObjFileInfo<MachineModuleInfoMachO>();
838
839 // Output stubs for dynamically-linked functions.
840 MachineModuleInfoMachO::SymbolListTy Stubs;
841
842 Stubs = MMIMacho.GetFnStubList();
843 if (!Stubs.empty()) {
844 const MCSection *TheSection =
845 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
846 MCSectionMachO::S_SYMBOL_STUBS |
847 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
848 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
849 5, SectionKind::getMetadata());
850 OutStreamer.SwitchSection(TheSection);
851
852 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
853 Stubs[i].first->print(O, MAI);
854 O << ":\n" << "\t.indirect_symbol ";
855 // Get the MCSymbol without the $stub suffix.
856 Stubs[i].second->print(O, MAI);
857 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
858 }
859 O << '\n';
860
861 Stubs.clear();
862 }
863
864 // Output stubs for external and common global variables.
865 Stubs = MMIMacho.GetGVStubList();
866 if (!Stubs.empty()) {
867 const MCSection *TheSection =
868 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
869 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
870 SectionKind::getMetadata());
871 OutStreamer.SwitchSection(TheSection);
872
873 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
874 Stubs[i].first->print(O, MAI);
875 O << ":\n\t.indirect_symbol ";
876 Stubs[i].second->print(O, MAI);
877 O << "\n\t.long\t0\n";
878 }
879 Stubs.clear();
880 }
881
882 Stubs = MMIMacho.GetHiddenGVStubList();
883 if (!Stubs.empty()) {
884 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
885 EmitAlignment(2);
886
887 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
888 Stubs[i].first->print(O, MAI);
889 O << ":\n" << MAI->getData32bitsDirective();
890 Stubs[i].second->print(O, MAI);
891 O << '\n';
892 }
893 Stubs.clear();
894 }
895
896 // Funny Darwin hack: This flag tells the linker that no global symbols
897 // contain code that falls through to other global symbols (e.g. the obvious
898 // implementation of multiple entry points). If this doesn't occur, the
899 // linker can safely perform dead code stripping. Since LLVM never
900 // generates code that does this, it is always safe to set.
Chris Lattner74cd3b72009-10-19 18:03:08 +0000901 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000902 }
903
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000904 if (Subtarget->isTargetCOFF()) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000905 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000906 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000907
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000908 // Emit type information for external functions
909 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000910 E = COFFMMI.stub_end(); I != E; ++I) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000911 O << "\t.def\t " << I->getKeyData()
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000912 << ";\t.scl\t" << COFF::C_EXT
913 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
914 << ";\t.endef\n";
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000915 }
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000916
917 if (Subtarget->isTargetCygMing()) {
918 // Necessary for dllexport support
919 std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
920
921 TargetLoweringObjectFileCOFF &TLOFCOFF =
922 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
923
924 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
925 if (I->hasDLLExportLinkage()) {
926 std::string Name = Mang->getMangledName(I);
927 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
928 DLLExportedFns.push_back(Name);
929 }
930
931 for (Module::const_global_iterator I = M.global_begin(),
932 E = M.global_end(); I != E; ++I)
933 if (I->hasDLLExportLinkage()) {
934 std::string Name = Mang->getMangledName(I);
935 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
936 DLLExportedGlobals.push_back(Mang->getMangledName(I));
937 }
938
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 Lattner0dc32ea2009-09-20 07:41:30 +0000943 SectionKind::getMetadata()));
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000944 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
945 O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
946
947 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
948 O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";
949 }
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000950 }
951 }
952}
953
954
955//===----------------------------------------------------------------------===//
956// Target Registry Stuff
957//===----------------------------------------------------------------------===//
958
959static MCInstPrinter *createX86MCInstPrinter(const Target &T,
960 unsigned SyntaxVariant,
961 const MCAsmInfo &MAI,
962 raw_ostream &O) {
963 if (SyntaxVariant == 0)
964 return new X86ATTInstPrinter(O, MAI);
965 if (SyntaxVariant == 1)
966 return new X86IntelInstPrinter(O, MAI);
967 return 0;
968}
969
970// Force static initialization.
971extern "C" void LLVMInitializeX86AsmPrinter() {
972 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
973 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
974
975 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
976 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);
977}