blob: 07670ea62beaaba321bf1276bbdc4491a42f65bf [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.
102 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
103 break;
104 case Function::DLLExportLinkage:
105 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
106 //FALLS THROUGH
107 case Function::ExternalLinkage:
108 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
109 O << "\t.globl\t" << CurrentFnName << "\n";
110 break;
111 case Function::LinkOnceLinkage:
112 case Function::WeakLinkage:
113 if (Subtarget->isTargetDarwin()) {
Evan Cheng1baa62e2007-07-25 22:28:16 +0000114 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 O << "\t.globl\t" << CurrentFnName << "\n";
116 O << "\t.weak_definition\t" << CurrentFnName << "\n";
117 } else if (Subtarget->isTargetCygMing()) {
118 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
119 O << "\t.globl " << CurrentFnName << "\n";
120 O << "\t.linkonce discard\n";
121 } else {
122 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
123 O << "\t.weak " << CurrentFnName << "\n";
124 }
125 break;
126 }
127 if (F->hasHiddenVisibility()) {
128 if (const char *Directive = TAI->getHiddenDirective())
129 O << Directive << CurrentFnName << "\n";
130 } else if (F->hasProtectedVisibility()) {
131 if (const char *Directive = TAI->getProtectedDirective())
132 O << Directive << CurrentFnName << "\n";
133 }
134
135 if (Subtarget->isTargetELF())
136 O << "\t.type " << CurrentFnName << ",@function\n";
137 else if (Subtarget->isTargetCygMing()) {
138 O << "\t.def\t " << CurrentFnName
139 << ";\t.scl\t" <<
140 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
141 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
142 << ";\t.endef\n";
143 }
144
145 O << CurrentFnName << ":\n";
146 // Add some workaround for linkonce linkage on Cygwin\MinGW
147 if (Subtarget->isTargetCygMing() &&
148 (F->getLinkage() == Function::LinkOnceLinkage ||
149 F->getLinkage() == Function::WeakLinkage))
150 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
151
152 if (TAI->doesSupportDebugInformation()) {
153 // Emit pre-function debug information.
154 DW.BeginFunction(&MF);
155 }
156
157 // Print out code for the function.
158 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
159 I != E; ++I) {
160 // Print a label for the basic block.
161 if (I->pred_begin() != I->pred_end()) {
162 printBasicBlockLabel(I, true);
163 O << '\n';
164 }
165 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
166 II != E; ++II) {
167 // Print the assembly for the instruction.
168 O << "\t";
169 printMachineInstruction(II);
170 }
171 }
172
173 if (TAI->hasDotTypeDotSizeDirective())
174 O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
175
176 if (TAI->doesSupportDebugInformation()) {
177 // Emit post-function debug information.
178 DW.EndFunction();
179 }
180
181 // Print out jump tables referenced by the function.
182 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
183
184 // We didn't modify anything.
185 return false;
186}
187
188static inline bool printGOT(TargetMachine &TM, const X86Subtarget* ST) {
189 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
190}
191
192static inline bool printStub(TargetMachine &TM, const X86Subtarget* ST) {
193 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
194}
195
196void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
197 const char *Modifier, bool NotRIPRel) {
198 const MachineOperand &MO = MI->getOperand(OpNo);
199 const MRegisterInfo &RI = *TM.getRegisterInfo();
200 switch (MO.getType()) {
201 case MachineOperand::MO_Register: {
202 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
203 "Virtual registers should not make it this far!");
204 O << '%';
205 unsigned Reg = MO.getReg();
206 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
207 MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
208 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
209 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
210 Reg = getX86SubSuperRegister(Reg, VT);
211 }
212 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
213 O << (char)tolower(*Name);
214 return;
215 }
216
217 case MachineOperand::MO_Immediate:
218 if (!Modifier ||
219 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
220 O << '$';
221 O << MO.getImmedValue();
222 return;
223 case MachineOperand::MO_MachineBasicBlock:
224 printBasicBlockLabel(MO.getMachineBasicBlock());
225 return;
226 case MachineOperand::MO_JumpTableIndex: {
227 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
228 if (!isMemOp) O << '$';
229 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
230 << MO.getJumpTableIndex();
231
232 if (TM.getRelocationModel() == Reloc::PIC_) {
233 if (Subtarget->isPICStyleStub())
234 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
235 << "$pb\"";
236 else if (Subtarget->isPICStyleGOT())
237 O << "@GOTOFF";
238 }
239
240 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
241 O << "(%rip)";
242 return;
243 }
244 case MachineOperand::MO_ConstantPoolIndex: {
245 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
246 if (!isMemOp) O << '$';
247 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
248 << MO.getConstantPoolIndex();
249
250 if (TM.getRelocationModel() == Reloc::PIC_) {
251 if (Subtarget->isPICStyleStub())
252 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
253 << "$pb\"";
254 else if (Subtarget->isPICStyleGOT())
255 O << "@GOTOFF";
256 }
257
258 int Offset = MO.getOffset();
259 if (Offset > 0)
260 O << "+" << Offset;
261 else if (Offset < 0)
262 O << Offset;
263
264 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
265 O << "(%rip)";
266 return;
267 }
268 case MachineOperand::MO_GlobalAddress: {
269 bool isCallOp = Modifier && !strcmp(Modifier, "call");
270 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
271 bool needCloseParen = false;
272
273 GlobalValue *GV = MO.getGlobal();
274 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
275 bool isThreadLocal = GVar && GVar->isThreadLocal();
276
277 std::string Name = Mang->getValueName(GV);
278 X86SharedAsmPrinter::decorateName(Name, GV);
279
280 if (!isMemOp && !isCallOp)
281 O << '$';
282 else if (Name[0] == '$') {
283 // The name begins with a dollar-sign. In order to avoid having it look
284 // like an integer immediate to the assembler, enclose it in parens.
285 O << '(';
286 needCloseParen = true;
287 }
288
289 if (printStub(TM, Subtarget)) {
290 // Link-once, declaration, or Weakly-linked global variables need
291 // non-lazily-resolved stubs
292 if (GV->isDeclaration() ||
293 GV->hasWeakLinkage() ||
294 GV->hasLinkOnceLinkage()) {
295 // Dynamically-resolved functions need a stub for the function.
296 if (isCallOp && isa<Function>(GV)) {
297 FnStubs.insert(Name);
298 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
299 } else {
300 GVStubs.insert(Name);
301 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
302 }
303 } else {
304 if (GV->hasDLLImportLinkage())
305 O << "__imp_";
306 O << Name;
307 }
308
309 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
310 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
311 << "$pb\"";
312 } else {
313 if (GV->hasDLLImportLinkage()) {
314 O << "__imp_";
315 }
316 O << Name;
317
318 if (isCallOp && isa<Function>(GV)) {
319 if (printGOT(TM, Subtarget)) {
320 // Assemble call via PLT for non-local symbols
321 if (!(GV->hasHiddenVisibility() || GV->hasProtectedVisibility()) ||
322 GV->isDeclaration())
323 O << "@PLT";
324 }
325 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
326 // Save function name for later type emission
327 FnStubs.insert(Name);
328 }
329 }
330
331 if (GV->hasExternalWeakLinkage())
332 ExtWeakSymbols.insert(GV);
333
334 int Offset = MO.getOffset();
335 if (Offset > 0)
336 O << "+" << Offset;
337 else if (Offset < 0)
338 O << Offset;
339
340 if (isThreadLocal) {
341 if (TM.getRelocationModel() == Reloc::PIC_)
342 O << "@TLSGD"; // general dynamic TLS model
343 else
344 if (GV->isDeclaration())
345 O << "@INDNTPOFF"; // initial exec TLS model
346 else
347 O << "@NTPOFF"; // local exec TLS model
348 } else if (isMemOp) {
349 if (printGOT(TM, Subtarget)) {
350 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
351 O << "@GOT";
352 else
353 O << "@GOTOFF";
354 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
355 if ((GV->isDeclaration() ||
356 GV->hasWeakLinkage() ||
357 GV->hasLinkOnceLinkage()) &&
358 TM.getRelocationModel() != Reloc::Static)
359 O << "@GOTPCREL";
360
361 if (needCloseParen) {
362 needCloseParen = false;
363 O << ')';
364 }
365
366 // Use rip when possible to reduce code size, except when
367 // index or base register are also part of the address. e.g.
368 // foo(%rip)(%rcx,%rax,4) is not legal
369 O << "(%rip)";
370 }
371 }
372
373 if (needCloseParen)
374 O << ')';
375
376 return;
377 }
378 case MachineOperand::MO_ExternalSymbol: {
379 bool isCallOp = Modifier && !strcmp(Modifier, "call");
380 bool needCloseParen = false;
381 std::string Name(TAI->getGlobalPrefix());
382 Name += MO.getSymbolName();
383 if (isCallOp && printStub(TM, Subtarget)) {
384 FnStubs.insert(Name);
385 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
386 return;
387 }
388 if (!isCallOp)
389 O << '$';
390 else if (Name[0] == '$') {
391 // The name begins with a dollar-sign. In order to avoid having it look
392 // like an integer immediate to the assembler, enclose it in parens.
393 O << '(';
394 needCloseParen = true;
395 }
396
397 O << Name;
398
399 if (printGOT(TM, Subtarget)) {
400 std::string GOTName(TAI->getGlobalPrefix());
401 GOTName+="_GLOBAL_OFFSET_TABLE_";
402 if (Name == GOTName)
403 // HACK! Emit extra offset to PC during printing GOT offset to
404 // compensate for the size of popl instruction. The resulting code
405 // should look like:
406 // call .piclabel
407 // piclabel:
408 // popl %some_register
409 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
410 O << " + [.-"
411 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
412
413 if (isCallOp)
414 O << "@PLT";
415 }
416
417 if (needCloseParen)
418 O << ')';
419
420 if (!isCallOp && Subtarget->isPICStyleRIPRel())
421 O << "(%rip)";
422
423 return;
424 }
425 default:
426 O << "<unknown operand type>"; return;
427 }
428}
429
430void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
431 unsigned char value = MI->getOperand(Op).getImmedValue();
432 assert(value <= 7 && "Invalid ssecc argument!");
433 switch (value) {
434 case 0: O << "eq"; break;
435 case 1: O << "lt"; break;
436 case 2: O << "le"; break;
437 case 3: O << "unord"; break;
438 case 4: O << "neq"; break;
439 case 5: O << "nlt"; break;
440 case 6: O << "nle"; break;
441 case 7: O << "ord"; break;
442 }
443}
444
445void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
446 const char *Modifier){
447 assert(isMem(MI, Op) && "Invalid memory reference!");
448 MachineOperand BaseReg = MI->getOperand(Op);
449 MachineOperand IndexReg = MI->getOperand(Op+2);
450 const MachineOperand &DispSpec = MI->getOperand(Op+3);
451
452 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
453 if (DispSpec.isGlobalAddress() ||
454 DispSpec.isConstantPoolIndex() ||
455 DispSpec.isJumpTableIndex()) {
456 printOperand(MI, Op+3, "mem", NotRIPRel);
457 } else {
458 int DispVal = DispSpec.getImmedValue();
459 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
460 O << DispVal;
461 }
462
463 if (IndexReg.getReg() || BaseReg.getReg()) {
464 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
465 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
466
467 // There are cases where we can end up with ESP/RSP in the indexreg slot.
468 // If this happens, swap the base/index register to support assemblers that
469 // don't work when the index is *SP.
470 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
471 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
472 std::swap(BaseReg, IndexReg);
473 std::swap(BaseRegOperand, IndexRegOperand);
474 }
475
476 O << "(";
477 if (BaseReg.getReg())
478 printOperand(MI, Op+BaseRegOperand, Modifier);
479
480 if (IndexReg.getReg()) {
481 O << ",";
482 printOperand(MI, Op+IndexRegOperand, Modifier);
483 if (ScaleVal != 1)
484 O << "," << ScaleVal;
485 }
486 O << ")";
487 }
488}
489
490void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
491 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
492 O << label << "\n" << label << ":";
493}
494
495
496bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
497 const char Mode) {
498 const MRegisterInfo &RI = *TM.getRegisterInfo();
499 unsigned Reg = MO.getReg();
500 switch (Mode) {
501 default: return true; // Unknown mode.
502 case 'b': // Print QImode register
503 Reg = getX86SubSuperRegister(Reg, MVT::i8);
504 break;
505 case 'h': // Print QImode high register
506 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
507 break;
508 case 'w': // Print HImode register
509 Reg = getX86SubSuperRegister(Reg, MVT::i16);
510 break;
511 case 'k': // Print SImode register
512 Reg = getX86SubSuperRegister(Reg, MVT::i32);
513 break;
514 }
515
516 O << '%';
517 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
518 O << (char)tolower(*Name);
519 return false;
520}
521
522/// PrintAsmOperand - Print out an operand for an inline asm expression.
523///
524bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
525 unsigned AsmVariant,
526 const char *ExtraCode) {
527 // Does this asm operand have a single letter operand modifier?
528 if (ExtraCode && ExtraCode[0]) {
529 if (ExtraCode[1] != 0) return true; // Unknown modifier.
530
531 switch (ExtraCode[0]) {
532 default: return true; // Unknown modifier.
533 case 'c': // Don't print "$" before a global var name or constant.
534 printOperand(MI, OpNo, "mem");
535 return false;
536 case 'b': // Print QImode register
537 case 'h': // Print QImode high register
538 case 'w': // Print HImode register
539 case 'k': // Print SImode register
540 if (MI->getOperand(OpNo).isReg())
541 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
542 printOperand(MI, OpNo);
543 return false;
544
545 case 'P': // Don't print @PLT, but do print as memory.
546 printOperand(MI, OpNo, "mem");
547 return false;
548 }
549 }
550
551 printOperand(MI, OpNo);
552 return false;
553}
554
555bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
556 unsigned OpNo,
557 unsigned AsmVariant,
558 const char *ExtraCode) {
559 if (ExtraCode && ExtraCode[0])
560 return true; // Unknown modifier.
561 printMemReference(MI, OpNo);
562 return false;
563}
564
565/// printMachineInstruction -- Print out a single X86 LLVM instruction
566/// MI in AT&T syntax to the current output stream.
567///
568void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
569 ++EmittedInsts;
570
571 // See if a truncate instruction can be turned into a nop.
572 switch (MI->getOpcode()) {
573 default: break;
574 case X86::TRUNC_64to32:
575 case X86::TRUNC_64to16:
576 case X86::TRUNC_32to16:
577 case X86::TRUNC_32to8:
578 case X86::TRUNC_16to8:
579 case X86::TRUNC_32_to8:
580 case X86::TRUNC_16_to8: {
581 const MachineOperand &MO0 = MI->getOperand(0);
582 const MachineOperand &MO1 = MI->getOperand(1);
583 unsigned Reg0 = MO0.getReg();
584 unsigned Reg1 = MO1.getReg();
585 unsigned Opc = MI->getOpcode();
586 if (Opc == X86::TRUNC_64to32)
587 Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
588 else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
589 Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
590 else
591 Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
592 O << TAI->getCommentString() << " TRUNCATE ";
593 if (Reg0 != Reg1)
594 O << "\n\t";
595 break;
596 }
597 case X86::PsMOVZX64rr32:
598 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
599 break;
600 }
601
602 // Call the autogenerated instruction printer routines.
603 printInstruction(MI);
604}
605
606// Include the auto-generated portion of the assembly writer.
607#include "X86GenAsmWriter.inc"
608