1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 X86 machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86AsmPrinter.h"
16 #include "InstPrinter/X86ATTInstPrinter.h"
17 #include "MCTargetDesc/X86BaseInfo.h"
18 #include "X86InstrInfo.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
23 #include "llvm/CodeGen/MachineValueType.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCSectionCOFF.h"
34 #include "llvm/MC/MCSectionMachO.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/COFF.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/TargetRegistry.h"
41 using namespace llvm;
42
43 //===----------------------------------------------------------------------===//
44 // Primitive Helper Functions.
45 //===----------------------------------------------------------------------===//
46
47 /// runOnMachineFunction - Emit the function body.
48 ///
runOnMachineFunction(MachineFunction & MF)49 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
50 SMShadowTracker.startFunction(MF);
51
52 SetupMachineFunction(MF);
53
54 if (Subtarget->isTargetCOFF()) {
55 bool Intrn = MF.getFunction()->hasInternalLinkage();
56 OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
57 OutStreamer.EmitCOFFSymbolStorageClass(Intrn ? COFF::IMAGE_SYM_CLASS_STATIC
58 : COFF::IMAGE_SYM_CLASS_EXTERNAL);
59 OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
60 << COFF::SCT_COMPLEX_TYPE_SHIFT);
61 OutStreamer.EndCOFFSymbolDef();
62 }
63
64 // Have common code print out the function header with linkage info etc.
65 EmitFunctionHeader();
66
67 // Emit the rest of the function body.
68 EmitFunctionBody();
69
70 // We didn't modify anything.
71 return false;
72 }
73
74 /// printSymbolOperand - Print a raw symbol reference operand. This handles
75 /// jump tables, constant pools, global address and external symbols, all of
76 /// which print to a label with various suffixes for relocation types etc.
printSymbolOperand(X86AsmPrinter & P,const MachineOperand & MO,raw_ostream & O)77 static void printSymbolOperand(X86AsmPrinter &P, const MachineOperand &MO,
78 raw_ostream &O) {
79 switch (MO.getType()) {
80 default: llvm_unreachable("unknown symbol type!");
81 case MachineOperand::MO_ConstantPoolIndex:
82 O << *P.GetCPISymbol(MO.getIndex());
83 P.printOffset(MO.getOffset(), O);
84 break;
85 case MachineOperand::MO_GlobalAddress: {
86 const GlobalValue *GV = MO.getGlobal();
87
88 MCSymbol *GVSym;
89 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
90 GVSym = P.getSymbolWithGlobalValueBase(GV, "$stub");
91 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
92 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
93 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
94 GVSym = P.getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
95 else
96 GVSym = P.getSymbol(GV);
97
98 // Handle dllimport linkage.
99 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
100 GVSym =
101 P.OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
102
103 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
104 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
105 MCSymbol *Sym = P.getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
106 MachineModuleInfoImpl::StubValueTy &StubSym =
107 P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
108 if (!StubSym.getPointer())
109 StubSym = MachineModuleInfoImpl::
110 StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
111 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
112 MCSymbol *Sym = P.getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
113 MachineModuleInfoImpl::StubValueTy &StubSym =
114 P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(
115 Sym);
116 if (!StubSym.getPointer())
117 StubSym = MachineModuleInfoImpl::
118 StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
119 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
120 MCSymbol *Sym = P.getSymbolWithGlobalValueBase(GV, "$stub");
121 MachineModuleInfoImpl::StubValueTy &StubSym =
122 P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
123 if (!StubSym.getPointer())
124 StubSym = MachineModuleInfoImpl::
125 StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
126 }
127
128 // If the name begins with a dollar-sign, enclose it in parens. We do this
129 // to avoid having it look like an integer immediate to the assembler.
130 if (GVSym->getName()[0] != '$')
131 O << *GVSym;
132 else
133 O << '(' << *GVSym << ')';
134 P.printOffset(MO.getOffset(), O);
135 break;
136 }
137 }
138
139 switch (MO.getTargetFlags()) {
140 default:
141 llvm_unreachable("Unknown target flag on GV operand");
142 case X86II::MO_NO_FLAG: // No flag.
143 break;
144 case X86II::MO_DARWIN_NONLAZY:
145 case X86II::MO_DLLIMPORT:
146 case X86II::MO_DARWIN_STUB:
147 // These affect the name of the symbol, not any suffix.
148 break;
149 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
150 O << " + [.-" << *P.MF->getPICBaseSymbol() << ']';
151 break;
152 case X86II::MO_PIC_BASE_OFFSET:
153 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
154 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
155 O << '-' << *P.MF->getPICBaseSymbol();
156 break;
157 case X86II::MO_TLSGD: O << "@TLSGD"; break;
158 case X86II::MO_TLSLD: O << "@TLSLD"; break;
159 case X86II::MO_TLSLDM: O << "@TLSLDM"; break;
160 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
161 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
162 case X86II::MO_TPOFF: O << "@TPOFF"; break;
163 case X86II::MO_DTPOFF: O << "@DTPOFF"; break;
164 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
165 case X86II::MO_GOTNTPOFF: O << "@GOTNTPOFF"; break;
166 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
167 case X86II::MO_GOT: O << "@GOT"; break;
168 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
169 case X86II::MO_PLT: O << "@PLT"; break;
170 case X86II::MO_TLVP: O << "@TLVP"; break;
171 case X86II::MO_TLVP_PIC_BASE:
172 O << "@TLVP" << '-' << *P.MF->getPICBaseSymbol();
173 break;
174 case X86II::MO_SECREL: O << "@SECREL32"; break;
175 }
176 }
177
178 static void printOperand(X86AsmPrinter &P, const MachineInstr *MI,
179 unsigned OpNo, raw_ostream &O,
180 const char *Modifier = nullptr, unsigned AsmVariant = 0);
181
182 /// printPCRelImm - This is used to print an immediate value that ends up
183 /// being encoded as a pc-relative value. These print slightly differently, for
184 /// example, a $ is not emitted.
printPCRelImm(X86AsmPrinter & P,const MachineInstr * MI,unsigned OpNo,raw_ostream & O)185 static void printPCRelImm(X86AsmPrinter &P, const MachineInstr *MI,
186 unsigned OpNo, raw_ostream &O) {
187 const MachineOperand &MO = MI->getOperand(OpNo);
188 switch (MO.getType()) {
189 default: llvm_unreachable("Unknown pcrel immediate operand");
190 case MachineOperand::MO_Register:
191 // pc-relativeness was handled when computing the value in the reg.
192 printOperand(P, MI, OpNo, O);
193 return;
194 case MachineOperand::MO_Immediate:
195 O << MO.getImm();
196 return;
197 case MachineOperand::MO_GlobalAddress:
198 printSymbolOperand(P, MO, O);
199 return;
200 }
201 }
202
printOperand(X86AsmPrinter & P,const MachineInstr * MI,unsigned OpNo,raw_ostream & O,const char * Modifier,unsigned AsmVariant)203 static void printOperand(X86AsmPrinter &P, const MachineInstr *MI,
204 unsigned OpNo, raw_ostream &O, const char *Modifier,
205 unsigned AsmVariant) {
206 const MachineOperand &MO = MI->getOperand(OpNo);
207 switch (MO.getType()) {
208 default: llvm_unreachable("unknown operand type!");
209 case MachineOperand::MO_Register: {
210 // FIXME: Enumerating AsmVariant, so we can remove magic number.
211 if (AsmVariant == 0) O << '%';
212 unsigned Reg = MO.getReg();
213 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
214 MVT::SimpleValueType VT = (strcmp(Modifier+6,"64") == 0) ?
215 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
216 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
217 Reg = getX86SubSuperRegister(Reg, VT);
218 }
219 O << X86ATTInstPrinter::getRegisterName(Reg);
220 return;
221 }
222
223 case MachineOperand::MO_Immediate:
224 if (AsmVariant == 0) O << '$';
225 O << MO.getImm();
226 return;
227
228 case MachineOperand::MO_GlobalAddress: {
229 if (AsmVariant == 0) O << '$';
230 printSymbolOperand(P, MO, O);
231 break;
232 }
233 }
234 }
235
printLeaMemReference(X86AsmPrinter & P,const MachineInstr * MI,unsigned Op,raw_ostream & O,const char * Modifier=nullptr)236 static void printLeaMemReference(X86AsmPrinter &P, const MachineInstr *MI,
237 unsigned Op, raw_ostream &O,
238 const char *Modifier = nullptr) {
239 const MachineOperand &BaseReg = MI->getOperand(Op+X86::AddrBaseReg);
240 const MachineOperand &IndexReg = MI->getOperand(Op+X86::AddrIndexReg);
241 const MachineOperand &DispSpec = MI->getOperand(Op+X86::AddrDisp);
242
243 // If we really don't want to print out (rip), don't.
244 bool HasBaseReg = BaseReg.getReg() != 0;
245 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
246 BaseReg.getReg() == X86::RIP)
247 HasBaseReg = false;
248
249 // HasParenPart - True if we will print out the () part of the mem ref.
250 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
251
252 switch (DispSpec.getType()) {
253 default:
254 llvm_unreachable("unknown operand type!");
255 case MachineOperand::MO_Immediate: {
256 int DispVal = DispSpec.getImm();
257 if (DispVal || !HasParenPart)
258 O << DispVal;
259 break;
260 }
261 case MachineOperand::MO_GlobalAddress:
262 case MachineOperand::MO_ConstantPoolIndex:
263 printSymbolOperand(P, DispSpec, O);
264 }
265
266 if (Modifier && strcmp(Modifier, "H") == 0)
267 O << "+8";
268
269 if (HasParenPart) {
270 assert(IndexReg.getReg() != X86::ESP &&
271 "X86 doesn't allow scaling by ESP");
272
273 O << '(';
274 if (HasBaseReg)
275 printOperand(P, MI, Op+X86::AddrBaseReg, O, Modifier);
276
277 if (IndexReg.getReg()) {
278 O << ',';
279 printOperand(P, MI, Op+X86::AddrIndexReg, O, Modifier);
280 unsigned ScaleVal = MI->getOperand(Op+X86::AddrScaleAmt).getImm();
281 if (ScaleVal != 1)
282 O << ',' << ScaleVal;
283 }
284 O << ')';
285 }
286 }
287
printMemReference(X86AsmPrinter & P,const MachineInstr * MI,unsigned Op,raw_ostream & O,const char * Modifier=nullptr)288 static void printMemReference(X86AsmPrinter &P, const MachineInstr *MI,
289 unsigned Op, raw_ostream &O,
290 const char *Modifier = nullptr) {
291 assert(isMem(MI, Op) && "Invalid memory reference!");
292 const MachineOperand &Segment = MI->getOperand(Op+X86::AddrSegmentReg);
293 if (Segment.getReg()) {
294 printOperand(P, MI, Op+X86::AddrSegmentReg, O, Modifier);
295 O << ':';
296 }
297 printLeaMemReference(P, MI, Op, O, Modifier);
298 }
299
printIntelMemReference(X86AsmPrinter & P,const MachineInstr * MI,unsigned Op,raw_ostream & O,const char * Modifier=nullptr,unsigned AsmVariant=1)300 static void printIntelMemReference(X86AsmPrinter &P, const MachineInstr *MI,
301 unsigned Op, raw_ostream &O,
302 const char *Modifier = nullptr,
303 unsigned AsmVariant = 1) {
304 const MachineOperand &BaseReg = MI->getOperand(Op+X86::AddrBaseReg);
305 unsigned ScaleVal = MI->getOperand(Op+X86::AddrScaleAmt).getImm();
306 const MachineOperand &IndexReg = MI->getOperand(Op+X86::AddrIndexReg);
307 const MachineOperand &DispSpec = MI->getOperand(Op+X86::AddrDisp);
308 const MachineOperand &SegReg = MI->getOperand(Op+X86::AddrSegmentReg);
309
310 // If this has a segment register, print it.
311 if (SegReg.getReg()) {
312 printOperand(P, MI, Op+X86::AddrSegmentReg, O, Modifier, AsmVariant);
313 O << ':';
314 }
315
316 O << '[';
317
318 bool NeedPlus = false;
319 if (BaseReg.getReg()) {
320 printOperand(P, MI, Op+X86::AddrBaseReg, O, Modifier, AsmVariant);
321 NeedPlus = true;
322 }
323
324 if (IndexReg.getReg()) {
325 if (NeedPlus) O << " + ";
326 if (ScaleVal != 1)
327 O << ScaleVal << '*';
328 printOperand(P, MI, Op+X86::AddrIndexReg, O, Modifier, AsmVariant);
329 NeedPlus = true;
330 }
331
332 if (!DispSpec.isImm()) {
333 if (NeedPlus) O << " + ";
334 printOperand(P, MI, Op+X86::AddrDisp, O, Modifier, AsmVariant);
335 } else {
336 int64_t DispVal = DispSpec.getImm();
337 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg())) {
338 if (NeedPlus) {
339 if (DispVal > 0)
340 O << " + ";
341 else {
342 O << " - ";
343 DispVal = -DispVal;
344 }
345 }
346 O << DispVal;
347 }
348 }
349 O << ']';
350 }
351
printAsmMRegister(X86AsmPrinter & P,const MachineOperand & MO,char Mode,raw_ostream & O)352 static bool printAsmMRegister(X86AsmPrinter &P, const MachineOperand &MO,
353 char Mode, raw_ostream &O) {
354 unsigned Reg = MO.getReg();
355 switch (Mode) {
356 default: return true; // Unknown mode.
357 case 'b': // Print QImode register
358 Reg = getX86SubSuperRegister(Reg, MVT::i8);
359 break;
360 case 'h': // Print QImode high register
361 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
362 break;
363 case 'w': // Print HImode register
364 Reg = getX86SubSuperRegister(Reg, MVT::i16);
365 break;
366 case 'k': // Print SImode register
367 Reg = getX86SubSuperRegister(Reg, MVT::i32);
368 break;
369 case 'q':
370 // Print 64-bit register names if 64-bit integer registers are available.
371 // Otherwise, print 32-bit register names.
372 MVT::SimpleValueType Ty = P.getSubtarget().is64Bit() ? MVT::i64 : MVT::i32;
373 Reg = getX86SubSuperRegister(Reg, Ty);
374 break;
375 }
376
377 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
378 return false;
379 }
380
381 /// PrintAsmOperand - Print out an operand for an inline asm expression.
382 ///
PrintAsmOperand(const MachineInstr * MI,unsigned OpNo,unsigned AsmVariant,const char * ExtraCode,raw_ostream & O)383 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
384 unsigned AsmVariant,
385 const char *ExtraCode, raw_ostream &O) {
386 // Does this asm operand have a single letter operand modifier?
387 if (ExtraCode && ExtraCode[0]) {
388 if (ExtraCode[1] != 0) return true; // Unknown modifier.
389
390 const MachineOperand &MO = MI->getOperand(OpNo);
391
392 switch (ExtraCode[0]) {
393 default:
394 // See if this is a generic print operand
395 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
396 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
397 switch (MO.getType()) {
398 default:
399 return true;
400 case MachineOperand::MO_Immediate:
401 O << MO.getImm();
402 return false;
403 case MachineOperand::MO_ConstantPoolIndex:
404 case MachineOperand::MO_JumpTableIndex:
405 case MachineOperand::MO_ExternalSymbol:
406 llvm_unreachable("unexpected operand type!");
407 case MachineOperand::MO_GlobalAddress:
408 printSymbolOperand(*this, MO, O);
409 if (Subtarget->isPICStyleRIPRel())
410 O << "(%rip)";
411 return false;
412 case MachineOperand::MO_Register:
413 O << '(';
414 printOperand(*this, MI, OpNo, O);
415 O << ')';
416 return false;
417 }
418
419 case 'c': // Don't print "$" before a global var name or constant.
420 switch (MO.getType()) {
421 default:
422 printOperand(*this, MI, OpNo, O);
423 break;
424 case MachineOperand::MO_Immediate:
425 O << MO.getImm();
426 break;
427 case MachineOperand::MO_ConstantPoolIndex:
428 case MachineOperand::MO_JumpTableIndex:
429 case MachineOperand::MO_ExternalSymbol:
430 llvm_unreachable("unexpected operand type!");
431 case MachineOperand::MO_GlobalAddress:
432 printSymbolOperand(*this, MO, O);
433 break;
434 }
435 return false;
436
437 case 'A': // Print '*' before a register (it must be a register)
438 if (MO.isReg()) {
439 O << '*';
440 printOperand(*this, MI, OpNo, O);
441 return false;
442 }
443 return true;
444
445 case 'b': // Print QImode register
446 case 'h': // Print QImode high register
447 case 'w': // Print HImode register
448 case 'k': // Print SImode register
449 case 'q': // Print DImode register
450 if (MO.isReg())
451 return printAsmMRegister(*this, MO, ExtraCode[0], O);
452 printOperand(*this, MI, OpNo, O);
453 return false;
454
455 case 'P': // This is the operand of a call, treat specially.
456 printPCRelImm(*this, MI, OpNo, O);
457 return false;
458
459 case 'n': // Negate the immediate or print a '-' before the operand.
460 // Note: this is a temporary solution. It should be handled target
461 // independently as part of the 'MC' work.
462 if (MO.isImm()) {
463 O << -MO.getImm();
464 return false;
465 }
466 O << '-';
467 }
468 }
469
470 printOperand(*this, MI, OpNo, O, /*Modifier*/ nullptr, AsmVariant);
471 return false;
472 }
473
PrintAsmMemoryOperand(const MachineInstr * MI,unsigned OpNo,unsigned AsmVariant,const char * ExtraCode,raw_ostream & O)474 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
475 unsigned OpNo, unsigned AsmVariant,
476 const char *ExtraCode,
477 raw_ostream &O) {
478 if (AsmVariant) {
479 printIntelMemReference(*this, MI, OpNo, O);
480 return false;
481 }
482
483 if (ExtraCode && ExtraCode[0]) {
484 if (ExtraCode[1] != 0) return true; // Unknown modifier.
485
486 switch (ExtraCode[0]) {
487 default: return true; // Unknown modifier.
488 case 'b': // Print QImode register
489 case 'h': // Print QImode high register
490 case 'w': // Print HImode register
491 case 'k': // Print SImode register
492 case 'q': // Print SImode register
493 // These only apply to registers, ignore on mem.
494 break;
495 case 'H':
496 printMemReference(*this, MI, OpNo, O, "H");
497 return false;
498 case 'P': // Don't print @PLT, but do print as memory.
499 printMemReference(*this, MI, OpNo, O, "no-rip");
500 return false;
501 }
502 }
503 printMemReference(*this, MI, OpNo, O);
504 return false;
505 }
506
EmitStartOfAsmFile(Module & M)507 void X86AsmPrinter::EmitStartOfAsmFile(Module &M) {
508 if (Subtarget->isTargetMachO())
509 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
510
511 if (Subtarget->isTargetCOFF()) {
512 // Emit an absolute @feat.00 symbol. This appears to be some kind of
513 // compiler features bitfield read by link.exe.
514 if (!Subtarget->is64Bit()) {
515 MCSymbol *S = MMI->getContext().GetOrCreateSymbol(StringRef("@feat.00"));
516 OutStreamer.BeginCOFFSymbolDef(S);
517 OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
518 OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
519 OutStreamer.EndCOFFSymbolDef();
520 // According to the PE-COFF spec, the LSB of this value marks the object
521 // for "registered SEH". This means that all SEH handler entry points
522 // must be registered in .sxdata. Use of any unregistered handlers will
523 // cause the process to terminate immediately. LLVM does not know how to
524 // register any SEH handlers, so its object files should be safe.
525 S->setAbsolute();
526 OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
527 OutStreamer.EmitAssignment(
528 S, MCConstantExpr::Create(int64_t(1), MMI->getContext()));
529 }
530 }
531 }
532
533 static void
emitNonLazySymbolPointer(MCStreamer & OutStreamer,MCSymbol * StubLabel,MachineModuleInfoImpl::StubValueTy & MCSym)534 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
535 MachineModuleInfoImpl::StubValueTy &MCSym) {
536 // L_foo$stub:
537 OutStreamer.EmitLabel(StubLabel);
538 // .indirect_symbol _foo
539 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
540
541 if (MCSym.getInt())
542 // External to current translation unit.
543 OutStreamer.EmitIntValue(0, 4/*size*/);
544 else
545 // Internal to current translation unit.
546 //
547 // When we place the LSDA into the TEXT section, the type info
548 // pointers need to be indirect and pc-rel. We accomplish this by
549 // using NLPs; however, sometimes the types are local to the file.
550 // We need to fill in the value for the NLP in those cases.
551 OutStreamer.EmitValue(
552 MCSymbolRefExpr::Create(MCSym.getPointer(), OutStreamer.getContext()),
553 4 /*size*/);
554 }
555
GetCPISymbol(unsigned CPID) const556 MCSymbol *X86AsmPrinter::GetCPISymbol(unsigned CPID) const {
557 if (Subtarget->isTargetKnownWindowsMSVC()) {
558 const MachineConstantPoolEntry &CPE =
559 MF->getConstantPool()->getConstants()[CPID];
560 if (!CPE.isMachineConstantPoolEntry()) {
561 SectionKind Kind =
562 CPE.getSectionKind(TM.getSubtargetImpl()->getDataLayout());
563 const Constant *C = CPE.Val.ConstVal;
564 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
565 getObjFileLowering().getSectionForConstant(Kind, C))) {
566 if (MCSymbol *Sym = S->getCOMDATSymbol()) {
567 if (Sym->isUndefined())
568 OutStreamer.EmitSymbolAttribute(Sym, MCSA_Global);
569 return Sym;
570 }
571 }
572 }
573 }
574
575 return AsmPrinter::GetCPISymbol(CPID);
576 }
577
GenerateExportDirective(const MCSymbol * Sym,bool IsData)578 void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
579 SmallString<128> Directive;
580 raw_svector_ostream OS(Directive);
581 StringRef Name = Sym->getName();
582
583 if (Subtarget->isTargetKnownWindowsMSVC())
584 OS << " /EXPORT:";
585 else
586 OS << " -export:";
587
588 if ((Subtarget->isTargetWindowsGNU() || Subtarget->isTargetWindowsCygwin()) &&
589 (Name[0] == getDataLayout().getGlobalPrefix()))
590 Name = Name.drop_front();
591
592 OS << Name;
593
594 if (IsData) {
595 if (Subtarget->isTargetKnownWindowsMSVC())
596 OS << ",DATA";
597 else
598 OS << ",data";
599 }
600
601 OS.flush();
602 OutStreamer.EmitBytes(Directive);
603 }
604
EmitEndOfAsmFile(Module & M)605 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
606 if (Subtarget->isTargetMachO()) {
607 // All darwin targets use mach-o.
608 MachineModuleInfoMachO &MMIMacho =
609 MMI->getObjFileInfo<MachineModuleInfoMachO>();
610
611 // Output stubs for dynamically-linked functions.
612 MachineModuleInfoMachO::SymbolListTy Stubs;
613
614 Stubs = MMIMacho.GetFnStubList();
615 if (!Stubs.empty()) {
616 const MCSection *TheSection =
617 OutContext.getMachOSection("__IMPORT", "__jump_table",
618 MachO::S_SYMBOL_STUBS |
619 MachO::S_ATTR_SELF_MODIFYING_CODE |
620 MachO::S_ATTR_PURE_INSTRUCTIONS,
621 5, SectionKind::getMetadata());
622 OutStreamer.SwitchSection(TheSection);
623
624 for (const auto &Stub : Stubs) {
625 // L_foo$stub:
626 OutStreamer.EmitLabel(Stub.first);
627 // .indirect_symbol _foo
628 OutStreamer.EmitSymbolAttribute(Stub.second.getPointer(),
629 MCSA_IndirectSymbol);
630 // hlt; hlt; hlt; hlt; hlt hlt = 0xf4.
631 const char HltInsts[] = "\xf4\xf4\xf4\xf4\xf4";
632 OutStreamer.EmitBytes(StringRef(HltInsts, 5));
633 }
634
635 Stubs.clear();
636 OutStreamer.AddBlankLine();
637 }
638
639 // Output stubs for external and common global variables.
640 Stubs = MMIMacho.GetGVStubList();
641 if (!Stubs.empty()) {
642 const MCSection *TheSection =
643 OutContext.getMachOSection("__IMPORT", "__pointers",
644 MachO::S_NON_LAZY_SYMBOL_POINTERS,
645 SectionKind::getMetadata());
646 OutStreamer.SwitchSection(TheSection);
647
648 for (auto &Stub : Stubs)
649 emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
650
651 Stubs.clear();
652 OutStreamer.AddBlankLine();
653 }
654
655 Stubs = MMIMacho.GetHiddenGVStubList();
656 if (!Stubs.empty()) {
657 const MCSection *TheSection =
658 OutContext.getMachOSection("__IMPORT", "__pointers",
659 MachO::S_NON_LAZY_SYMBOL_POINTERS,
660 SectionKind::getMetadata());
661 OutStreamer.SwitchSection(TheSection);
662
663 for (auto &Stub : Stubs)
664 emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
665
666 Stubs.clear();
667 OutStreamer.AddBlankLine();
668 }
669
670 SM.serializeToStackMapSection();
671
672 // Funny Darwin hack: This flag tells the linker that no global symbols
673 // contain code that falls through to other global symbols (e.g. the obvious
674 // implementation of multiple entry points). If this doesn't occur, the
675 // linker can safely perform dead code stripping. Since LLVM never
676 // generates code that does this, it is always safe to set.
677 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
678 }
679
680 if (Subtarget->isTargetKnownWindowsMSVC() && MMI->usesVAFloatArgument()) {
681 StringRef SymbolName = Subtarget->is64Bit() ? "_fltused" : "__fltused";
682 MCSymbol *S = MMI->getContext().GetOrCreateSymbol(SymbolName);
683 OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
684 }
685
686 if (Subtarget->isTargetCOFF()) {
687 // Necessary for dllexport support
688 std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
689
690 for (const auto &Function : M)
691 if (Function.hasDLLExportStorageClass() && !Function.isDeclaration())
692 DLLExportedFns.push_back(getSymbol(&Function));
693
694 for (const auto &Global : M.globals())
695 if (Global.hasDLLExportStorageClass() && !Global.isDeclaration())
696 DLLExportedGlobals.push_back(getSymbol(&Global));
697
698 for (const auto &Alias : M.aliases()) {
699 if (!Alias.hasDLLExportStorageClass())
700 continue;
701
702 if (Alias.getType()->getElementType()->isFunctionTy())
703 DLLExportedFns.push_back(getSymbol(&Alias));
704 else
705 DLLExportedGlobals.push_back(getSymbol(&Alias));
706 }
707
708 // Output linker support code for dllexported globals on windows.
709 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
710 const TargetLoweringObjectFileCOFF &TLOFCOFF =
711 static_cast<const TargetLoweringObjectFileCOFF&>(getObjFileLowering());
712
713 OutStreamer.SwitchSection(TLOFCOFF.getDrectveSection());
714
715 for (auto & Symbol : DLLExportedGlobals)
716 GenerateExportDirective(Symbol, /*IsData=*/true);
717 for (auto & Symbol : DLLExportedFns)
718 GenerateExportDirective(Symbol, /*IsData=*/false);
719 }
720 }
721
722 if (Subtarget->isTargetELF()) {
723 const TargetLoweringObjectFileELF &TLOFELF =
724 static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
725
726 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
727
728 // Output stubs for external and common global variables.
729 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
730 if (!Stubs.empty()) {
731 OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
732 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
733
734 for (const auto &Stub : Stubs) {
735 OutStreamer.EmitLabel(Stub.first);
736 OutStreamer.EmitSymbolValue(Stub.second.getPointer(),
737 TD->getPointerSize());
738 }
739 Stubs.clear();
740 }
741
742 SM.serializeToStackMapSection();
743 }
744 }
745
746 //===----------------------------------------------------------------------===//
747 // Target Registry Stuff
748 //===----------------------------------------------------------------------===//
749
750 // Force static initialization.
LLVMInitializeX86AsmPrinter()751 extern "C" void LLVMInitializeX86AsmPrinter() {
752 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
753 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
754 }
755