1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/MDNode.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/CodeGen/DwarfWriter.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Target/TargetOptions.h"
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
48 //===----------------------------------------------------------------------===//
49 // Primitive Helper Functions.
50 //===----------------------------------------------------------------------===//
52 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
53 if (Subtarget->isTargetDarwin())
54 O << "\"L" << getFunctionNumber() << "$pb\"";
55 else if (Subtarget->isTargetELF())
56 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
58 llvm_unreachable("Don't know how to print PIC label!");
61 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
62 /// Don't print things like \\n or \\0.
63 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
64 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
70 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
71 const TargetData *TD) {
72 X86MachineFunctionInfo Info;
75 switch (F->getCallingConv()) {
76 case CallingConv::X86_StdCall:
77 Info.setDecorationStyle(StdCall);
79 case CallingConv::X86_FastCall:
80 Info.setDecorationStyle(FastCall);
87 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
88 AI != AE; ++AI, ++argNum) {
89 const Type* Ty = AI->getType();
91 // 'Dereference' type in case of byval parameter attribute
92 if (F->paramHasAttr(argNum, Attribute::ByVal))
93 Ty = cast<PointerType>(Ty)->getElementType();
95 // Size should be aligned to DWORD boundary
96 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
99 // We're not supporting tooooo huge arguments :)
100 Info.setBytesToPopOnReturn((unsigned int)Size);
104 /// decorateName - Query FunctionInfoMap and use this information for various
106 void X86ATTAsmPrinter::decorateName(std::string &Name,
107 const GlobalValue *GV) {
108 const Function *F = dyn_cast<Function>(GV);
111 // Save function name for later type emission.
112 if (Subtarget->isTargetCygMing() && F->isDeclaration())
113 CygMingStubs.insert(Name);
115 // We don't want to decorate non-stdcall or non-fastcall functions right now
116 unsigned CC = F->getCallingConv();
117 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
120 // Decorate names only when we're targeting Cygwin/Mingw32 targets
121 if (!Subtarget->isTargetCygMing())
124 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
126 const X86MachineFunctionInfo *Info;
127 if (info_item == FunctionInfoMap.end()) {
128 // Calculate apropriate function info and populate map
129 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
130 Info = &FunctionInfoMap[F];
132 Info = &info_item->second;
135 const FunctionType *FT = F->getFunctionType();
136 switch (Info->getDecorationStyle()) {
140 // "Pure" variadic functions do not receive @0 suffix.
141 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
142 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
143 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
146 // "Pure" variadic functions do not receive @0 suffix.
147 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
148 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
149 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
151 if (Name[0] == '_') {
158 llvm_unreachable("Unsupported DecorationStyle");
162 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
163 unsigned FnAlign = MF.getAlignment();
164 const Function *F = MF.getFunction();
166 decorateName(CurrentFnName, F);
168 SwitchToSection(TAI->SectionForGlobal(F));
169 switch (F->getLinkage()) {
170 default: llvm_unreachable("Unknown linkage type!");
171 case Function::InternalLinkage: // Symbols default to internal.
172 case Function::PrivateLinkage:
173 EmitAlignment(FnAlign, F);
175 case Function::DLLExportLinkage:
176 case Function::ExternalLinkage:
177 EmitAlignment(FnAlign, F);
178 O << "\t.globl\t" << CurrentFnName << '\n';
180 case Function::LinkOnceAnyLinkage:
181 case Function::LinkOnceODRLinkage:
182 case Function::WeakAnyLinkage:
183 case Function::WeakODRLinkage:
184 EmitAlignment(FnAlign, F);
185 if (Subtarget->isTargetDarwin()) {
186 O << "\t.globl\t" << CurrentFnName << '\n';
187 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
188 } else if (Subtarget->isTargetCygMing()) {
189 O << "\t.globl\t" << CurrentFnName << "\n"
190 "\t.linkonce discard\n";
192 O << "\t.weak\t" << CurrentFnName << '\n';
197 printVisibility(CurrentFnName, F->getVisibility());
199 if (Subtarget->isTargetELF())
200 O << "\t.type\t" << CurrentFnName << ",@function\n";
201 else if (Subtarget->isTargetCygMing()) {
202 O << "\t.def\t " << CurrentFnName
204 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
205 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
209 O << CurrentFnName << ":\n";
210 // Add some workaround for linkonce linkage on Cygwin\MinGW
211 if (Subtarget->isTargetCygMing() &&
212 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
213 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
216 /// runOnMachineFunction - This uses the printMachineInstruction()
217 /// method to print assembly for each instruction.
219 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
220 const Function *F = MF.getFunction();
222 unsigned CC = F->getCallingConv();
224 SetupMachineFunction(MF);
227 // Populate function information map. Actually, We don't want to populate
228 // non-stdcall or non-fastcall functions' information right now.
229 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
230 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
232 // Print out constants referenced by the function
233 EmitConstantPool(MF.getConstantPool());
235 if (F->hasDLLExportLinkage())
236 DLLExportedFns.insert(Mang->getValueName(F));
238 // Print the 'header' of function
239 emitFunctionHeader(MF);
241 // Emit pre-function debug and/or EH information.
242 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
243 DW->BeginFunction(&MF);
245 // Print out code for the function.
246 bool hasAnyRealCode = false;
247 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
249 // Print a label for the basic block.
250 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
251 // This is an entry block or a block that's only reachable via a
252 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
254 printBasicBlockLabel(I, true, true, VerboseAsm);
257 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
259 // Print the assembly for the instruction.
261 hasAnyRealCode = true;
262 printMachineInstruction(II);
266 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
267 // If the function is empty, then we need to emit *something*. Otherwise,
268 // the function's label might be associated with something that it wasn't
269 // meant to be associated with. We emit a noop in this situation.
270 // We are assuming inline asms are code.
274 if (TAI->hasDotTypeDotSizeDirective())
275 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
277 // Emit post-function debug information.
278 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
279 DW->EndFunction(&MF);
281 // Print out jump tables referenced by the function.
282 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
286 // We didn't modify anything.
290 /// printSymbolOperand - Print a raw symbol reference operand. This handles
291 /// jump tables, constant pools, global address and external symbols, all of
292 /// which print to a label with various suffixes for relocation types etc.
293 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
294 switch (MO.getType()) {
295 default: llvm_unreachable("unknown symbol type!");
296 case MachineOperand::MO_JumpTableIndex:
297 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
300 case MachineOperand::MO_ConstantPoolIndex:
301 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
303 printOffset(MO.getOffset());
305 case MachineOperand::MO_GlobalAddress: {
306 const GlobalValue *GV = MO.getGlobal();
307 std::string Name = Mang->getValueName(GV);
308 decorateName(Name, GV);
310 bool needCloseParen = false;
311 if (Name[0] == '$') {
312 // The name begins with a dollar-sign. In order to avoid having it look
313 // like an integer immediate to the assembler, enclose it in parens.
315 needCloseParen = true;
318 // Handle dllimport linkage.
319 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT) {
320 O << "__imp_" << Name;
321 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
322 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
323 GVStubs.insert(Name);
324 printSuffixedName(Name, "$non_lazy_ptr");
325 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
326 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
327 HiddenGVStubs.insert(Name);
328 printSuffixedName(Name, "$non_lazy_ptr");
329 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
330 FnStubs.insert(Name);
331 printSuffixedName(Name, "$stub");
339 printOffset(MO.getOffset());
342 case MachineOperand::MO_ExternalSymbol: {
343 bool needCloseParen = false;
344 std::string Name(TAI->getGlobalPrefix());
345 Name += MO.getSymbolName();
347 if (Name[0] == '$') {
348 // The name begins with a dollar-sign. In order to avoid having it look
349 // like an integer immediate to the assembler, enclose it in parens.
351 needCloseParen = true;
354 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
355 FnStubs.insert(Name);
356 printSuffixedName(Name, "$stub");
367 switch (MO.getTargetFlags()) {
369 llvm_unreachable("Unknown target flag on GV operand");
370 case X86II::MO_NO_FLAG: // No flag.
372 case X86II::MO_DARWIN_NONLAZY:
373 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
374 case X86II::MO_DLLIMPORT:
375 case X86II::MO_DARWIN_STUB:
376 // These affect the name of the symbol, not any suffix.
378 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
380 PrintPICBaseSymbol();
383 case X86II::MO_PIC_BASE_OFFSET:
384 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
385 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
387 PrintPICBaseSymbol();
389 case X86II::MO_TLSGD: O << "@TLSGD"; break;
390 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
391 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
392 case X86II::MO_TPOFF: O << "@TPOFF"; break;
393 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
394 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
395 case X86II::MO_GOT: O << "@GOT"; break;
396 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
397 case X86II::MO_PLT: O << "@PLT"; break;
401 /// print_pcrel_imm - This is used to print an immediate value that ends up
402 /// being encoded as a pc-relative value. These print slightly differently, for
403 /// example, a $ is not emitted.
404 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
405 const MachineOperand &MO = MI->getOperand(OpNo);
406 switch (MO.getType()) {
407 default: llvm_unreachable("Unknown pcrel immediate operand");
408 case MachineOperand::MO_Immediate:
411 case MachineOperand::MO_MachineBasicBlock:
412 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
414 case MachineOperand::MO_GlobalAddress:
415 printSymbolOperand(MO);
417 case MachineOperand::MO_ExternalSymbol:
418 printSymbolOperand(MO);
425 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
426 const char *Modifier) {
427 const MachineOperand &MO = MI->getOperand(OpNo);
428 switch (MO.getType()) {
429 default: llvm_unreachable("unknown operand type!");
430 case MachineOperand::MO_Register: {
431 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
432 "Virtual registers should not make it this far!");
434 unsigned Reg = MO.getReg();
435 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
436 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
437 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
438 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
439 Reg = getX86SubSuperRegister(Reg, VT);
441 O << TRI->getAsmName(Reg);
445 case MachineOperand::MO_Immediate:
446 O << '$' << MO.getImm();
449 case MachineOperand::MO_JumpTableIndex:
450 case MachineOperand::MO_ConstantPoolIndex:
451 case MachineOperand::MO_GlobalAddress:
452 case MachineOperand::MO_ExternalSymbol: {
454 printSymbolOperand(MO);
460 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
461 unsigned char value = MI->getOperand(Op).getImm();
462 assert(value <= 7 && "Invalid ssecc argument!");
464 case 0: O << "eq"; break;
465 case 1: O << "lt"; break;
466 case 2: O << "le"; break;
467 case 3: O << "unord"; break;
468 case 4: O << "neq"; break;
469 case 5: O << "nlt"; break;
470 case 6: O << "nle"; break;
471 case 7: O << "ord"; break;
475 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
476 const char *Modifier) {
477 const MachineOperand &BaseReg = MI->getOperand(Op);
478 const MachineOperand &IndexReg = MI->getOperand(Op+2);
479 const MachineOperand &DispSpec = MI->getOperand(Op+3);
481 // If we really don't want to print out (rip), don't.
482 bool HasBaseReg = BaseReg.getReg() != 0;
483 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
484 BaseReg.getReg() == X86::RIP)
487 // HasParenPart - True if we will print out the () part of the mem ref.
488 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
490 if (DispSpec.isImm()) {
491 int DispVal = DispSpec.getImm();
492 if (DispVal || !HasParenPart)
495 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
496 DispSpec.isJTI() || DispSpec.isSymbol());
497 printSymbolOperand(MI->getOperand(Op+3));
501 assert(IndexReg.getReg() != X86::ESP &&
502 "X86 doesn't allow scaling by ESP");
506 printOperand(MI, Op, Modifier);
508 if (IndexReg.getReg()) {
510 printOperand(MI, Op+2, Modifier);
511 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
513 O << ',' << ScaleVal;
519 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
520 const char *Modifier) {
521 assert(isMem(MI, Op) && "Invalid memory reference!");
522 const MachineOperand &Segment = MI->getOperand(Op+4);
523 if (Segment.getReg()) {
524 printOperand(MI, Op+4, Modifier);
527 printLeaMemReference(MI, Op, Modifier);
530 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
531 const MachineBasicBlock *MBB) const {
532 if (!TAI->getSetDirective())
535 // We don't need .set machinery if we have GOT-style relocations
536 if (Subtarget->isPICStyleGOT())
539 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
540 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
541 printBasicBlockLabel(MBB, false, false, false);
542 if (Subtarget->isPICStyleRIPRel())
543 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
544 << '_' << uid << '\n';
547 PrintPICBaseSymbol();
553 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
554 PrintPICBaseSymbol();
556 PrintPICBaseSymbol();
561 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
562 const MachineBasicBlock *MBB,
563 unsigned uid) const {
564 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
565 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
567 O << JTEntryDirective << ' ';
569 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
570 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
571 << '_' << uid << "_set_" << MBB->getNumber();
572 } else if (Subtarget->isPICStyleGOT()) {
573 printBasicBlockLabel(MBB, false, false, false);
576 printBasicBlockLabel(MBB, false, false, false);
579 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
580 unsigned Reg = MO.getReg();
582 default: return true; // Unknown mode.
583 case 'b': // Print QImode register
584 Reg = getX86SubSuperRegister(Reg, MVT::i8);
586 case 'h': // Print QImode high register
587 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
589 case 'w': // Print HImode register
590 Reg = getX86SubSuperRegister(Reg, MVT::i16);
592 case 'k': // Print SImode register
593 Reg = getX86SubSuperRegister(Reg, MVT::i32);
595 case 'q': // Print DImode register
596 Reg = getX86SubSuperRegister(Reg, MVT::i64);
600 O << '%'<< TRI->getAsmName(Reg);
604 /// PrintAsmOperand - Print out an operand for an inline asm expression.
606 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
608 const char *ExtraCode) {
609 // Does this asm operand have a single letter operand modifier?
610 if (ExtraCode && ExtraCode[0]) {
611 if (ExtraCode[1] != 0) return true; // Unknown modifier.
613 const MachineOperand &MO = MI->getOperand(OpNo);
615 switch (ExtraCode[0]) {
616 default: return true; // Unknown modifier.
617 case 'c': // Don't print "$" before a global var name or constant.
620 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
621 printSymbolOperand(MO);
623 printOperand(MI, OpNo);
626 case 'A': // Print '*' before a register (it must be a register)
629 printOperand(MI, OpNo);
634 case 'b': // Print QImode register
635 case 'h': // Print QImode high register
636 case 'w': // Print HImode register
637 case 'k': // Print SImode register
638 case 'q': // Print DImode register
640 return printAsmMRegister(MO, ExtraCode[0]);
641 printOperand(MI, OpNo);
644 case 'P': // This is the operand of a call, treat specially.
645 print_pcrel_imm(MI, OpNo);
648 case 'n': // Negate the immediate or print a '-' before the operand.
649 // Note: this is a temporary solution. It should be handled target
650 // independently as part of the 'MC' work.
659 printOperand(MI, OpNo);
663 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
666 const char *ExtraCode) {
667 if (ExtraCode && ExtraCode[0]) {
668 if (ExtraCode[1] != 0) return true; // Unknown modifier.
670 switch (ExtraCode[0]) {
671 default: return true; // Unknown modifier.
672 case 'b': // Print QImode register
673 case 'h': // Print QImode high register
674 case 'w': // Print HImode register
675 case 'k': // Print SImode register
676 case 'q': // Print SImode register
677 // These only apply to registers, ignore on mem.
679 case 'P': // Don't print @PLT, but do print as memory.
680 printMemReference(MI, OpNo, "no-rip");
684 printMemReference(MI, OpNo);
688 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
689 // Convert registers in the addr mode according to subreg64.
690 for (unsigned i = 0; i != 4; ++i) {
691 if (!MI->getOperand(i).isReg()) continue;
693 unsigned Reg = MI->getOperand(i).getReg();
694 if (Reg == 0) continue;
696 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
700 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
701 /// AT&T syntax to the current output stream.
703 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
707 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
711 } else if (MI->isLabel()) {
714 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
717 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
718 printImplicitDef(MI);
725 TmpInst.setOpcode(MI->getOpcode());
727 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
728 const MachineOperand &MO = MI->getOperand(i);
732 MCOp.MakeReg(MO.getReg());
733 } else if (MO.isImm()) {
734 MCOp.MakeImm(MO.getImm());
735 } else if (MO.isMBB()) {
736 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
738 llvm_unreachable("Unimp");
741 TmpInst.addOperand(MCOp);
744 switch (TmpInst.getOpcode()) {
746 // Handle the 'subreg rewriting' for the lea64_32mem operand.
747 lower_lea64_32mem(&TmpInst, 1);
751 // FIXME: Convert TmpInst.
752 printInstruction(&TmpInst);
756 // Call the autogenerated instruction printer routines.
757 printInstruction(MI);
761 bool X86ATTAsmPrinter::doInitialization(Module &M) {
763 Context = new MCContext();
764 // FIXME: Send this to "O" instead of outs(). For now, we force it to
765 // stdout to make it easy to compare.
766 Streamer = createAsmStreamer(*Context, outs());
769 return AsmPrinter::doInitialization(M);
772 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
773 const TargetData *TD = TM.getTargetData();
775 if (!GVar->hasInitializer())
776 return; // External global require no code
778 // Check to see if this is a special global used by LLVM, if so, emit it.
779 if (EmitSpecialLLVMGlobal(GVar)) {
780 if (Subtarget->isTargetDarwin() &&
781 TM.getRelocationModel() == Reloc::Static) {
782 if (GVar->getName() == "llvm.global_ctors")
783 O << ".reference .constructors_used\n";
784 else if (GVar->getName() == "llvm.global_dtors")
785 O << ".reference .destructors_used\n";
790 std::string name = Mang->getValueName(GVar);
791 Constant *C = GVar->getInitializer();
792 if (isa<MDNode>(C) || isa<MDString>(C))
794 const Type *Type = C->getType();
795 unsigned Size = TD->getTypeAllocSize(Type);
796 unsigned Align = TD->getPreferredAlignmentLog(GVar);
798 printVisibility(name, GVar->getVisibility());
800 if (Subtarget->isTargetELF())
801 O << "\t.type\t" << name << ",@object\n";
803 SwitchToSection(TAI->SectionForGlobal(GVar));
805 if (C->isNullValue() && !GVar->hasSection() &&
806 !(Subtarget->isTargetDarwin() &&
807 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
808 // FIXME: This seems to be pretty darwin-specific
809 if (GVar->hasExternalLinkage()) {
810 if (const char *Directive = TAI->getZeroFillDirective()) {
811 O << "\t.globl " << name << '\n';
812 O << Directive << "__DATA, __common, " << name << ", "
813 << Size << ", " << Align << '\n';
818 if (!GVar->isThreadLocal() &&
819 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
820 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
822 if (TAI->getLCOMMDirective() != NULL) {
823 if (GVar->hasLocalLinkage()) {
824 O << TAI->getLCOMMDirective() << name << ',' << Size;
825 if (Subtarget->isTargetDarwin())
827 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
828 O << "\t.globl " << name << '\n'
829 << TAI->getWeakDefDirective() << name << '\n';
830 EmitAlignment(Align, GVar);
833 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
834 PrintUnmangledNameSafely(GVar, O);
837 EmitGlobalConstant(C);
840 O << TAI->getCOMMDirective() << name << ',' << Size;
841 if (TAI->getCOMMDirectiveTakesAlignment())
842 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
845 if (!Subtarget->isTargetCygMing()) {
846 if (GVar->hasLocalLinkage())
847 O << "\t.local\t" << name << '\n';
849 O << TAI->getCOMMDirective() << name << ',' << Size;
850 if (TAI->getCOMMDirectiveTakesAlignment())
851 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
854 O << "\t\t" << TAI->getCommentString() << ' ';
855 PrintUnmangledNameSafely(GVar, O);
862 switch (GVar->getLinkage()) {
863 case GlobalValue::CommonLinkage:
864 case GlobalValue::LinkOnceAnyLinkage:
865 case GlobalValue::LinkOnceODRLinkage:
866 case GlobalValue::WeakAnyLinkage:
867 case GlobalValue::WeakODRLinkage:
868 if (Subtarget->isTargetDarwin()) {
869 O << "\t.globl " << name << '\n'
870 << TAI->getWeakDefDirective() << name << '\n';
871 } else if (Subtarget->isTargetCygMing()) {
872 O << "\t.globl\t" << name << "\n"
873 "\t.linkonce same_size\n";
875 O << "\t.weak\t" << name << '\n';
878 case GlobalValue::DLLExportLinkage:
879 case GlobalValue::AppendingLinkage:
880 // FIXME: appending linkage variables should go into a section of
881 // their name or something. For now, just emit them as external.
882 case GlobalValue::ExternalLinkage:
883 // If external or appending, declare as a global symbol
884 O << "\t.globl " << name << '\n';
886 case GlobalValue::PrivateLinkage:
887 case GlobalValue::InternalLinkage:
890 llvm_unreachable("Unknown linkage type!");
893 EmitAlignment(Align, GVar);
896 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
897 PrintUnmangledNameSafely(GVar, O);
900 if (TAI->hasDotTypeDotSizeDirective())
901 O << "\t.size\t" << name << ", " << Size << '\n';
903 EmitGlobalConstant(C);
906 bool X86ATTAsmPrinter::doFinalization(Module &M) {
907 // Print out module-level global variables here.
908 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
910 printModuleLevelGV(I);
912 if (I->hasDLLExportLinkage())
913 DLLExportedGVs.insert(Mang->getValueName(I));
916 if (Subtarget->isTargetDarwin()) {
917 SwitchToDataSection("");
919 // Add the (possibly multiple) personalities to the set of global value
920 // stubs. Only referenced functions get into the Personalities list.
921 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
922 const std::vector<Function*> &Personalities = MMI->getPersonalities();
923 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
924 if (Personalities[i] == 0)
926 std::string Name = Mang->getValueName(Personalities[i]);
927 decorateName(Name, Personalities[i]);
928 GVStubs.insert(Name);
932 // Output stubs for dynamically-linked functions
933 if (!FnStubs.empty()) {
934 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
936 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
937 "self_modifying_code+pure_instructions,5", 0);
938 const char *Name = I->getKeyData();
939 printSuffixedName(Name, "$stub");
941 "\t.indirect_symbol " << Name << "\n"
942 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
947 // Output stubs for external and common global variables.
948 if (!GVStubs.empty()) {
950 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
951 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
953 const char *Name = I->getKeyData();
954 printSuffixedName(Name, "$non_lazy_ptr");
955 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
959 if (!HiddenGVStubs.empty()) {
960 SwitchToSection(TAI->getDataSection());
962 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
963 E = HiddenGVStubs.end(); I != E; ++I) {
964 const char *Name = I->getKeyData();
965 printSuffixedName(Name, "$non_lazy_ptr");
966 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
970 // Funny Darwin hack: This flag tells the linker that no global symbols
971 // contain code that falls through to other global symbols (e.g. the obvious
972 // implementation of multiple entry points). If this doesn't occur, the
973 // linker can safely perform dead code stripping. Since LLVM never
974 // generates code that does this, it is always safe to set.
975 O << "\t.subsections_via_symbols\n";
976 } else if (Subtarget->isTargetCygMing()) {
977 // Emit type information for external functions
978 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
980 O << "\t.def\t " << i->getKeyData()
981 << ";\t.scl\t" << COFF::C_EXT
982 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
988 // Output linker support code for dllexported globals on windows.
989 if (!DLLExportedGVs.empty()) {
990 SwitchToDataSection(".section .drectve");
992 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
993 e = DLLExportedGVs.end(); i != e; ++i)
994 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
997 if (!DLLExportedFns.empty()) {
998 SwitchToDataSection(".section .drectve");
1000 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1001 e = DLLExportedFns.end();
1003 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1006 // Do common shutdown.
1007 bool Changed = AsmPrinter::doFinalization(M);
1009 if (NewAsmPrinter) {
1021 // Include the auto-generated portion of the assembly writer.
1022 #include "X86GenAsmWriter.inc"