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);
772 if (ShouldPrintDebugScopes) {
773 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
774 const HandlerInfo &OI = Handlers[III];
775 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
776 TimePassesIsEnabled);
777 OI.Handler->endInstruction();
783 // If the last instruction was a prolog label, then we have a situation where
784 // we emitted a prolog but no function body. This results in the ending prolog
785 // label equaling the end of function label and an invalid "row" in the
786 // FDE. We need to emit a noop in this situation so that the FDE's rows are
788 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
790 // If the function is empty and the object file uses .subsections_via_symbols,
791 // then we need to emit *something* to the function body to prevent the
792 // labels from collapsing together. Just emit a noop.
793 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
795 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
796 if (Noop.getOpcode()) {
797 OutStreamer.AddComment("avoids zero-length function");
798 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
799 } else // Target not mc-ized yet.
800 OutStreamer.EmitRawText(StringRef("\tnop\n"));
803 const Function *F = MF->getFunction();
804 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
805 const BasicBlock *BB = i;
806 if (!BB->hasAddressTaken())
808 MCSymbol *Sym = GetBlockAddressSymbol(BB);
809 if (Sym->isDefined())
811 OutStreamer.AddComment("Address of block that was removed by CodeGen");
812 OutStreamer.EmitLabel(Sym);
815 // Emit target-specific gunk after the function body.
816 EmitFunctionBodyEnd();
818 // If the target wants a .size directive for the size of the function, emit
820 if (MAI->hasDotTypeDotSizeDirective()) {
821 // Create a symbol for the end of function, so we can get the size as
822 // difference between the function label and the temp label.
823 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
824 OutStreamer.EmitLabel(FnEndLabel);
826 const MCExpr *SizeExp =
827 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
828 MCSymbolRefExpr::Create(CurrentFnSymForSize,
831 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
834 // Emit post-function debug and/or EH information.
835 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
836 const HandlerInfo &OI = Handlers[I];
837 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
838 OI.Handler->endFunction(MF);
842 // Print out jump tables referenced by the function.
845 OutStreamer.AddBlankLine();
848 /// EmitDwarfRegOp - Emit dwarf register operation.
849 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
850 bool Indirect) const {
851 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
852 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
854 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
856 Reg = TRI->getDwarfRegNum(*SR, false);
857 // FIXME: Get the bit range this register uses of the superregister
858 // so that we can produce a DW_OP_bit_piece
861 // FIXME: Handle cases like a super register being encoded as
862 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
864 // FIXME: We have no reasonable way of handling errors in here. The
865 // caller might be in the middle of an dwarf expression. We should
866 // probably assert that Reg >= 0 once debug info generation is more mature.
868 if (MLoc.isIndirect() || Indirect) {
870 OutStreamer.AddComment(
871 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
872 EmitInt8(dwarf::DW_OP_breg0 + Reg);
874 OutStreamer.AddComment("DW_OP_bregx");
875 EmitInt8(dwarf::DW_OP_bregx);
876 OutStreamer.AddComment(Twine(Reg));
879 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
880 if (MLoc.isIndirect() && Indirect)
881 EmitInt8(dwarf::DW_OP_deref);
884 OutStreamer.AddComment(
885 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
886 EmitInt8(dwarf::DW_OP_reg0 + Reg);
888 OutStreamer.AddComment("DW_OP_regx");
889 EmitInt8(dwarf::DW_OP_regx);
890 OutStreamer.AddComment(Twine(Reg));
895 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
898 bool AsmPrinter::doFinalization(Module &M) {
899 // Emit global variables.
900 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
902 EmitGlobalVariable(I);
904 // Emit visibility info for declarations
905 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
906 const Function &F = *I;
907 if (!F.isDeclaration())
909 GlobalValue::VisibilityTypes V = F.getVisibility();
910 if (V == GlobalValue::DefaultVisibility)
913 MCSymbol *Name = getSymbol(&F);
914 EmitVisibility(Name, V, false);
917 // Emit module flags.
918 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
919 M.getModuleFlagsMetadata(ModuleFlags);
920 if (!ModuleFlags.empty())
921 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
923 // Make sure we wrote out everything we need.
926 // Finalize debug and EH information.
927 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
928 const HandlerInfo &OI = Handlers[I];
929 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
930 TimePassesIsEnabled);
931 OI.Handler->endModule();
937 // If the target wants to know about weak references, print them all.
938 if (MAI->getWeakRefDirective()) {
939 // FIXME: This is not lazy, it would be nice to only print weak references
940 // to stuff that is actually used. Note that doing so would require targets
941 // to notice uses in operands (due to constant exprs etc). This should
942 // happen with the MC stuff eventually.
944 // Print out module-level global variables here.
945 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
947 if (!I->hasExternalWeakLinkage()) continue;
948 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
951 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
952 if (!I->hasExternalWeakLinkage()) continue;
953 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
957 if (MAI->hasSetDirective()) {
958 OutStreamer.AddBlankLine();
959 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
961 MCSymbol *Name = getSymbol(I);
963 const GlobalValue *GV = I->getAliasedGlobal();
964 if (GV->isDeclaration()) {
965 report_fatal_error(Name->getName() +
966 ": Target doesn't support aliases to declarations");
969 MCSymbol *Target = getSymbol(GV);
971 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
972 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
973 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
974 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
976 assert(I->hasLocalLinkage() && "Invalid alias linkage");
978 EmitVisibility(Name, I->getVisibility());
980 // Emit the directives as assignments aka .set:
981 OutStreamer.EmitAssignment(Name,
982 MCSymbolRefExpr::Create(Target, OutContext));
986 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
987 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
988 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
989 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
990 MP->finishAssembly(*this);
992 // Emit llvm.ident metadata in an '.ident' directive.
995 // If we don't have any trampolines, then we don't require stack memory
996 // to be executable. Some targets have a directive to declare this.
997 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
998 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
999 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1000 OutStreamer.SwitchSection(S);
1002 // Allow the target to emit any magic that it wants at the end of the file,
1003 // after everything else has gone out.
1004 EmitEndOfAsmFile(M);
1006 delete Mang; Mang = 0;
1009 OutStreamer.Finish();
1010 OutStreamer.reset();
1015 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1017 // Get the function symbol.
1018 CurrentFnSym = getSymbol(MF.getFunction());
1019 CurrentFnSymForSize = CurrentFnSym;
1022 LI = &getAnalysis<MachineLoopInfo>();
1026 // SectionCPs - Keep track the alignment, constpool entries per Section.
1030 SmallVector<unsigned, 4> CPEs;
1031 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1035 /// EmitConstantPool - Print to the current output stream assembly
1036 /// representations of the constants in the constant pool MCP. This is
1037 /// used to print out constants which have been "spilled to memory" by
1038 /// the code generator.
1040 void AsmPrinter::EmitConstantPool() {
1041 const MachineConstantPool *MCP = MF->getConstantPool();
1042 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1043 if (CP.empty()) return;
1045 // Calculate sections for constant pool entries. We collect entries to go into
1046 // the same section together to reduce amount of section switch statements.
1047 SmallVector<SectionCPs, 4> CPSections;
1048 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1049 const MachineConstantPoolEntry &CPE = CP[i];
1050 unsigned Align = CPE.getAlignment();
1053 switch (CPE.getRelocationInfo()) {
1054 default: llvm_unreachable("Unknown section kind");
1055 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1057 Kind = SectionKind::getReadOnlyWithRelLocal();
1060 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1061 case 4: Kind = SectionKind::getMergeableConst4(); break;
1062 case 8: Kind = SectionKind::getMergeableConst8(); break;
1063 case 16: Kind = SectionKind::getMergeableConst16();break;
1064 default: Kind = SectionKind::getMergeableConst(); break;
1068 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1070 // The number of sections are small, just do a linear search from the
1071 // last section to the first.
1073 unsigned SecIdx = CPSections.size();
1074 while (SecIdx != 0) {
1075 if (CPSections[--SecIdx].S == S) {
1081 SecIdx = CPSections.size();
1082 CPSections.push_back(SectionCPs(S, Align));
1085 if (Align > CPSections[SecIdx].Alignment)
1086 CPSections[SecIdx].Alignment = Align;
1087 CPSections[SecIdx].CPEs.push_back(i);
1090 // Now print stuff into the calculated sections.
1091 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1092 OutStreamer.SwitchSection(CPSections[i].S);
1093 EmitAlignment(Log2_32(CPSections[i].Alignment));
1095 unsigned Offset = 0;
1096 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1097 unsigned CPI = CPSections[i].CPEs[j];
1098 MachineConstantPoolEntry CPE = CP[CPI];
1100 // Emit inter-object padding for alignment.
1101 unsigned AlignMask = CPE.getAlignment() - 1;
1102 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1103 OutStreamer.EmitZeros(NewOffset - Offset);
1105 Type *Ty = CPE.getType();
1106 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1107 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1109 if (CPE.isMachineConstantPoolEntry())
1110 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1112 EmitGlobalConstant(CPE.Val.ConstVal);
1117 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1118 /// by the current function to the current output stream.
1120 void AsmPrinter::EmitJumpTableInfo() {
1121 const DataLayout *DL = MF->getTarget().getDataLayout();
1122 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1123 if (MJTI == 0) return;
1124 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1125 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1126 if (JT.empty()) return;
1128 // Pick the directive to use to print the jump table entries, and switch to
1129 // the appropriate section.
1130 const Function *F = MF->getFunction();
1131 bool JTInDiffSection = false;
1132 if (// In PIC mode, we need to emit the jump table to the same section as the
1133 // function body itself, otherwise the label differences won't make sense.
1134 // FIXME: Need a better predicate for this: what about custom entries?
1135 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1136 // We should also do if the section name is NULL or function is declared
1137 // in discardable section
1138 // FIXME: this isn't the right predicate, should be based on the MCSection
1139 // for the function.
1140 F->isWeakForLinker()) {
1141 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1143 // Otherwise, drop it in the readonly section.
1144 const MCSection *ReadOnlySection =
1145 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1146 OutStreamer.SwitchSection(ReadOnlySection);
1147 JTInDiffSection = true;
1150 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1152 // Jump tables in code sections are marked with a data_region directive
1153 // where that's supported.
1154 if (!JTInDiffSection)
1155 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1157 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1158 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1160 // If this jump table was deleted, ignore it.
1161 if (JTBBs.empty()) continue;
1163 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1164 // .set directive for each unique entry. This reduces the number of
1165 // relocations the assembler will generate for the jump table.
1166 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1167 MAI->hasSetDirective()) {
1168 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1169 const TargetLowering *TLI = TM.getTargetLowering();
1170 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1171 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1172 const MachineBasicBlock *MBB = JTBBs[ii];
1173 if (!EmittedSets.insert(MBB)) continue;
1175 // .set LJTSet, LBB32-base
1177 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1178 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1179 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1183 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1184 // before each jump table. The first label is never referenced, but tells
1185 // the assembler and linker the extents of the jump table object. The
1186 // second label is actually referenced by the code.
1187 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1188 // FIXME: This doesn't have to have any specific name, just any randomly
1189 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1190 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1192 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1194 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1195 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1197 if (!JTInDiffSection)
1198 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1201 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1203 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1204 const MachineBasicBlock *MBB,
1205 unsigned UID) const {
1206 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1207 const MCExpr *Value = 0;
1208 switch (MJTI->getEntryKind()) {
1209 case MachineJumpTableInfo::EK_Inline:
1210 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1211 case MachineJumpTableInfo::EK_Custom32:
1212 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1215 case MachineJumpTableInfo::EK_BlockAddress:
1216 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1218 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1220 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1221 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1222 // with a relocation as gp-relative, e.g.:
1224 MCSymbol *MBBSym = MBB->getSymbol();
1225 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1229 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1230 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1231 // with a relocation as gp-relative, e.g.:
1233 MCSymbol *MBBSym = MBB->getSymbol();
1234 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1238 case MachineJumpTableInfo::EK_LabelDifference32: {
1239 // EK_LabelDifference32 - Each entry is the address of the block minus
1240 // the address of the jump table. This is used for PIC jump tables where
1241 // gprel32 is not supported. e.g.:
1242 // .word LBB123 - LJTI1_2
1243 // If the .set directive is supported, this is emitted as:
1244 // .set L4_5_set_123, LBB123 - LJTI1_2
1245 // .word L4_5_set_123
1247 // If we have emitted set directives for the jump table entries, print
1248 // them rather than the entries themselves. If we're emitting PIC, then
1249 // emit the table entries as differences between two text section labels.
1250 if (MAI->hasSetDirective()) {
1251 // If we used .set, reference the .set's symbol.
1252 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1256 // Otherwise, use the difference as the jump table entry.
1257 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1258 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1259 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1264 assert(Value && "Unknown entry kind!");
1266 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1267 OutStreamer.EmitValue(Value, EntrySize);
1271 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1272 /// special global used by LLVM. If so, emit it and return true, otherwise
1273 /// do nothing and return false.
1274 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1275 if (GV->getName() == "llvm.used") {
1276 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1277 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1281 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1282 if (GV->getSection() == "llvm.metadata" ||
1283 GV->hasAvailableExternallyLinkage())
1286 if (!GV->hasAppendingLinkage()) return false;
1288 assert(GV->hasInitializer() && "Not a special LLVM global!");
1290 if (GV->getName() == "llvm.global_ctors") {
1291 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1293 if (TM.getRelocationModel() == Reloc::Static &&
1294 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1295 StringRef Sym(".constructors_used");
1296 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1302 if (GV->getName() == "llvm.global_dtors") {
1303 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1305 if (TM.getRelocationModel() == Reloc::Static &&
1306 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1307 StringRef Sym(".destructors_used");
1308 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1317 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1318 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1319 /// is true, as being used with this directive.
1320 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1321 // Should be an array of 'i8*'.
1322 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1323 const GlobalValue *GV =
1324 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1325 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1326 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1330 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1332 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1333 // Should be an array of '{ int, void ()* }' structs. The first value is the
1335 if (!isa<ConstantArray>(List)) return;
1337 // Sanity check the structors list.
1338 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1339 if (!InitList) return; // Not an array!
1340 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1341 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1342 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1343 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1345 // Gather the structors in a form that's convenient for sorting by priority.
1346 typedef std::pair<unsigned, Constant *> Structor;
1347 SmallVector<Structor, 8> Structors;
1348 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1349 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1350 if (!CS) continue; // Malformed.
1351 if (CS->getOperand(1)->isNullValue())
1352 break; // Found a null terminator, skip the rest.
1353 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1354 if (!Priority) continue; // Malformed.
1355 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1356 CS->getOperand(1)));
1359 // Emit the function pointers in the target-specific order
1360 const DataLayout *DL = TM.getDataLayout();
1361 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1362 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1363 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1364 const MCSection *OutputSection =
1366 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1367 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1368 OutStreamer.SwitchSection(OutputSection);
1369 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1370 EmitAlignment(Align);
1371 EmitXXStructor(Structors[i].second);
1375 void AsmPrinter::EmitModuleIdents(Module &M) {
1376 if (!MAI->hasIdentDirective())
1379 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1380 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1381 const MDNode *N = NMD->getOperand(i);
1382 assert(N->getNumOperands() == 1 &&
1383 "llvm.ident metadata entry can have only one operand");
1384 const MDString *S = cast<MDString>(N->getOperand(0));
1385 OutStreamer.EmitIdent(S->getString());
1390 //===--------------------------------------------------------------------===//
1391 // Emission and print routines
1394 /// EmitInt8 - Emit a byte directive and value.
1396 void AsmPrinter::EmitInt8(int Value) const {
1397 OutStreamer.EmitIntValue(Value, 1);
1400 /// EmitInt16 - Emit a short directive and value.
1402 void AsmPrinter::EmitInt16(int Value) const {
1403 OutStreamer.EmitIntValue(Value, 2);
1406 /// EmitInt32 - Emit a long directive and value.
1408 void AsmPrinter::EmitInt32(int Value) const {
1409 OutStreamer.EmitIntValue(Value, 4);
1412 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1413 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1414 /// labels. This implicitly uses .set if it is available.
1415 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1416 unsigned Size) const {
1417 // Get the Hi-Lo expression.
1418 const MCExpr *Diff =
1419 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1420 MCSymbolRefExpr::Create(Lo, OutContext),
1423 if (!MAI->hasSetDirective()) {
1424 OutStreamer.EmitValue(Diff, Size);
1428 // Otherwise, emit with .set (aka assignment).
1429 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1430 OutStreamer.EmitAssignment(SetLabel, Diff);
1431 OutStreamer.EmitSymbolValue(SetLabel, Size);
1434 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1435 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1436 /// specify the labels. This implicitly uses .set if it is available.
1437 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1439 unsigned Size) const {
1441 // Emit Hi+Offset - Lo
1442 // Get the Hi+Offset expression.
1443 const MCExpr *Plus =
1444 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1445 MCConstantExpr::Create(Offset, OutContext),
1448 // Get the Hi+Offset-Lo expression.
1449 const MCExpr *Diff =
1450 MCBinaryExpr::CreateSub(Plus,
1451 MCSymbolRefExpr::Create(Lo, OutContext),
1454 if (!MAI->hasSetDirective())
1455 OutStreamer.EmitValue(Diff, Size);
1457 // Otherwise, emit with .set (aka assignment).
1458 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1459 OutStreamer.EmitAssignment(SetLabel, Diff);
1460 OutStreamer.EmitSymbolValue(SetLabel, Size);
1464 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1465 /// where the size in bytes of the directive is specified by Size and Label
1466 /// specifies the label. This implicitly uses .set if it is available.
1467 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1469 bool IsSectionRelative) const {
1470 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1471 OutStreamer.EmitCOFFSecRel32(Label);
1475 // Emit Label+Offset (or just Label if Offset is zero)
1476 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1478 Expr = MCBinaryExpr::CreateAdd(
1479 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1481 OutStreamer.EmitValue(Expr, Size);
1484 //===----------------------------------------------------------------------===//
1486 // EmitAlignment - Emit an alignment directive to the specified power of
1487 // two boundary. For example, if you pass in 3 here, you will get an 8
1488 // byte alignment. If a global value is specified, and if that global has
1489 // an explicit alignment requested, it will override the alignment request
1490 // if required for correctness.
1492 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1493 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1495 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1497 if (getCurrentSection()->getKind().isText())
1498 OutStreamer.EmitCodeAlignment(1 << NumBits);
1500 OutStreamer.EmitValueToAlignment(1 << NumBits);
1503 //===----------------------------------------------------------------------===//
1504 // Constant emission.
1505 //===----------------------------------------------------------------------===//
1507 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1509 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1510 MCContext &Ctx = AP.OutContext;
1512 if (CV->isNullValue() || isa<UndefValue>(CV))
1513 return MCConstantExpr::Create(0, Ctx);
1515 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1516 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1518 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1519 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1521 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1522 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1524 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1526 llvm_unreachable("Unknown constant value to lower!");
1529 if (const MCExpr *RelocExpr =
1530 AP.getObjFileLowering().getExecutableRelativeSymbol(CE, AP.Mang))
1533 switch (CE->getOpcode()) {
1535 // If the code isn't optimized, there may be outstanding folding
1536 // opportunities. Attempt to fold the expression using DataLayout as a
1537 // last resort before giving up.
1539 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1541 return lowerConstant(C, AP);
1543 // Otherwise report the problem to the user.
1546 raw_string_ostream OS(S);
1547 OS << "Unsupported expression in static initializer: ";
1548 CE->printAsOperand(OS, /*PrintType=*/false,
1549 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1550 report_fatal_error(OS.str());
1552 case Instruction::GetElementPtr: {
1553 const DataLayout &DL = *AP.TM.getDataLayout();
1554 // Generate a symbolic expression for the byte address
1555 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1556 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1558 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1562 int64_t Offset = OffsetAI.getSExtValue();
1563 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1567 case Instruction::Trunc:
1568 // We emit the value and depend on the assembler to truncate the generated
1569 // expression properly. This is important for differences between
1570 // blockaddress labels. Since the two labels are in the same function, it
1571 // is reasonable to treat their delta as a 32-bit value.
1573 case Instruction::BitCast:
1574 return lowerConstant(CE->getOperand(0), AP);
1576 case Instruction::IntToPtr: {
1577 const DataLayout &DL = *AP.TM.getDataLayout();
1578 // Handle casts to pointers by changing them into casts to the appropriate
1579 // integer type. This promotes constant folding and simplifies this code.
1580 Constant *Op = CE->getOperand(0);
1581 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1583 return lowerConstant(Op, AP);
1586 case Instruction::PtrToInt: {
1587 const DataLayout &DL = *AP.TM.getDataLayout();
1588 // Support only foldable casts to/from pointers that can be eliminated by
1589 // changing the pointer to the appropriately sized integer type.
1590 Constant *Op = CE->getOperand(0);
1591 Type *Ty = CE->getType();
1593 const MCExpr *OpExpr = lowerConstant(Op, AP);
1595 // We can emit the pointer value into this slot if the slot is an
1596 // integer slot equal to the size of the pointer.
1597 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1600 // Otherwise the pointer is smaller than the resultant integer, mask off
1601 // the high bits so we are sure to get a proper truncation if the input is
1603 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1604 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1605 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1608 // The MC library also has a right-shift operator, but it isn't consistently
1609 // signed or unsigned between different targets.
1610 case Instruction::Add:
1611 case Instruction::Sub:
1612 case Instruction::Mul:
1613 case Instruction::SDiv:
1614 case Instruction::SRem:
1615 case Instruction::Shl:
1616 case Instruction::And:
1617 case Instruction::Or:
1618 case Instruction::Xor: {
1619 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1620 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1621 switch (CE->getOpcode()) {
1622 default: llvm_unreachable("Unknown binary operator constant cast expr");
1623 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1624 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1625 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1626 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1627 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1628 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1629 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1630 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1631 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1637 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1639 /// isRepeatedByteSequence - Determine whether the given value is
1640 /// composed of a repeated sequence of identical bytes and return the
1641 /// byte value. If it is not a repeated sequence, return -1.
1642 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1643 StringRef Data = V->getRawDataValues();
1644 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1646 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1647 if (Data[i] != C) return -1;
1648 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1652 /// isRepeatedByteSequence - Determine whether the given value is
1653 /// composed of a repeated sequence of identical bytes and return the
1654 /// byte value. If it is not a repeated sequence, return -1.
1655 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1657 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1658 if (CI->getBitWidth() > 64) return -1;
1660 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1661 uint64_t Value = CI->getZExtValue();
1663 // Make sure the constant is at least 8 bits long and has a power
1664 // of 2 bit width. This guarantees the constant bit width is
1665 // always a multiple of 8 bits, avoiding issues with padding out
1666 // to Size and other such corner cases.
1667 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1669 uint8_t Byte = static_cast<uint8_t>(Value);
1671 for (unsigned i = 1; i < Size; ++i) {
1673 if (static_cast<uint8_t>(Value) != Byte) return -1;
1677 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1678 // Make sure all array elements are sequences of the same repeated
1680 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1681 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1682 if (Byte == -1) return -1;
1684 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1685 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1686 if (ThisByte == -1) return -1;
1687 if (Byte != ThisByte) return -1;
1692 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1693 return isRepeatedByteSequence(CDS);
1698 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1701 // See if we can aggregate this into a .fill, if so, emit it as such.
1702 int Value = isRepeatedByteSequence(CDS, AP.TM);
1704 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1705 // Don't emit a 1-byte object as a .fill.
1707 return AP.OutStreamer.EmitFill(Bytes, Value);
1710 // If this can be emitted with .ascii/.asciz, emit it as such.
1711 if (CDS->isString())
1712 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1714 // Otherwise, emit the values in successive locations.
1715 unsigned ElementByteSize = CDS->getElementByteSize();
1716 if (isa<IntegerType>(CDS->getElementType())) {
1717 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1719 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1720 CDS->getElementAsInteger(i));
1721 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1724 } else if (ElementByteSize == 4) {
1725 // FP Constants are printed as integer constants to avoid losing
1727 assert(CDS->getElementType()->isFloatTy());
1728 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1734 F = CDS->getElementAsFloat(i);
1736 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1737 AP.OutStreamer.EmitIntValue(I, 4);
1740 assert(CDS->getElementType()->isDoubleTy());
1741 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1747 F = CDS->getElementAsDouble(i);
1749 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1750 AP.OutStreamer.EmitIntValue(I, 8);
1754 const DataLayout &DL = *AP.TM.getDataLayout();
1755 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1756 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1757 CDS->getNumElements();
1758 if (unsigned Padding = Size - EmittedSize)
1759 AP.OutStreamer.EmitZeros(Padding);
1763 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1764 // See if we can aggregate some values. Make sure it can be
1765 // represented as a series of bytes of the constant value.
1766 int Value = isRepeatedByteSequence(CA, AP.TM);
1769 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1770 AP.OutStreamer.EmitFill(Bytes, Value);
1773 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1774 emitGlobalConstantImpl(CA->getOperand(i), AP);
1778 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1779 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1780 emitGlobalConstantImpl(CV->getOperand(i), AP);
1782 const DataLayout &DL = *AP.TM.getDataLayout();
1783 unsigned Size = DL.getTypeAllocSize(CV->getType());
1784 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1785 CV->getType()->getNumElements();
1786 if (unsigned Padding = Size - EmittedSize)
1787 AP.OutStreamer.EmitZeros(Padding);
1790 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1791 // Print the fields in successive locations. Pad to align if needed!
1792 const DataLayout *DL = AP.TM.getDataLayout();
1793 unsigned Size = DL->getTypeAllocSize(CS->getType());
1794 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1795 uint64_t SizeSoFar = 0;
1796 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1797 const Constant *Field = CS->getOperand(i);
1799 // Check if padding is needed and insert one or more 0s.
1800 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1801 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1802 - Layout->getElementOffset(i)) - FieldSize;
1803 SizeSoFar += FieldSize + PadSize;
1805 // Now print the actual field value.
1806 emitGlobalConstantImpl(Field, AP);
1808 // Insert padding - this may include padding to increase the size of the
1809 // current field up to the ABI size (if the struct is not packed) as well
1810 // as padding to ensure that the next field starts at the right offset.
1811 AP.OutStreamer.EmitZeros(PadSize);
1813 assert(SizeSoFar == Layout->getSizeInBytes() &&
1814 "Layout of constant struct may be incorrect!");
1817 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1818 APInt API = CFP->getValueAPF().bitcastToAPInt();
1820 // First print a comment with what we think the original floating-point value
1821 // should have been.
1822 if (AP.isVerbose()) {
1823 SmallString<8> StrVal;
1824 CFP->getValueAPF().toString(StrVal);
1826 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1827 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1830 // Now iterate through the APInt chunks, emitting them in endian-correct
1831 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1833 unsigned NumBytes = API.getBitWidth() / 8;
1834 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1835 const uint64_t *p = API.getRawData();
1837 // PPC's long double has odd notions of endianness compared to how LLVM
1838 // handles it: p[0] goes first for *big* endian on PPC.
1839 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1840 int Chunk = API.getNumWords() - 1;
1843 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1845 for (; Chunk >= 0; --Chunk)
1846 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1849 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1850 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1853 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1856 // Emit the tail padding for the long double.
1857 const DataLayout &DL = *AP.TM.getDataLayout();
1858 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1859 DL.getTypeStoreSize(CFP->getType()));
1862 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1863 const DataLayout *DL = AP.TM.getDataLayout();
1864 unsigned BitWidth = CI->getBitWidth();
1866 // Copy the value as we may massage the layout for constants whose bit width
1867 // is not a multiple of 64-bits.
1868 APInt Realigned(CI->getValue());
1869 uint64_t ExtraBits = 0;
1870 unsigned ExtraBitsSize = BitWidth & 63;
1872 if (ExtraBitsSize) {
1873 // The bit width of the data is not a multiple of 64-bits.
1874 // The extra bits are expected to be at the end of the chunk of the memory.
1876 // * Nothing to be done, just record the extra bits to emit.
1878 // * Record the extra bits to emit.
1879 // * Realign the raw data to emit the chunks of 64-bits.
1880 if (DL->isBigEndian()) {
1881 // Basically the structure of the raw data is a chunk of 64-bits cells:
1882 // 0 1 BitWidth / 64
1883 // [chunk1][chunk2] ... [chunkN].
1884 // The most significant chunk is chunkN and it should be emitted first.
1885 // However, due to the alignment issue chunkN contains useless bits.
1886 // Realign the chunks so that they contain only useless information:
1887 // ExtraBits 0 1 (BitWidth / 64) - 1
1888 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1889 ExtraBits = Realigned.getRawData()[0] &
1890 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1891 Realigned = Realigned.lshr(ExtraBitsSize);
1893 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1896 // We don't expect assemblers to support integer data directives
1897 // for more than 64 bits, so we emit the data in at most 64-bit
1898 // quantities at a time.
1899 const uint64_t *RawData = Realigned.getRawData();
1900 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1901 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1902 AP.OutStreamer.EmitIntValue(Val, 8);
1905 if (ExtraBitsSize) {
1906 // Emit the extra bits after the 64-bits chunks.
1908 // Emit a directive that fills the expected size.
1909 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1910 Size -= (BitWidth / 64) * 8;
1911 assert(Size && Size * 8 >= ExtraBitsSize &&
1912 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1913 == ExtraBits && "Directive too small for extra bits.");
1914 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1918 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1919 const DataLayout *DL = AP.TM.getDataLayout();
1920 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1921 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1922 return AP.OutStreamer.EmitZeros(Size);
1924 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1931 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1932 CI->getZExtValue());
1933 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1936 emitGlobalConstantLargeInt(CI, AP);
1941 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1942 return emitGlobalConstantFP(CFP, AP);
1944 if (isa<ConstantPointerNull>(CV)) {
1945 AP.OutStreamer.EmitIntValue(0, Size);
1949 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1950 return emitGlobalConstantDataSequential(CDS, AP);
1952 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1953 return emitGlobalConstantArray(CVA, AP);
1955 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1956 return emitGlobalConstantStruct(CVS, AP);
1958 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1959 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1961 if (CE->getOpcode() == Instruction::BitCast)
1962 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1965 // If the constant expression's size is greater than 64-bits, then we have
1966 // to emit the value in chunks. Try to constant fold the value and emit it
1968 Constant *New = ConstantFoldConstantExpression(CE, DL);
1969 if (New && New != CE)
1970 return emitGlobalConstantImpl(New, AP);
1974 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1975 return emitGlobalConstantVector(V, AP);
1977 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1978 // thread the streamer with EmitValue.
1979 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1982 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1983 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1984 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1986 emitGlobalConstantImpl(CV, *this);
1987 else if (MAI->hasSubsectionsViaSymbols()) {
1988 // If the global has zero size, emit a single byte so that two labels don't
1989 // look like they are at the same location.
1990 OutStreamer.EmitIntValue(0, 1);
1994 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1995 // Target doesn't support this yet!
1996 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1999 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2001 OS << '+' << Offset;
2002 else if (Offset < 0)
2006 //===----------------------------------------------------------------------===//
2007 // Symbol Lowering Routines.
2008 //===----------------------------------------------------------------------===//
2010 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2011 /// temporary label with the specified stem and unique ID.
2012 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
2013 const DataLayout *DL = TM.getDataLayout();
2014 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2018 /// GetTempSymbol - Return an assembler temporary label with the specified
2020 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2021 const DataLayout *DL = TM.getDataLayout();
2022 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2027 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2028 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2031 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2032 return MMI->getAddrLabelSymbol(BB);
2035 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2036 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2037 const DataLayout *DL = TM.getDataLayout();
2038 return OutContext.GetOrCreateSymbol
2039 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2040 + "_" + Twine(CPID));
2043 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2044 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2045 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2048 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2049 /// FIXME: privatize to AsmPrinter.
2050 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2051 const DataLayout *DL = TM.getDataLayout();
2052 return OutContext.GetOrCreateSymbol
2053 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2054 Twine(UID) + "_set_" + Twine(MBBID));
2057 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2058 StringRef Suffix) const {
2059 return getObjFileLowering().getSymbolWithGlobalValueBase(*Mang, GV, Suffix);
2062 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2064 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2065 SmallString<60> NameStr;
2066 Mang->getNameWithPrefix(NameStr, Sym);
2067 return OutContext.GetOrCreateSymbol(NameStr.str());
2072 /// PrintParentLoopComment - Print comments about parent loops of this one.
2073 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2074 unsigned FunctionNumber) {
2075 if (Loop == 0) return;
2076 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2077 OS.indent(Loop->getLoopDepth()*2)
2078 << "Parent Loop BB" << FunctionNumber << "_"
2079 << Loop->getHeader()->getNumber()
2080 << " Depth=" << Loop->getLoopDepth() << '\n';
2084 /// PrintChildLoopComment - Print comments about child loops within
2085 /// the loop for this basic block, with nesting.
2086 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2087 unsigned FunctionNumber) {
2088 // Add child loop information
2089 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2090 OS.indent((*CL)->getLoopDepth()*2)
2091 << "Child Loop BB" << FunctionNumber << "_"
2092 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2094 PrintChildLoopComment(OS, *CL, FunctionNumber);
2098 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2099 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2100 const MachineLoopInfo *LI,
2101 const AsmPrinter &AP) {
2102 // Add loop depth information
2103 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2104 if (Loop == 0) return;
2106 MachineBasicBlock *Header = Loop->getHeader();
2107 assert(Header && "No header for loop");
2109 // If this block is not a loop header, just print out what is the loop header
2111 if (Header != &MBB) {
2112 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2113 Twine(AP.getFunctionNumber())+"_" +
2114 Twine(Loop->getHeader()->getNumber())+
2115 " Depth="+Twine(Loop->getLoopDepth()));
2119 // Otherwise, it is a loop header. Print out information about child and
2121 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2123 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2126 OS.indent(Loop->getLoopDepth()*2-2);
2131 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2133 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2137 /// EmitBasicBlockStart - This method prints the label for the specified
2138 /// MachineBasicBlock, an alignment (if present) and a comment describing
2139 /// it if appropriate.
2140 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2141 // Emit an alignment directive for this block, if needed.
2142 if (unsigned Align = MBB->getAlignment())
2143 EmitAlignment(Align);
2145 // If the block has its address taken, emit any labels that were used to
2146 // reference the block. It is possible that there is more than one label
2147 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2148 // the references were generated.
2149 if (MBB->hasAddressTaken()) {
2150 const BasicBlock *BB = MBB->getBasicBlock();
2152 OutStreamer.AddComment("Block address taken");
2154 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2156 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2157 OutStreamer.EmitLabel(Syms[i]);
2160 // Print some verbose block comments.
2162 if (const BasicBlock *BB = MBB->getBasicBlock())
2164 OutStreamer.AddComment("%" + BB->getName());
2165 emitBasicBlockLoopComments(*MBB, LI, *this);
2168 // Print the main label for the block.
2169 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2171 // NOTE: Want this comment at start of line, don't emit with AddComment.
2172 OutStreamer.emitRawComment(" BB#" + Twine(MBB->getNumber()) + ":", false);
2175 OutStreamer.EmitLabel(MBB->getSymbol());
2179 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2180 bool IsDefinition) const {
2181 MCSymbolAttr Attr = MCSA_Invalid;
2183 switch (Visibility) {
2185 case GlobalValue::HiddenVisibility:
2187 Attr = MAI->getHiddenVisibilityAttr();
2189 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2191 case GlobalValue::ProtectedVisibility:
2192 Attr = MAI->getProtectedVisibilityAttr();
2196 if (Attr != MCSA_Invalid)
2197 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2200 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2201 /// exactly one predecessor and the control transfer mechanism between
2202 /// the predecessor and this block is a fall-through.
2204 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2205 // If this is a landing pad, it isn't a fall through. If it has no preds,
2206 // then nothing falls through to it.
2207 if (MBB->isLandingPad() || MBB->pred_empty())
2210 // If there isn't exactly one predecessor, it can't be a fall through.
2211 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2213 if (PI2 != MBB->pred_end())
2216 // The predecessor has to be immediately before this block.
2217 MachineBasicBlock *Pred = *PI;
2219 if (!Pred->isLayoutSuccessor(MBB))
2222 // If the block is completely empty, then it definitely does fall through.
2226 // Check the terminators in the previous blocks
2227 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2228 IE = Pred->end(); II != IE; ++II) {
2229 MachineInstr &MI = *II;
2231 // If it is not a simple branch, we are in a table somewhere.
2232 if (!MI.isBranch() || MI.isIndirectBranch())
2235 // If we are the operands of one of the branches, this is not a fall
2236 // through. Note that targets with delay slots will usually bundle
2237 // terminators with the delay slot instruction.
2238 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2241 if (OP->isMBB() && OP->getMBB() == MBB)
2251 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2252 if (!S->usesMetadata())
2255 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2256 gcp_map_type::iterator GCPI = GCMap.find(S);
2257 if (GCPI != GCMap.end())
2258 return GCPI->second;
2260 const char *Name = S->getName().c_str();
2262 for (GCMetadataPrinterRegistry::iterator
2263 I = GCMetadataPrinterRegistry::begin(),
2264 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2265 if (strcmp(Name, I->getName()) == 0) {
2266 GCMetadataPrinter *GMP = I->instantiate();
2268 GCMap.insert(std::make_pair(S, GMP));
2272 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2275 /// Pin vtable to this file.
2276 AsmPrinterHandler::~AsmPrinterHandler() {}