1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
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 implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/CodeGen/GCMetadataPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBundle.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/DebugInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCSection.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/Utils/GlobalStatus.h"
53 #include "WinCodeViewLineTables.h"
56 static const char *const DWARFGroupName = "DWARF Emission";
57 static const char *const DbgTimerName = "Debug Info Emission";
58 static const char *const EHTimerName = "DWARF Exception Writer";
59 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
61 STATISTIC(EmittedInsts, "Number of machine instrs printed");
63 char AsmPrinter::ID = 0;
65 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
66 static gcp_map_type &getGCMap(void *&P) {
68 P = new gcp_map_type();
69 return *(gcp_map_type*)P;
73 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
74 /// value in log2 form. This rounds up to the preferred alignment if possible
76 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
77 unsigned InBits = 0) {
79 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
80 NumBits = TD.getPreferredAlignmentLog(GVar);
82 // If InBits is specified, round it to it.
86 // If the GV has a specified alignment, take it into account.
87 if (GV->getAlignment() == 0)
90 unsigned GVAlign = Log2_32(GV->getAlignment());
92 // If the GVAlign is larger than NumBits, or if we are required to obey
93 // NumBits because the GV has an assigned section, obey it.
94 if (GVAlign > NumBits || GV->hasSection())
99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
100 : MachineFunctionPass(ID),
101 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
102 OutContext(Streamer.getContext()),
103 OutStreamer(Streamer),
104 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105 DD = 0; MMI = 0; LI = 0; MF = 0;
106 CurrentFnSym = CurrentFnSymForSize = 0;
107 GCMetadataPrinters = 0;
108 VerboseAsm = Streamer.isVerboseAsm();
111 AsmPrinter::~AsmPrinter() {
112 assert(DD == 0 && Handlers.empty() && "Debug/EH info didn't get finalized");
114 if (GCMetadataPrinters != 0) {
115 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
117 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
120 GCMetadataPrinters = 0;
126 /// getFunctionNumber - Return a unique ID for the current function.
128 unsigned AsmPrinter::getFunctionNumber() const {
129 return MF->getFunctionNumber();
132 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
133 return TM.getTargetLowering()->getObjFileLowering();
136 /// getDataLayout - Return information about data layout.
137 const DataLayout &AsmPrinter::getDataLayout() const {
138 return *TM.getDataLayout();
141 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
142 return TM.getSubtarget<MCSubtargetInfo>();
145 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
146 S.EmitInstruction(Inst, getSubtargetInfo());
149 StringRef AsmPrinter::getTargetTriple() const {
150 return TM.getTargetTriple();
153 /// getCurrentSection() - Return the current section we are emitting to.
154 const MCSection *AsmPrinter::getCurrentSection() const {
155 return OutStreamer.getCurrentSection().first;
160 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
161 AU.setPreservesAll();
162 MachineFunctionPass::getAnalysisUsage(AU);
163 AU.addRequired<MachineModuleInfo>();
164 AU.addRequired<GCModuleInfo>();
166 AU.addRequired<MachineLoopInfo>();
169 bool AsmPrinter::doInitialization(Module &M) {
170 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
171 MMI->AnalyzeModule(M);
173 // Initialize TargetLoweringObjectFile.
174 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
175 .Initialize(OutContext, TM);
177 OutStreamer.InitSections(false);
179 Mang = new Mangler(TM.getDataLayout());
181 // Allow the target to emit any magic that it wants at the start of the file.
182 EmitStartOfAsmFile(M);
184 // Very minimal debug info. It is ignored if we emit actual debug info. If we
185 // don't, this at least helps the user find where a global came from.
186 if (MAI->hasSingleParameterDotFile()) {
188 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
191 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
192 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
193 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
194 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
195 MP->beginAssembly(*this);
197 // Emit module-level inline asm if it exists.
198 if (!M.getModuleInlineAsm().empty()) {
199 OutStreamer.AddComment("Start of file scope inline assembly");
200 OutStreamer.AddBlankLine();
201 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
202 OutStreamer.AddComment("End of file scope inline assembly");
203 OutStreamer.AddBlankLine();
206 if (MAI->doesSupportDebugInformation()) {
207 if (Triple(TM.getTargetTriple()).getOS() == Triple::Win32) {
208 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
210 CodeViewLineTablesGroupName));
212 DD = new DwarfDebug(this, &M);
213 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
217 DwarfException *DE = 0;
218 switch (MAI->getExceptionHandlingType()) {
219 case ExceptionHandling::None:
221 case ExceptionHandling::SjLj:
222 case ExceptionHandling::DwarfCFI:
223 DE = new DwarfCFIException(this);
225 case ExceptionHandling::ARM:
226 DE = new ARMException(this);
228 case ExceptionHandling::Win64:
229 DE = new Win64Exception(this);
233 Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
237 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
238 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
240 case GlobalValue::CommonLinkage:
241 case GlobalValue::LinkOnceAnyLinkage:
242 case GlobalValue::LinkOnceODRLinkage:
243 case GlobalValue::WeakAnyLinkage:
244 case GlobalValue::WeakODRLinkage:
245 case GlobalValue::LinkerPrivateWeakLinkage:
246 if (MAI->hasWeakDefDirective()) {
248 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
250 bool CanBeHidden = false;
252 if (Linkage == GlobalValue::LinkOnceODRLinkage &&
253 MAI->hasWeakDefCanBeHiddenDirective()) {
254 if (GV->hasUnnamedAddr()) {
258 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
264 // .weak_definition _foo
265 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
267 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
268 } else if (MAI->hasLinkOnceDirective()) {
270 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
271 //NOTE: linkonce is handled by the section the symbol was assigned to.
274 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
277 case GlobalValue::AppendingLinkage:
278 // FIXME: appending linkage variables should go into a section of
279 // their name or something. For now, just emit them as external.
280 case GlobalValue::ExternalLinkage:
281 // If external or appending, declare as a global symbol.
283 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
285 case GlobalValue::PrivateLinkage:
286 case GlobalValue::InternalLinkage:
287 case GlobalValue::LinkerPrivateLinkage:
289 case GlobalValue::AvailableExternallyLinkage:
290 llvm_unreachable("Should never emit this");
291 case GlobalValue::ExternalWeakLinkage:
292 llvm_unreachable("Don't know how to emit these");
294 llvm_unreachable("Unknown linkage type!");
297 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
298 return getObjFileLowering().getSymbol(*Mang, GV);
301 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
302 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
303 if (GV->hasInitializer()) {
304 // Check to see if this is a special global used by LLVM, if so, emit it.
305 if (EmitSpecialLLVMGlobal(GV))
309 GV->printAsOperand(OutStreamer.GetCommentOS(),
310 /*PrintType=*/false, GV->getParent());
311 OutStreamer.GetCommentOS() << '\n';
315 MCSymbol *GVSym = getSymbol(GV);
316 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
318 if (!GV->hasInitializer()) // External globals require no extra code.
321 if (MAI->hasDotTypeDotSizeDirective())
322 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
324 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
326 const DataLayout *DL = TM.getDataLayout();
327 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
329 // If the alignment is specified, we *must* obey it. Overaligning a global
330 // with a specified alignment is a prompt way to break globals emitted to
331 // sections and expected to be contiguous (e.g. ObjC metadata).
332 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
334 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
335 const HandlerInfo &OI = Handlers[I];
336 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
337 OI.Handler->setSymbolSize(GVSym, Size);
340 // Handle common and BSS local symbols (.lcomm).
341 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
342 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
343 unsigned Align = 1 << AlignLog;
345 // Handle common symbols.
346 if (GVKind.isCommon()) {
347 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
351 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
355 // Handle local BSS symbols.
356 if (MAI->hasMachoZeroFillDirective()) {
357 const MCSection *TheSection =
358 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
359 // .zerofill __DATA, __bss, _foo, 400, 5
360 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
364 // Use .lcomm only if it supports user-specified alignment.
365 // Otherwise, while it would still be correct to use .lcomm in some
366 // cases (e.g. when Align == 1), the external assembler might enfore
367 // some -unknown- default alignment behavior, which could cause
368 // spurious differences between external and integrated assembler.
369 // Prefer to simply fall back to .local / .comm in this case.
370 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
372 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
376 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
380 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
382 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
386 const MCSection *TheSection =
387 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
389 // Handle the zerofill directive on darwin, which is a special form of BSS
391 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
392 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
395 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
396 // .zerofill __DATA, __common, _foo, 400, 5
397 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
401 // Handle thread local data for mach-o which requires us to output an
402 // additional structure of data and mangle the original symbol so that we
403 // can reference it later.
405 // TODO: This should become an "emit thread local global" method on TLOF.
406 // All of this macho specific stuff should be sunk down into TLOFMachO and
407 // stuff like "TLSExtraDataSection" should no longer be part of the parent
408 // TLOF class. This will also make it more obvious that stuff like
409 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
411 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
412 // Emit the .tbss symbol
414 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
416 if (GVKind.isThreadBSS()) {
417 TheSection = getObjFileLowering().getTLSBSSSection();
418 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
419 } else if (GVKind.isThreadData()) {
420 OutStreamer.SwitchSection(TheSection);
422 EmitAlignment(AlignLog, GV);
423 OutStreamer.EmitLabel(MangSym);
425 EmitGlobalConstant(GV->getInitializer());
428 OutStreamer.AddBlankLine();
430 // Emit the variable struct for the runtime.
431 const MCSection *TLVSect
432 = getObjFileLowering().getTLSExtraDataSection();
434 OutStreamer.SwitchSection(TLVSect);
435 // Emit the linkage here.
436 EmitLinkage(GV, GVSym);
437 OutStreamer.EmitLabel(GVSym);
439 // Three pointers in size:
440 // - __tlv_bootstrap - used to make sure support exists
441 // - spare pointer, used when mapped by the runtime
442 // - pointer to mangled symbol above with initializer
443 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
444 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
446 OutStreamer.EmitIntValue(0, PtrSize);
447 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
449 OutStreamer.AddBlankLine();
453 OutStreamer.SwitchSection(TheSection);
455 EmitLinkage(GV, GVSym);
456 EmitAlignment(AlignLog, GV);
458 OutStreamer.EmitLabel(GVSym);
460 EmitGlobalConstant(GV->getInitializer());
462 if (MAI->hasDotTypeDotSizeDirective())
464 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
466 OutStreamer.AddBlankLine();
469 /// EmitFunctionHeader - This method emits the header for the current
471 void AsmPrinter::EmitFunctionHeader() {
472 // Print out constants referenced by the function
475 // Print the 'header' of function.
476 const Function *F = MF->getFunction();
478 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
479 EmitVisibility(CurrentFnSym, F->getVisibility());
481 EmitLinkage(F, CurrentFnSym);
482 EmitAlignment(MF->getAlignment(), F);
484 if (MAI->hasDotTypeDotSizeDirective())
485 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
488 F->printAsOperand(OutStreamer.GetCommentOS(),
489 /*PrintType=*/false, F->getParent());
490 OutStreamer.GetCommentOS() << '\n';
493 // Emit the CurrentFnSym. This is a virtual function to allow targets to
494 // do their wild and crazy things as required.
495 EmitFunctionEntryLabel();
497 // If the function had address-taken blocks that got deleted, then we have
498 // references to the dangling symbols. Emit them at the start of the function
499 // so that we don't get references to undefined symbols.
500 std::vector<MCSymbol*> DeadBlockSyms;
501 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
502 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
503 OutStreamer.AddComment("Address taken block that was later removed");
504 OutStreamer.EmitLabel(DeadBlockSyms[i]);
507 // Emit pre-function debug and/or EH information.
508 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
509 const HandlerInfo &OI = Handlers[I];
510 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
511 OI.Handler->beginFunction(MF);
514 // Emit the prefix data.
515 if (F->hasPrefixData())
516 EmitGlobalConstant(F->getPrefixData());
519 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
520 /// function. This can be overridden by targets as required to do custom stuff.
521 void AsmPrinter::EmitFunctionEntryLabel() {
522 // The function label could have already been emitted if two symbols end up
523 // conflicting due to asm renaming. Detect this and emit an error.
524 if (CurrentFnSym->isUndefined())
525 return OutStreamer.EmitLabel(CurrentFnSym);
527 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
528 "' label emitted multiple times to assembly file");
531 /// emitComments - Pretty-print comments for instructions.
532 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
533 const MachineFunction *MF = MI.getParent()->getParent();
534 const TargetMachine &TM = MF->getTarget();
536 // Check for spills and reloads
539 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
541 // We assume a single instruction only has a spill or reload, not
543 const MachineMemOperand *MMO;
544 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
545 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
546 MMO = *MI.memoperands_begin();
547 CommentOS << MMO->getSize() << "-byte Reload\n";
549 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
550 if (FrameInfo->isSpillSlotObjectIndex(FI))
551 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
552 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
553 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
554 MMO = *MI.memoperands_begin();
555 CommentOS << MMO->getSize() << "-byte Spill\n";
557 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
558 if (FrameInfo->isSpillSlotObjectIndex(FI))
559 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
562 // Check for spill-induced copies
563 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
564 CommentOS << " Reload Reuse\n";
567 /// emitImplicitDef - This method emits the specified machine instruction
568 /// that is an implicit def.
569 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
570 unsigned RegNo = MI->getOperand(0).getReg();
571 OutStreamer.AddComment(Twine("implicit-def: ") +
572 TM.getRegisterInfo()->getName(RegNo));
573 OutStreamer.AddBlankLine();
576 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
577 std::string Str = "kill:";
578 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
579 const MachineOperand &Op = MI->getOperand(i);
580 assert(Op.isReg() && "KILL instruction must have only register operands");
582 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
583 Str += (Op.isDef() ? "<def>" : "<kill>");
585 AP.OutStreamer.AddComment(Str);
586 AP.OutStreamer.AddBlankLine();
589 /// emitDebugValueComment - This method handles the target-independent form
590 /// of DBG_VALUE, returning true if it was able to do so. A false return
591 /// means the target will need to handle MI in EmitInstruction.
592 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
593 // This code handles only the 3-operand target-independent form.
594 if (MI->getNumOperands() != 3)
597 SmallString<128> Str;
598 raw_svector_ostream OS(Str);
599 OS << "DEBUG_VALUE: ";
601 DIVariable V(MI->getOperand(2).getMetadata());
602 if (V.getContext().isSubprogram()) {
603 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
607 OS << V.getName() << " <- ";
609 // The second operand is only an offset if it's an immediate.
610 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
611 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
613 // Register or immediate value. Register 0 means undef.
614 if (MI->getOperand(0).isFPImm()) {
615 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
616 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
617 OS << (double)APF.convertToFloat();
618 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
619 OS << APF.convertToDouble();
621 // There is no good way to print long double. Convert a copy to
622 // double. Ah well, it's only a comment.
624 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
626 OS << "(long double) " << APF.convertToDouble();
628 } else if (MI->getOperand(0).isImm()) {
629 OS << MI->getOperand(0).getImm();
630 } else if (MI->getOperand(0).isCImm()) {
631 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
634 if (MI->getOperand(0).isReg()) {
635 Reg = MI->getOperand(0).getReg();
637 assert(MI->getOperand(0).isFI() && "Unknown operand type");
638 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
639 Offset += TFI->getFrameIndexReference(*AP.MF,
640 MI->getOperand(0).getIndex(), Reg);
644 // Suppress offset, it is not meaningful here.
646 // NOTE: Want this comment at start of line, don't emit with AddComment.
647 AP.OutStreamer.emitRawComment(OS.str());
652 OS << AP.TM.getRegisterInfo()->getName(Reg);
656 OS << '+' << Offset << ']';
658 // NOTE: Want this comment at start of line, don't emit with AddComment.
659 AP.OutStreamer.emitRawComment(OS.str());
663 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
664 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
665 MF->getFunction()->needsUnwindTableEntry())
668 if (MMI->hasDebugInfo())
674 bool AsmPrinter::needsSEHMoves() {
675 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
676 MF->getFunction()->needsUnwindTableEntry();
679 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
680 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
682 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
685 if (needsCFIMoves() == CFI_M_None)
688 if (MMI->getCompactUnwindEncoding() != 0)
689 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
691 const MachineModuleInfo &MMI = MF->getMMI();
692 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
693 bool FoundOne = false;
695 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
696 E = Instrs.end(); I != E; ++I) {
697 if (I->getLabel() == Label) {
698 emitCFIInstruction(*I);
705 /// EmitFunctionBody - This method emits the body and trailer for a
707 void AsmPrinter::EmitFunctionBody() {
708 // Emit target-specific gunk before the function body.
709 EmitFunctionBodyStart();
711 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
713 // Print out code for the function.
714 bool HasAnyRealCode = false;
715 const MachineInstr *LastMI = 0;
716 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
718 // Print a label for the basic block.
719 EmitBasicBlockStart(I);
720 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
724 // Print the assembly for the instruction.
725 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
726 !II->isDebugValue()) {
727 HasAnyRealCode = true;
731 if (ShouldPrintDebugScopes) {
732 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
733 const HandlerInfo &OI = Handlers[III];
734 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
735 TimePassesIsEnabled);
736 OI.Handler->beginInstruction(II);
741 emitComments(*II, OutStreamer.GetCommentOS());
743 switch (II->getOpcode()) {
744 case TargetOpcode::PROLOG_LABEL:
745 emitPrologLabel(*II);
748 case TargetOpcode::EH_LABEL:
749 case TargetOpcode::GC_LABEL:
750 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
752 case TargetOpcode::INLINEASM:
755 case TargetOpcode::DBG_VALUE:
757 if (!emitDebugValueComment(II, *this))
761 case TargetOpcode::IMPLICIT_DEF:
762 if (isVerbose()) emitImplicitDef(II);
764 case TargetOpcode::KILL:
765 if (isVerbose()) emitKill(II, *this);
768 if (!TM.hasMCUseLoc())
769 MCLineEntry::Make(&OutStreamer, getCurrentSection());
775 if (ShouldPrintDebugScopes) {
776 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
777 const HandlerInfo &OI = Handlers[III];
778 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
779 TimePassesIsEnabled);
780 OI.Handler->endInstruction();
786 // If the last instruction was a prolog label, then we have a situation where
787 // we emitted a prolog but no function body. This results in the ending prolog
788 // label equaling the end of function label and an invalid "row" in the
789 // FDE. We need to emit a noop in this situation so that the FDE's rows are
791 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
793 // If the function is empty and the object file uses .subsections_via_symbols,
794 // then we need to emit *something* to the function body to prevent the
795 // labels from collapsing together. Just emit a noop.
796 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
798 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
799 if (Noop.getOpcode()) {
800 OutStreamer.AddComment("avoids zero-length function");
801 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
802 } else // Target not mc-ized yet.
803 OutStreamer.EmitRawText(StringRef("\tnop\n"));
806 const Function *F = MF->getFunction();
807 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
808 const BasicBlock *BB = i;
809 if (!BB->hasAddressTaken())
811 MCSymbol *Sym = GetBlockAddressSymbol(BB);
812 if (Sym->isDefined())
814 OutStreamer.AddComment("Address of block that was removed by CodeGen");
815 OutStreamer.EmitLabel(Sym);
818 // Emit target-specific gunk after the function body.
819 EmitFunctionBodyEnd();
821 // If the target wants a .size directive for the size of the function, emit
823 if (MAI->hasDotTypeDotSizeDirective()) {
824 // Create a symbol for the end of function, so we can get the size as
825 // difference between the function label and the temp label.
826 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
827 OutStreamer.EmitLabel(FnEndLabel);
829 const MCExpr *SizeExp =
830 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
831 MCSymbolRefExpr::Create(CurrentFnSymForSize,
834 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
837 // Emit post-function debug and/or EH information.
838 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
839 const HandlerInfo &OI = Handlers[I];
840 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
841 OI.Handler->endFunction(MF);
845 // Print out jump tables referenced by the function.
848 OutStreamer.AddBlankLine();
851 /// EmitDwarfRegOp - Emit dwarf register operation.
852 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
853 bool Indirect) const {
854 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
855 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
857 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
859 Reg = TRI->getDwarfRegNum(*SR, false);
860 // FIXME: Get the bit range this register uses of the superregister
861 // so that we can produce a DW_OP_bit_piece
864 // FIXME: Handle cases like a super register being encoded as
865 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
867 // FIXME: We have no reasonable way of handling errors in here. The
868 // caller might be in the middle of an dwarf expression. We should
869 // probably assert that Reg >= 0 once debug info generation is more mature.
871 if (MLoc.isIndirect() || Indirect) {
873 OutStreamer.AddComment(
874 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
875 EmitInt8(dwarf::DW_OP_breg0 + Reg);
877 OutStreamer.AddComment("DW_OP_bregx");
878 EmitInt8(dwarf::DW_OP_bregx);
879 OutStreamer.AddComment(Twine(Reg));
882 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
883 if (MLoc.isIndirect() && Indirect)
884 EmitInt8(dwarf::DW_OP_deref);
887 OutStreamer.AddComment(
888 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
889 EmitInt8(dwarf::DW_OP_reg0 + Reg);
891 OutStreamer.AddComment("DW_OP_regx");
892 EmitInt8(dwarf::DW_OP_regx);
893 OutStreamer.AddComment(Twine(Reg));
898 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
901 bool AsmPrinter::doFinalization(Module &M) {
902 // Emit global variables.
903 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
905 EmitGlobalVariable(I);
907 // Emit visibility info for declarations
908 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
909 const Function &F = *I;
910 if (!F.isDeclaration())
912 GlobalValue::VisibilityTypes V = F.getVisibility();
913 if (V == GlobalValue::DefaultVisibility)
916 MCSymbol *Name = getSymbol(&F);
917 EmitVisibility(Name, V, false);
920 // Emit module flags.
921 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
922 M.getModuleFlagsMetadata(ModuleFlags);
923 if (!ModuleFlags.empty())
924 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
926 // Make sure we wrote out everything we need.
929 // Finalize debug and EH information.
930 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
931 const HandlerInfo &OI = Handlers[I];
932 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
933 TimePassesIsEnabled);
934 OI.Handler->endModule();
940 // If the target wants to know about weak references, print them all.
941 if (MAI->getWeakRefDirective()) {
942 // FIXME: This is not lazy, it would be nice to only print weak references
943 // to stuff that is actually used. Note that doing so would require targets
944 // to notice uses in operands (due to constant exprs etc). This should
945 // happen with the MC stuff eventually.
947 // Print out module-level global variables here.
948 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
950 if (!I->hasExternalWeakLinkage()) continue;
951 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
954 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
955 if (!I->hasExternalWeakLinkage()) continue;
956 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
960 if (MAI->hasSetDirective()) {
961 OutStreamer.AddBlankLine();
962 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
964 MCSymbol *Name = getSymbol(I);
966 const GlobalValue *GV = I->getAliasedGlobal();
967 if (GV->isDeclaration()) {
968 report_fatal_error(Name->getName() +
969 ": Target doesn't support aliases to declarations");
972 MCSymbol *Target = getSymbol(GV);
974 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
975 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
976 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
977 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
979 assert(I->hasLocalLinkage() && "Invalid alias linkage");
981 EmitVisibility(Name, I->getVisibility());
983 // Emit the directives as assignments aka .set:
984 OutStreamer.EmitAssignment(Name,
985 MCSymbolRefExpr::Create(Target, OutContext));
989 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
990 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
991 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
992 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
993 MP->finishAssembly(*this);
995 // Emit llvm.ident metadata in an '.ident' directive.
998 // If we don't have any trampolines, then we don't require stack memory
999 // to be executable. Some targets have a directive to declare this.
1000 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1001 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1002 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1003 OutStreamer.SwitchSection(S);
1005 // Allow the target to emit any magic that it wants at the end of the file,
1006 // after everything else has gone out.
1007 EmitEndOfAsmFile(M);
1009 delete Mang; Mang = 0;
1012 OutStreamer.Finish();
1013 OutStreamer.reset();
1018 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1020 // Get the function symbol.
1021 CurrentFnSym = getSymbol(MF.getFunction());
1022 CurrentFnSymForSize = CurrentFnSym;
1025 LI = &getAnalysis<MachineLoopInfo>();
1029 // SectionCPs - Keep track the alignment, constpool entries per Section.
1033 SmallVector<unsigned, 4> CPEs;
1034 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1038 /// EmitConstantPool - Print to the current output stream assembly
1039 /// representations of the constants in the constant pool MCP. This is
1040 /// used to print out constants which have been "spilled to memory" by
1041 /// the code generator.
1043 void AsmPrinter::EmitConstantPool() {
1044 const MachineConstantPool *MCP = MF->getConstantPool();
1045 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1046 if (CP.empty()) return;
1048 // Calculate sections for constant pool entries. We collect entries to go into
1049 // the same section together to reduce amount of section switch statements.
1050 SmallVector<SectionCPs, 4> CPSections;
1051 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1052 const MachineConstantPoolEntry &CPE = CP[i];
1053 unsigned Align = CPE.getAlignment();
1056 switch (CPE.getRelocationInfo()) {
1057 default: llvm_unreachable("Unknown section kind");
1058 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1060 Kind = SectionKind::getReadOnlyWithRelLocal();
1063 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1064 case 4: Kind = SectionKind::getMergeableConst4(); break;
1065 case 8: Kind = SectionKind::getMergeableConst8(); break;
1066 case 16: Kind = SectionKind::getMergeableConst16();break;
1067 default: Kind = SectionKind::getMergeableConst(); break;
1071 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1073 // The number of sections are small, just do a linear search from the
1074 // last section to the first.
1076 unsigned SecIdx = CPSections.size();
1077 while (SecIdx != 0) {
1078 if (CPSections[--SecIdx].S == S) {
1084 SecIdx = CPSections.size();
1085 CPSections.push_back(SectionCPs(S, Align));
1088 if (Align > CPSections[SecIdx].Alignment)
1089 CPSections[SecIdx].Alignment = Align;
1090 CPSections[SecIdx].CPEs.push_back(i);
1093 // Now print stuff into the calculated sections.
1094 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1095 OutStreamer.SwitchSection(CPSections[i].S);
1096 EmitAlignment(Log2_32(CPSections[i].Alignment));
1098 unsigned Offset = 0;
1099 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1100 unsigned CPI = CPSections[i].CPEs[j];
1101 MachineConstantPoolEntry CPE = CP[CPI];
1103 // Emit inter-object padding for alignment.
1104 unsigned AlignMask = CPE.getAlignment() - 1;
1105 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1106 OutStreamer.EmitZeros(NewOffset - Offset);
1108 Type *Ty = CPE.getType();
1109 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1110 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1112 if (CPE.isMachineConstantPoolEntry())
1113 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1115 EmitGlobalConstant(CPE.Val.ConstVal);
1120 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1121 /// by the current function to the current output stream.
1123 void AsmPrinter::EmitJumpTableInfo() {
1124 const DataLayout *DL = MF->getTarget().getDataLayout();
1125 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1126 if (MJTI == 0) return;
1127 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1128 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1129 if (JT.empty()) return;
1131 // Pick the directive to use to print the jump table entries, and switch to
1132 // the appropriate section.
1133 const Function *F = MF->getFunction();
1134 bool JTInDiffSection = false;
1135 if (// In PIC mode, we need to emit the jump table to the same section as the
1136 // function body itself, otherwise the label differences won't make sense.
1137 // FIXME: Need a better predicate for this: what about custom entries?
1138 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1139 // We should also do if the section name is NULL or function is declared
1140 // in discardable section
1141 // FIXME: this isn't the right predicate, should be based on the MCSection
1142 // for the function.
1143 F->isWeakForLinker()) {
1144 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1146 // Otherwise, drop it in the readonly section.
1147 const MCSection *ReadOnlySection =
1148 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1149 OutStreamer.SwitchSection(ReadOnlySection);
1150 JTInDiffSection = true;
1153 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1155 // Jump tables in code sections are marked with a data_region directive
1156 // where that's supported.
1157 if (!JTInDiffSection)
1158 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1160 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1161 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1163 // If this jump table was deleted, ignore it.
1164 if (JTBBs.empty()) continue;
1166 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1167 // .set directive for each unique entry. This reduces the number of
1168 // relocations the assembler will generate for the jump table.
1169 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1170 MAI->hasSetDirective()) {
1171 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1172 const TargetLowering *TLI = TM.getTargetLowering();
1173 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1174 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1175 const MachineBasicBlock *MBB = JTBBs[ii];
1176 if (!EmittedSets.insert(MBB)) continue;
1178 // .set LJTSet, LBB32-base
1180 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1181 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1182 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1186 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1187 // before each jump table. The first label is never referenced, but tells
1188 // the assembler and linker the extents of the jump table object. The
1189 // second label is actually referenced by the code.
1190 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1191 // FIXME: This doesn't have to have any specific name, just any randomly
1192 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1193 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1195 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1197 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1198 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1200 if (!JTInDiffSection)
1201 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1204 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1206 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1207 const MachineBasicBlock *MBB,
1208 unsigned UID) const {
1209 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1210 const MCExpr *Value = 0;
1211 switch (MJTI->getEntryKind()) {
1212 case MachineJumpTableInfo::EK_Inline:
1213 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1214 case MachineJumpTableInfo::EK_Custom32:
1215 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1218 case MachineJumpTableInfo::EK_BlockAddress:
1219 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1221 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1223 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1224 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1225 // with a relocation as gp-relative, e.g.:
1227 MCSymbol *MBBSym = MBB->getSymbol();
1228 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1232 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1233 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1234 // with a relocation as gp-relative, e.g.:
1236 MCSymbol *MBBSym = MBB->getSymbol();
1237 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1241 case MachineJumpTableInfo::EK_LabelDifference32: {
1242 // EK_LabelDifference32 - Each entry is the address of the block minus
1243 // the address of the jump table. This is used for PIC jump tables where
1244 // gprel32 is not supported. e.g.:
1245 // .word LBB123 - LJTI1_2
1246 // If the .set directive is supported, this is emitted as:
1247 // .set L4_5_set_123, LBB123 - LJTI1_2
1248 // .word L4_5_set_123
1250 // If we have emitted set directives for the jump table entries, print
1251 // them rather than the entries themselves. If we're emitting PIC, then
1252 // emit the table entries as differences between two text section labels.
1253 if (MAI->hasSetDirective()) {
1254 // If we used .set, reference the .set's symbol.
1255 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1259 // Otherwise, use the difference as the jump table entry.
1260 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1261 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1262 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1267 assert(Value && "Unknown entry kind!");
1269 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1270 OutStreamer.EmitValue(Value, EntrySize);
1274 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1275 /// special global used by LLVM. If so, emit it and return true, otherwise
1276 /// do nothing and return false.
1277 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1278 if (GV->getName() == "llvm.used") {
1279 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1280 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1284 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1285 if (GV->getSection() == "llvm.metadata" ||
1286 GV->hasAvailableExternallyLinkage())
1289 if (!GV->hasAppendingLinkage()) return false;
1291 assert(GV->hasInitializer() && "Not a special LLVM global!");
1293 if (GV->getName() == "llvm.global_ctors") {
1294 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1296 if (TM.getRelocationModel() == Reloc::Static &&
1297 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1298 StringRef Sym(".constructors_used");
1299 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1305 if (GV->getName() == "llvm.global_dtors") {
1306 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1308 if (TM.getRelocationModel() == Reloc::Static &&
1309 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1310 StringRef Sym(".destructors_used");
1311 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1320 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1321 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1322 /// is true, as being used with this directive.
1323 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1324 // Should be an array of 'i8*'.
1325 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1326 const GlobalValue *GV =
1327 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1328 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1329 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1333 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1335 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1336 // Should be an array of '{ int, void ()* }' structs. The first value is the
1338 if (!isa<ConstantArray>(List)) return;
1340 // Sanity check the structors list.
1341 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1342 if (!InitList) return; // Not an array!
1343 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1344 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1345 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1346 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1348 // Gather the structors in a form that's convenient for sorting by priority.
1349 typedef std::pair<unsigned, Constant *> Structor;
1350 SmallVector<Structor, 8> Structors;
1351 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1352 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1353 if (!CS) continue; // Malformed.
1354 if (CS->getOperand(1)->isNullValue())
1355 break; // Found a null terminator, skip the rest.
1356 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1357 if (!Priority) continue; // Malformed.
1358 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1359 CS->getOperand(1)));
1362 // Emit the function pointers in the target-specific order
1363 const DataLayout *DL = TM.getDataLayout();
1364 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1365 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1366 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1367 const MCSection *OutputSection =
1369 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1370 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1371 OutStreamer.SwitchSection(OutputSection);
1372 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1373 EmitAlignment(Align);
1374 EmitXXStructor(Structors[i].second);
1378 void AsmPrinter::EmitModuleIdents(Module &M) {
1379 if (!MAI->hasIdentDirective())
1382 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1383 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1384 const MDNode *N = NMD->getOperand(i);
1385 assert(N->getNumOperands() == 1 &&
1386 "llvm.ident metadata entry can have only one operand");
1387 const MDString *S = cast<MDString>(N->getOperand(0));
1388 OutStreamer.EmitIdent(S->getString());
1393 //===--------------------------------------------------------------------===//
1394 // Emission and print routines
1397 /// EmitInt8 - Emit a byte directive and value.
1399 void AsmPrinter::EmitInt8(int Value) const {
1400 OutStreamer.EmitIntValue(Value, 1);
1403 /// EmitInt16 - Emit a short directive and value.
1405 void AsmPrinter::EmitInt16(int Value) const {
1406 OutStreamer.EmitIntValue(Value, 2);
1409 /// EmitInt32 - Emit a long directive and value.
1411 void AsmPrinter::EmitInt32(int Value) const {
1412 OutStreamer.EmitIntValue(Value, 4);
1415 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1416 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1417 /// labels. This implicitly uses .set if it is available.
1418 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1419 unsigned Size) const {
1420 // Get the Hi-Lo expression.
1421 const MCExpr *Diff =
1422 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1423 MCSymbolRefExpr::Create(Lo, OutContext),
1426 if (!MAI->hasSetDirective()) {
1427 OutStreamer.EmitValue(Diff, Size);
1431 // Otherwise, emit with .set (aka assignment).
1432 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1433 OutStreamer.EmitAssignment(SetLabel, Diff);
1434 OutStreamer.EmitSymbolValue(SetLabel, Size);
1437 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1438 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1439 /// specify the labels. This implicitly uses .set if it is available.
1440 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1442 unsigned Size) const {
1444 // Emit Hi+Offset - Lo
1445 // Get the Hi+Offset expression.
1446 const MCExpr *Plus =
1447 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1448 MCConstantExpr::Create(Offset, OutContext),
1451 // Get the Hi+Offset-Lo expression.
1452 const MCExpr *Diff =
1453 MCBinaryExpr::CreateSub(Plus,
1454 MCSymbolRefExpr::Create(Lo, OutContext),
1457 if (!MAI->hasSetDirective())
1458 OutStreamer.EmitValue(Diff, Size);
1460 // Otherwise, emit with .set (aka assignment).
1461 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1462 OutStreamer.EmitAssignment(SetLabel, Diff);
1463 OutStreamer.EmitSymbolValue(SetLabel, Size);
1467 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1468 /// where the size in bytes of the directive is specified by Size and Label
1469 /// specifies the label. This implicitly uses .set if it is available.
1470 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1472 bool IsSectionRelative) const {
1473 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1474 OutStreamer.EmitCOFFSecRel32(Label);
1478 // Emit Label+Offset (or just Label if Offset is zero)
1479 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1481 Expr = MCBinaryExpr::CreateAdd(
1482 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1484 OutStreamer.EmitValue(Expr, Size);
1487 //===----------------------------------------------------------------------===//
1489 // EmitAlignment - Emit an alignment directive to the specified power of
1490 // two boundary. For example, if you pass in 3 here, you will get an 8
1491 // byte alignment. If a global value is specified, and if that global has
1492 // an explicit alignment requested, it will override the alignment request
1493 // if required for correctness.
1495 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1496 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1498 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1500 if (getCurrentSection()->getKind().isText())
1501 OutStreamer.EmitCodeAlignment(1 << NumBits);
1503 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1506 //===----------------------------------------------------------------------===//
1507 // Constant emission.
1508 //===----------------------------------------------------------------------===//
1510 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1512 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1513 MCContext &Ctx = AP.OutContext;
1515 if (CV->isNullValue() || isa<UndefValue>(CV))
1516 return MCConstantExpr::Create(0, Ctx);
1518 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1519 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1521 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1522 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1524 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1525 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1527 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1529 llvm_unreachable("Unknown constant value to lower!");
1532 if (const MCExpr *RelocExpr =
1533 AP.getObjFileLowering().getExecutableRelativeSymbol(CE, AP.Mang))
1536 switch (CE->getOpcode()) {
1538 // If the code isn't optimized, there may be outstanding folding
1539 // opportunities. Attempt to fold the expression using DataLayout as a
1540 // last resort before giving up.
1542 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1544 return lowerConstant(C, AP);
1546 // Otherwise report the problem to the user.
1549 raw_string_ostream OS(S);
1550 OS << "Unsupported expression in static initializer: ";
1551 CE->printAsOperand(OS, /*PrintType=*/false,
1552 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1553 report_fatal_error(OS.str());
1555 case Instruction::GetElementPtr: {
1556 const DataLayout &DL = *AP.TM.getDataLayout();
1557 // Generate a symbolic expression for the byte address
1558 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1559 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1561 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1565 int64_t Offset = OffsetAI.getSExtValue();
1566 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1570 case Instruction::Trunc:
1571 // We emit the value and depend on the assembler to truncate the generated
1572 // expression properly. This is important for differences between
1573 // blockaddress labels. Since the two labels are in the same function, it
1574 // is reasonable to treat their delta as a 32-bit value.
1576 case Instruction::BitCast:
1577 return lowerConstant(CE->getOperand(0), AP);
1579 case Instruction::IntToPtr: {
1580 const DataLayout &DL = *AP.TM.getDataLayout();
1581 // Handle casts to pointers by changing them into casts to the appropriate
1582 // integer type. This promotes constant folding and simplifies this code.
1583 Constant *Op = CE->getOperand(0);
1584 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1586 return lowerConstant(Op, AP);
1589 case Instruction::PtrToInt: {
1590 const DataLayout &DL = *AP.TM.getDataLayout();
1591 // Support only foldable casts to/from pointers that can be eliminated by
1592 // changing the pointer to the appropriately sized integer type.
1593 Constant *Op = CE->getOperand(0);
1594 Type *Ty = CE->getType();
1596 const MCExpr *OpExpr = lowerConstant(Op, AP);
1598 // We can emit the pointer value into this slot if the slot is an
1599 // integer slot equal to the size of the pointer.
1600 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1603 // Otherwise the pointer is smaller than the resultant integer, mask off
1604 // the high bits so we are sure to get a proper truncation if the input is
1606 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1607 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1608 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1611 // The MC library also has a right-shift operator, but it isn't consistently
1612 // signed or unsigned between different targets.
1613 case Instruction::Add:
1614 case Instruction::Sub:
1615 case Instruction::Mul:
1616 case Instruction::SDiv:
1617 case Instruction::SRem:
1618 case Instruction::Shl:
1619 case Instruction::And:
1620 case Instruction::Or:
1621 case Instruction::Xor: {
1622 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1623 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1624 switch (CE->getOpcode()) {
1625 default: llvm_unreachable("Unknown binary operator constant cast expr");
1626 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1627 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1628 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1629 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1630 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1631 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1632 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1633 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1634 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1640 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1642 /// isRepeatedByteSequence - Determine whether the given value is
1643 /// composed of a repeated sequence of identical bytes and return the
1644 /// byte value. If it is not a repeated sequence, return -1.
1645 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1646 StringRef Data = V->getRawDataValues();
1647 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1649 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1650 if (Data[i] != C) return -1;
1651 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1655 /// isRepeatedByteSequence - Determine whether the given value is
1656 /// composed of a repeated sequence of identical bytes and return the
1657 /// byte value. If it is not a repeated sequence, return -1.
1658 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1660 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1661 if (CI->getBitWidth() > 64) return -1;
1663 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1664 uint64_t Value = CI->getZExtValue();
1666 // Make sure the constant is at least 8 bits long and has a power
1667 // of 2 bit width. This guarantees the constant bit width is
1668 // always a multiple of 8 bits, avoiding issues with padding out
1669 // to Size and other such corner cases.
1670 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1672 uint8_t Byte = static_cast<uint8_t>(Value);
1674 for (unsigned i = 1; i < Size; ++i) {
1676 if (static_cast<uint8_t>(Value) != Byte) return -1;
1680 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1681 // Make sure all array elements are sequences of the same repeated
1683 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1684 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1685 if (Byte == -1) return -1;
1687 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1688 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1689 if (ThisByte == -1) return -1;
1690 if (Byte != ThisByte) return -1;
1695 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1696 return isRepeatedByteSequence(CDS);
1701 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1704 // See if we can aggregate this into a .fill, if so, emit it as such.
1705 int Value = isRepeatedByteSequence(CDS, AP.TM);
1707 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1708 // Don't emit a 1-byte object as a .fill.
1710 return AP.OutStreamer.EmitFill(Bytes, Value);
1713 // If this can be emitted with .ascii/.asciz, emit it as such.
1714 if (CDS->isString())
1715 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1717 // Otherwise, emit the values in successive locations.
1718 unsigned ElementByteSize = CDS->getElementByteSize();
1719 if (isa<IntegerType>(CDS->getElementType())) {
1720 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1722 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1723 CDS->getElementAsInteger(i));
1724 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1727 } else if (ElementByteSize == 4) {
1728 // FP Constants are printed as integer constants to avoid losing
1730 assert(CDS->getElementType()->isFloatTy());
1731 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1737 F = CDS->getElementAsFloat(i);
1739 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1740 AP.OutStreamer.EmitIntValue(I, 4);
1743 assert(CDS->getElementType()->isDoubleTy());
1744 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1750 F = CDS->getElementAsDouble(i);
1752 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1753 AP.OutStreamer.EmitIntValue(I, 8);
1757 const DataLayout &DL = *AP.TM.getDataLayout();
1758 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1759 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1760 CDS->getNumElements();
1761 if (unsigned Padding = Size - EmittedSize)
1762 AP.OutStreamer.EmitZeros(Padding);
1766 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1767 // See if we can aggregate some values. Make sure it can be
1768 // represented as a series of bytes of the constant value.
1769 int Value = isRepeatedByteSequence(CA, AP.TM);
1772 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1773 AP.OutStreamer.EmitFill(Bytes, Value);
1776 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1777 emitGlobalConstantImpl(CA->getOperand(i), AP);
1781 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1782 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1783 emitGlobalConstantImpl(CV->getOperand(i), AP);
1785 const DataLayout &DL = *AP.TM.getDataLayout();
1786 unsigned Size = DL.getTypeAllocSize(CV->getType());
1787 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1788 CV->getType()->getNumElements();
1789 if (unsigned Padding = Size - EmittedSize)
1790 AP.OutStreamer.EmitZeros(Padding);
1793 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1794 // Print the fields in successive locations. Pad to align if needed!
1795 const DataLayout *DL = AP.TM.getDataLayout();
1796 unsigned Size = DL->getTypeAllocSize(CS->getType());
1797 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1798 uint64_t SizeSoFar = 0;
1799 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1800 const Constant *Field = CS->getOperand(i);
1802 // Check if padding is needed and insert one or more 0s.
1803 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1804 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1805 - Layout->getElementOffset(i)) - FieldSize;
1806 SizeSoFar += FieldSize + PadSize;
1808 // Now print the actual field value.
1809 emitGlobalConstantImpl(Field, AP);
1811 // Insert padding - this may include padding to increase the size of the
1812 // current field up to the ABI size (if the struct is not packed) as well
1813 // as padding to ensure that the next field starts at the right offset.
1814 AP.OutStreamer.EmitZeros(PadSize);
1816 assert(SizeSoFar == Layout->getSizeInBytes() &&
1817 "Layout of constant struct may be incorrect!");
1820 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1821 APInt API = CFP->getValueAPF().bitcastToAPInt();
1823 // First print a comment with what we think the original floating-point value
1824 // should have been.
1825 if (AP.isVerbose()) {
1826 SmallString<8> StrVal;
1827 CFP->getValueAPF().toString(StrVal);
1829 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1830 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1833 // Now iterate through the APInt chunks, emitting them in endian-correct
1834 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1836 unsigned NumBytes = API.getBitWidth() / 8;
1837 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1838 const uint64_t *p = API.getRawData();
1840 // PPC's long double has odd notions of endianness compared to how LLVM
1841 // handles it: p[0] goes first for *big* endian on PPC.
1842 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1843 int Chunk = API.getNumWords() - 1;
1846 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1848 for (; Chunk >= 0; --Chunk)
1849 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1852 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1853 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1856 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1859 // Emit the tail padding for the long double.
1860 const DataLayout &DL = *AP.TM.getDataLayout();
1861 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1862 DL.getTypeStoreSize(CFP->getType()));
1865 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1866 const DataLayout *DL = AP.TM.getDataLayout();
1867 unsigned BitWidth = CI->getBitWidth();
1869 // Copy the value as we may massage the layout for constants whose bit width
1870 // is not a multiple of 64-bits.
1871 APInt Realigned(CI->getValue());
1872 uint64_t ExtraBits = 0;
1873 unsigned ExtraBitsSize = BitWidth & 63;
1875 if (ExtraBitsSize) {
1876 // The bit width of the data is not a multiple of 64-bits.
1877 // The extra bits are expected to be at the end of the chunk of the memory.
1879 // * Nothing to be done, just record the extra bits to emit.
1881 // * Record the extra bits to emit.
1882 // * Realign the raw data to emit the chunks of 64-bits.
1883 if (DL->isBigEndian()) {
1884 // Basically the structure of the raw data is a chunk of 64-bits cells:
1885 // 0 1 BitWidth / 64
1886 // [chunk1][chunk2] ... [chunkN].
1887 // The most significant chunk is chunkN and it should be emitted first.
1888 // However, due to the alignment issue chunkN contains useless bits.
1889 // Realign the chunks so that they contain only useless information:
1890 // ExtraBits 0 1 (BitWidth / 64) - 1
1891 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1892 ExtraBits = Realigned.getRawData()[0] &
1893 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1894 Realigned = Realigned.lshr(ExtraBitsSize);
1896 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1899 // We don't expect assemblers to support integer data directives
1900 // for more than 64 bits, so we emit the data in at most 64-bit
1901 // quantities at a time.
1902 const uint64_t *RawData = Realigned.getRawData();
1903 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1904 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1905 AP.OutStreamer.EmitIntValue(Val, 8);
1908 if (ExtraBitsSize) {
1909 // Emit the extra bits after the 64-bits chunks.
1911 // Emit a directive that fills the expected size.
1912 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1913 Size -= (BitWidth / 64) * 8;
1914 assert(Size && Size * 8 >= ExtraBitsSize &&
1915 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1916 == ExtraBits && "Directive too small for extra bits.");
1917 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1921 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1922 const DataLayout *DL = AP.TM.getDataLayout();
1923 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1924 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1925 return AP.OutStreamer.EmitZeros(Size);
1927 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1934 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1935 CI->getZExtValue());
1936 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1939 emitGlobalConstantLargeInt(CI, AP);
1944 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1945 return emitGlobalConstantFP(CFP, AP);
1947 if (isa<ConstantPointerNull>(CV)) {
1948 AP.OutStreamer.EmitIntValue(0, Size);
1952 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1953 return emitGlobalConstantDataSequential(CDS, AP);
1955 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1956 return emitGlobalConstantArray(CVA, AP);
1958 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1959 return emitGlobalConstantStruct(CVS, AP);
1961 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1962 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1964 if (CE->getOpcode() == Instruction::BitCast)
1965 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1968 // If the constant expression's size is greater than 64-bits, then we have
1969 // to emit the value in chunks. Try to constant fold the value and emit it
1971 Constant *New = ConstantFoldConstantExpression(CE, DL);
1972 if (New && New != CE)
1973 return emitGlobalConstantImpl(New, AP);
1977 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1978 return emitGlobalConstantVector(V, AP);
1980 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1981 // thread the streamer with EmitValue.
1982 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1985 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1986 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1987 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1989 emitGlobalConstantImpl(CV, *this);
1990 else if (MAI->hasSubsectionsViaSymbols()) {
1991 // If the global has zero size, emit a single byte so that two labels don't
1992 // look like they are at the same location.
1993 OutStreamer.EmitIntValue(0, 1);
1997 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1998 // Target doesn't support this yet!
1999 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2002 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2004 OS << '+' << Offset;
2005 else if (Offset < 0)
2009 //===----------------------------------------------------------------------===//
2010 // Symbol Lowering Routines.
2011 //===----------------------------------------------------------------------===//
2013 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2014 /// temporary label with the specified stem and unique ID.
2015 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
2016 const DataLayout *DL = TM.getDataLayout();
2017 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2021 /// GetTempSymbol - Return an assembler temporary label with the specified
2023 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2024 const DataLayout *DL = TM.getDataLayout();
2025 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2030 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2031 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2034 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2035 return MMI->getAddrLabelSymbol(BB);
2038 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2039 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2040 const DataLayout *DL = TM.getDataLayout();
2041 return OutContext.GetOrCreateSymbol
2042 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2043 + "_" + Twine(CPID));
2046 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2047 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2048 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2051 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2052 /// FIXME: privatize to AsmPrinter.
2053 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2054 const DataLayout *DL = TM.getDataLayout();
2055 return OutContext.GetOrCreateSymbol
2056 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2057 Twine(UID) + "_set_" + Twine(MBBID));
2060 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2061 StringRef Suffix) const {
2062 return getObjFileLowering().getSymbolWithGlobalValueBase(*Mang, GV, Suffix);
2065 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2067 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2068 SmallString<60> NameStr;
2069 Mang->getNameWithPrefix(NameStr, Sym);
2070 return OutContext.GetOrCreateSymbol(NameStr.str());
2075 /// PrintParentLoopComment - Print comments about parent loops of this one.
2076 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2077 unsigned FunctionNumber) {
2078 if (Loop == 0) return;
2079 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2080 OS.indent(Loop->getLoopDepth()*2)
2081 << "Parent Loop BB" << FunctionNumber << "_"
2082 << Loop->getHeader()->getNumber()
2083 << " Depth=" << Loop->getLoopDepth() << '\n';
2087 /// PrintChildLoopComment - Print comments about child loops within
2088 /// the loop for this basic block, with nesting.
2089 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2090 unsigned FunctionNumber) {
2091 // Add child loop information
2092 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2093 OS.indent((*CL)->getLoopDepth()*2)
2094 << "Child Loop BB" << FunctionNumber << "_"
2095 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2097 PrintChildLoopComment(OS, *CL, FunctionNumber);
2101 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2102 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2103 const MachineLoopInfo *LI,
2104 const AsmPrinter &AP) {
2105 // Add loop depth information
2106 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2107 if (Loop == 0) return;
2109 MachineBasicBlock *Header = Loop->getHeader();
2110 assert(Header && "No header for loop");
2112 // If this block is not a loop header, just print out what is the loop header
2114 if (Header != &MBB) {
2115 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2116 Twine(AP.getFunctionNumber())+"_" +
2117 Twine(Loop->getHeader()->getNumber())+
2118 " Depth="+Twine(Loop->getLoopDepth()));
2122 // Otherwise, it is a loop header. Print out information about child and
2124 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2126 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2129 OS.indent(Loop->getLoopDepth()*2-2);
2134 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2136 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2140 /// EmitBasicBlockStart - This method prints the label for the specified
2141 /// MachineBasicBlock, an alignment (if present) and a comment describing
2142 /// it if appropriate.
2143 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2144 // Emit an alignment directive for this block, if needed.
2145 if (unsigned Align = MBB->getAlignment())
2146 EmitAlignment(Align);
2148 // If the block has its address taken, emit any labels that were used to
2149 // reference the block. It is possible that there is more than one label
2150 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2151 // the references were generated.
2152 if (MBB->hasAddressTaken()) {
2153 const BasicBlock *BB = MBB->getBasicBlock();
2155 OutStreamer.AddComment("Block address taken");
2157 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2159 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2160 OutStreamer.EmitLabel(Syms[i]);
2163 // Print some verbose block comments.
2165 if (const BasicBlock *BB = MBB->getBasicBlock())
2167 OutStreamer.AddComment("%" + BB->getName());
2168 emitBasicBlockLoopComments(*MBB, LI, *this);
2171 // Print the main label for the block.
2172 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2174 // NOTE: Want this comment at start of line, don't emit with AddComment.
2175 OutStreamer.emitRawComment(" BB#" + Twine(MBB->getNumber()) + ":", false);
2178 OutStreamer.EmitLabel(MBB->getSymbol());
2182 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2183 bool IsDefinition) const {
2184 MCSymbolAttr Attr = MCSA_Invalid;
2186 switch (Visibility) {
2188 case GlobalValue::HiddenVisibility:
2190 Attr = MAI->getHiddenVisibilityAttr();
2192 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2194 case GlobalValue::ProtectedVisibility:
2195 Attr = MAI->getProtectedVisibilityAttr();
2199 if (Attr != MCSA_Invalid)
2200 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2203 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2204 /// exactly one predecessor and the control transfer mechanism between
2205 /// the predecessor and this block is a fall-through.
2207 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2208 // If this is a landing pad, it isn't a fall through. If it has no preds,
2209 // then nothing falls through to it.
2210 if (MBB->isLandingPad() || MBB->pred_empty())
2213 // If there isn't exactly one predecessor, it can't be a fall through.
2214 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2216 if (PI2 != MBB->pred_end())
2219 // The predecessor has to be immediately before this block.
2220 MachineBasicBlock *Pred = *PI;
2222 if (!Pred->isLayoutSuccessor(MBB))
2225 // If the block is completely empty, then it definitely does fall through.
2229 // Check the terminators in the previous blocks
2230 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2231 IE = Pred->end(); II != IE; ++II) {
2232 MachineInstr &MI = *II;
2234 // If it is not a simple branch, we are in a table somewhere.
2235 if (!MI.isBranch() || MI.isIndirectBranch())
2238 // If we are the operands of one of the branches, this is not a fall
2239 // through. Note that targets with delay slots will usually bundle
2240 // terminators with the delay slot instruction.
2241 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2244 if (OP->isMBB() && OP->getMBB() == MBB)
2254 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2255 if (!S->usesMetadata())
2258 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2259 gcp_map_type::iterator GCPI = GCMap.find(S);
2260 if (GCPI != GCMap.end())
2261 return GCPI->second;
2263 const char *Name = S->getName().c_str();
2265 for (GCMetadataPrinterRegistry::iterator
2266 I = GCMetadataPrinterRegistry::begin(),
2267 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2268 if (strcmp(Name, I->getName()) == 0) {
2269 GCMetadataPrinter *GMP = I->instantiate();
2271 GCMap.insert(std::make_pair(S, GMP));
2275 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2278 /// Pin vtable to this file.
2279 AsmPrinterHandler::~AsmPrinterHandler() {}