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 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "Win64Exception.h"
18 #include "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/JumpInstrTableInfo.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/GCMetadataPrinter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBundle.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Target/TargetFrameLowering.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
57 #define DEBUG_TYPE "asm-printer"
59 static const char *const DWARFGroupName = "DWARF Emission";
60 static const char *const DbgTimerName = "Debug Info Emission";
61 static const char *const EHTimerName = "DWARF Exception Writer";
62 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
64 STATISTIC(EmittedInsts, "Number of machine instrs printed");
66 char AsmPrinter::ID = 0;
68 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
69 static gcp_map_type &getGCMap(void *&P) {
71 P = new gcp_map_type();
72 return *(gcp_map_type*)P;
76 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
77 /// value in log2 form. This rounds up to the preferred alignment if possible
79 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
80 unsigned InBits = 0) {
82 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
83 NumBits = TD.getPreferredAlignmentLog(GVar);
85 // If InBits is specified, round it to it.
89 // If the GV has a specified alignment, take it into account.
90 if (GV->getAlignment() == 0)
93 unsigned GVAlign = Log2_32(GV->getAlignment());
95 // If the GVAlign is larger than NumBits, or if we are required to obey
96 // NumBits because the GV has an assigned section, obey it.
97 if (GVAlign > NumBits || GV->hasSection())
102 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
103 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
104 OutContext(Streamer->getContext()), OutStreamer(*Streamer.release()),
105 LastMI(nullptr), LastFn(0), Counter(~0U), SetCounter(0) {
110 CurrentFnSym = CurrentFnSymForSize = nullptr;
111 GCMetadataPrinters = nullptr;
112 VerboseAsm = OutStreamer.isVerboseAsm();
115 AsmPrinter::~AsmPrinter() {
116 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
118 if (GCMetadataPrinters) {
119 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
122 GCMetadataPrinters = nullptr;
128 /// getFunctionNumber - Return a unique ID for the current function.
130 unsigned AsmPrinter::getFunctionNumber() const {
131 return MF->getFunctionNumber();
134 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
135 return *TM.getObjFileLowering();
138 /// getDataLayout - Return information about data layout.
139 const DataLayout &AsmPrinter::getDataLayout() const {
140 return *TM.getDataLayout();
143 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
144 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
145 return MF->getSubtarget<MCSubtargetInfo>();
148 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
149 S.EmitInstruction(Inst, getSubtargetInfo());
152 StringRef AsmPrinter::getTargetTriple() const {
153 return TM.getTargetTriple();
156 /// getCurrentSection() - Return the current section we are emitting to.
157 const MCSection *AsmPrinter::getCurrentSection() const {
158 return OutStreamer.getCurrentSection().first;
163 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
164 AU.setPreservesAll();
165 MachineFunctionPass::getAnalysisUsage(AU);
166 AU.addRequired<MachineModuleInfo>();
167 AU.addRequired<GCModuleInfo>();
169 AU.addRequired<MachineLoopInfo>();
172 bool AsmPrinter::doInitialization(Module &M) {
173 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
174 MMI->AnalyzeModule(M);
176 // Initialize TargetLoweringObjectFile.
177 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
178 .Initialize(OutContext, TM);
180 OutStreamer.InitSections(false);
182 Mang = new Mangler(TM.getDataLayout());
184 // Emit the version-min deplyment target directive if needed.
186 // FIXME: If we end up with a collection of these sorts of Darwin-specific
187 // or ELF-specific things, it may make sense to have a platform helper class
188 // that will work with the target helper class. For now keep it here, as the
189 // alternative is duplicated code in each of the target asm printers that
190 // use the directive, where it would need the same conditionalization
192 Triple TT(getTargetTriple());
193 if (TT.isOSDarwin()) {
194 unsigned Major, Minor, Update;
195 TT.getOSVersion(Major, Minor, Update);
196 // If there is a version specified, Major will be non-zero.
198 OutStreamer.EmitVersionMin((TT.isMacOSX() ?
199 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
200 Major, Minor, Update);
203 // Allow the target to emit any magic that it wants at the start of the file.
204 EmitStartOfAsmFile(M);
206 // Very minimal debug info. It is ignored if we emit actual debug info. If we
207 // don't, this at least helps the user find where a global came from.
208 if (MAI->hasSingleParameterDotFile()) {
210 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
213 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
214 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
216 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
217 MP->beginAssembly(M, *MI, *this);
219 // Emit module-level inline asm if it exists.
220 if (!M.getModuleInlineAsm().empty()) {
221 OutStreamer.AddComment("Start of file scope inline assembly");
222 OutStreamer.AddBlankLine();
223 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
224 OutStreamer.AddComment("End of file scope inline assembly");
225 OutStreamer.AddBlankLine();
228 if (MAI->doesSupportDebugInformation()) {
229 bool skip_dwarf = false;
230 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
231 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
233 CodeViewLineTablesGroupName));
234 // FIXME: Don't emit DWARF debug info if there's at least one function
235 // with AddressSanitizer instrumentation.
236 // This is a band-aid fix for PR22032.
237 for (auto &F : M.functions()) {
238 if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
245 DD = new DwarfDebug(this, &M);
246 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
250 EHStreamer *ES = nullptr;
251 switch (MAI->getExceptionHandlingType()) {
252 case ExceptionHandling::None:
254 case ExceptionHandling::SjLj:
255 case ExceptionHandling::DwarfCFI:
256 ES = new DwarfCFIException(this);
258 case ExceptionHandling::ARM:
259 ES = new ARMException(this);
261 case ExceptionHandling::WinEH:
262 switch (MAI->getWinEHEncodingType()) {
263 default: llvm_unreachable("unsupported unwinding information encoding");
264 case WinEH::EncodingType::Itanium:
265 ES = new Win64Exception(this);
271 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
275 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
276 if (!MAI.hasWeakDefCanBeHiddenDirective())
279 return canBeOmittedFromSymbolTable(GV);
282 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
283 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
285 case GlobalValue::CommonLinkage:
286 case GlobalValue::LinkOnceAnyLinkage:
287 case GlobalValue::LinkOnceODRLinkage:
288 case GlobalValue::WeakAnyLinkage:
289 case GlobalValue::WeakODRLinkage:
290 if (MAI->hasWeakDefDirective()) {
292 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
294 if (!canBeHidden(GV, *MAI))
295 // .weak_definition _foo
296 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
298 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
299 } else if (MAI->hasLinkOnceDirective()) {
301 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
302 //NOTE: linkonce is handled by the section the symbol was assigned to.
305 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
308 case GlobalValue::AppendingLinkage:
309 // FIXME: appending linkage variables should go into a section of
310 // their name or something. For now, just emit them as external.
311 case GlobalValue::ExternalLinkage:
312 // If external or appending, declare as a global symbol.
314 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
316 case GlobalValue::PrivateLinkage:
317 case GlobalValue::InternalLinkage:
319 case GlobalValue::AvailableExternallyLinkage:
320 llvm_unreachable("Should never emit this");
321 case GlobalValue::ExternalWeakLinkage:
322 llvm_unreachable("Don't know how to emit these");
324 llvm_unreachable("Unknown linkage type!");
327 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
328 const GlobalValue *GV) const {
329 TM.getNameWithPrefix(Name, GV, *Mang);
332 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
333 return TM.getSymbol(GV, *Mang);
336 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
337 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
338 if (GV->hasInitializer()) {
339 // Check to see if this is a special global used by LLVM, if so, emit it.
340 if (EmitSpecialLLVMGlobal(GV))
344 GV->printAsOperand(OutStreamer.GetCommentOS(),
345 /*PrintType=*/false, GV->getParent());
346 OutStreamer.GetCommentOS() << '\n';
350 MCSymbol *GVSym = getSymbol(GV);
351 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
353 if (!GV->hasInitializer()) // External globals require no extra code.
356 GVSym->redefineIfPossible();
357 if (GVSym->isDefined() || GVSym->isVariable())
358 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
359 "' is already defined");
361 if (MAI->hasDotTypeDotSizeDirective())
362 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
364 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
366 const DataLayout *DL = TM.getDataLayout();
367 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
369 // If the alignment is specified, we *must* obey it. Overaligning a global
370 // with a specified alignment is a prompt way to break globals emitted to
371 // sections and expected to be contiguous (e.g. ObjC metadata).
372 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
374 for (const HandlerInfo &HI : Handlers) {
375 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
376 HI.Handler->setSymbolSize(GVSym, Size);
379 // Handle common and BSS local symbols (.lcomm).
380 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
381 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
382 unsigned Align = 1 << AlignLog;
384 // Handle common symbols.
385 if (GVKind.isCommon()) {
386 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
390 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
394 // Handle local BSS symbols.
395 if (MAI->hasMachoZeroFillDirective()) {
396 const MCSection *TheSection =
397 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
398 // .zerofill __DATA, __bss, _foo, 400, 5
399 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
403 // Use .lcomm only if it supports user-specified alignment.
404 // Otherwise, while it would still be correct to use .lcomm in some
405 // cases (e.g. when Align == 1), the external assembler might enfore
406 // some -unknown- default alignment behavior, which could cause
407 // spurious differences between external and integrated assembler.
408 // Prefer to simply fall back to .local / .comm in this case.
409 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
411 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
415 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
419 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
421 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
425 const MCSection *TheSection =
426 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
428 // Handle the zerofill directive on darwin, which is a special form of BSS
430 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
431 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
434 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
435 // .zerofill __DATA, __common, _foo, 400, 5
436 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
440 // Handle thread local data for mach-o which requires us to output an
441 // additional structure of data and mangle the original symbol so that we
442 // can reference it later.
444 // TODO: This should become an "emit thread local global" method on TLOF.
445 // All of this macho specific stuff should be sunk down into TLOFMachO and
446 // stuff like "TLSExtraDataSection" should no longer be part of the parent
447 // TLOF class. This will also make it more obvious that stuff like
448 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
450 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
451 // Emit the .tbss symbol
453 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
455 if (GVKind.isThreadBSS()) {
456 TheSection = getObjFileLowering().getTLSBSSSection();
457 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
458 } else if (GVKind.isThreadData()) {
459 OutStreamer.SwitchSection(TheSection);
461 EmitAlignment(AlignLog, GV);
462 OutStreamer.EmitLabel(MangSym);
464 EmitGlobalConstant(GV->getInitializer());
467 OutStreamer.AddBlankLine();
469 // Emit the variable struct for the runtime.
470 const MCSection *TLVSect
471 = getObjFileLowering().getTLSExtraDataSection();
473 OutStreamer.SwitchSection(TLVSect);
474 // Emit the linkage here.
475 EmitLinkage(GV, GVSym);
476 OutStreamer.EmitLabel(GVSym);
478 // Three pointers in size:
479 // - __tlv_bootstrap - used to make sure support exists
480 // - spare pointer, used when mapped by the runtime
481 // - pointer to mangled symbol above with initializer
482 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
483 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
485 OutStreamer.EmitIntValue(0, PtrSize);
486 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
488 OutStreamer.AddBlankLine();
492 OutStreamer.SwitchSection(TheSection);
494 EmitLinkage(GV, GVSym);
495 EmitAlignment(AlignLog, GV);
497 OutStreamer.EmitLabel(GVSym);
499 EmitGlobalConstant(GV->getInitializer());
501 if (MAI->hasDotTypeDotSizeDirective())
503 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
505 OutStreamer.AddBlankLine();
508 /// EmitFunctionHeader - This method emits the header for the current
510 void AsmPrinter::EmitFunctionHeader() {
511 // Print out constants referenced by the function
514 // Print the 'header' of function.
515 const Function *F = MF->getFunction();
517 OutStreamer.SwitchSection(
518 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
519 EmitVisibility(CurrentFnSym, F->getVisibility());
521 EmitLinkage(F, CurrentFnSym);
522 EmitAlignment(MF->getAlignment(), F);
524 if (MAI->hasDotTypeDotSizeDirective())
525 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
528 F->printAsOperand(OutStreamer.GetCommentOS(),
529 /*PrintType=*/false, F->getParent());
530 OutStreamer.GetCommentOS() << '\n';
533 // Emit the prefix data.
534 if (F->hasPrefixData())
535 EmitGlobalConstant(F->getPrefixData());
537 // Emit the CurrentFnSym. This is a virtual function to allow targets to
538 // do their wild and crazy things as required.
539 EmitFunctionEntryLabel();
541 // If the function had address-taken blocks that got deleted, then we have
542 // references to the dangling symbols. Emit them at the start of the function
543 // so that we don't get references to undefined symbols.
544 std::vector<MCSymbol*> DeadBlockSyms;
545 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
546 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
547 OutStreamer.AddComment("Address taken block that was later removed");
548 OutStreamer.EmitLabel(DeadBlockSyms[i]);
551 // Emit pre-function debug and/or EH information.
552 for (const HandlerInfo &HI : Handlers) {
553 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
554 HI.Handler->beginFunction(MF);
557 // Emit the prologue data.
558 if (F->hasPrologueData())
559 EmitGlobalConstant(F->getPrologueData());
562 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
563 /// function. This can be overridden by targets as required to do custom stuff.
564 void AsmPrinter::EmitFunctionEntryLabel() {
565 CurrentFnSym->redefineIfPossible();
567 // The function label could have already been emitted if two symbols end up
568 // conflicting due to asm renaming. Detect this and emit an error.
569 if (CurrentFnSym->isVariable())
570 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
571 "' is a protected alias");
572 if (CurrentFnSym->isDefined())
573 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
574 "' label emitted multiple times to assembly file");
576 return OutStreamer.EmitLabel(CurrentFnSym);
579 /// emitComments - Pretty-print comments for instructions.
580 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
581 const MachineFunction *MF = MI.getParent()->getParent();
582 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
584 // Check for spills and reloads
587 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
589 // We assume a single instruction only has a spill or reload, not
591 const MachineMemOperand *MMO;
592 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
593 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
594 MMO = *MI.memoperands_begin();
595 CommentOS << MMO->getSize() << "-byte Reload\n";
597 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
598 if (FrameInfo->isSpillSlotObjectIndex(FI))
599 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
600 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
601 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
602 MMO = *MI.memoperands_begin();
603 CommentOS << MMO->getSize() << "-byte Spill\n";
605 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
606 if (FrameInfo->isSpillSlotObjectIndex(FI))
607 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
610 // Check for spill-induced copies
611 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
612 CommentOS << " Reload Reuse\n";
615 /// emitImplicitDef - This method emits the specified machine instruction
616 /// that is an implicit def.
617 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
618 unsigned RegNo = MI->getOperand(0).getReg();
619 OutStreamer.AddComment(Twine("implicit-def: ") +
620 MMI->getContext().getRegisterInfo()->getName(RegNo));
621 OutStreamer.AddBlankLine();
624 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
625 std::string Str = "kill:";
626 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
627 const MachineOperand &Op = MI->getOperand(i);
628 assert(Op.isReg() && "KILL instruction must have only register operands");
630 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
631 Str += (Op.isDef() ? "<def>" : "<kill>");
633 AP.OutStreamer.AddComment(Str);
634 AP.OutStreamer.AddBlankLine();
637 /// emitDebugValueComment - This method handles the target-independent form
638 /// of DBG_VALUE, returning true if it was able to do so. A false return
639 /// means the target will need to handle MI in EmitInstruction.
640 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
641 // This code handles only the 4-operand target-independent form.
642 if (MI->getNumOperands() != 4)
645 SmallString<128> Str;
646 raw_svector_ostream OS(Str);
647 OS << "DEBUG_VALUE: ";
649 DIVariable V = MI->getDebugVariable();
650 if (V.getContext().isSubprogram()) {
651 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
657 DIExpression Expr = MI->getDebugExpression();
658 if (Expr.isBitPiece())
659 OS << " [bit_piece offset=" << Expr.getBitPieceOffset()
660 << " size=" << Expr.getBitPieceSize() << "]";
663 // The second operand is only an offset if it's an immediate.
664 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
665 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
667 // Register or immediate value. Register 0 means undef.
668 if (MI->getOperand(0).isFPImm()) {
669 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
670 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
671 OS << (double)APF.convertToFloat();
672 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
673 OS << APF.convertToDouble();
675 // There is no good way to print long double. Convert a copy to
676 // double. Ah well, it's only a comment.
678 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
680 OS << "(long double) " << APF.convertToDouble();
682 } else if (MI->getOperand(0).isImm()) {
683 OS << MI->getOperand(0).getImm();
684 } else if (MI->getOperand(0).isCImm()) {
685 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
688 if (MI->getOperand(0).isReg()) {
689 Reg = MI->getOperand(0).getReg();
691 assert(MI->getOperand(0).isFI() && "Unknown operand type");
692 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
693 Offset += TFI->getFrameIndexReference(*AP.MF,
694 MI->getOperand(0).getIndex(), Reg);
698 // Suppress offset, it is not meaningful here.
700 // NOTE: Want this comment at start of line, don't emit with AddComment.
701 AP.OutStreamer.emitRawComment(OS.str());
706 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
710 OS << '+' << Offset << ']';
712 // NOTE: Want this comment at start of line, don't emit with AddComment.
713 AP.OutStreamer.emitRawComment(OS.str());
717 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
718 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
719 MF->getFunction()->needsUnwindTableEntry())
722 if (MMI->hasDebugInfo())
728 bool AsmPrinter::needsSEHMoves() {
729 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
732 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
733 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
734 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
735 ExceptionHandlingType != ExceptionHandling::ARM)
738 if (needsCFIMoves() == CFI_M_None)
741 const MachineModuleInfo &MMI = MF->getMMI();
742 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
743 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
744 const MCCFIInstruction &CFI = Instrs[CFIIndex];
745 emitCFIInstruction(CFI);
748 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
749 // The operands are the MCSymbol and the frame offset of the allocation.
750 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
751 int FrameOffset = MI.getOperand(1).getImm();
753 // Emit a symbol assignment.
754 OutStreamer.EmitAssignment(FrameAllocSym,
755 MCConstantExpr::Create(FrameOffset, OutContext));
758 /// EmitFunctionBody - This method emits the body and trailer for a
760 void AsmPrinter::EmitFunctionBody() {
761 // Emit target-specific gunk before the function body.
762 EmitFunctionBodyStart();
764 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
766 // Print out code for the function.
767 bool HasAnyRealCode = false;
768 for (auto &MBB : *MF) {
769 // Print a label for the basic block.
770 EmitBasicBlockStart(MBB);
771 for (auto &MI : MBB) {
773 // Print the assembly for the instruction.
774 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
775 !MI.isDebugValue()) {
776 HasAnyRealCode = true;
780 if (ShouldPrintDebugScopes) {
781 for (const HandlerInfo &HI : Handlers) {
782 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
783 TimePassesIsEnabled);
784 HI.Handler->beginInstruction(&MI);
789 emitComments(MI, OutStreamer.GetCommentOS());
791 switch (MI.getOpcode()) {
792 case TargetOpcode::CFI_INSTRUCTION:
793 emitCFIInstruction(MI);
796 case TargetOpcode::FRAME_ALLOC:
800 case TargetOpcode::EH_LABEL:
801 case TargetOpcode::GC_LABEL:
802 OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
804 case TargetOpcode::INLINEASM:
807 case TargetOpcode::DBG_VALUE:
809 if (!emitDebugValueComment(&MI, *this))
810 EmitInstruction(&MI);
813 case TargetOpcode::IMPLICIT_DEF:
814 if (isVerbose()) emitImplicitDef(&MI);
816 case TargetOpcode::KILL:
817 if (isVerbose()) emitKill(&MI, *this);
820 EmitInstruction(&MI);
824 if (ShouldPrintDebugScopes) {
825 for (const HandlerInfo &HI : Handlers) {
826 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
827 TimePassesIsEnabled);
828 HI.Handler->endInstruction();
833 EmitBasicBlockEnd(MBB);
836 // If the function is empty and the object file uses .subsections_via_symbols,
837 // then we need to emit *something* to the function body to prevent the
838 // labels from collapsing together. Just emit a noop.
839 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
841 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
842 OutStreamer.AddComment("avoids zero-length function");
844 // Targets can opt-out of emitting the noop here by leaving the opcode
846 if (Noop.getOpcode())
847 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
850 const Function *F = MF->getFunction();
851 for (const auto &BB : *F) {
852 if (!BB.hasAddressTaken())
854 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
855 if (Sym->isDefined())
857 OutStreamer.AddComment("Address of block that was removed by CodeGen");
858 OutStreamer.EmitLabel(Sym);
861 // Emit target-specific gunk after the function body.
862 EmitFunctionBodyEnd();
864 // If the target wants a .size directive for the size of the function, emit
866 if (MAI->hasDotTypeDotSizeDirective()) {
867 // Create a symbol for the end of function, so we can get the size as
868 // difference between the function label and the temp label.
869 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
870 OutStreamer.EmitLabel(FnEndLabel);
872 const MCExpr *SizeExp =
873 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
874 MCSymbolRefExpr::Create(CurrentFnSymForSize,
877 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
880 // Emit post-function debug and/or EH information.
881 for (const HandlerInfo &HI : Handlers) {
882 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
883 HI.Handler->endFunction(MF);
887 // Print out jump tables referenced by the function.
890 OutStreamer.AddBlankLine();
893 bool AsmPrinter::doFinalization(Module &M) {
894 // Emit global variables.
895 for (const auto &G : M.globals())
896 EmitGlobalVariable(&G);
898 // Emit visibility info for declarations
899 for (const Function &F : M) {
900 if (!F.isDeclaration())
902 GlobalValue::VisibilityTypes V = F.getVisibility();
903 if (V == GlobalValue::DefaultVisibility)
906 MCSymbol *Name = getSymbol(&F);
907 EmitVisibility(Name, V, false);
910 // Get information about jump-instruction tables to print.
911 JumpInstrTableInfo *JITI = getAnalysisIfAvailable<JumpInstrTableInfo>();
913 if (JITI && !JITI->getTables().empty()) {
914 // Since we're at the module level we can't use a function specific
915 // MCSubtargetInfo - instead create one with the module defaults.
916 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
917 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
918 unsigned Arch = Triple(getTargetTriple()).getArch();
919 bool IsThumb = (Arch == Triple::thumb || Arch == Triple::thumbeb);
920 const TargetInstrInfo *TII = TM.getSubtargetImpl()->getInstrInfo();
922 TII->getTrap(TrapInst);
923 unsigned LogAlignment = llvm::Log2_64(JITI->entryByteAlignment());
925 // Emit the right section for these functions.
926 OutStreamer.SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
927 for (const auto &KV : JITI->getTables()) {
929 for (const auto &FunPair : KV.second) {
930 // Emit the function labels to make this be a function entry point.
932 OutContext.GetOrCreateSymbol(FunPair.second->getName());
933 EmitAlignment(LogAlignment);
935 OutStreamer.EmitThumbFunc(FunSym);
936 if (MAI->hasDotTypeDotSizeDirective())
937 OutStreamer.EmitSymbolAttribute(FunSym, MCSA_ELF_TypeFunction);
938 OutStreamer.EmitLabel(FunSym);
940 // Emit the jump instruction to transfer control to the original
943 MCSymbol *TargetSymbol =
944 OutContext.GetOrCreateSymbol(FunPair.first->getName());
945 const MCSymbolRefExpr *TargetSymRef =
946 MCSymbolRefExpr::Create(TargetSymbol, MCSymbolRefExpr::VK_PLT,
948 TII->getUnconditionalBranch(JumpToFun, TargetSymRef);
949 OutStreamer.EmitInstruction(JumpToFun, *STI);
953 // Emit enough padding instructions to fill up to the next power of two.
954 uint64_t Remaining = NextPowerOf2(Count) - Count;
955 for (uint64_t C = 0; C < Remaining; ++C) {
956 EmitAlignment(LogAlignment);
957 OutStreamer.EmitInstruction(TrapInst, *STI);
963 // Emit module flags.
964 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
965 M.getModuleFlagsMetadata(ModuleFlags);
966 if (!ModuleFlags.empty())
967 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
969 // Make sure we wrote out everything we need.
972 // Finalize debug and EH information.
973 for (const HandlerInfo &HI : Handlers) {
974 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
975 TimePassesIsEnabled);
976 HI.Handler->endModule();
982 // If the target wants to know about weak references, print them all.
983 if (MAI->getWeakRefDirective()) {
984 // FIXME: This is not lazy, it would be nice to only print weak references
985 // to stuff that is actually used. Note that doing so would require targets
986 // to notice uses in operands (due to constant exprs etc). This should
987 // happen with the MC stuff eventually.
989 // Print out module-level global variables here.
990 for (const auto &G : M.globals()) {
991 if (!G.hasExternalWeakLinkage())
993 OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
996 for (const auto &F : M) {
997 if (!F.hasExternalWeakLinkage())
999 OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1003 OutStreamer.AddBlankLine();
1004 for (const auto &Alias : M.aliases()) {
1005 MCSymbol *Name = getSymbol(&Alias);
1007 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1008 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1009 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1010 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1012 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1014 EmitVisibility(Name, Alias.getVisibility());
1016 // Emit the directives as assignments aka .set:
1017 OutStreamer.EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1020 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1021 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1022 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1023 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1024 MP->finishAssembly(M, *MI, *this);
1026 // Emit llvm.ident metadata in an '.ident' directive.
1027 EmitModuleIdents(M);
1029 // Emit __morestack address if needed for indirect calls.
1030 if (MMI->usesMorestackAddr()) {
1031 const MCSection *ReadOnlySection =
1032 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1034 OutStreamer.SwitchSection(ReadOnlySection);
1036 MCSymbol *AddrSymbol =
1037 OutContext.GetOrCreateSymbol(StringRef("__morestack_addr"));
1038 OutStreamer.EmitLabel(AddrSymbol);
1040 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1041 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1045 // If we don't have any trampolines, then we don't require stack memory
1046 // to be executable. Some targets have a directive to declare this.
1047 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1048 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1049 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1050 OutStreamer.SwitchSection(S);
1052 // Allow the target to emit any magic that it wants at the end of the file,
1053 // after everything else has gone out.
1054 EmitEndOfAsmFile(M);
1056 delete Mang; Mang = nullptr;
1059 OutStreamer.Finish();
1060 OutStreamer.reset();
1065 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1067 // Get the function symbol.
1068 CurrentFnSym = getSymbol(MF.getFunction());
1069 CurrentFnSymForSize = CurrentFnSym;
1072 LI = &getAnalysis<MachineLoopInfo>();
1076 // SectionCPs - Keep track the alignment, constpool entries per Section.
1080 SmallVector<unsigned, 4> CPEs;
1081 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1085 /// EmitConstantPool - Print to the current output stream assembly
1086 /// representations of the constants in the constant pool MCP. This is
1087 /// used to print out constants which have been "spilled to memory" by
1088 /// the code generator.
1090 void AsmPrinter::EmitConstantPool() {
1091 const MachineConstantPool *MCP = MF->getConstantPool();
1092 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1093 if (CP.empty()) return;
1095 // Calculate sections for constant pool entries. We collect entries to go into
1096 // the same section together to reduce amount of section switch statements.
1097 SmallVector<SectionCPs, 4> CPSections;
1098 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1099 const MachineConstantPoolEntry &CPE = CP[i];
1100 unsigned Align = CPE.getAlignment();
1103 CPE.getSectionKind(TM.getDataLayout());
1105 const Constant *C = nullptr;
1106 if (!CPE.isMachineConstantPoolEntry())
1107 C = CPE.Val.ConstVal;
1109 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1111 // The number of sections are small, just do a linear search from the
1112 // last section to the first.
1114 unsigned SecIdx = CPSections.size();
1115 while (SecIdx != 0) {
1116 if (CPSections[--SecIdx].S == S) {
1122 SecIdx = CPSections.size();
1123 CPSections.push_back(SectionCPs(S, Align));
1126 if (Align > CPSections[SecIdx].Alignment)
1127 CPSections[SecIdx].Alignment = Align;
1128 CPSections[SecIdx].CPEs.push_back(i);
1131 // Now print stuff into the calculated sections.
1132 const MCSection *CurSection = nullptr;
1133 unsigned Offset = 0;
1134 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1135 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1136 unsigned CPI = CPSections[i].CPEs[j];
1137 MCSymbol *Sym = GetCPISymbol(CPI);
1138 if (!Sym->isUndefined())
1141 if (CurSection != CPSections[i].S) {
1142 OutStreamer.SwitchSection(CPSections[i].S);
1143 EmitAlignment(Log2_32(CPSections[i].Alignment));
1144 CurSection = CPSections[i].S;
1148 MachineConstantPoolEntry CPE = CP[CPI];
1150 // Emit inter-object padding for alignment.
1151 unsigned AlignMask = CPE.getAlignment() - 1;
1152 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1153 OutStreamer.EmitZeros(NewOffset - Offset);
1155 Type *Ty = CPE.getType();
1156 Offset = NewOffset +
1157 TM.getDataLayout()->getTypeAllocSize(Ty);
1159 OutStreamer.EmitLabel(Sym);
1160 if (CPE.isMachineConstantPoolEntry())
1161 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1163 EmitGlobalConstant(CPE.Val.ConstVal);
1168 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1169 /// by the current function to the current output stream.
1171 void AsmPrinter::EmitJumpTableInfo() {
1172 const DataLayout *DL = MF->getTarget().getDataLayout();
1173 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1175 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1176 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1177 if (JT.empty()) return;
1179 // Pick the directive to use to print the jump table entries, and switch to
1180 // the appropriate section.
1181 const Function *F = MF->getFunction();
1182 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1183 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1184 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1186 if (!JTInDiffSection) {
1187 OutStreamer.SwitchSection(TLOF.SectionForGlobal(F, *Mang, TM));
1189 // Otherwise, drop it in the readonly section.
1190 const MCSection *ReadOnlySection =
1191 TLOF.getSectionForJumpTable(*F, *Mang, TM);
1192 OutStreamer.SwitchSection(ReadOnlySection);
1195 EmitAlignment(Log2_32(
1196 MJTI->getEntryAlignment(*TM.getDataLayout())));
1198 // Jump tables in code sections are marked with a data_region directive
1199 // where that's supported.
1200 if (!JTInDiffSection)
1201 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1203 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1204 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1206 // If this jump table was deleted, ignore it.
1207 if (JTBBs.empty()) continue;
1209 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1210 /// emit a .set directive for each unique entry.
1211 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1212 MAI->doesSetDirectiveSuppressesReloc()) {
1213 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1214 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1215 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1216 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1217 const MachineBasicBlock *MBB = JTBBs[ii];
1218 if (!EmittedSets.insert(MBB).second)
1221 // .set LJTSet, LBB32-base
1223 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1224 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1225 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1229 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1230 // before each jump table. The first label is never referenced, but tells
1231 // the assembler and linker the extents of the jump table object. The
1232 // second label is actually referenced by the code.
1233 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1234 // FIXME: This doesn't have to have any specific name, just any randomly
1235 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1236 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1238 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1240 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1241 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1243 if (!JTInDiffSection)
1244 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1247 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1249 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1250 const MachineBasicBlock *MBB,
1251 unsigned UID) const {
1252 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1253 const MCExpr *Value = nullptr;
1254 switch (MJTI->getEntryKind()) {
1255 case MachineJumpTableInfo::EK_Inline:
1256 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1257 case MachineJumpTableInfo::EK_Custom32:
1258 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1259 MJTI, MBB, UID, OutContext);
1261 case MachineJumpTableInfo::EK_BlockAddress:
1262 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1264 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1266 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1267 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1268 // with a relocation as gp-relative, e.g.:
1270 MCSymbol *MBBSym = MBB->getSymbol();
1271 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1275 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1276 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1277 // with a relocation as gp-relative, e.g.:
1279 MCSymbol *MBBSym = MBB->getSymbol();
1280 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1284 case MachineJumpTableInfo::EK_LabelDifference32: {
1285 // Each entry is the address of the block minus the address of the jump
1286 // table. This is used for PIC jump tables where gprel32 is not supported.
1288 // .word LBB123 - LJTI1_2
1289 // If the .set directive avoids relocations, this is emitted as:
1290 // .set L4_5_set_123, LBB123 - LJTI1_2
1291 // .word L4_5_set_123
1292 if (MAI->doesSetDirectiveSuppressesReloc()) {
1293 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1297 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1298 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1299 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1300 Value = MCBinaryExpr::CreateSub(Value, Base, OutContext);
1305 assert(Value && "Unknown entry kind!");
1307 unsigned EntrySize =
1308 MJTI->getEntrySize(*TM.getDataLayout());
1309 OutStreamer.EmitValue(Value, EntrySize);
1313 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1314 /// special global used by LLVM. If so, emit it and return true, otherwise
1315 /// do nothing and return false.
1316 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1317 if (GV->getName() == "llvm.used") {
1318 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1319 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1323 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1324 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1325 GV->hasAvailableExternallyLinkage())
1328 if (!GV->hasAppendingLinkage()) return false;
1330 assert(GV->hasInitializer() && "Not a special LLVM global!");
1332 if (GV->getName() == "llvm.global_ctors") {
1333 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1335 if (TM.getRelocationModel() == Reloc::Static &&
1336 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1337 StringRef Sym(".constructors_used");
1338 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1344 if (GV->getName() == "llvm.global_dtors") {
1345 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1347 if (TM.getRelocationModel() == Reloc::Static &&
1348 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1349 StringRef Sym(".destructors_used");
1350 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1359 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1360 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1361 /// is true, as being used with this directive.
1362 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1363 // Should be an array of 'i8*'.
1364 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1365 const GlobalValue *GV =
1366 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1368 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1374 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1376 llvm::Constant *Func;
1377 llvm::GlobalValue *ComdatKey;
1381 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1383 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1384 // Should be an array of '{ int, void ()* }' structs. The first value is the
1386 if (!isa<ConstantArray>(List)) return;
1388 // Sanity check the structors list.
1389 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1390 if (!InitList) return; // Not an array!
1391 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1392 // FIXME: Only allow the 3-field form in LLVM 4.0.
1393 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1394 return; // Not an array of two or three elements!
1395 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1396 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1397 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1398 return; // Not (int, ptr, ptr).
1400 // Gather the structors in a form that's convenient for sorting by priority.
1401 SmallVector<Structor, 8> Structors;
1402 for (Value *O : InitList->operands()) {
1403 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1404 if (!CS) continue; // Malformed.
1405 if (CS->getOperand(1)->isNullValue())
1406 break; // Found a null terminator, skip the rest.
1407 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1408 if (!Priority) continue; // Malformed.
1409 Structors.push_back(Structor());
1410 Structor &S = Structors.back();
1411 S.Priority = Priority->getLimitedValue(65535);
1412 S.Func = CS->getOperand(1);
1413 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1414 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1417 // Emit the function pointers in the target-specific order
1418 const DataLayout *DL = TM.getDataLayout();
1419 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1420 std::stable_sort(Structors.begin(), Structors.end(),
1421 [](const Structor &L,
1422 const Structor &R) { return L.Priority < R.Priority; });
1423 for (Structor &S : Structors) {
1424 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1425 const MCSymbol *KeySym = nullptr;
1426 if (GlobalValue *GV = S.ComdatKey) {
1427 if (GV->hasAvailableExternallyLinkage())
1428 // If the associated variable is available_externally, some other TU
1429 // will provide its dynamic initializer.
1432 KeySym = getSymbol(GV);
1434 const MCSection *OutputSection =
1435 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1436 : Obj.getStaticDtorSection(S.Priority, KeySym));
1437 OutStreamer.SwitchSection(OutputSection);
1438 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1439 EmitAlignment(Align);
1440 EmitXXStructor(S.Func);
1444 void AsmPrinter::EmitModuleIdents(Module &M) {
1445 if (!MAI->hasIdentDirective())
1448 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1449 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1450 const MDNode *N = NMD->getOperand(i);
1451 assert(N->getNumOperands() == 1 &&
1452 "llvm.ident metadata entry can have only one operand");
1453 const MDString *S = cast<MDString>(N->getOperand(0));
1454 OutStreamer.EmitIdent(S->getString());
1459 //===--------------------------------------------------------------------===//
1460 // Emission and print routines
1463 /// EmitInt8 - Emit a byte directive and value.
1465 void AsmPrinter::EmitInt8(int Value) const {
1466 OutStreamer.EmitIntValue(Value, 1);
1469 /// EmitInt16 - Emit a short directive and value.
1471 void AsmPrinter::EmitInt16(int Value) const {
1472 OutStreamer.EmitIntValue(Value, 2);
1475 /// EmitInt32 - Emit a long directive and value.
1477 void AsmPrinter::EmitInt32(int Value) const {
1478 OutStreamer.EmitIntValue(Value, 4);
1481 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1482 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1483 /// .set if it avoids relocations.
1484 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1485 unsigned Size) const {
1486 // Get the Hi-Lo expression.
1487 const MCExpr *Diff =
1488 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1489 MCSymbolRefExpr::Create(Lo, OutContext),
1492 if (!MAI->doesSetDirectiveSuppressesReloc()) {
1493 OutStreamer.EmitValue(Diff, Size);
1497 // Otherwise, emit with .set (aka assignment).
1498 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1499 OutStreamer.EmitAssignment(SetLabel, Diff);
1500 OutStreamer.EmitSymbolValue(SetLabel, Size);
1503 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1504 /// where the size in bytes of the directive is specified by Size and Label
1505 /// specifies the label. This implicitly uses .set if it is available.
1506 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1508 bool IsSectionRelative) const {
1509 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1510 OutStreamer.EmitCOFFSecRel32(Label);
1514 // Emit Label+Offset (or just Label if Offset is zero)
1515 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1517 Expr = MCBinaryExpr::CreateAdd(
1518 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1520 OutStreamer.EmitValue(Expr, Size);
1523 //===----------------------------------------------------------------------===//
1525 // EmitAlignment - Emit an alignment directive to the specified power of
1526 // two boundary. For example, if you pass in 3 here, you will get an 8
1527 // byte alignment. If a global value is specified, and if that global has
1528 // an explicit alignment requested, it will override the alignment request
1529 // if required for correctness.
1531 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1533 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1536 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1539 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1540 "undefined behavior");
1541 if (getCurrentSection()->getKind().isText())
1542 OutStreamer.EmitCodeAlignment(1u << NumBits);
1544 OutStreamer.EmitValueToAlignment(1u << NumBits);
1547 //===----------------------------------------------------------------------===//
1548 // Constant emission.
1549 //===----------------------------------------------------------------------===//
1551 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1552 MCContext &Ctx = OutContext;
1554 if (CV->isNullValue() || isa<UndefValue>(CV))
1555 return MCConstantExpr::Create(0, Ctx);
1557 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1558 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1560 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1561 return MCSymbolRefExpr::Create(getSymbol(GV), Ctx);
1563 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1564 return MCSymbolRefExpr::Create(GetBlockAddressSymbol(BA), Ctx);
1566 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1568 llvm_unreachable("Unknown constant value to lower!");
1571 if (const MCExpr *RelocExpr
1572 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1575 switch (CE->getOpcode()) {
1577 // If the code isn't optimized, there may be outstanding folding
1578 // opportunities. Attempt to fold the expression using DataLayout as a
1579 // last resort before giving up.
1580 if (Constant *C = ConstantFoldConstantExpression(
1581 CE, TM.getDataLayout()))
1583 return lowerConstant(C);
1585 // Otherwise report the problem to the user.
1588 raw_string_ostream OS(S);
1589 OS << "Unsupported expression in static initializer: ";
1590 CE->printAsOperand(OS, /*PrintType=*/false,
1591 !MF ? nullptr : MF->getFunction()->getParent());
1592 report_fatal_error(OS.str());
1594 case Instruction::GetElementPtr: {
1595 const DataLayout &DL = *TM.getDataLayout();
1597 // Generate a symbolic expression for the byte address
1598 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1599 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1601 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1605 int64_t Offset = OffsetAI.getSExtValue();
1606 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1610 case Instruction::Trunc:
1611 // We emit the value and depend on the assembler to truncate the generated
1612 // expression properly. This is important for differences between
1613 // blockaddress labels. Since the two labels are in the same function, it
1614 // is reasonable to treat their delta as a 32-bit value.
1616 case Instruction::BitCast:
1617 return lowerConstant(CE->getOperand(0));
1619 case Instruction::IntToPtr: {
1620 const DataLayout &DL = *TM.getDataLayout();
1622 // Handle casts to pointers by changing them into casts to the appropriate
1623 // integer type. This promotes constant folding and simplifies this code.
1624 Constant *Op = CE->getOperand(0);
1625 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1627 return lowerConstant(Op);
1630 case Instruction::PtrToInt: {
1631 const DataLayout &DL = *TM.getDataLayout();
1633 // Support only foldable casts to/from pointers that can be eliminated by
1634 // changing the pointer to the appropriately sized integer type.
1635 Constant *Op = CE->getOperand(0);
1636 Type *Ty = CE->getType();
1638 const MCExpr *OpExpr = lowerConstant(Op);
1640 // We can emit the pointer value into this slot if the slot is an
1641 // integer slot equal to the size of the pointer.
1642 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1645 // Otherwise the pointer is smaller than the resultant integer, mask off
1646 // the high bits so we are sure to get a proper truncation if the input is
1648 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1649 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1650 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1653 // The MC library also has a right-shift operator, but it isn't consistently
1654 // signed or unsigned between different targets.
1655 case Instruction::Add:
1656 case Instruction::Sub:
1657 case Instruction::Mul:
1658 case Instruction::SDiv:
1659 case Instruction::SRem:
1660 case Instruction::Shl:
1661 case Instruction::And:
1662 case Instruction::Or:
1663 case Instruction::Xor: {
1664 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1665 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1666 switch (CE->getOpcode()) {
1667 default: llvm_unreachable("Unknown binary operator constant cast expr");
1668 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1669 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1670 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1671 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1672 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1673 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1674 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1675 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1676 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1682 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1684 /// isRepeatedByteSequence - Determine whether the given value is
1685 /// composed of a repeated sequence of identical bytes and return the
1686 /// byte value. If it is not a repeated sequence, return -1.
1687 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1688 StringRef Data = V->getRawDataValues();
1689 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1691 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1692 if (Data[i] != C) return -1;
1693 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1697 /// isRepeatedByteSequence - Determine whether the given value is
1698 /// composed of a repeated sequence of identical bytes and return the
1699 /// byte value. If it is not a repeated sequence, return -1.
1700 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1702 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1703 if (CI->getBitWidth() > 64) return -1;
1706 TM.getDataLayout()->getTypeAllocSize(V->getType());
1707 uint64_t Value = CI->getZExtValue();
1709 // Make sure the constant is at least 8 bits long and has a power
1710 // of 2 bit width. This guarantees the constant bit width is
1711 // always a multiple of 8 bits, avoiding issues with padding out
1712 // to Size and other such corner cases.
1713 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1715 uint8_t Byte = static_cast<uint8_t>(Value);
1717 for (unsigned i = 1; i < Size; ++i) {
1719 if (static_cast<uint8_t>(Value) != Byte) return -1;
1723 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1724 // Make sure all array elements are sequences of the same repeated
1726 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1727 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1728 if (Byte == -1) return -1;
1730 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1731 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1732 if (ThisByte == -1) return -1;
1733 if (Byte != ThisByte) return -1;
1738 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1739 return isRepeatedByteSequence(CDS);
1744 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1747 // See if we can aggregate this into a .fill, if so, emit it as such.
1748 int Value = isRepeatedByteSequence(CDS, AP.TM);
1751 AP.TM.getDataLayout()->getTypeAllocSize(
1753 // Don't emit a 1-byte object as a .fill.
1755 return AP.OutStreamer.EmitFill(Bytes, Value);
1758 // If this can be emitted with .ascii/.asciz, emit it as such.
1759 if (CDS->isString())
1760 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1762 // Otherwise, emit the values in successive locations.
1763 unsigned ElementByteSize = CDS->getElementByteSize();
1764 if (isa<IntegerType>(CDS->getElementType())) {
1765 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1767 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1768 CDS->getElementAsInteger(i));
1769 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1772 } else if (ElementByteSize == 4) {
1773 // FP Constants are printed as integer constants to avoid losing
1775 assert(CDS->getElementType()->isFloatTy());
1776 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1782 F = CDS->getElementAsFloat(i);
1784 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1785 AP.OutStreamer.EmitIntValue(I, 4);
1788 assert(CDS->getElementType()->isDoubleTy());
1789 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1795 F = CDS->getElementAsDouble(i);
1797 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1798 AP.OutStreamer.EmitIntValue(I, 8);
1802 const DataLayout &DL = *AP.TM.getDataLayout();
1803 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1804 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1805 CDS->getNumElements();
1806 if (unsigned Padding = Size - EmittedSize)
1807 AP.OutStreamer.EmitZeros(Padding);
1811 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1812 // See if we can aggregate some values. Make sure it can be
1813 // represented as a series of bytes of the constant value.
1814 int Value = isRepeatedByteSequence(CA, AP.TM);
1818 AP.TM.getDataLayout()->getTypeAllocSize(
1820 AP.OutStreamer.EmitFill(Bytes, Value);
1823 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1824 emitGlobalConstantImpl(CA->getOperand(i), AP);
1828 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1829 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1830 emitGlobalConstantImpl(CV->getOperand(i), AP);
1832 const DataLayout &DL = *AP.TM.getDataLayout();
1833 unsigned Size = DL.getTypeAllocSize(CV->getType());
1834 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1835 CV->getType()->getNumElements();
1836 if (unsigned Padding = Size - EmittedSize)
1837 AP.OutStreamer.EmitZeros(Padding);
1840 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1841 // Print the fields in successive locations. Pad to align if needed!
1842 const DataLayout *DL = AP.TM.getDataLayout();
1843 unsigned Size = DL->getTypeAllocSize(CS->getType());
1844 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1845 uint64_t SizeSoFar = 0;
1846 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1847 const Constant *Field = CS->getOperand(i);
1849 // Check if padding is needed and insert one or more 0s.
1850 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1851 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1852 - Layout->getElementOffset(i)) - FieldSize;
1853 SizeSoFar += FieldSize + PadSize;
1855 // Now print the actual field value.
1856 emitGlobalConstantImpl(Field, AP);
1858 // Insert padding - this may include padding to increase the size of the
1859 // current field up to the ABI size (if the struct is not packed) as well
1860 // as padding to ensure that the next field starts at the right offset.
1861 AP.OutStreamer.EmitZeros(PadSize);
1863 assert(SizeSoFar == Layout->getSizeInBytes() &&
1864 "Layout of constant struct may be incorrect!");
1867 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1868 APInt API = CFP->getValueAPF().bitcastToAPInt();
1870 // First print a comment with what we think the original floating-point value
1871 // should have been.
1872 if (AP.isVerbose()) {
1873 SmallString<8> StrVal;
1874 CFP->getValueAPF().toString(StrVal);
1877 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1879 AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
1880 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1883 // Now iterate through the APInt chunks, emitting them in endian-correct
1884 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1886 unsigned NumBytes = API.getBitWidth() / 8;
1887 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1888 const uint64_t *p = API.getRawData();
1890 // PPC's long double has odd notions of endianness compared to how LLVM
1891 // handles it: p[0] goes first for *big* endian on PPC.
1892 if (AP.TM.getDataLayout()->isBigEndian() &&
1893 !CFP->getType()->isPPC_FP128Ty()) {
1894 int Chunk = API.getNumWords() - 1;
1897 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1899 for (; Chunk >= 0; --Chunk)
1900 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1903 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1904 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1907 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1910 // Emit the tail padding for the long double.
1911 const DataLayout &DL = *AP.TM.getDataLayout();
1912 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1913 DL.getTypeStoreSize(CFP->getType()));
1916 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1917 const DataLayout *DL = AP.TM.getDataLayout();
1918 unsigned BitWidth = CI->getBitWidth();
1920 // Copy the value as we may massage the layout for constants whose bit width
1921 // is not a multiple of 64-bits.
1922 APInt Realigned(CI->getValue());
1923 uint64_t ExtraBits = 0;
1924 unsigned ExtraBitsSize = BitWidth & 63;
1926 if (ExtraBitsSize) {
1927 // The bit width of the data is not a multiple of 64-bits.
1928 // The extra bits are expected to be at the end of the chunk of the memory.
1930 // * Nothing to be done, just record the extra bits to emit.
1932 // * Record the extra bits to emit.
1933 // * Realign the raw data to emit the chunks of 64-bits.
1934 if (DL->isBigEndian()) {
1935 // Basically the structure of the raw data is a chunk of 64-bits cells:
1936 // 0 1 BitWidth / 64
1937 // [chunk1][chunk2] ... [chunkN].
1938 // The most significant chunk is chunkN and it should be emitted first.
1939 // However, due to the alignment issue chunkN contains useless bits.
1940 // Realign the chunks so that they contain only useless information:
1941 // ExtraBits 0 1 (BitWidth / 64) - 1
1942 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1943 ExtraBits = Realigned.getRawData()[0] &
1944 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1945 Realigned = Realigned.lshr(ExtraBitsSize);
1947 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1950 // We don't expect assemblers to support integer data directives
1951 // for more than 64 bits, so we emit the data in at most 64-bit
1952 // quantities at a time.
1953 const uint64_t *RawData = Realigned.getRawData();
1954 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1955 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1956 AP.OutStreamer.EmitIntValue(Val, 8);
1959 if (ExtraBitsSize) {
1960 // Emit the extra bits after the 64-bits chunks.
1962 // Emit a directive that fills the expected size.
1963 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
1965 Size -= (BitWidth / 64) * 8;
1966 assert(Size && Size * 8 >= ExtraBitsSize &&
1967 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1968 == ExtraBits && "Directive too small for extra bits.");
1969 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1973 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1974 const DataLayout *DL = AP.TM.getDataLayout();
1975 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1976 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1977 return AP.OutStreamer.EmitZeros(Size);
1979 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1986 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1987 CI->getZExtValue());
1988 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1991 emitGlobalConstantLargeInt(CI, AP);
1996 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1997 return emitGlobalConstantFP(CFP, AP);
1999 if (isa<ConstantPointerNull>(CV)) {
2000 AP.OutStreamer.EmitIntValue(0, Size);
2004 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2005 return emitGlobalConstantDataSequential(CDS, AP);
2007 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2008 return emitGlobalConstantArray(CVA, AP);
2010 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2011 return emitGlobalConstantStruct(CVS, AP);
2013 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2014 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2016 if (CE->getOpcode() == Instruction::BitCast)
2017 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2020 // If the constant expression's size is greater than 64-bits, then we have
2021 // to emit the value in chunks. Try to constant fold the value and emit it
2023 Constant *New = ConstantFoldConstantExpression(CE, DL);
2024 if (New && New != CE)
2025 return emitGlobalConstantImpl(New, AP);
2029 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2030 return emitGlobalConstantVector(V, AP);
2032 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2033 // thread the streamer with EmitValue.
2034 AP.OutStreamer.EmitValue(AP.lowerConstant(CV), Size);
2037 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2038 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2040 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2042 emitGlobalConstantImpl(CV, *this);
2043 else if (MAI->hasSubsectionsViaSymbols()) {
2044 // If the global has zero size, emit a single byte so that two labels don't
2045 // look like they are at the same location.
2046 OutStreamer.EmitIntValue(0, 1);
2050 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2051 // Target doesn't support this yet!
2052 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2055 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2057 OS << '+' << Offset;
2058 else if (Offset < 0)
2062 //===----------------------------------------------------------------------===//
2063 // Symbol Lowering Routines.
2064 //===----------------------------------------------------------------------===//
2066 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2067 /// temporary label with the specified stem and unique ID.
2068 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name, unsigned ID) const {
2069 const DataLayout *DL = TM.getDataLayout();
2070 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2074 /// GetTempSymbol - Return an assembler temporary label with the specified
2076 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name) const {
2077 const DataLayout *DL = TM.getDataLayout();
2078 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2083 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2084 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2087 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2088 return MMI->getAddrLabelSymbol(BB);
2091 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2092 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2093 const DataLayout *DL = TM.getDataLayout();
2094 return OutContext.GetOrCreateSymbol
2095 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2096 + "_" + Twine(CPID));
2099 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2100 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2101 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2104 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2105 /// FIXME: privatize to AsmPrinter.
2106 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2107 const DataLayout *DL = TM.getDataLayout();
2108 return OutContext.GetOrCreateSymbol
2109 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2110 Twine(UID) + "_set_" + Twine(MBBID));
2113 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2114 StringRef Suffix) const {
2115 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2119 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2121 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2122 SmallString<60> NameStr;
2123 Mang->getNameWithPrefix(NameStr, Sym);
2124 return OutContext.GetOrCreateSymbol(NameStr.str());
2129 /// PrintParentLoopComment - Print comments about parent loops of this one.
2130 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2131 unsigned FunctionNumber) {
2133 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2134 OS.indent(Loop->getLoopDepth()*2)
2135 << "Parent Loop BB" << FunctionNumber << "_"
2136 << Loop->getHeader()->getNumber()
2137 << " Depth=" << Loop->getLoopDepth() << '\n';
2141 /// PrintChildLoopComment - Print comments about child loops within
2142 /// the loop for this basic block, with nesting.
2143 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2144 unsigned FunctionNumber) {
2145 // Add child loop information
2146 for (const MachineLoop *CL : *Loop) {
2147 OS.indent(CL->getLoopDepth()*2)
2148 << "Child Loop BB" << FunctionNumber << "_"
2149 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2151 PrintChildLoopComment(OS, CL, FunctionNumber);
2155 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2156 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2157 const MachineLoopInfo *LI,
2158 const AsmPrinter &AP) {
2159 // Add loop depth information
2160 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2163 MachineBasicBlock *Header = Loop->getHeader();
2164 assert(Header && "No header for loop");
2166 // If this block is not a loop header, just print out what is the loop header
2168 if (Header != &MBB) {
2169 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2170 Twine(AP.getFunctionNumber())+"_" +
2171 Twine(Loop->getHeader()->getNumber())+
2172 " Depth="+Twine(Loop->getLoopDepth()));
2176 // Otherwise, it is a loop header. Print out information about child and
2178 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2180 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2183 OS.indent(Loop->getLoopDepth()*2-2);
2188 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2190 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2194 /// EmitBasicBlockStart - This method prints the label for the specified
2195 /// MachineBasicBlock, an alignment (if present) and a comment describing
2196 /// it if appropriate.
2197 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2198 // Emit an alignment directive for this block, if needed.
2199 if (unsigned Align = MBB.getAlignment())
2200 EmitAlignment(Align);
2202 // If the block has its address taken, emit any labels that were used to
2203 // reference the block. It is possible that there is more than one label
2204 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2205 // the references were generated.
2206 if (MBB.hasAddressTaken()) {
2207 const BasicBlock *BB = MBB.getBasicBlock();
2209 OutStreamer.AddComment("Block address taken");
2211 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2212 for (auto *Sym : Symbols)
2213 OutStreamer.EmitLabel(Sym);
2216 // Print some verbose block comments.
2218 if (const BasicBlock *BB = MBB.getBasicBlock())
2220 OutStreamer.AddComment("%" + BB->getName());
2221 emitBasicBlockLoopComments(MBB, LI, *this);
2224 // Print the main label for the block.
2225 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2227 // NOTE: Want this comment at start of line, don't emit with AddComment.
2228 OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2231 OutStreamer.EmitLabel(MBB.getSymbol());
2235 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2236 bool IsDefinition) const {
2237 MCSymbolAttr Attr = MCSA_Invalid;
2239 switch (Visibility) {
2241 case GlobalValue::HiddenVisibility:
2243 Attr = MAI->getHiddenVisibilityAttr();
2245 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2247 case GlobalValue::ProtectedVisibility:
2248 Attr = MAI->getProtectedVisibilityAttr();
2252 if (Attr != MCSA_Invalid)
2253 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2256 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2257 /// exactly one predecessor and the control transfer mechanism between
2258 /// the predecessor and this block is a fall-through.
2260 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2261 // If this is a landing pad, it isn't a fall through. If it has no preds,
2262 // then nothing falls through to it.
2263 if (MBB->isLandingPad() || MBB->pred_empty())
2266 // If there isn't exactly one predecessor, it can't be a fall through.
2267 if (MBB->pred_size() > 1)
2270 // The predecessor has to be immediately before this block.
2271 MachineBasicBlock *Pred = *MBB->pred_begin();
2272 if (!Pred->isLayoutSuccessor(MBB))
2275 // If the block is completely empty, then it definitely does fall through.
2279 // Check the terminators in the previous blocks
2280 for (const auto &MI : Pred->terminators()) {
2281 // If it is not a simple branch, we are in a table somewhere.
2282 if (!MI.isBranch() || MI.isIndirectBranch())
2285 // If we are the operands of one of the branches, this is not a fall
2286 // through. Note that targets with delay slots will usually bundle
2287 // terminators with the delay slot instruction.
2288 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2291 if (OP->isMBB() && OP->getMBB() == MBB)
2301 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2302 if (!S.usesMetadata())
2305 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2306 " stackmap formats, please see the documentation for a description of"
2307 " the default format. If you really need a custom serialized format,"
2308 " please file a bug");
2310 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2311 gcp_map_type::iterator GCPI = GCMap.find(&S);
2312 if (GCPI != GCMap.end())
2313 return GCPI->second.get();
2315 const char *Name = S.getName().c_str();
2317 for (GCMetadataPrinterRegistry::iterator
2318 I = GCMetadataPrinterRegistry::begin(),
2319 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2320 if (strcmp(Name, I->getName()) == 0) {
2321 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2323 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2324 return IterBool.first->second.get();
2327 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2330 /// Pin vtable to this file.
2331 AsmPrinterHandler::~AsmPrinterHandler() {}