blob: b0e6ed127d4be1c4d5d8d7e5ba8fc12809d111f9 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// 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'.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "asm-printer"
17#include "X86ATTAsmPrinter.h"
18#include "X86.h"
19#include "X86COFF.h"
20#include "X86MachineFunctionInfo.h"
21#include "X86TargetMachine.h"
22#include "X86TargetAsmInfo.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/CallingConv.h"
25#include "llvm/Module.h"
26#include "llvm/Support/Mangler.h"
27#include "llvm/Target/TargetAsmInfo.h"
28#include "llvm/Target/TargetOptions.h"
29#include "llvm/ADT/Statistic.h"
30using namespace llvm;
31
32STATISTIC(EmittedInsts, "Number of machine instrs printed");
33
34static std::string computePICLabel(unsigned FnNum,
35 const TargetAsmInfo *TAI,
36 const X86Subtarget* Subtarget) {
37 std::string label;
38 if (Subtarget->isTargetDarwin())
39 label = "\"L" + utostr_32(FnNum) + "$pb\"";
40 else if (Subtarget->isTargetELF())
41 label = ".Lllvm$" + utostr_32(FnNum) + "$piclabel";
42 else
43 assert(0 && "Don't know how to print PIC label!\n");
44
45 return label;
46}
47
48/// getSectionForFunction - Return the section that we should emit the
49/// specified function body into.
50std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
51 switch (F.getLinkage()) {
52 default: assert(0 && "Unknown linkage type!");
53 case Function::InternalLinkage:
54 case Function::DLLExportLinkage:
55 case Function::ExternalLinkage:
56 return TAI->getTextSection();
57 case Function::WeakLinkage:
58 case Function::LinkOnceLinkage:
59 if (Subtarget->isTargetDarwin()) {
60 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
61 } else if (Subtarget->isTargetCygMing()) {
62 return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"";
63 } else {
64 return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
65 ",\"ax\",@progbits";
66 }
67 }
68}
69
70/// runOnMachineFunction - This uses the printMachineInstruction()
71/// method to print assembly for each instruction.
72///
73bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
74 if (TAI->doesSupportDebugInformation()) {
75 // Let PassManager know we need debug information and relay
76 // the MachineModuleInfo address on to DwarfWriter.
77 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
78 }
79
80 SetupMachineFunction(MF);
81 O << "\n\n";
82
83 // Print out constants referenced by the function
84 EmitConstantPool(MF.getConstantPool());
85
86 // Print out labels for the function.
87 const Function *F = MF.getFunction();
88 unsigned CC = F->getCallingConv();
89
90 // Populate function information map. Actually, We don't want to populate
91 // non-stdcall or non-fastcall functions' information right now.
92 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
93 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
94
95 X86SharedAsmPrinter::decorateName(CurrentFnName, F);
96
97 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
98
99 switch (F->getLinkage()) {
100 default: assert(0 && "Unknown linkage type!");
101 case Function::InternalLinkage: // Symbols default to internal.
Evan Cheng27f41ab2007-07-25 23:36:05 +0000102 if (Subtarget->isTargetDarwin())
103 // FIXME: This should be parameterized somewhere.
104 EmitAlignment(4, F, 0, true, 0x90);
105 else
106 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 break;
108 case Function::DLLExportLinkage:
109 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
110 //FALLS THROUGH
111 case Function::ExternalLinkage:
Evan Cheng27f41ab2007-07-25 23:36:05 +0000112 if (Subtarget->isTargetDarwin())
113 // FIXME: This should be parameterized somewhere.
114 EmitAlignment(4, F, 0, true, 0x90);
115 else
116 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 O << "\t.globl\t" << CurrentFnName << "\n";
118 break;
119 case Function::LinkOnceLinkage:
120 case Function::WeakLinkage:
121 if (Subtarget->isTargetDarwin()) {
Evan Cheng27f41ab2007-07-25 23:36:05 +0000122 // FIXME: This should be parameterized somewhere.
123 EmitAlignment(4, F, 0, true, 0x90);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 O << "\t.globl\t" << CurrentFnName << "\n";
125 O << "\t.weak_definition\t" << CurrentFnName << "\n";
126 } else if (Subtarget->isTargetCygMing()) {
127 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
128 O << "\t.globl " << CurrentFnName << "\n";
129 O << "\t.linkonce discard\n";
130 } else {
131 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
Dan Gohman721e6582007-07-30 15:08:02 +0000132 O << "\t.weak\t" << CurrentFnName << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 }
134 break;
135 }
136 if (F->hasHiddenVisibility()) {
137 if (const char *Directive = TAI->getHiddenDirective())
138 O << Directive << CurrentFnName << "\n";
139 } else if (F->hasProtectedVisibility()) {
140 if (const char *Directive = TAI->getProtectedDirective())
141 O << Directive << CurrentFnName << "\n";
142 }
143
144 if (Subtarget->isTargetELF())
Dan Gohman721e6582007-07-30 15:08:02 +0000145 O << "\t.type\t" << CurrentFnName << ",@function\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 else if (Subtarget->isTargetCygMing()) {
147 O << "\t.def\t " << CurrentFnName
148 << ";\t.scl\t" <<
149 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
150 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
151 << ";\t.endef\n";
152 }
153
154 O << CurrentFnName << ":\n";
155 // Add some workaround for linkonce linkage on Cygwin\MinGW
156 if (Subtarget->isTargetCygMing() &&
157 (F->getLinkage() == Function::LinkOnceLinkage ||
158 F->getLinkage() == Function::WeakLinkage))
159 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
160
161 if (TAI->doesSupportDebugInformation()) {
162 // Emit pre-function debug information.
163 DW.BeginFunction(&MF);
164 }
165
166 // Print out code for the function.
167 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
168 I != E; ++I) {
169 // Print a label for the basic block.
170 if (I->pred_begin() != I->pred_end()) {
171 printBasicBlockLabel(I, true);
172 O << '\n';
173 }
174 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
175 II != E; ++II) {
176 // Print the assembly for the instruction.
177 O << "\t";
178 printMachineInstruction(II);
179 }
180 }
181
182 if (TAI->hasDotTypeDotSizeDirective())
Dan Gohmandd1aa3a2007-08-01 14:42:30 +0000183 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184
185 if (TAI->doesSupportDebugInformation()) {
186 // Emit post-function debug information.
187 DW.EndFunction();
188 }
189
190 // Print out jump tables referenced by the function.
191 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
192
193 // We didn't modify anything.
194 return false;
195}
196
197static inline bool printGOT(TargetMachine &TM, const X86Subtarget* ST) {
198 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
199}
200
201static inline bool printStub(TargetMachine &TM, const X86Subtarget* ST) {
202 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
203}
204
205void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
206 const char *Modifier, bool NotRIPRel) {
207 const MachineOperand &MO = MI->getOperand(OpNo);
208 const MRegisterInfo &RI = *TM.getRegisterInfo();
209 switch (MO.getType()) {
210 case MachineOperand::MO_Register: {
211 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
212 "Virtual registers should not make it this far!");
213 O << '%';
214 unsigned Reg = MO.getReg();
215 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
216 MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
217 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
218 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
219 Reg = getX86SubSuperRegister(Reg, VT);
220 }
221 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
222 O << (char)tolower(*Name);
223 return;
224 }
225
226 case MachineOperand::MO_Immediate:
227 if (!Modifier ||
228 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
229 O << '$';
230 O << MO.getImmedValue();
231 return;
232 case MachineOperand::MO_MachineBasicBlock:
233 printBasicBlockLabel(MO.getMachineBasicBlock());
234 return;
235 case MachineOperand::MO_JumpTableIndex: {
236 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
237 if (!isMemOp) O << '$';
238 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
239 << MO.getJumpTableIndex();
240
241 if (TM.getRelocationModel() == Reloc::PIC_) {
242 if (Subtarget->isPICStyleStub())
243 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
244 << "$pb\"";
245 else if (Subtarget->isPICStyleGOT())
246 O << "@GOTOFF";
247 }
248
249 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
250 O << "(%rip)";
251 return;
252 }
253 case MachineOperand::MO_ConstantPoolIndex: {
254 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
255 if (!isMemOp) O << '$';
256 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
257 << MO.getConstantPoolIndex();
258
259 if (TM.getRelocationModel() == Reloc::PIC_) {
260 if (Subtarget->isPICStyleStub())
261 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
262 << "$pb\"";
263 else if (Subtarget->isPICStyleGOT())
264 O << "@GOTOFF";
265 }
266
267 int Offset = MO.getOffset();
268 if (Offset > 0)
269 O << "+" << Offset;
270 else if (Offset < 0)
271 O << Offset;
272
273 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
274 O << "(%rip)";
275 return;
276 }
277 case MachineOperand::MO_GlobalAddress: {
278 bool isCallOp = Modifier && !strcmp(Modifier, "call");
279 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
280 bool needCloseParen = false;
281
282 GlobalValue *GV = MO.getGlobal();
283 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
284 bool isThreadLocal = GVar && GVar->isThreadLocal();
285
286 std::string Name = Mang->getValueName(GV);
287 X86SharedAsmPrinter::decorateName(Name, GV);
288
289 if (!isMemOp && !isCallOp)
290 O << '$';
291 else if (Name[0] == '$') {
292 // The name begins with a dollar-sign. In order to avoid having it look
293 // like an integer immediate to the assembler, enclose it in parens.
294 O << '(';
295 needCloseParen = true;
296 }
297
298 if (printStub(TM, Subtarget)) {
299 // Link-once, declaration, or Weakly-linked global variables need
300 // non-lazily-resolved stubs
301 if (GV->isDeclaration() ||
302 GV->hasWeakLinkage() ||
303 GV->hasLinkOnceLinkage()) {
304 // Dynamically-resolved functions need a stub for the function.
305 if (isCallOp && isa<Function>(GV)) {
306 FnStubs.insert(Name);
307 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
308 } else {
309 GVStubs.insert(Name);
310 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
311 }
312 } else {
313 if (GV->hasDLLImportLinkage())
314 O << "__imp_";
315 O << Name;
316 }
317
318 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
319 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
320 << "$pb\"";
321 } else {
322 if (GV->hasDLLImportLinkage()) {
323 O << "__imp_";
324 }
325 O << Name;
326
327 if (isCallOp && isa<Function>(GV)) {
328 if (printGOT(TM, Subtarget)) {
329 // Assemble call via PLT for non-local symbols
330 if (!(GV->hasHiddenVisibility() || GV->hasProtectedVisibility()) ||
331 GV->isDeclaration())
332 O << "@PLT";
333 }
334 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
335 // Save function name for later type emission
336 FnStubs.insert(Name);
337 }
338 }
339
340 if (GV->hasExternalWeakLinkage())
341 ExtWeakSymbols.insert(GV);
342
343 int Offset = MO.getOffset();
344 if (Offset > 0)
345 O << "+" << Offset;
346 else if (Offset < 0)
347 O << Offset;
348
349 if (isThreadLocal) {
350 if (TM.getRelocationModel() == Reloc::PIC_)
351 O << "@TLSGD"; // general dynamic TLS model
352 else
353 if (GV->isDeclaration())
354 O << "@INDNTPOFF"; // initial exec TLS model
355 else
356 O << "@NTPOFF"; // local exec TLS model
357 } else if (isMemOp) {
358 if (printGOT(TM, Subtarget)) {
359 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
360 O << "@GOT";
361 else
362 O << "@GOTOFF";
363 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
364 if ((GV->isDeclaration() ||
365 GV->hasWeakLinkage() ||
366 GV->hasLinkOnceLinkage()) &&
367 TM.getRelocationModel() != Reloc::Static)
368 O << "@GOTPCREL";
369
370 if (needCloseParen) {
371 needCloseParen = false;
372 O << ')';
373 }
374
375 // Use rip when possible to reduce code size, except when
376 // index or base register are also part of the address. e.g.
377 // foo(%rip)(%rcx,%rax,4) is not legal
378 O << "(%rip)";
379 }
380 }
381
382 if (needCloseParen)
383 O << ')';
384
385 return;
386 }
387 case MachineOperand::MO_ExternalSymbol: {
388 bool isCallOp = Modifier && !strcmp(Modifier, "call");
389 bool needCloseParen = false;
390 std::string Name(TAI->getGlobalPrefix());
391 Name += MO.getSymbolName();
392 if (isCallOp && printStub(TM, Subtarget)) {
393 FnStubs.insert(Name);
394 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
395 return;
396 }
397 if (!isCallOp)
398 O << '$';
399 else if (Name[0] == '$') {
400 // The name begins with a dollar-sign. In order to avoid having it look
401 // like an integer immediate to the assembler, enclose it in parens.
402 O << '(';
403 needCloseParen = true;
404 }
405
406 O << Name;
407
408 if (printGOT(TM, Subtarget)) {
409 std::string GOTName(TAI->getGlobalPrefix());
410 GOTName+="_GLOBAL_OFFSET_TABLE_";
411 if (Name == GOTName)
412 // HACK! Emit extra offset to PC during printing GOT offset to
413 // compensate for the size of popl instruction. The resulting code
414 // should look like:
415 // call .piclabel
416 // piclabel:
417 // popl %some_register
418 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
419 O << " + [.-"
420 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
421
422 if (isCallOp)
423 O << "@PLT";
424 }
425
426 if (needCloseParen)
427 O << ')';
428
429 if (!isCallOp && Subtarget->isPICStyleRIPRel())
430 O << "(%rip)";
431
432 return;
433 }
434 default:
435 O << "<unknown operand type>"; return;
436 }
437}
438
439void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
440 unsigned char value = MI->getOperand(Op).getImmedValue();
441 assert(value <= 7 && "Invalid ssecc argument!");
442 switch (value) {
443 case 0: O << "eq"; break;
444 case 1: O << "lt"; break;
445 case 2: O << "le"; break;
446 case 3: O << "unord"; break;
447 case 4: O << "neq"; break;
448 case 5: O << "nlt"; break;
449 case 6: O << "nle"; break;
450 case 7: O << "ord"; break;
451 }
452}
453
454void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
455 const char *Modifier){
456 assert(isMem(MI, Op) && "Invalid memory reference!");
457 MachineOperand BaseReg = MI->getOperand(Op);
458 MachineOperand IndexReg = MI->getOperand(Op+2);
459 const MachineOperand &DispSpec = MI->getOperand(Op+3);
460
461 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
462 if (DispSpec.isGlobalAddress() ||
463 DispSpec.isConstantPoolIndex() ||
464 DispSpec.isJumpTableIndex()) {
465 printOperand(MI, Op+3, "mem", NotRIPRel);
466 } else {
467 int DispVal = DispSpec.getImmedValue();
468 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
469 O << DispVal;
470 }
471
472 if (IndexReg.getReg() || BaseReg.getReg()) {
473 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
474 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
475
476 // There are cases where we can end up with ESP/RSP in the indexreg slot.
477 // If this happens, swap the base/index register to support assemblers that
478 // don't work when the index is *SP.
479 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
480 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
481 std::swap(BaseReg, IndexReg);
482 std::swap(BaseRegOperand, IndexRegOperand);
483 }
484
485 O << "(";
486 if (BaseReg.getReg())
487 printOperand(MI, Op+BaseRegOperand, Modifier);
488
489 if (IndexReg.getReg()) {
490 O << ",";
491 printOperand(MI, Op+IndexRegOperand, Modifier);
492 if (ScaleVal != 1)
493 O << "," << ScaleVal;
494 }
495 O << ")";
496 }
497}
498
499void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
500 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
501 O << label << "\n" << label << ":";
502}
503
504
505bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
506 const char Mode) {
507 const MRegisterInfo &RI = *TM.getRegisterInfo();
508 unsigned Reg = MO.getReg();
509 switch (Mode) {
510 default: return true; // Unknown mode.
511 case 'b': // Print QImode register
512 Reg = getX86SubSuperRegister(Reg, MVT::i8);
513 break;
514 case 'h': // Print QImode high register
515 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
516 break;
517 case 'w': // Print HImode register
518 Reg = getX86SubSuperRegister(Reg, MVT::i16);
519 break;
520 case 'k': // Print SImode register
521 Reg = getX86SubSuperRegister(Reg, MVT::i32);
522 break;
523 }
524
525 O << '%';
526 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
527 O << (char)tolower(*Name);
528 return false;
529}
530
531/// PrintAsmOperand - Print out an operand for an inline asm expression.
532///
533bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
534 unsigned AsmVariant,
535 const char *ExtraCode) {
536 // Does this asm operand have a single letter operand modifier?
537 if (ExtraCode && ExtraCode[0]) {
538 if (ExtraCode[1] != 0) return true; // Unknown modifier.
539
540 switch (ExtraCode[0]) {
541 default: return true; // Unknown modifier.
542 case 'c': // Don't print "$" before a global var name or constant.
543 printOperand(MI, OpNo, "mem");
544 return false;
545 case 'b': // Print QImode register
546 case 'h': // Print QImode high register
547 case 'w': // Print HImode register
548 case 'k': // Print SImode register
549 if (MI->getOperand(OpNo).isReg())
550 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
551 printOperand(MI, OpNo);
552 return false;
553
554 case 'P': // Don't print @PLT, but do print as memory.
555 printOperand(MI, OpNo, "mem");
556 return false;
557 }
558 }
559
560 printOperand(MI, OpNo);
561 return false;
562}
563
564bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
565 unsigned OpNo,
566 unsigned AsmVariant,
567 const char *ExtraCode) {
568 if (ExtraCode && ExtraCode[0])
569 return true; // Unknown modifier.
570 printMemReference(MI, OpNo);
571 return false;
572}
573
574/// printMachineInstruction -- Print out a single X86 LLVM instruction
575/// MI in AT&T syntax to the current output stream.
576///
577void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
578 ++EmittedInsts;
579
580 // See if a truncate instruction can be turned into a nop.
581 switch (MI->getOpcode()) {
582 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 case X86::PsMOVZX64rr32:
584 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
585 break;
586 }
587
588 // Call the autogenerated instruction printer routines.
589 printInstruction(MI);
590}
591
592// Include the auto-generated portion of the assembly writer.
593#include "X86GenAsmWriter.inc"
594