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 "WinException.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/MachineModuleInfoImpls.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/MCSymbolELF.h"
44 #include "llvm/MC/MCValue.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetLoweringObjectFile.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
58 #define DEBUG_TYPE "asm-printer"
60 static const char *const DWARFGroupName = "DWARF Emission";
61 static const char *const DbgTimerName = "Debug Info Emission";
62 static const char *const EHTimerName = "DWARF Exception Writer";
63 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
65 STATISTIC(EmittedInsts, "Number of machine instrs printed");
67 char AsmPrinter::ID = 0;
69 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
70 static gcp_map_type &getGCMap(void *&P) {
72 P = new gcp_map_type();
73 return *(gcp_map_type*)P;
77 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
78 /// value in log2 form. This rounds up to the preferred alignment if possible
80 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
81 unsigned InBits = 0) {
83 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
84 NumBits = DL.getPreferredAlignmentLog(GVar);
86 // If InBits is specified, round it to it.
90 // If the GV has a specified alignment, take it into account.
91 if (GV->getAlignment() == 0)
94 unsigned GVAlign = Log2_32(GV->getAlignment());
96 // If the GVAlign is larger than NumBits, or if we are required to obey
97 // NumBits because the GV has an assigned section, obey it.
98 if (GVAlign > NumBits || GV->hasSection())
103 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
104 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
105 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
106 LastMI(nullptr), LastFn(0), Counter(~0U) {
111 CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
112 CurrentFnBegin = nullptr;
113 CurrentFnEnd = nullptr;
114 GCMetadataPrinters = nullptr;
115 VerboseAsm = OutStreamer->isVerboseAsm();
118 AsmPrinter::~AsmPrinter() {
119 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
121 if (GCMetadataPrinters) {
122 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
125 GCMetadataPrinters = nullptr;
129 /// getFunctionNumber - Return a unique ID for the current function.
131 unsigned AsmPrinter::getFunctionNumber() const {
132 return MF->getFunctionNumber();
135 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
136 return *TM.getObjFileLowering();
139 /// getDataLayout - Return information about data layout.
140 const DataLayout &AsmPrinter::getDataLayout() const {
141 return *TM.getDataLayout();
144 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
145 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
146 return MF->getSubtarget<MCSubtargetInfo>();
149 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
150 S.EmitInstruction(Inst, getSubtargetInfo());
153 StringRef AsmPrinter::getTargetTriple() const {
154 return TM.getTargetTriple();
157 /// getCurrentSection() - Return the current section we are emitting to.
158 const MCSection *AsmPrinter::getCurrentSection() const {
159 return OutStreamer->getCurrentSection().first;
164 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
165 AU.setPreservesAll();
166 MachineFunctionPass::getAnalysisUsage(AU);
167 AU.addRequired<MachineModuleInfo>();
168 AU.addRequired<GCModuleInfo>();
170 AU.addRequired<MachineLoopInfo>();
173 bool AsmPrinter::doInitialization(Module &M) {
174 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
175 MMI->AnalyzeModule(M);
177 // Initialize TargetLoweringObjectFile.
178 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
179 .Initialize(OutContext, TM);
181 OutStreamer->InitSections(false);
183 Mang = new Mangler(TM.getDataLayout());
185 // Emit the version-min deplyment target directive if needed.
187 // FIXME: If we end up with a collection of these sorts of Darwin-specific
188 // or ELF-specific things, it may make sense to have a platform helper class
189 // that will work with the target helper class. For now keep it here, as the
190 // alternative is duplicated code in each of the target asm printers that
191 // use the directive, where it would need the same conditionalization
193 Triple TT(getTargetTriple());
194 if (TT.isOSDarwin()) {
195 unsigned Major, Minor, Update;
196 TT.getOSVersion(Major, Minor, Update);
197 // If there is a version specified, Major will be non-zero.
199 OutStreamer->EmitVersionMin((TT.isMacOSX() ?
200 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
201 Major, Minor, Update);
204 // Allow the target to emit any magic that it wants at the start of the file.
205 EmitStartOfAsmFile(M);
207 // Very minimal debug info. It is ignored if we emit actual debug info. If we
208 // don't, this at least helps the user find where a global came from.
209 if (MAI->hasSingleParameterDotFile()) {
211 OutStreamer->EmitFileDirective(M.getModuleIdentifier());
214 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
215 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
217 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
218 MP->beginAssembly(M, *MI, *this);
220 // Emit module-level inline asm if it exists.
221 if (!M.getModuleInlineAsm().empty()) {
222 // We're at the module level. Construct MCSubtarget from the default CPU
223 // and target triple.
224 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
225 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
226 OutStreamer->AddComment("Start of file scope inline assembly");
227 OutStreamer->AddBlankLine();
228 EmitInlineAsm(M.getModuleInlineAsm()+"\n", *STI, TM.Options.MCOptions);
229 OutStreamer->AddComment("End of file scope inline assembly");
230 OutStreamer->AddBlankLine();
233 if (MAI->doesSupportDebugInformation()) {
234 bool skip_dwarf = false;
235 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
236 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
238 CodeViewLineTablesGroupName));
239 // FIXME: Don't emit DWARF debug info if there's at least one function
240 // with AddressSanitizer instrumentation.
241 // This is a band-aid fix for PR22032.
242 for (auto &F : M.functions()) {
243 if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
250 DD = new DwarfDebug(this, &M);
251 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
255 EHStreamer *ES = nullptr;
256 switch (MAI->getExceptionHandlingType()) {
257 case ExceptionHandling::None:
259 case ExceptionHandling::SjLj:
260 case ExceptionHandling::DwarfCFI:
261 ES = new DwarfCFIException(this);
263 case ExceptionHandling::ARM:
264 ES = new ARMException(this);
266 case ExceptionHandling::WinEH:
267 switch (MAI->getWinEHEncodingType()) {
268 default: llvm_unreachable("unsupported unwinding information encoding");
269 case WinEH::EncodingType::Invalid:
271 case WinEH::EncodingType::X86:
272 case WinEH::EncodingType::Itanium:
273 ES = new WinException(this);
279 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
283 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
284 if (!MAI.hasWeakDefCanBeHiddenDirective())
287 return canBeOmittedFromSymbolTable(GV);
290 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
291 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
293 case GlobalValue::CommonLinkage:
294 case GlobalValue::LinkOnceAnyLinkage:
295 case GlobalValue::LinkOnceODRLinkage:
296 case GlobalValue::WeakAnyLinkage:
297 case GlobalValue::WeakODRLinkage:
298 if (MAI->hasWeakDefDirective()) {
300 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
302 if (!canBeHidden(GV, *MAI))
303 // .weak_definition _foo
304 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
306 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
307 } else if (MAI->hasLinkOnceDirective()) {
309 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
310 //NOTE: linkonce is handled by the section the symbol was assigned to.
313 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
316 case GlobalValue::AppendingLinkage:
317 // FIXME: appending linkage variables should go into a section of
318 // their name or something. For now, just emit them as external.
319 case GlobalValue::ExternalLinkage:
320 // If external or appending, declare as a global symbol.
322 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
324 case GlobalValue::PrivateLinkage:
325 case GlobalValue::InternalLinkage:
327 case GlobalValue::AvailableExternallyLinkage:
328 llvm_unreachable("Should never emit this");
329 case GlobalValue::ExternalWeakLinkage:
330 llvm_unreachable("Don't know how to emit these");
332 llvm_unreachable("Unknown linkage type!");
335 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
336 const GlobalValue *GV) const {
337 TM.getNameWithPrefix(Name, GV, *Mang);
340 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
341 return TM.getSymbol(GV, *Mang);
344 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
345 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
346 if (GV->hasInitializer()) {
347 // Check to see if this is a special global used by LLVM, if so, emit it.
348 if (EmitSpecialLLVMGlobal(GV))
351 // Skip the emission of global equivalents. The symbol can be emitted later
352 // on by emitGlobalGOTEquivs in case it turns out to be needed.
353 if (GlobalGOTEquivs.count(getSymbol(GV)))
357 GV->printAsOperand(OutStreamer->GetCommentOS(),
358 /*PrintType=*/false, GV->getParent());
359 OutStreamer->GetCommentOS() << '\n';
363 MCSymbol *GVSym = getSymbol(GV);
364 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
366 if (!GV->hasInitializer()) // External globals require no extra code.
369 GVSym->redefineIfPossible();
370 if (GVSym->isDefined() || GVSym->isVariable())
371 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
372 "' is already defined");
374 if (MAI->hasDotTypeDotSizeDirective())
375 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
377 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
379 const DataLayout *DL = TM.getDataLayout();
380 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
382 // If the alignment is specified, we *must* obey it. Overaligning a global
383 // with a specified alignment is a prompt way to break globals emitted to
384 // sections and expected to be contiguous (e.g. ObjC metadata).
385 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
387 for (const HandlerInfo &HI : Handlers) {
388 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
389 HI.Handler->setSymbolSize(GVSym, Size);
392 // Handle common and BSS local symbols (.lcomm).
393 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
394 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
395 unsigned Align = 1 << AlignLog;
397 // Handle common symbols.
398 if (GVKind.isCommon()) {
399 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
403 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
407 // Handle local BSS symbols.
408 if (MAI->hasMachoZeroFillDirective()) {
409 MCSection *TheSection =
410 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
411 // .zerofill __DATA, __bss, _foo, 400, 5
412 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
416 // Use .lcomm only if it supports user-specified alignment.
417 // Otherwise, while it would still be correct to use .lcomm in some
418 // cases (e.g. when Align == 1), the external assembler might enfore
419 // some -unknown- default alignment behavior, which could cause
420 // spurious differences between external and integrated assembler.
421 // Prefer to simply fall back to .local / .comm in this case.
422 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
424 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
428 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
432 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
434 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
438 MCSection *TheSection =
439 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
441 // Handle the zerofill directive on darwin, which is a special form of BSS
443 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
444 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
447 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
448 // .zerofill __DATA, __common, _foo, 400, 5
449 OutStreamer->EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
453 // Handle thread local data for mach-o which requires us to output an
454 // additional structure of data and mangle the original symbol so that we
455 // can reference it later.
457 // TODO: This should become an "emit thread local global" method on TLOF.
458 // All of this macho specific stuff should be sunk down into TLOFMachO and
459 // stuff like "TLSExtraDataSection" should no longer be part of the parent
460 // TLOF class. This will also make it more obvious that stuff like
461 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
463 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
464 // Emit the .tbss symbol
466 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
468 if (GVKind.isThreadBSS()) {
469 TheSection = getObjFileLowering().getTLSBSSSection();
470 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
471 } else if (GVKind.isThreadData()) {
472 OutStreamer->SwitchSection(TheSection);
474 EmitAlignment(AlignLog, GV);
475 OutStreamer->EmitLabel(MangSym);
477 EmitGlobalConstant(GV->getInitializer());
480 OutStreamer->AddBlankLine();
482 // Emit the variable struct for the runtime.
483 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
485 OutStreamer->SwitchSection(TLVSect);
486 // Emit the linkage here.
487 EmitLinkage(GV, GVSym);
488 OutStreamer->EmitLabel(GVSym);
490 // Three pointers in size:
491 // - __tlv_bootstrap - used to make sure support exists
492 // - spare pointer, used when mapped by the runtime
493 // - pointer to mangled symbol above with initializer
494 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
495 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
497 OutStreamer->EmitIntValue(0, PtrSize);
498 OutStreamer->EmitSymbolValue(MangSym, PtrSize);
500 OutStreamer->AddBlankLine();
504 OutStreamer->SwitchSection(TheSection);
506 EmitLinkage(GV, GVSym);
507 EmitAlignment(AlignLog, GV);
509 OutStreamer->EmitLabel(GVSym);
511 EmitGlobalConstant(GV->getInitializer());
513 if (MAI->hasDotTypeDotSizeDirective())
515 OutStreamer->emitELFSize(cast<MCSymbolELF>(GVSym),
516 MCConstantExpr::create(Size, OutContext));
518 OutStreamer->AddBlankLine();
521 /// EmitFunctionHeader - This method emits the header for the current
523 void AsmPrinter::EmitFunctionHeader() {
524 // Print out constants referenced by the function
527 // Print the 'header' of function.
528 const Function *F = MF->getFunction();
530 OutStreamer->SwitchSection(
531 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
532 EmitVisibility(CurrentFnSym, F->getVisibility());
534 EmitLinkage(F, CurrentFnSym);
535 if (MAI->hasFunctionAlignment())
536 EmitAlignment(MF->getAlignment(), F);
538 if (MAI->hasDotTypeDotSizeDirective())
539 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
542 F->printAsOperand(OutStreamer->GetCommentOS(),
543 /*PrintType=*/false, F->getParent());
544 OutStreamer->GetCommentOS() << '\n';
547 // Emit the prefix data.
548 if (F->hasPrefixData())
549 EmitGlobalConstant(F->getPrefixData());
551 // Emit the CurrentFnSym. This is a virtual function to allow targets to
552 // do their wild and crazy things as required.
553 EmitFunctionEntryLabel();
555 // If the function had address-taken blocks that got deleted, then we have
556 // references to the dangling symbols. Emit them at the start of the function
557 // so that we don't get references to undefined symbols.
558 std::vector<MCSymbol*> DeadBlockSyms;
559 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
560 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
561 OutStreamer->AddComment("Address taken block that was later removed");
562 OutStreamer->EmitLabel(DeadBlockSyms[i]);
565 if (CurrentFnBegin) {
566 if (MAI->useAssignmentForEHBegin()) {
567 MCSymbol *CurPos = OutContext.createTempSymbol();
568 OutStreamer->EmitLabel(CurPos);
569 OutStreamer->EmitAssignment(CurrentFnBegin,
570 MCSymbolRefExpr::create(CurPos, OutContext));
572 OutStreamer->EmitLabel(CurrentFnBegin);
576 // Emit pre-function debug and/or EH information.
577 for (const HandlerInfo &HI : Handlers) {
578 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
579 HI.Handler->beginFunction(MF);
582 // Emit the prologue data.
583 if (F->hasPrologueData())
584 EmitGlobalConstant(F->getPrologueData());
587 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
588 /// function. This can be overridden by targets as required to do custom stuff.
589 void AsmPrinter::EmitFunctionEntryLabel() {
590 CurrentFnSym->redefineIfPossible();
592 // The function label could have already been emitted if two symbols end up
593 // conflicting due to asm renaming. Detect this and emit an error.
594 if (CurrentFnSym->isVariable())
595 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
596 "' is a protected alias");
597 if (CurrentFnSym->isDefined())
598 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
599 "' label emitted multiple times to assembly file");
601 return OutStreamer->EmitLabel(CurrentFnSym);
604 /// emitComments - Pretty-print comments for instructions.
605 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
606 const MachineFunction *MF = MI.getParent()->getParent();
607 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
609 // Check for spills and reloads
612 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
614 // We assume a single instruction only has a spill or reload, not
616 const MachineMemOperand *MMO;
617 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
618 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
619 MMO = *MI.memoperands_begin();
620 CommentOS << MMO->getSize() << "-byte Reload\n";
622 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
623 if (FrameInfo->isSpillSlotObjectIndex(FI))
624 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
625 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
626 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
627 MMO = *MI.memoperands_begin();
628 CommentOS << MMO->getSize() << "-byte Spill\n";
630 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
631 if (FrameInfo->isSpillSlotObjectIndex(FI))
632 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
635 // Check for spill-induced copies
636 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
637 CommentOS << " Reload Reuse\n";
640 /// emitImplicitDef - This method emits the specified machine instruction
641 /// that is an implicit def.
642 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
643 unsigned RegNo = MI->getOperand(0).getReg();
644 OutStreamer->AddComment(Twine("implicit-def: ") +
645 MMI->getContext().getRegisterInfo()->getName(RegNo));
646 OutStreamer->AddBlankLine();
649 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
650 std::string Str = "kill:";
651 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
652 const MachineOperand &Op = MI->getOperand(i);
653 assert(Op.isReg() && "KILL instruction must have only register operands");
655 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
656 Str += (Op.isDef() ? "<def>" : "<kill>");
658 AP.OutStreamer->AddComment(Str);
659 AP.OutStreamer->AddBlankLine();
662 /// emitDebugValueComment - This method handles the target-independent form
663 /// of DBG_VALUE, returning true if it was able to do so. A false return
664 /// means the target will need to handle MI in EmitInstruction.
665 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
666 // This code handles only the 4-operand target-independent form.
667 if (MI->getNumOperands() != 4)
670 SmallString<128> Str;
671 raw_svector_ostream OS(Str);
672 OS << "DEBUG_VALUE: ";
674 const DILocalVariable *V = MI->getDebugVariable();
675 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
676 StringRef Name = SP->getDisplayName();
682 const DIExpression *Expr = MI->getDebugExpression();
683 if (Expr->isBitPiece())
684 OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
685 << " size=" << Expr->getBitPieceSize() << "]";
688 // The second operand is only an offset if it's an immediate.
689 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
690 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
692 // Register or immediate value. Register 0 means undef.
693 if (MI->getOperand(0).isFPImm()) {
694 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
695 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
696 OS << (double)APF.convertToFloat();
697 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
698 OS << APF.convertToDouble();
700 // There is no good way to print long double. Convert a copy to
701 // double. Ah well, it's only a comment.
703 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
705 OS << "(long double) " << APF.convertToDouble();
707 } else if (MI->getOperand(0).isImm()) {
708 OS << MI->getOperand(0).getImm();
709 } else if (MI->getOperand(0).isCImm()) {
710 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
713 if (MI->getOperand(0).isReg()) {
714 Reg = MI->getOperand(0).getReg();
716 assert(MI->getOperand(0).isFI() && "Unknown operand type");
717 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
718 Offset += TFI->getFrameIndexReference(*AP.MF,
719 MI->getOperand(0).getIndex(), Reg);
723 // Suppress offset, it is not meaningful here.
725 // NOTE: Want this comment at start of line, don't emit with AddComment.
726 AP.OutStreamer->emitRawComment(OS.str());
731 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
735 OS << '+' << Offset << ']';
737 // NOTE: Want this comment at start of line, don't emit with AddComment.
738 AP.OutStreamer->emitRawComment(OS.str());
742 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
743 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
744 MF->getFunction()->needsUnwindTableEntry())
747 if (MMI->hasDebugInfo())
753 bool AsmPrinter::needsSEHMoves() {
754 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
757 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
758 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
759 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
760 ExceptionHandlingType != ExceptionHandling::ARM)
763 if (needsCFIMoves() == CFI_M_None)
766 const MachineModuleInfo &MMI = MF->getMMI();
767 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
768 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
769 const MCCFIInstruction &CFI = Instrs[CFIIndex];
770 emitCFIInstruction(CFI);
773 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
774 // The operands are the MCSymbol and the frame offset of the allocation.
775 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
776 int FrameOffset = MI.getOperand(1).getImm();
778 // Emit a symbol assignment.
779 OutStreamer->EmitAssignment(FrameAllocSym,
780 MCConstantExpr::create(FrameOffset, OutContext));
783 /// EmitFunctionBody - This method emits the body and trailer for a
785 void AsmPrinter::EmitFunctionBody() {
786 EmitFunctionHeader();
788 // Emit target-specific gunk before the function body.
789 EmitFunctionBodyStart();
791 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
793 // Print out code for the function.
794 bool HasAnyRealCode = false;
795 for (auto &MBB : *MF) {
796 // Print a label for the basic block.
797 EmitBasicBlockStart(MBB);
798 for (auto &MI : MBB) {
800 // Print the assembly for the instruction.
801 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
802 !MI.isDebugValue()) {
803 HasAnyRealCode = true;
807 if (ShouldPrintDebugScopes) {
808 for (const HandlerInfo &HI : Handlers) {
809 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
810 TimePassesIsEnabled);
811 HI.Handler->beginInstruction(&MI);
816 emitComments(MI, OutStreamer->GetCommentOS());
818 switch (MI.getOpcode()) {
819 case TargetOpcode::CFI_INSTRUCTION:
820 emitCFIInstruction(MI);
823 case TargetOpcode::FRAME_ALLOC:
827 case TargetOpcode::EH_LABEL:
828 case TargetOpcode::GC_LABEL:
829 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
831 case TargetOpcode::INLINEASM:
834 case TargetOpcode::DBG_VALUE:
836 if (!emitDebugValueComment(&MI, *this))
837 EmitInstruction(&MI);
840 case TargetOpcode::IMPLICIT_DEF:
841 if (isVerbose()) emitImplicitDef(&MI);
843 case TargetOpcode::KILL:
844 if (isVerbose()) emitKill(&MI, *this);
847 EmitInstruction(&MI);
851 if (ShouldPrintDebugScopes) {
852 for (const HandlerInfo &HI : Handlers) {
853 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
854 TimePassesIsEnabled);
855 HI.Handler->endInstruction();
860 EmitBasicBlockEnd(MBB);
863 // If the function is empty and the object file uses .subsections_via_symbols,
864 // then we need to emit *something* to the function body to prevent the
865 // labels from collapsing together. Just emit a noop.
866 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
868 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
869 OutStreamer->AddComment("avoids zero-length function");
871 // Targets can opt-out of emitting the noop here by leaving the opcode
873 if (Noop.getOpcode())
874 OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
877 const Function *F = MF->getFunction();
878 for (const auto &BB : *F) {
879 if (!BB.hasAddressTaken())
881 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
882 if (Sym->isDefined())
884 OutStreamer->AddComment("Address of block that was removed by CodeGen");
885 OutStreamer->EmitLabel(Sym);
888 // Emit target-specific gunk after the function body.
889 EmitFunctionBodyEnd();
891 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
892 MAI->hasDotTypeDotSizeDirective()) {
893 // Create a symbol for the end of function.
894 CurrentFnEnd = createTempSymbol("func_end");
895 OutStreamer->EmitLabel(CurrentFnEnd);
898 // If the target wants a .size directive for the size of the function, emit
900 if (MAI->hasDotTypeDotSizeDirective()) {
901 // We can get the size as difference between the function label and the
903 const MCExpr *SizeExp =
904 MCBinaryExpr::createSub(MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
905 MCSymbolRefExpr::create(CurrentFnSymForSize,
908 OutStreamer->emitELFSize(cast<MCSymbolELF>(CurrentFnSym), SizeExp);
911 for (const HandlerInfo &HI : Handlers) {
912 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
913 HI.Handler->markFunctionEnd();
916 // Print out jump tables referenced by the function.
919 // Emit post-function debug and/or EH information.
920 for (const HandlerInfo &HI : Handlers) {
921 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
922 HI.Handler->endFunction(MF);
926 OutStreamer->AddBlankLine();
929 /// \brief Compute the number of Global Variables that uses a Constant.
930 static unsigned getNumGlobalVariableUses(const Constant *C) {
934 if (isa<GlobalVariable>(C))
937 unsigned NumUses = 0;
938 for (auto *CU : C->users())
939 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
944 /// \brief Only consider global GOT equivalents if at least one user is a
945 /// cstexpr inside an initializer of another global variables. Also, don't
946 /// handle cstexpr inside instructions. During global variable emission,
947 /// candidates are skipped and are emitted later in case at least one cstexpr
948 /// isn't replaced by a PC relative GOT entry access.
949 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
950 unsigned &NumGOTEquivUsers) {
951 // Global GOT equivalents are unnamed private globals with a constant
952 // pointer initializer to another global symbol. They must point to a
953 // GlobalVariable or Function, i.e., as GlobalValue.
954 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
955 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
958 // To be a got equivalent, at least one of its users need to be a constant
959 // expression used by another global variable.
960 for (auto *U : GV->users())
961 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
963 return NumGOTEquivUsers > 0;
966 /// \brief Unnamed constant global variables solely contaning a pointer to
967 /// another globals variable is equivalent to a GOT table entry; it contains the
968 /// the address of another symbol. Optimize it and replace accesses to these
969 /// "GOT equivalents" by using the GOT entry for the final global instead.
970 /// Compute GOT equivalent candidates among all global variables to avoid
971 /// emitting them if possible later on, after it use is replaced by a GOT entry
973 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
974 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
977 for (const auto &G : M.globals()) {
978 unsigned NumGOTEquivUsers = 0;
979 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
982 const MCSymbol *GOTEquivSym = getSymbol(&G);
983 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
987 /// \brief Constant expressions using GOT equivalent globals may not be eligible
988 /// for PC relative GOT entry conversion, in such cases we need to emit such
989 /// globals we previously omitted in EmitGlobalVariable.
990 void AsmPrinter::emitGlobalGOTEquivs() {
991 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
994 SmallVector<const GlobalVariable *, 8> FailedCandidates;
995 for (auto &I : GlobalGOTEquivs) {
996 const GlobalVariable *GV = I.second.first;
997 unsigned Cnt = I.second.second;
999 FailedCandidates.push_back(GV);
1001 GlobalGOTEquivs.clear();
1003 for (auto *GV : FailedCandidates)
1004 EmitGlobalVariable(GV);
1007 bool AsmPrinter::doFinalization(Module &M) {
1008 // Set the MachineFunction to nullptr so that we can catch attempted
1009 // accesses to MF specific features at the module level and so that
1010 // we can conditionalize accesses based on whether or not it is nullptr.
1013 // Gather all GOT equivalent globals in the module. We really need two
1014 // passes over the globals: one to compute and another to avoid its emission
1015 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1016 // where the got equivalent shows up before its use.
1017 computeGlobalGOTEquivs(M);
1019 // Emit global variables.
1020 for (const auto &G : M.globals())
1021 EmitGlobalVariable(&G);
1023 // Emit remaining GOT equivalent globals.
1024 emitGlobalGOTEquivs();
1026 // Emit visibility info for declarations
1027 for (const Function &F : M) {
1028 if (!F.isDeclaration())
1030 GlobalValue::VisibilityTypes V = F.getVisibility();
1031 if (V == GlobalValue::DefaultVisibility)
1034 MCSymbol *Name = getSymbol(&F);
1035 EmitVisibility(Name, V, false);
1038 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1040 // Emit module flags.
1041 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1042 M.getModuleFlagsMetadata(ModuleFlags);
1043 if (!ModuleFlags.empty())
1044 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1046 Triple TT(TM.getTargetTriple());
1047 if (TT.isOSBinFormatELF()) {
1048 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1050 // Output stubs for external and common global variables.
1051 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1052 if (!Stubs.empty()) {
1053 OutStreamer->SwitchSection(TLOF.getDataRelSection());
1054 const DataLayout *DL = TM.getDataLayout();
1056 for (const auto &Stub : Stubs) {
1057 OutStreamer->EmitLabel(Stub.first);
1058 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1059 DL->getPointerSize());
1064 // Make sure we wrote out everything we need.
1065 OutStreamer->Flush();
1067 // Finalize debug and EH information.
1068 for (const HandlerInfo &HI : Handlers) {
1069 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1070 TimePassesIsEnabled);
1071 HI.Handler->endModule();
1077 // If the target wants to know about weak references, print them all.
1078 if (MAI->getWeakRefDirective()) {
1079 // FIXME: This is not lazy, it would be nice to only print weak references
1080 // to stuff that is actually used. Note that doing so would require targets
1081 // to notice uses in operands (due to constant exprs etc). This should
1082 // happen with the MC stuff eventually.
1084 // Print out module-level global variables here.
1085 for (const auto &G : M.globals()) {
1086 if (!G.hasExternalWeakLinkage())
1088 OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1091 for (const auto &F : M) {
1092 if (!F.hasExternalWeakLinkage())
1094 OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1098 OutStreamer->AddBlankLine();
1099 for (const auto &Alias : M.aliases()) {
1100 MCSymbol *Name = getSymbol(&Alias);
1102 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1103 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1104 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1105 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1107 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1109 EmitVisibility(Name, Alias.getVisibility());
1111 // Emit the directives as assignments aka .set:
1112 OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1115 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1116 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1117 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1118 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1119 MP->finishAssembly(M, *MI, *this);
1121 // Emit llvm.ident metadata in an '.ident' directive.
1122 EmitModuleIdents(M);
1124 // Emit __morestack address if needed for indirect calls.
1125 if (MMI->usesMorestackAddr()) {
1126 MCSection *ReadOnlySection =
1127 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1129 OutStreamer->SwitchSection(ReadOnlySection);
1131 MCSymbol *AddrSymbol =
1132 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1133 OutStreamer->EmitLabel(AddrSymbol);
1135 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1136 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1140 // If we don't have any trampolines, then we don't require stack memory
1141 // to be executable. Some targets have a directive to declare this.
1142 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1143 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1144 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1145 OutStreamer->SwitchSection(S);
1147 // Allow the target to emit any magic that it wants at the end of the file,
1148 // after everything else has gone out.
1149 EmitEndOfAsmFile(M);
1151 delete Mang; Mang = nullptr;
1154 OutStreamer->Finish();
1155 OutStreamer->reset();
1160 MCSymbol *AsmPrinter::getCurExceptionSym() {
1161 if (!CurExceptionSym)
1162 CurExceptionSym = createTempSymbol("exception");
1163 return CurExceptionSym;
1166 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1168 // Get the function symbol.
1169 CurrentFnSym = getSymbol(MF.getFunction());
1170 CurrentFnSymForSize = CurrentFnSym;
1171 CurrentFnBegin = nullptr;
1172 CurExceptionSym = nullptr;
1173 bool NeedsLocalForSize = MAI->needsLocalForSize();
1174 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1175 NeedsLocalForSize) {
1176 CurrentFnBegin = createTempSymbol("func_begin");
1177 if (NeedsLocalForSize)
1178 CurrentFnSymForSize = CurrentFnBegin;
1182 LI = &getAnalysis<MachineLoopInfo>();
1186 // Keep track the alignment, constpool entries per Section.
1190 SmallVector<unsigned, 4> CPEs;
1191 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1195 /// EmitConstantPool - Print to the current output stream assembly
1196 /// representations of the constants in the constant pool MCP. This is
1197 /// used to print out constants which have been "spilled to memory" by
1198 /// the code generator.
1200 void AsmPrinter::EmitConstantPool() {
1201 const MachineConstantPool *MCP = MF->getConstantPool();
1202 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1203 if (CP.empty()) return;
1205 // Calculate sections for constant pool entries. We collect entries to go into
1206 // the same section together to reduce amount of section switch statements.
1207 SmallVector<SectionCPs, 4> CPSections;
1208 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1209 const MachineConstantPoolEntry &CPE = CP[i];
1210 unsigned Align = CPE.getAlignment();
1213 CPE.getSectionKind(TM.getDataLayout());
1215 const Constant *C = nullptr;
1216 if (!CPE.isMachineConstantPoolEntry())
1217 C = CPE.Val.ConstVal;
1219 MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1221 // The number of sections are small, just do a linear search from the
1222 // last section to the first.
1224 unsigned SecIdx = CPSections.size();
1225 while (SecIdx != 0) {
1226 if (CPSections[--SecIdx].S == S) {
1232 SecIdx = CPSections.size();
1233 CPSections.push_back(SectionCPs(S, Align));
1236 if (Align > CPSections[SecIdx].Alignment)
1237 CPSections[SecIdx].Alignment = Align;
1238 CPSections[SecIdx].CPEs.push_back(i);
1241 // Now print stuff into the calculated sections.
1242 const MCSection *CurSection = nullptr;
1243 unsigned Offset = 0;
1244 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1245 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1246 unsigned CPI = CPSections[i].CPEs[j];
1247 MCSymbol *Sym = GetCPISymbol(CPI);
1248 if (!Sym->isUndefined())
1251 if (CurSection != CPSections[i].S) {
1252 OutStreamer->SwitchSection(CPSections[i].S);
1253 EmitAlignment(Log2_32(CPSections[i].Alignment));
1254 CurSection = CPSections[i].S;
1258 MachineConstantPoolEntry CPE = CP[CPI];
1260 // Emit inter-object padding for alignment.
1261 unsigned AlignMask = CPE.getAlignment() - 1;
1262 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1263 OutStreamer->EmitZeros(NewOffset - Offset);
1265 Type *Ty = CPE.getType();
1266 Offset = NewOffset +
1267 TM.getDataLayout()->getTypeAllocSize(Ty);
1269 OutStreamer->EmitLabel(Sym);
1270 if (CPE.isMachineConstantPoolEntry())
1271 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1273 EmitGlobalConstant(CPE.Val.ConstVal);
1278 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1279 /// by the current function to the current output stream.
1281 void AsmPrinter::EmitJumpTableInfo() {
1282 const DataLayout *DL = MF->getTarget().getDataLayout();
1283 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1285 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1286 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1287 if (JT.empty()) return;
1289 // Pick the directive to use to print the jump table entries, and switch to
1290 // the appropriate section.
1291 const Function *F = MF->getFunction();
1292 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1293 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1294 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1296 if (JTInDiffSection) {
1297 // Drop it in the readonly section.
1298 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1299 OutStreamer->SwitchSection(ReadOnlySection);
1302 EmitAlignment(Log2_32(
1303 MJTI->getEntryAlignment(*TM.getDataLayout())));
1305 // Jump tables in code sections are marked with a data_region directive
1306 // where that's supported.
1307 if (!JTInDiffSection)
1308 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1310 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1311 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1313 // If this jump table was deleted, ignore it.
1314 if (JTBBs.empty()) continue;
1316 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1317 /// emit a .set directive for each unique entry.
1318 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1319 MAI->doesSetDirectiveSuppressesReloc()) {
1320 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1321 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1322 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1323 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1324 const MachineBasicBlock *MBB = JTBBs[ii];
1325 if (!EmittedSets.insert(MBB).second)
1328 // .set LJTSet, LBB32-base
1330 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1331 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1332 MCBinaryExpr::createSub(LHS, Base,
1337 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1338 // before each jump table. The first label is never referenced, but tells
1339 // the assembler and linker the extents of the jump table object. The
1340 // second label is actually referenced by the code.
1341 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1342 // FIXME: This doesn't have to have any specific name, just any randomly
1343 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1344 OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1346 OutStreamer->EmitLabel(GetJTISymbol(JTI));
1348 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1349 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1351 if (!JTInDiffSection)
1352 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1355 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1357 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1358 const MachineBasicBlock *MBB,
1359 unsigned UID) const {
1360 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1361 const MCExpr *Value = nullptr;
1362 switch (MJTI->getEntryKind()) {
1363 case MachineJumpTableInfo::EK_Inline:
1364 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1365 case MachineJumpTableInfo::EK_Custom32:
1366 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1367 MJTI, MBB, UID, OutContext);
1369 case MachineJumpTableInfo::EK_BlockAddress:
1370 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1372 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1374 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1375 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1376 // with a relocation as gp-relative, e.g.:
1378 MCSymbol *MBBSym = MBB->getSymbol();
1379 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1383 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1384 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1385 // with a relocation as gp-relative, e.g.:
1387 MCSymbol *MBBSym = MBB->getSymbol();
1388 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1392 case MachineJumpTableInfo::EK_LabelDifference32: {
1393 // Each entry is the address of the block minus the address of the jump
1394 // table. This is used for PIC jump tables where gprel32 is not supported.
1396 // .word LBB123 - LJTI1_2
1397 // If the .set directive avoids relocations, this is emitted as:
1398 // .set L4_5_set_123, LBB123 - LJTI1_2
1399 // .word L4_5_set_123
1400 if (MAI->doesSetDirectiveSuppressesReloc()) {
1401 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1405 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1406 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1407 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1408 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1413 assert(Value && "Unknown entry kind!");
1415 unsigned EntrySize =
1416 MJTI->getEntrySize(*TM.getDataLayout());
1417 OutStreamer->EmitValue(Value, EntrySize);
1421 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1422 /// special global used by LLVM. If so, emit it and return true, otherwise
1423 /// do nothing and return false.
1424 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1425 if (GV->getName() == "llvm.used") {
1426 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1427 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1431 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1432 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1433 GV->hasAvailableExternallyLinkage())
1436 if (!GV->hasAppendingLinkage()) return false;
1438 assert(GV->hasInitializer() && "Not a special LLVM global!");
1440 if (GV->getName() == "llvm.global_ctors") {
1441 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1443 if (TM.getRelocationModel() == Reloc::Static &&
1444 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1445 StringRef Sym(".constructors_used");
1446 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1452 if (GV->getName() == "llvm.global_dtors") {
1453 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1455 if (TM.getRelocationModel() == Reloc::Static &&
1456 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1457 StringRef Sym(".destructors_used");
1458 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1467 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1468 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1469 /// is true, as being used with this directive.
1470 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1471 // Should be an array of 'i8*'.
1472 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1473 const GlobalValue *GV =
1474 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1476 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1482 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1484 llvm::Constant *Func;
1485 llvm::GlobalValue *ComdatKey;
1489 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1491 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1492 // Should be an array of '{ int, void ()* }' structs. The first value is the
1494 if (!isa<ConstantArray>(List)) return;
1496 // Sanity check the structors list.
1497 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1498 if (!InitList) return; // Not an array!
1499 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1500 // FIXME: Only allow the 3-field form in LLVM 4.0.
1501 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1502 return; // Not an array of two or three elements!
1503 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1504 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1505 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1506 return; // Not (int, ptr, ptr).
1508 // Gather the structors in a form that's convenient for sorting by priority.
1509 SmallVector<Structor, 8> Structors;
1510 for (Value *O : InitList->operands()) {
1511 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1512 if (!CS) continue; // Malformed.
1513 if (CS->getOperand(1)->isNullValue())
1514 break; // Found a null terminator, skip the rest.
1515 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1516 if (!Priority) continue; // Malformed.
1517 Structors.push_back(Structor());
1518 Structor &S = Structors.back();
1519 S.Priority = Priority->getLimitedValue(65535);
1520 S.Func = CS->getOperand(1);
1521 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1522 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1525 // Emit the function pointers in the target-specific order
1526 const DataLayout *DL = TM.getDataLayout();
1527 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1528 std::stable_sort(Structors.begin(), Structors.end(),
1529 [](const Structor &L,
1530 const Structor &R) { return L.Priority < R.Priority; });
1531 for (Structor &S : Structors) {
1532 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1533 const MCSymbol *KeySym = nullptr;
1534 if (GlobalValue *GV = S.ComdatKey) {
1535 if (GV->hasAvailableExternallyLinkage())
1536 // If the associated variable is available_externally, some other TU
1537 // will provide its dynamic initializer.
1540 KeySym = getSymbol(GV);
1542 MCSection *OutputSection =
1543 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1544 : Obj.getStaticDtorSection(S.Priority, KeySym));
1545 OutStreamer->SwitchSection(OutputSection);
1546 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1547 EmitAlignment(Align);
1548 EmitXXStructor(S.Func);
1552 void AsmPrinter::EmitModuleIdents(Module &M) {
1553 if (!MAI->hasIdentDirective())
1556 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1557 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1558 const MDNode *N = NMD->getOperand(i);
1559 assert(N->getNumOperands() == 1 &&
1560 "llvm.ident metadata entry can have only one operand");
1561 const MDString *S = cast<MDString>(N->getOperand(0));
1562 OutStreamer->EmitIdent(S->getString());
1567 //===--------------------------------------------------------------------===//
1568 // Emission and print routines
1571 /// EmitInt8 - Emit a byte directive and value.
1573 void AsmPrinter::EmitInt8(int Value) const {
1574 OutStreamer->EmitIntValue(Value, 1);
1577 /// EmitInt16 - Emit a short directive and value.
1579 void AsmPrinter::EmitInt16(int Value) const {
1580 OutStreamer->EmitIntValue(Value, 2);
1583 /// EmitInt32 - Emit a long directive and value.
1585 void AsmPrinter::EmitInt32(int Value) const {
1586 OutStreamer->EmitIntValue(Value, 4);
1589 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1590 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1591 /// .set if it avoids relocations.
1592 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1593 unsigned Size) const {
1594 if (!MAI->doesDwarfUseRelocationsAcrossSections())
1595 if (OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size))
1598 // Get the Hi-Lo expression.
1599 const MCExpr *Diff =
1600 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, OutContext),
1601 MCSymbolRefExpr::create(Lo, OutContext),
1604 if (!MAI->doesSetDirectiveSuppressesReloc()) {
1605 OutStreamer->EmitValue(Diff, Size);
1609 // Otherwise, emit with .set (aka assignment).
1610 MCSymbol *SetLabel = createTempSymbol("set");
1611 OutStreamer->EmitAssignment(SetLabel, Diff);
1612 OutStreamer->EmitSymbolValue(SetLabel, Size);
1615 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1616 /// where the size in bytes of the directive is specified by Size and Label
1617 /// specifies the label. This implicitly uses .set if it is available.
1618 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1620 bool IsSectionRelative) const {
1621 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1622 OutStreamer->EmitCOFFSecRel32(Label);
1626 // Emit Label+Offset (or just Label if Offset is zero)
1627 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1629 Expr = MCBinaryExpr::createAdd(
1630 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1632 OutStreamer->EmitValue(Expr, Size);
1635 //===----------------------------------------------------------------------===//
1637 // EmitAlignment - Emit an alignment directive to the specified power of
1638 // two boundary. For example, if you pass in 3 here, you will get an 8
1639 // byte alignment. If a global value is specified, and if that global has
1640 // an explicit alignment requested, it will override the alignment request
1641 // if required for correctness.
1643 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1645 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1648 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1651 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1652 "undefined behavior");
1653 if (getCurrentSection()->getKind().isText())
1654 OutStreamer->EmitCodeAlignment(1u << NumBits);
1656 OutStreamer->EmitValueToAlignment(1u << NumBits);
1659 //===----------------------------------------------------------------------===//
1660 // Constant emission.
1661 //===----------------------------------------------------------------------===//
1663 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1664 MCContext &Ctx = OutContext;
1666 if (CV->isNullValue() || isa<UndefValue>(CV))
1667 return MCConstantExpr::create(0, Ctx);
1669 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1670 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1672 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1673 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1675 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1676 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1678 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1680 llvm_unreachable("Unknown constant value to lower!");
1683 if (const MCExpr *RelocExpr
1684 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1687 switch (CE->getOpcode()) {
1689 // If the code isn't optimized, there may be outstanding folding
1690 // opportunities. Attempt to fold the expression using DataLayout as a
1691 // last resort before giving up.
1692 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
1694 return lowerConstant(C);
1696 // Otherwise report the problem to the user.
1699 raw_string_ostream OS(S);
1700 OS << "Unsupported expression in static initializer: ";
1701 CE->printAsOperand(OS, /*PrintType=*/false,
1702 !MF ? nullptr : MF->getFunction()->getParent());
1703 report_fatal_error(OS.str());
1705 case Instruction::GetElementPtr: {
1706 const DataLayout &DL = *TM.getDataLayout();
1708 // Generate a symbolic expression for the byte address
1709 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1710 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1712 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1716 int64_t Offset = OffsetAI.getSExtValue();
1717 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1721 case Instruction::Trunc:
1722 // We emit the value and depend on the assembler to truncate the generated
1723 // expression properly. This is important for differences between
1724 // blockaddress labels. Since the two labels are in the same function, it
1725 // is reasonable to treat their delta as a 32-bit value.
1727 case Instruction::BitCast:
1728 return lowerConstant(CE->getOperand(0));
1730 case Instruction::IntToPtr: {
1731 const DataLayout &DL = *TM.getDataLayout();
1733 // Handle casts to pointers by changing them into casts to the appropriate
1734 // integer type. This promotes constant folding and simplifies this code.
1735 Constant *Op = CE->getOperand(0);
1736 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1738 return lowerConstant(Op);
1741 case Instruction::PtrToInt: {
1742 const DataLayout &DL = *TM.getDataLayout();
1744 // Support only foldable casts to/from pointers that can be eliminated by
1745 // changing the pointer to the appropriately sized integer type.
1746 Constant *Op = CE->getOperand(0);
1747 Type *Ty = CE->getType();
1749 const MCExpr *OpExpr = lowerConstant(Op);
1751 // We can emit the pointer value into this slot if the slot is an
1752 // integer slot equal to the size of the pointer.
1753 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1756 // Otherwise the pointer is smaller than the resultant integer, mask off
1757 // the high bits so we are sure to get a proper truncation if the input is
1759 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1760 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1761 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1764 // The MC library also has a right-shift operator, but it isn't consistently
1765 // signed or unsigned between different targets.
1766 case Instruction::Add:
1767 case Instruction::Sub:
1768 case Instruction::Mul:
1769 case Instruction::SDiv:
1770 case Instruction::SRem:
1771 case Instruction::Shl:
1772 case Instruction::And:
1773 case Instruction::Or:
1774 case Instruction::Xor: {
1775 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1776 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1777 switch (CE->getOpcode()) {
1778 default: llvm_unreachable("Unknown binary operator constant cast expr");
1779 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1780 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1781 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1782 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1783 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1784 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1785 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1786 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1787 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1793 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1794 const Constant *BaseCV = nullptr,
1795 uint64_t Offset = 0);
1797 /// isRepeatedByteSequence - Determine whether the given value is
1798 /// composed of a repeated sequence of identical bytes and return the
1799 /// byte value. If it is not a repeated sequence, return -1.
1800 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1801 StringRef Data = V->getRawDataValues();
1802 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1804 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1805 if (Data[i] != C) return -1;
1806 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1810 /// isRepeatedByteSequence - Determine whether the given value is
1811 /// composed of a repeated sequence of identical bytes and return the
1812 /// byte value. If it is not a repeated sequence, return -1.
1813 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1815 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1816 if (CI->getBitWidth() > 64) return -1;
1819 TM.getDataLayout()->getTypeAllocSize(V->getType());
1820 uint64_t Value = CI->getZExtValue();
1822 // Make sure the constant is at least 8 bits long and has a power
1823 // of 2 bit width. This guarantees the constant bit width is
1824 // always a multiple of 8 bits, avoiding issues with padding out
1825 // to Size and other such corner cases.
1826 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1828 uint8_t Byte = static_cast<uint8_t>(Value);
1830 for (unsigned i = 1; i < Size; ++i) {
1832 if (static_cast<uint8_t>(Value) != Byte) return -1;
1836 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1837 // Make sure all array elements are sequences of the same repeated
1839 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1840 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1841 if (Byte == -1) return -1;
1843 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1844 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1845 if (ThisByte == -1) return -1;
1846 if (Byte != ThisByte) return -1;
1851 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1852 return isRepeatedByteSequence(CDS);
1857 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1860 // See if we can aggregate this into a .fill, if so, emit it as such.
1861 int Value = isRepeatedByteSequence(CDS, AP.TM);
1864 AP.TM.getDataLayout()->getTypeAllocSize(
1866 // Don't emit a 1-byte object as a .fill.
1868 return AP.OutStreamer->EmitFill(Bytes, Value);
1871 // If this can be emitted with .ascii/.asciz, emit it as such.
1872 if (CDS->isString())
1873 return AP.OutStreamer->EmitBytes(CDS->getAsString());
1875 // Otherwise, emit the values in successive locations.
1876 unsigned ElementByteSize = CDS->getElementByteSize();
1877 if (isa<IntegerType>(CDS->getElementType())) {
1878 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1880 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1881 CDS->getElementAsInteger(i));
1882 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1885 } else if (ElementByteSize == 4) {
1886 // FP Constants are printed as integer constants to avoid losing
1888 assert(CDS->getElementType()->isFloatTy());
1889 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1895 F = CDS->getElementAsFloat(i);
1897 AP.OutStreamer->GetCommentOS() << "float " << F << '\n';
1898 AP.OutStreamer->EmitIntValue(I, 4);
1901 assert(CDS->getElementType()->isDoubleTy());
1902 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1908 F = CDS->getElementAsDouble(i);
1910 AP.OutStreamer->GetCommentOS() << "double " << F << '\n';
1911 AP.OutStreamer->EmitIntValue(I, 8);
1915 const DataLayout &DL = *AP.TM.getDataLayout();
1916 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1917 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1918 CDS->getNumElements();
1919 if (unsigned Padding = Size - EmittedSize)
1920 AP.OutStreamer->EmitZeros(Padding);
1924 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP,
1925 const Constant *BaseCV, uint64_t Offset) {
1926 // See if we can aggregate some values. Make sure it can be
1927 // represented as a series of bytes of the constant value.
1928 int Value = isRepeatedByteSequence(CA, AP.TM);
1929 const DataLayout &DL = *AP.TM.getDataLayout();
1932 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1933 AP.OutStreamer->EmitFill(Bytes, Value);
1936 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1937 emitGlobalConstantImpl(CA->getOperand(i), AP, BaseCV, Offset);
1938 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1943 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1944 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1945 emitGlobalConstantImpl(CV->getOperand(i), AP);
1947 const DataLayout &DL = *AP.TM.getDataLayout();
1948 unsigned Size = DL.getTypeAllocSize(CV->getType());
1949 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1950 CV->getType()->getNumElements();
1951 if (unsigned Padding = Size - EmittedSize)
1952 AP.OutStreamer->EmitZeros(Padding);
1955 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP,
1956 const Constant *BaseCV, uint64_t Offset) {
1957 // Print the fields in successive locations. Pad to align if needed!
1958 const DataLayout *DL = AP.TM.getDataLayout();
1959 unsigned Size = DL->getTypeAllocSize(CS->getType());
1960 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1961 uint64_t SizeSoFar = 0;
1962 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1963 const Constant *Field = CS->getOperand(i);
1965 // Print the actual field value.
1966 emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
1968 // Check if padding is needed and insert one or more 0s.
1969 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1970 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1971 - Layout->getElementOffset(i)) - FieldSize;
1972 SizeSoFar += FieldSize + PadSize;
1974 // Insert padding - this may include padding to increase the size of the
1975 // current field up to the ABI size (if the struct is not packed) as well
1976 // as padding to ensure that the next field starts at the right offset.
1977 AP.OutStreamer->EmitZeros(PadSize);
1979 assert(SizeSoFar == Layout->getSizeInBytes() &&
1980 "Layout of constant struct may be incorrect!");
1983 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1984 APInt API = CFP->getValueAPF().bitcastToAPInt();
1986 // First print a comment with what we think the original floating-point value
1987 // should have been.
1988 if (AP.isVerbose()) {
1989 SmallString<8> StrVal;
1990 CFP->getValueAPF().toString(StrVal);
1993 CFP->getType()->print(AP.OutStreamer->GetCommentOS());
1995 AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
1996 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
1999 // Now iterate through the APInt chunks, emitting them in endian-correct
2000 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2002 unsigned NumBytes = API.getBitWidth() / 8;
2003 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2004 const uint64_t *p = API.getRawData();
2006 // PPC's long double has odd notions of endianness compared to how LLVM
2007 // handles it: p[0] goes first for *big* endian on PPC.
2008 if (AP.TM.getDataLayout()->isBigEndian() &&
2009 !CFP->getType()->isPPC_FP128Ty()) {
2010 int Chunk = API.getNumWords() - 1;
2013 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2015 for (; Chunk >= 0; --Chunk)
2016 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2019 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2020 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2023 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2026 // Emit the tail padding for the long double.
2027 const DataLayout &DL = *AP.TM.getDataLayout();
2028 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2029 DL.getTypeStoreSize(CFP->getType()));
2032 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2033 const DataLayout *DL = AP.TM.getDataLayout();
2034 unsigned BitWidth = CI->getBitWidth();
2036 // Copy the value as we may massage the layout for constants whose bit width
2037 // is not a multiple of 64-bits.
2038 APInt Realigned(CI->getValue());
2039 uint64_t ExtraBits = 0;
2040 unsigned ExtraBitsSize = BitWidth & 63;
2042 if (ExtraBitsSize) {
2043 // The bit width of the data is not a multiple of 64-bits.
2044 // The extra bits are expected to be at the end of the chunk of the memory.
2046 // * Nothing to be done, just record the extra bits to emit.
2048 // * Record the extra bits to emit.
2049 // * Realign the raw data to emit the chunks of 64-bits.
2050 if (DL->isBigEndian()) {
2051 // Basically the structure of the raw data is a chunk of 64-bits cells:
2052 // 0 1 BitWidth / 64
2053 // [chunk1][chunk2] ... [chunkN].
2054 // The most significant chunk is chunkN and it should be emitted first.
2055 // However, due to the alignment issue chunkN contains useless bits.
2056 // Realign the chunks so that they contain only useless information:
2057 // ExtraBits 0 1 (BitWidth / 64) - 1
2058 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2059 ExtraBits = Realigned.getRawData()[0] &
2060 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2061 Realigned = Realigned.lshr(ExtraBitsSize);
2063 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2066 // We don't expect assemblers to support integer data directives
2067 // for more than 64 bits, so we emit the data in at most 64-bit
2068 // quantities at a time.
2069 const uint64_t *RawData = Realigned.getRawData();
2070 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2071 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2072 AP.OutStreamer->EmitIntValue(Val, 8);
2075 if (ExtraBitsSize) {
2076 // Emit the extra bits after the 64-bits chunks.
2078 // Emit a directive that fills the expected size.
2079 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
2081 Size -= (BitWidth / 64) * 8;
2082 assert(Size && Size * 8 >= ExtraBitsSize &&
2083 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2084 == ExtraBits && "Directive too small for extra bits.");
2085 AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2089 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2090 /// equivalent global, by a target specific GOT pc relative access to the
2092 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2093 const Constant *BaseCst,
2095 // The global @foo below illustrates a global that uses a got equivalent.
2097 // @bar = global i32 42
2098 // @gotequiv = private unnamed_addr constant i32* @bar
2099 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2100 // i64 ptrtoint (i32* @foo to i64))
2103 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2104 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2107 // foo = cstexpr, where
2108 // cstexpr := <gotequiv> - "." + <cst>
2109 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2111 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2113 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2114 // gotpcrelcst := <offset from @foo base> + <cst>
2117 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2120 const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2121 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2124 const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2128 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2129 if (BaseSym != &MV.getSymB()->getSymbol())
2132 // Make sure to match:
2134 // gotpcrelcst := <offset from @foo base> + <cst>
2136 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2137 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2138 // if the target knows how to encode it.
2140 int64_t GOTPCRelCst = Offset + MV.getConstant();
2141 if (GOTPCRelCst < 0)
2143 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2146 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2153 // .long gotequiv - "." + <cst>
2155 // is replaced by the target specific equivalent to:
2160 // .long bar@GOTPCREL+<gotpcrelcst>
2162 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2163 const GlobalVariable *GV = Result.first;
2164 int NumUses = (int)Result.second;
2165 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2166 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2167 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2168 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2170 // Update GOT equivalent usage information
2173 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2176 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2177 const Constant *BaseCV, uint64_t Offset) {
2178 const DataLayout *DL = AP.TM.getDataLayout();
2179 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2181 // Globals with sub-elements such as combinations of arrays and structs
2182 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2183 // constant symbol base and the current position with BaseCV and Offset.
2184 if (!BaseCV && CV->hasOneUse())
2185 BaseCV = dyn_cast<Constant>(CV->user_back());
2187 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2188 return AP.OutStreamer->EmitZeros(Size);
2190 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2197 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2198 CI->getZExtValue());
2199 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2202 emitGlobalConstantLargeInt(CI, AP);
2207 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2208 return emitGlobalConstantFP(CFP, AP);
2210 if (isa<ConstantPointerNull>(CV)) {
2211 AP.OutStreamer->EmitIntValue(0, Size);
2215 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2216 return emitGlobalConstantDataSequential(CDS, AP);
2218 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2219 return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2221 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2222 return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2224 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2225 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2227 if (CE->getOpcode() == Instruction::BitCast)
2228 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2231 // If the constant expression's size is greater than 64-bits, then we have
2232 // to emit the value in chunks. Try to constant fold the value and emit it
2234 Constant *New = ConstantFoldConstantExpression(CE, *DL);
2235 if (New && New != CE)
2236 return emitGlobalConstantImpl(New, AP);
2240 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2241 return emitGlobalConstantVector(V, AP);
2243 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2244 // thread the streamer with EmitValue.
2245 const MCExpr *ME = AP.lowerConstant(CV);
2247 // Since lowerConstant already folded and got rid of all IR pointer and
2248 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2250 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2251 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2253 AP.OutStreamer->EmitValue(ME, Size);
2256 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2257 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2259 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2261 emitGlobalConstantImpl(CV, *this);
2262 else if (MAI->hasSubsectionsViaSymbols()) {
2263 // If the global has zero size, emit a single byte so that two labels don't
2264 // look like they are at the same location.
2265 OutStreamer->EmitIntValue(0, 1);
2269 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2270 // Target doesn't support this yet!
2271 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2274 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2276 OS << '+' << Offset;
2277 else if (Offset < 0)
2281 //===----------------------------------------------------------------------===//
2282 // Symbol Lowering Routines.
2283 //===----------------------------------------------------------------------===//
2285 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2286 return OutContext.createTempSymbol(Name, true);
2289 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2290 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2293 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2294 return MMI->getAddrLabelSymbol(BB);
2297 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2298 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2299 const DataLayout *DL = TM.getDataLayout();
2300 return OutContext.getOrCreateSymbol
2301 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2302 + "_" + Twine(CPID));
2305 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2306 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2307 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2310 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2311 /// FIXME: privatize to AsmPrinter.
2312 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2313 const DataLayout *DL = TM.getDataLayout();
2314 return OutContext.getOrCreateSymbol
2315 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2316 Twine(UID) + "_set_" + Twine(MBBID));
2319 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2320 StringRef Suffix) const {
2321 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2325 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2327 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2328 SmallString<60> NameStr;
2329 Mang->getNameWithPrefix(NameStr, Sym);
2330 return OutContext.getOrCreateSymbol(NameStr);
2335 /// PrintParentLoopComment - Print comments about parent loops of this one.
2336 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2337 unsigned FunctionNumber) {
2339 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2340 OS.indent(Loop->getLoopDepth()*2)
2341 << "Parent Loop BB" << FunctionNumber << "_"
2342 << Loop->getHeader()->getNumber()
2343 << " Depth=" << Loop->getLoopDepth() << '\n';
2347 /// PrintChildLoopComment - Print comments about child loops within
2348 /// the loop for this basic block, with nesting.
2349 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2350 unsigned FunctionNumber) {
2351 // Add child loop information
2352 for (const MachineLoop *CL : *Loop) {
2353 OS.indent(CL->getLoopDepth()*2)
2354 << "Child Loop BB" << FunctionNumber << "_"
2355 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2357 PrintChildLoopComment(OS, CL, FunctionNumber);
2361 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2362 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2363 const MachineLoopInfo *LI,
2364 const AsmPrinter &AP) {
2365 // Add loop depth information
2366 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2369 MachineBasicBlock *Header = Loop->getHeader();
2370 assert(Header && "No header for loop");
2372 // If this block is not a loop header, just print out what is the loop header
2374 if (Header != &MBB) {
2375 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2376 Twine(AP.getFunctionNumber())+"_" +
2377 Twine(Loop->getHeader()->getNumber())+
2378 " Depth="+Twine(Loop->getLoopDepth()));
2382 // Otherwise, it is a loop header. Print out information about child and
2384 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2386 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2389 OS.indent(Loop->getLoopDepth()*2-2);
2394 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2396 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2400 /// EmitBasicBlockStart - This method prints the label for the specified
2401 /// MachineBasicBlock, an alignment (if present) and a comment describing
2402 /// it if appropriate.
2403 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2404 // Emit an alignment directive for this block, if needed.
2405 if (unsigned Align = MBB.getAlignment())
2406 EmitAlignment(Align);
2408 // If the block has its address taken, emit any labels that were used to
2409 // reference the block. It is possible that there is more than one label
2410 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2411 // the references were generated.
2412 if (MBB.hasAddressTaken()) {
2413 const BasicBlock *BB = MBB.getBasicBlock();
2415 OutStreamer->AddComment("Block address taken");
2417 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2418 for (auto *Sym : Symbols)
2419 OutStreamer->EmitLabel(Sym);
2422 // Print some verbose block comments.
2424 if (const BasicBlock *BB = MBB.getBasicBlock())
2426 OutStreamer->AddComment("%" + BB->getName());
2427 emitBasicBlockLoopComments(MBB, LI, *this);
2430 // Print the main label for the block.
2431 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2433 // NOTE: Want this comment at start of line, don't emit with AddComment.
2434 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2437 OutStreamer->EmitLabel(MBB.getSymbol());
2441 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2442 bool IsDefinition) const {
2443 MCSymbolAttr Attr = MCSA_Invalid;
2445 switch (Visibility) {
2447 case GlobalValue::HiddenVisibility:
2449 Attr = MAI->getHiddenVisibilityAttr();
2451 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2453 case GlobalValue::ProtectedVisibility:
2454 Attr = MAI->getProtectedVisibilityAttr();
2458 if (Attr != MCSA_Invalid)
2459 OutStreamer->EmitSymbolAttribute(Sym, Attr);
2462 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2463 /// exactly one predecessor and the control transfer mechanism between
2464 /// the predecessor and this block is a fall-through.
2466 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2467 // If this is a landing pad, it isn't a fall through. If it has no preds,
2468 // then nothing falls through to it.
2469 if (MBB->isLandingPad() || MBB->pred_empty())
2472 // If there isn't exactly one predecessor, it can't be a fall through.
2473 if (MBB->pred_size() > 1)
2476 // The predecessor has to be immediately before this block.
2477 MachineBasicBlock *Pred = *MBB->pred_begin();
2478 if (!Pred->isLayoutSuccessor(MBB))
2481 // If the block is completely empty, then it definitely does fall through.
2485 // Check the terminators in the previous blocks
2486 for (const auto &MI : Pred->terminators()) {
2487 // If it is not a simple branch, we are in a table somewhere.
2488 if (!MI.isBranch() || MI.isIndirectBranch())
2491 // If we are the operands of one of the branches, this is not a fall
2492 // through. Note that targets with delay slots will usually bundle
2493 // terminators with the delay slot instruction.
2494 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2497 if (OP->isMBB() && OP->getMBB() == MBB)
2507 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2508 if (!S.usesMetadata())
2511 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2512 " stackmap formats, please see the documentation for a description of"
2513 " the default format. If you really need a custom serialized format,"
2514 " please file a bug");
2516 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2517 gcp_map_type::iterator GCPI = GCMap.find(&S);
2518 if (GCPI != GCMap.end())
2519 return GCPI->second.get();
2521 const char *Name = S.getName().c_str();
2523 for (GCMetadataPrinterRegistry::iterator
2524 I = GCMetadataPrinterRegistry::begin(),
2525 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2526 if (strcmp(Name, I->getName()) == 0) {
2527 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2529 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2530 return IterBool.first->second.get();
2533 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2536 /// Pin vtable to this file.
2537 AsmPrinterHandler::~AsmPrinterHandler() {}
2539 void AsmPrinterHandler::markFunctionEnd() {}