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/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 &TD,
81 unsigned InBits = 0) {
83 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
84 NumBits = TD.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(*Streamer.release()),
106 LastMI(nullptr), LastFn(0), Counter(~0U), SetCounter(0) {
111 CurrentFnSym = CurrentFnSymForSize = nullptr;
112 GCMetadataPrinters = nullptr;
113 VerboseAsm = OutStreamer.isVerboseAsm();
116 AsmPrinter::~AsmPrinter() {
117 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
119 if (GCMetadataPrinters) {
120 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
123 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 OutStreamer.AddComment("Start of file scope inline assembly");
223 OutStreamer.AddBlankLine();
224 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
225 OutStreamer.AddComment("End of file scope inline assembly");
226 OutStreamer.AddBlankLine();
229 if (MAI->doesSupportDebugInformation()) {
230 bool skip_dwarf = false;
231 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
232 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
234 CodeViewLineTablesGroupName));
235 // FIXME: Don't emit DWARF debug info if there's at least one function
236 // with AddressSanitizer instrumentation.
237 // This is a band-aid fix for PR22032.
238 for (auto &F : M.functions()) {
239 if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
246 DD = new DwarfDebug(this, &M);
247 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
251 EHStreamer *ES = nullptr;
252 switch (MAI->getExceptionHandlingType()) {
253 case ExceptionHandling::None:
255 case ExceptionHandling::SjLj:
256 case ExceptionHandling::DwarfCFI:
257 ES = new DwarfCFIException(this);
259 case ExceptionHandling::ARM:
260 ES = new ARMException(this);
262 case ExceptionHandling::WinEH:
263 switch (MAI->getWinEHEncodingType()) {
264 default: llvm_unreachable("unsupported unwinding information encoding");
265 case WinEH::EncodingType::Itanium:
266 ES = new Win64Exception(this);
272 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
276 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
277 if (!MAI.hasWeakDefCanBeHiddenDirective())
280 return canBeOmittedFromSymbolTable(GV);
283 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
284 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
286 case GlobalValue::CommonLinkage:
287 case GlobalValue::LinkOnceAnyLinkage:
288 case GlobalValue::LinkOnceODRLinkage:
289 case GlobalValue::WeakAnyLinkage:
290 case GlobalValue::WeakODRLinkage:
291 if (MAI->hasWeakDefDirective()) {
293 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
295 if (!canBeHidden(GV, *MAI))
296 // .weak_definition _foo
297 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
299 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
300 } else if (MAI->hasLinkOnceDirective()) {
302 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
303 //NOTE: linkonce is handled by the section the symbol was assigned to.
306 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
309 case GlobalValue::AppendingLinkage:
310 // FIXME: appending linkage variables should go into a section of
311 // their name or something. For now, just emit them as external.
312 case GlobalValue::ExternalLinkage:
313 // If external or appending, declare as a global symbol.
315 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
317 case GlobalValue::PrivateLinkage:
318 case GlobalValue::InternalLinkage:
320 case GlobalValue::AvailableExternallyLinkage:
321 llvm_unreachable("Should never emit this");
322 case GlobalValue::ExternalWeakLinkage:
323 llvm_unreachable("Don't know how to emit these");
325 llvm_unreachable("Unknown linkage type!");
328 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
329 const GlobalValue *GV) const {
330 TM.getNameWithPrefix(Name, GV, *Mang);
333 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
334 return TM.getSymbol(GV, *Mang);
337 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
338 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
339 if (GV->hasInitializer()) {
340 // Check to see if this is a special global used by LLVM, if so, emit it.
341 if (EmitSpecialLLVMGlobal(GV))
344 // Skip the emission of global equivalents. The symbol can be emitted later
345 // on by emitGlobalGOTEquivs in case it turns out to be needed.
346 if (GlobalGOTEquivs.count(getSymbol(GV)))
350 GV->printAsOperand(OutStreamer.GetCommentOS(),
351 /*PrintType=*/false, GV->getParent());
352 OutStreamer.GetCommentOS() << '\n';
356 MCSymbol *GVSym = getSymbol(GV);
357 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
359 if (!GV->hasInitializer()) // External globals require no extra code.
362 GVSym->redefineIfPossible();
363 if (GVSym->isDefined() || GVSym->isVariable())
364 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
365 "' is already defined");
367 if (MAI->hasDotTypeDotSizeDirective())
368 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
370 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
372 const DataLayout *DL = TM.getDataLayout();
373 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
375 // If the alignment is specified, we *must* obey it. Overaligning a global
376 // with a specified alignment is a prompt way to break globals emitted to
377 // sections and expected to be contiguous (e.g. ObjC metadata).
378 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
380 for (const HandlerInfo &HI : Handlers) {
381 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
382 HI.Handler->setSymbolSize(GVSym, Size);
385 // Handle common and BSS local symbols (.lcomm).
386 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
387 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
388 unsigned Align = 1 << AlignLog;
390 // Handle common symbols.
391 if (GVKind.isCommon()) {
392 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
396 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
400 // Handle local BSS symbols.
401 if (MAI->hasMachoZeroFillDirective()) {
402 const MCSection *TheSection =
403 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
404 // .zerofill __DATA, __bss, _foo, 400, 5
405 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
409 // Use .lcomm only if it supports user-specified alignment.
410 // Otherwise, while it would still be correct to use .lcomm in some
411 // cases (e.g. when Align == 1), the external assembler might enfore
412 // some -unknown- default alignment behavior, which could cause
413 // spurious differences between external and integrated assembler.
414 // Prefer to simply fall back to .local / .comm in this case.
415 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
417 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
421 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
425 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
427 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
431 const MCSection *TheSection =
432 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
434 // Handle the zerofill directive on darwin, which is a special form of BSS
436 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
437 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
440 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
441 // .zerofill __DATA, __common, _foo, 400, 5
442 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
446 // Handle thread local data for mach-o which requires us to output an
447 // additional structure of data and mangle the original symbol so that we
448 // can reference it later.
450 // TODO: This should become an "emit thread local global" method on TLOF.
451 // All of this macho specific stuff should be sunk down into TLOFMachO and
452 // stuff like "TLSExtraDataSection" should no longer be part of the parent
453 // TLOF class. This will also make it more obvious that stuff like
454 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
456 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
457 // Emit the .tbss symbol
459 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
461 if (GVKind.isThreadBSS()) {
462 TheSection = getObjFileLowering().getTLSBSSSection();
463 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
464 } else if (GVKind.isThreadData()) {
465 OutStreamer.SwitchSection(TheSection);
467 EmitAlignment(AlignLog, GV);
468 OutStreamer.EmitLabel(MangSym);
470 EmitGlobalConstant(GV->getInitializer());
473 OutStreamer.AddBlankLine();
475 // Emit the variable struct for the runtime.
476 const MCSection *TLVSect
477 = getObjFileLowering().getTLSExtraDataSection();
479 OutStreamer.SwitchSection(TLVSect);
480 // Emit the linkage here.
481 EmitLinkage(GV, GVSym);
482 OutStreamer.EmitLabel(GVSym);
484 // Three pointers in size:
485 // - __tlv_bootstrap - used to make sure support exists
486 // - spare pointer, used when mapped by the runtime
487 // - pointer to mangled symbol above with initializer
488 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
489 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
491 OutStreamer.EmitIntValue(0, PtrSize);
492 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
494 OutStreamer.AddBlankLine();
498 OutStreamer.SwitchSection(TheSection);
500 EmitLinkage(GV, GVSym);
501 EmitAlignment(AlignLog, GV);
503 OutStreamer.EmitLabel(GVSym);
505 EmitGlobalConstant(GV->getInitializer());
507 if (MAI->hasDotTypeDotSizeDirective())
509 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
511 OutStreamer.AddBlankLine();
514 /// EmitFunctionHeader - This method emits the header for the current
516 void AsmPrinter::EmitFunctionHeader() {
517 // Print out constants referenced by the function
520 // Print the 'header' of function.
521 const Function *F = MF->getFunction();
523 OutStreamer.SwitchSection(
524 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
525 EmitVisibility(CurrentFnSym, F->getVisibility());
527 EmitLinkage(F, CurrentFnSym);
528 EmitAlignment(MF->getAlignment(), F);
530 if (MAI->hasDotTypeDotSizeDirective())
531 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
534 F->printAsOperand(OutStreamer.GetCommentOS(),
535 /*PrintType=*/false, F->getParent());
536 OutStreamer.GetCommentOS() << '\n';
539 // Emit the prefix data.
540 if (F->hasPrefixData())
541 EmitGlobalConstant(F->getPrefixData());
543 // Emit the CurrentFnSym. This is a virtual function to allow targets to
544 // do their wild and crazy things as required.
545 EmitFunctionEntryLabel();
547 // If the function had address-taken blocks that got deleted, then we have
548 // references to the dangling symbols. Emit them at the start of the function
549 // so that we don't get references to undefined symbols.
550 std::vector<MCSymbol*> DeadBlockSyms;
551 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
552 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
553 OutStreamer.AddComment("Address taken block that was later removed");
554 OutStreamer.EmitLabel(DeadBlockSyms[i]);
557 // Emit pre-function debug and/or EH information.
558 for (const HandlerInfo &HI : Handlers) {
559 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
560 HI.Handler->beginFunction(MF);
563 // Emit the prologue data.
564 if (F->hasPrologueData())
565 EmitGlobalConstant(F->getPrologueData());
568 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
569 /// function. This can be overridden by targets as required to do custom stuff.
570 void AsmPrinter::EmitFunctionEntryLabel() {
571 CurrentFnSym->redefineIfPossible();
573 // The function label could have already been emitted if two symbols end up
574 // conflicting due to asm renaming. Detect this and emit an error.
575 if (CurrentFnSym->isVariable())
576 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
577 "' is a protected alias");
578 if (CurrentFnSym->isDefined())
579 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
580 "' label emitted multiple times to assembly file");
582 return OutStreamer.EmitLabel(CurrentFnSym);
585 /// emitComments - Pretty-print comments for instructions.
586 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
587 const MachineFunction *MF = MI.getParent()->getParent();
588 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
590 // Check for spills and reloads
593 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
595 // We assume a single instruction only has a spill or reload, not
597 const MachineMemOperand *MMO;
598 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
599 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
600 MMO = *MI.memoperands_begin();
601 CommentOS << MMO->getSize() << "-byte Reload\n";
603 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
604 if (FrameInfo->isSpillSlotObjectIndex(FI))
605 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
606 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
607 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
608 MMO = *MI.memoperands_begin();
609 CommentOS << MMO->getSize() << "-byte Spill\n";
611 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
612 if (FrameInfo->isSpillSlotObjectIndex(FI))
613 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
616 // Check for spill-induced copies
617 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
618 CommentOS << " Reload Reuse\n";
621 /// emitImplicitDef - This method emits the specified machine instruction
622 /// that is an implicit def.
623 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
624 unsigned RegNo = MI->getOperand(0).getReg();
625 OutStreamer.AddComment(Twine("implicit-def: ") +
626 MMI->getContext().getRegisterInfo()->getName(RegNo));
627 OutStreamer.AddBlankLine();
630 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
631 std::string Str = "kill:";
632 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
633 const MachineOperand &Op = MI->getOperand(i);
634 assert(Op.isReg() && "KILL instruction must have only register operands");
636 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
637 Str += (Op.isDef() ? "<def>" : "<kill>");
639 AP.OutStreamer.AddComment(Str);
640 AP.OutStreamer.AddBlankLine();
643 /// emitDebugValueComment - This method handles the target-independent form
644 /// of DBG_VALUE, returning true if it was able to do so. A false return
645 /// means the target will need to handle MI in EmitInstruction.
646 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
647 // This code handles only the 4-operand target-independent form.
648 if (MI->getNumOperands() != 4)
651 SmallString<128> Str;
652 raw_svector_ostream OS(Str);
653 OS << "DEBUG_VALUE: ";
655 DIVariable V = MI->getDebugVariable();
656 if (V.getContext().isSubprogram()) {
657 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
663 DIExpression Expr = MI->getDebugExpression();
664 if (Expr.isBitPiece())
665 OS << " [bit_piece offset=" << Expr.getBitPieceOffset()
666 << " size=" << Expr.getBitPieceSize() << "]";
669 // The second operand is only an offset if it's an immediate.
670 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
671 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
673 // Register or immediate value. Register 0 means undef.
674 if (MI->getOperand(0).isFPImm()) {
675 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
676 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
677 OS << (double)APF.convertToFloat();
678 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
679 OS << APF.convertToDouble();
681 // There is no good way to print long double. Convert a copy to
682 // double. Ah well, it's only a comment.
684 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
686 OS << "(long double) " << APF.convertToDouble();
688 } else if (MI->getOperand(0).isImm()) {
689 OS << MI->getOperand(0).getImm();
690 } else if (MI->getOperand(0).isCImm()) {
691 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
694 if (MI->getOperand(0).isReg()) {
695 Reg = MI->getOperand(0).getReg();
697 assert(MI->getOperand(0).isFI() && "Unknown operand type");
698 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
699 Offset += TFI->getFrameIndexReference(*AP.MF,
700 MI->getOperand(0).getIndex(), Reg);
704 // Suppress offset, it is not meaningful here.
706 // NOTE: Want this comment at start of line, don't emit with AddComment.
707 AP.OutStreamer.emitRawComment(OS.str());
712 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
716 OS << '+' << Offset << ']';
718 // NOTE: Want this comment at start of line, don't emit with AddComment.
719 AP.OutStreamer.emitRawComment(OS.str());
723 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
724 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
725 MF->getFunction()->needsUnwindTableEntry())
728 if (MMI->hasDebugInfo())
734 bool AsmPrinter::needsSEHMoves() {
735 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
738 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
739 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
740 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
741 ExceptionHandlingType != ExceptionHandling::ARM)
744 if (needsCFIMoves() == CFI_M_None)
747 const MachineModuleInfo &MMI = MF->getMMI();
748 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
749 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
750 const MCCFIInstruction &CFI = Instrs[CFIIndex];
751 emitCFIInstruction(CFI);
754 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
755 // The operands are the MCSymbol and the frame offset of the allocation.
756 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
757 int FrameOffset = MI.getOperand(1).getImm();
759 // Emit a symbol assignment.
760 OutStreamer.EmitAssignment(FrameAllocSym,
761 MCConstantExpr::Create(FrameOffset, OutContext));
764 /// EmitFunctionBody - This method emits the body and trailer for a
766 void AsmPrinter::EmitFunctionBody() {
767 // Emit target-specific gunk before the function body.
768 EmitFunctionBodyStart();
770 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
772 // Print out code for the function.
773 bool HasAnyRealCode = false;
774 for (auto &MBB : *MF) {
775 // Print a label for the basic block.
776 EmitBasicBlockStart(MBB);
777 for (auto &MI : MBB) {
779 // Print the assembly for the instruction.
780 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
781 !MI.isDebugValue()) {
782 HasAnyRealCode = true;
786 if (ShouldPrintDebugScopes) {
787 for (const HandlerInfo &HI : Handlers) {
788 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
789 TimePassesIsEnabled);
790 HI.Handler->beginInstruction(&MI);
795 emitComments(MI, OutStreamer.GetCommentOS());
797 switch (MI.getOpcode()) {
798 case TargetOpcode::CFI_INSTRUCTION:
799 emitCFIInstruction(MI);
802 case TargetOpcode::FRAME_ALLOC:
806 case TargetOpcode::EH_LABEL:
807 case TargetOpcode::GC_LABEL:
808 OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
810 case TargetOpcode::INLINEASM:
813 case TargetOpcode::DBG_VALUE:
815 if (!emitDebugValueComment(&MI, *this))
816 EmitInstruction(&MI);
819 case TargetOpcode::IMPLICIT_DEF:
820 if (isVerbose()) emitImplicitDef(&MI);
822 case TargetOpcode::KILL:
823 if (isVerbose()) emitKill(&MI, *this);
826 EmitInstruction(&MI);
830 if (ShouldPrintDebugScopes) {
831 for (const HandlerInfo &HI : Handlers) {
832 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
833 TimePassesIsEnabled);
834 HI.Handler->endInstruction();
839 EmitBasicBlockEnd(MBB);
842 // If the function is empty and the object file uses .subsections_via_symbols,
843 // then we need to emit *something* to the function body to prevent the
844 // labels from collapsing together. Just emit a noop.
845 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
847 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
848 OutStreamer.AddComment("avoids zero-length function");
850 // Targets can opt-out of emitting the noop here by leaving the opcode
852 if (Noop.getOpcode())
853 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
856 const Function *F = MF->getFunction();
857 for (const auto &BB : *F) {
858 if (!BB.hasAddressTaken())
860 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
861 if (Sym->isDefined())
863 OutStreamer.AddComment("Address of block that was removed by CodeGen");
864 OutStreamer.EmitLabel(Sym);
867 // Emit target-specific gunk after the function body.
868 EmitFunctionBodyEnd();
870 // If the target wants a .size directive for the size of the function, emit
872 if (MAI->hasDotTypeDotSizeDirective()) {
873 // Create a symbol for the end of function, so we can get the size as
874 // difference between the function label and the temp label.
875 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
876 OutStreamer.EmitLabel(FnEndLabel);
878 const MCExpr *SizeExp =
879 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
880 MCSymbolRefExpr::Create(CurrentFnSymForSize,
883 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
886 // Emit post-function debug and/or EH information.
887 for (const HandlerInfo &HI : Handlers) {
888 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
889 HI.Handler->endFunction(MF);
893 // Print out jump tables referenced by the function.
896 OutStreamer.AddBlankLine();
899 /// \brief Compute the number of Global Variables that uses a Constant.
900 static unsigned getNumGlobalVariableUses(const Constant *C) {
904 if (isa<GlobalVariable>(C))
907 unsigned NumUses = 0;
908 for (auto *CU : C->users())
909 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
914 /// \brief Only consider global GOT equivalents if at least one user is a
915 /// cstexpr inside an initializer of another global variables. Also, don't
916 /// handle cstexpr inside instructions. During global variable emission,
917 /// candidates are skipped and are emitted later in case at least one cstexpr
918 /// isn't replaced by a PC relative GOT entry access.
919 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
920 unsigned &NumGOTEquivUsers) {
921 // Global GOT equivalents are unnamed private globals with a constant
922 // pointer initializer to another global symbol. They must point to a
923 // GlobalVariable or Function, i.e., as GlobalValue.
924 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
925 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
928 // To be a got equivalent, at least one of its users need to be a constant
929 // expression used by another global variable.
930 for (auto *U : GV->users())
931 NumGOTEquivUsers += getNumGlobalVariableUses(cast<Constant>(U));
933 return NumGOTEquivUsers > 0;
936 /// \brief Unnamed constant global variables solely contaning a pointer to
937 /// another globals variable is equivalent to a GOT table entry; it contains the
938 /// the address of another symbol. Optimize it and replace accesses to these
939 /// "GOT equivalents" by using the GOT entry for the final global instead.
940 /// Compute GOT equivalent candidates among all global variables to avoid
941 /// emitting them if possible later on, after it use is replaced by a GOT entry
943 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
944 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
947 for (const auto &G : M.globals()) {
948 unsigned NumGOTEquivUsers = 0;
949 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
952 const MCSymbol *GOTEquivSym = getSymbol(&G);
953 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
957 /// \brief Constant expressions using GOT equivalent globals may not be eligible
958 /// for PC relative GOT entry conversion, in such cases we need to emit such
959 /// globals we previously omitted in EmitGlobalVariable.
960 void AsmPrinter::emitGlobalGOTEquivs() {
961 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
964 while (!GlobalGOTEquivs.empty()) {
965 DenseMap<const MCSymbol *, GOTEquivUsePair>::iterator I =
966 GlobalGOTEquivs.begin();
967 const MCSymbol *S = I->first;
968 const GlobalVariable *GV = I->second.first;
969 GlobalGOTEquivs.erase(S);
970 EmitGlobalVariable(GV);
974 bool AsmPrinter::doFinalization(Module &M) {
975 // Gather all GOT equivalent globals in the module. We really need two
976 // passes over the globals: one to compute and another to avoid its emission
977 // in EmitGlobalVariable, otherwise we would not be able to handle cases
978 // where the got equivalent shows up before its use.
979 computeGlobalGOTEquivs(M);
981 // Emit global variables.
982 for (const auto &G : M.globals())
983 EmitGlobalVariable(&G);
985 // Emit remaining GOT equivalent globals.
986 emitGlobalGOTEquivs();
988 // Emit visibility info for declarations
989 for (const Function &F : M) {
990 if (!F.isDeclaration())
992 GlobalValue::VisibilityTypes V = F.getVisibility();
993 if (V == GlobalValue::DefaultVisibility)
996 MCSymbol *Name = getSymbol(&F);
997 EmitVisibility(Name, V, false);
1000 // Get information about jump-instruction tables to print.
1001 JumpInstrTableInfo *JITI = getAnalysisIfAvailable<JumpInstrTableInfo>();
1003 if (JITI && !JITI->getTables().empty()) {
1004 // Since we're at the module level we can't use a function specific
1005 // MCSubtargetInfo - instead create one with the module defaults.
1006 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
1007 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
1008 unsigned Arch = Triple(getTargetTriple()).getArch();
1009 bool IsThumb = (Arch == Triple::thumb || Arch == Triple::thumbeb);
1010 const TargetInstrInfo *TII = TM.getSubtargetImpl()->getInstrInfo();
1012 TII->getTrap(TrapInst);
1013 unsigned LogAlignment = llvm::Log2_64(JITI->entryByteAlignment());
1015 // Emit the right section for these functions.
1016 OutStreamer.SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
1017 for (const auto &KV : JITI->getTables()) {
1019 for (const auto &FunPair : KV.second) {
1020 // Emit the function labels to make this be a function entry point.
1022 OutContext.GetOrCreateSymbol(FunPair.second->getName());
1023 EmitAlignment(LogAlignment);
1025 OutStreamer.EmitThumbFunc(FunSym);
1026 if (MAI->hasDotTypeDotSizeDirective())
1027 OutStreamer.EmitSymbolAttribute(FunSym, MCSA_ELF_TypeFunction);
1028 OutStreamer.EmitLabel(FunSym);
1030 // Emit the jump instruction to transfer control to the original
1033 MCSymbol *TargetSymbol =
1034 OutContext.GetOrCreateSymbol(FunPair.first->getName());
1035 const MCSymbolRefExpr *TargetSymRef =
1036 MCSymbolRefExpr::Create(TargetSymbol, MCSymbolRefExpr::VK_PLT,
1038 TII->getUnconditionalBranch(JumpToFun, TargetSymRef);
1039 OutStreamer.EmitInstruction(JumpToFun, *STI);
1043 // Emit enough padding instructions to fill up to the next power of two.
1044 uint64_t Remaining = NextPowerOf2(Count) - Count;
1045 for (uint64_t C = 0; C < Remaining; ++C) {
1046 EmitAlignment(LogAlignment);
1047 OutStreamer.EmitInstruction(TrapInst, *STI);
1053 // Emit module flags.
1054 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1055 M.getModuleFlagsMetadata(ModuleFlags);
1056 if (!ModuleFlags.empty())
1057 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
1059 // Make sure we wrote out everything we need.
1060 OutStreamer.Flush();
1062 // Finalize debug and EH information.
1063 for (const HandlerInfo &HI : Handlers) {
1064 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1065 TimePassesIsEnabled);
1066 HI.Handler->endModule();
1072 // If the target wants to know about weak references, print them all.
1073 if (MAI->getWeakRefDirective()) {
1074 // FIXME: This is not lazy, it would be nice to only print weak references
1075 // to stuff that is actually used. Note that doing so would require targets
1076 // to notice uses in operands (due to constant exprs etc). This should
1077 // happen with the MC stuff eventually.
1079 // Print out module-level global variables here.
1080 for (const auto &G : M.globals()) {
1081 if (!G.hasExternalWeakLinkage())
1083 OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1086 for (const auto &F : M) {
1087 if (!F.hasExternalWeakLinkage())
1089 OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1093 OutStreamer.AddBlankLine();
1094 for (const auto &Alias : M.aliases()) {
1095 MCSymbol *Name = getSymbol(&Alias);
1097 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1098 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1099 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1100 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1102 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1104 EmitVisibility(Name, Alias.getVisibility());
1106 // Emit the directives as assignments aka .set:
1107 OutStreamer.EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1110 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1111 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1112 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1113 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1114 MP->finishAssembly(M, *MI, *this);
1116 // Emit llvm.ident metadata in an '.ident' directive.
1117 EmitModuleIdents(M);
1119 // Emit __morestack address if needed for indirect calls.
1120 if (MMI->usesMorestackAddr()) {
1121 const MCSection *ReadOnlySection =
1122 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1124 OutStreamer.SwitchSection(ReadOnlySection);
1126 MCSymbol *AddrSymbol =
1127 OutContext.GetOrCreateSymbol(StringRef("__morestack_addr"));
1128 OutStreamer.EmitLabel(AddrSymbol);
1130 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1131 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1135 // If we don't have any trampolines, then we don't require stack memory
1136 // to be executable. Some targets have a directive to declare this.
1137 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1138 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1139 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1140 OutStreamer.SwitchSection(S);
1142 // Allow the target to emit any magic that it wants at the end of the file,
1143 // after everything else has gone out.
1144 EmitEndOfAsmFile(M);
1146 delete Mang; Mang = nullptr;
1149 OutStreamer.Finish();
1150 OutStreamer.reset();
1155 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1157 // Get the function symbol.
1158 CurrentFnSym = getSymbol(MF.getFunction());
1159 CurrentFnSymForSize = CurrentFnSym;
1162 LI = &getAnalysis<MachineLoopInfo>();
1166 // SectionCPs - Keep track the alignment, constpool entries per Section.
1170 SmallVector<unsigned, 4> CPEs;
1171 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1175 /// EmitConstantPool - Print to the current output stream assembly
1176 /// representations of the constants in the constant pool MCP. This is
1177 /// used to print out constants which have been "spilled to memory" by
1178 /// the code generator.
1180 void AsmPrinter::EmitConstantPool() {
1181 const MachineConstantPool *MCP = MF->getConstantPool();
1182 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1183 if (CP.empty()) return;
1185 // Calculate sections for constant pool entries. We collect entries to go into
1186 // the same section together to reduce amount of section switch statements.
1187 SmallVector<SectionCPs, 4> CPSections;
1188 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1189 const MachineConstantPoolEntry &CPE = CP[i];
1190 unsigned Align = CPE.getAlignment();
1193 CPE.getSectionKind(TM.getDataLayout());
1195 const Constant *C = nullptr;
1196 if (!CPE.isMachineConstantPoolEntry())
1197 C = CPE.Val.ConstVal;
1199 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1201 // The number of sections are small, just do a linear search from the
1202 // last section to the first.
1204 unsigned SecIdx = CPSections.size();
1205 while (SecIdx != 0) {
1206 if (CPSections[--SecIdx].S == S) {
1212 SecIdx = CPSections.size();
1213 CPSections.push_back(SectionCPs(S, Align));
1216 if (Align > CPSections[SecIdx].Alignment)
1217 CPSections[SecIdx].Alignment = Align;
1218 CPSections[SecIdx].CPEs.push_back(i);
1221 // Now print stuff into the calculated sections.
1222 const MCSection *CurSection = nullptr;
1223 unsigned Offset = 0;
1224 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1225 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1226 unsigned CPI = CPSections[i].CPEs[j];
1227 MCSymbol *Sym = GetCPISymbol(CPI);
1228 if (!Sym->isUndefined())
1231 if (CurSection != CPSections[i].S) {
1232 OutStreamer.SwitchSection(CPSections[i].S);
1233 EmitAlignment(Log2_32(CPSections[i].Alignment));
1234 CurSection = CPSections[i].S;
1238 MachineConstantPoolEntry CPE = CP[CPI];
1240 // Emit inter-object padding for alignment.
1241 unsigned AlignMask = CPE.getAlignment() - 1;
1242 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1243 OutStreamer.EmitZeros(NewOffset - Offset);
1245 Type *Ty = CPE.getType();
1246 Offset = NewOffset +
1247 TM.getDataLayout()->getTypeAllocSize(Ty);
1249 OutStreamer.EmitLabel(Sym);
1250 if (CPE.isMachineConstantPoolEntry())
1251 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1253 EmitGlobalConstant(CPE.Val.ConstVal);
1258 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1259 /// by the current function to the current output stream.
1261 void AsmPrinter::EmitJumpTableInfo() {
1262 const DataLayout *DL = MF->getTarget().getDataLayout();
1263 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1265 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1266 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1267 if (JT.empty()) return;
1269 // Pick the directive to use to print the jump table entries, and switch to
1270 // the appropriate section.
1271 const Function *F = MF->getFunction();
1272 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1273 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1274 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1276 if (!JTInDiffSection) {
1277 OutStreamer.SwitchSection(TLOF.SectionForGlobal(F, *Mang, TM));
1279 // Otherwise, drop it in the readonly section.
1280 const MCSection *ReadOnlySection =
1281 TLOF.getSectionForJumpTable(*F, *Mang, TM);
1282 OutStreamer.SwitchSection(ReadOnlySection);
1285 EmitAlignment(Log2_32(
1286 MJTI->getEntryAlignment(*TM.getDataLayout())));
1288 // Jump tables in code sections are marked with a data_region directive
1289 // where that's supported.
1290 if (!JTInDiffSection)
1291 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1293 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1294 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1296 // If this jump table was deleted, ignore it.
1297 if (JTBBs.empty()) continue;
1299 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1300 /// emit a .set directive for each unique entry.
1301 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1302 MAI->doesSetDirectiveSuppressesReloc()) {
1303 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1304 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1305 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1306 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1307 const MachineBasicBlock *MBB = JTBBs[ii];
1308 if (!EmittedSets.insert(MBB).second)
1311 // .set LJTSet, LBB32-base
1313 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1314 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1315 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1319 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1320 // before each jump table. The first label is never referenced, but tells
1321 // the assembler and linker the extents of the jump table object. The
1322 // second label is actually referenced by the code.
1323 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1324 // FIXME: This doesn't have to have any specific name, just any randomly
1325 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1326 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1328 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1330 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1331 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1333 if (!JTInDiffSection)
1334 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1337 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1339 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1340 const MachineBasicBlock *MBB,
1341 unsigned UID) const {
1342 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1343 const MCExpr *Value = nullptr;
1344 switch (MJTI->getEntryKind()) {
1345 case MachineJumpTableInfo::EK_Inline:
1346 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1347 case MachineJumpTableInfo::EK_Custom32:
1348 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1349 MJTI, MBB, UID, OutContext);
1351 case MachineJumpTableInfo::EK_BlockAddress:
1352 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1354 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1356 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1357 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1358 // with a relocation as gp-relative, e.g.:
1360 MCSymbol *MBBSym = MBB->getSymbol();
1361 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1365 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1366 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1367 // with a relocation as gp-relative, e.g.:
1369 MCSymbol *MBBSym = MBB->getSymbol();
1370 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1374 case MachineJumpTableInfo::EK_LabelDifference32: {
1375 // Each entry is the address of the block minus the address of the jump
1376 // table. This is used for PIC jump tables where gprel32 is not supported.
1378 // .word LBB123 - LJTI1_2
1379 // If the .set directive avoids relocations, this is emitted as:
1380 // .set L4_5_set_123, LBB123 - LJTI1_2
1381 // .word L4_5_set_123
1382 if (MAI->doesSetDirectiveSuppressesReloc()) {
1383 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1387 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1388 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1389 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1390 Value = MCBinaryExpr::CreateSub(Value, Base, OutContext);
1395 assert(Value && "Unknown entry kind!");
1397 unsigned EntrySize =
1398 MJTI->getEntrySize(*TM.getDataLayout());
1399 OutStreamer.EmitValue(Value, EntrySize);
1403 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1404 /// special global used by LLVM. If so, emit it and return true, otherwise
1405 /// do nothing and return false.
1406 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1407 if (GV->getName() == "llvm.used") {
1408 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1409 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1413 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1414 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1415 GV->hasAvailableExternallyLinkage())
1418 if (!GV->hasAppendingLinkage()) return false;
1420 assert(GV->hasInitializer() && "Not a special LLVM global!");
1422 if (GV->getName() == "llvm.global_ctors") {
1423 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1425 if (TM.getRelocationModel() == Reloc::Static &&
1426 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1427 StringRef Sym(".constructors_used");
1428 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1434 if (GV->getName() == "llvm.global_dtors") {
1435 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1437 if (TM.getRelocationModel() == Reloc::Static &&
1438 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1439 StringRef Sym(".destructors_used");
1440 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1449 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1450 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1451 /// is true, as being used with this directive.
1452 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1453 // Should be an array of 'i8*'.
1454 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1455 const GlobalValue *GV =
1456 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1458 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1464 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1466 llvm::Constant *Func;
1467 llvm::GlobalValue *ComdatKey;
1471 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1473 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1474 // Should be an array of '{ int, void ()* }' structs. The first value is the
1476 if (!isa<ConstantArray>(List)) return;
1478 // Sanity check the structors list.
1479 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1480 if (!InitList) return; // Not an array!
1481 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1482 // FIXME: Only allow the 3-field form in LLVM 4.0.
1483 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1484 return; // Not an array of two or three elements!
1485 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1486 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1487 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1488 return; // Not (int, ptr, ptr).
1490 // Gather the structors in a form that's convenient for sorting by priority.
1491 SmallVector<Structor, 8> Structors;
1492 for (Value *O : InitList->operands()) {
1493 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1494 if (!CS) continue; // Malformed.
1495 if (CS->getOperand(1)->isNullValue())
1496 break; // Found a null terminator, skip the rest.
1497 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1498 if (!Priority) continue; // Malformed.
1499 Structors.push_back(Structor());
1500 Structor &S = Structors.back();
1501 S.Priority = Priority->getLimitedValue(65535);
1502 S.Func = CS->getOperand(1);
1503 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1504 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1507 // Emit the function pointers in the target-specific order
1508 const DataLayout *DL = TM.getDataLayout();
1509 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1510 std::stable_sort(Structors.begin(), Structors.end(),
1511 [](const Structor &L,
1512 const Structor &R) { return L.Priority < R.Priority; });
1513 for (Structor &S : Structors) {
1514 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1515 const MCSymbol *KeySym = nullptr;
1516 if (GlobalValue *GV = S.ComdatKey) {
1517 if (GV->hasAvailableExternallyLinkage())
1518 // If the associated variable is available_externally, some other TU
1519 // will provide its dynamic initializer.
1522 KeySym = getSymbol(GV);
1524 const MCSection *OutputSection =
1525 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1526 : Obj.getStaticDtorSection(S.Priority, KeySym));
1527 OutStreamer.SwitchSection(OutputSection);
1528 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1529 EmitAlignment(Align);
1530 EmitXXStructor(S.Func);
1534 void AsmPrinter::EmitModuleIdents(Module &M) {
1535 if (!MAI->hasIdentDirective())
1538 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1539 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1540 const MDNode *N = NMD->getOperand(i);
1541 assert(N->getNumOperands() == 1 &&
1542 "llvm.ident metadata entry can have only one operand");
1543 const MDString *S = cast<MDString>(N->getOperand(0));
1544 OutStreamer.EmitIdent(S->getString());
1549 //===--------------------------------------------------------------------===//
1550 // Emission and print routines
1553 /// EmitInt8 - Emit a byte directive and value.
1555 void AsmPrinter::EmitInt8(int Value) const {
1556 OutStreamer.EmitIntValue(Value, 1);
1559 /// EmitInt16 - Emit a short directive and value.
1561 void AsmPrinter::EmitInt16(int Value) const {
1562 OutStreamer.EmitIntValue(Value, 2);
1565 /// EmitInt32 - Emit a long directive and value.
1567 void AsmPrinter::EmitInt32(int Value) const {
1568 OutStreamer.EmitIntValue(Value, 4);
1571 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1572 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1573 /// .set if it avoids relocations.
1574 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1575 unsigned Size) const {
1576 // Get the Hi-Lo expression.
1577 const MCExpr *Diff =
1578 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1579 MCSymbolRefExpr::Create(Lo, OutContext),
1582 if (!MAI->doesSetDirectiveSuppressesReloc()) {
1583 OutStreamer.EmitValue(Diff, Size);
1587 // Otherwise, emit with .set (aka assignment).
1588 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1589 OutStreamer.EmitAssignment(SetLabel, Diff);
1590 OutStreamer.EmitSymbolValue(SetLabel, Size);
1593 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1594 /// where the size in bytes of the directive is specified by Size and Label
1595 /// specifies the label. This implicitly uses .set if it is available.
1596 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1598 bool IsSectionRelative) const {
1599 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1600 OutStreamer.EmitCOFFSecRel32(Label);
1604 // Emit Label+Offset (or just Label if Offset is zero)
1605 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1607 Expr = MCBinaryExpr::CreateAdd(
1608 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1610 OutStreamer.EmitValue(Expr, Size);
1613 //===----------------------------------------------------------------------===//
1615 // EmitAlignment - Emit an alignment directive to the specified power of
1616 // two boundary. For example, if you pass in 3 here, you will get an 8
1617 // byte alignment. If a global value is specified, and if that global has
1618 // an explicit alignment requested, it will override the alignment request
1619 // if required for correctness.
1621 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1623 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1626 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1629 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1630 "undefined behavior");
1631 if (getCurrentSection()->getKind().isText())
1632 OutStreamer.EmitCodeAlignment(1u << NumBits);
1634 OutStreamer.EmitValueToAlignment(1u << NumBits);
1637 //===----------------------------------------------------------------------===//
1638 // Constant emission.
1639 //===----------------------------------------------------------------------===//
1641 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1642 MCContext &Ctx = OutContext;
1644 if (CV->isNullValue() || isa<UndefValue>(CV))
1645 return MCConstantExpr::Create(0, Ctx);
1647 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1648 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1650 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1651 return MCSymbolRefExpr::Create(getSymbol(GV), Ctx);
1653 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1654 return MCSymbolRefExpr::Create(GetBlockAddressSymbol(BA), Ctx);
1656 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1658 llvm_unreachable("Unknown constant value to lower!");
1661 if (const MCExpr *RelocExpr
1662 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1665 switch (CE->getOpcode()) {
1667 // If the code isn't optimized, there may be outstanding folding
1668 // opportunities. Attempt to fold the expression using DataLayout as a
1669 // last resort before giving up.
1670 if (Constant *C = ConstantFoldConstantExpression(
1671 CE, TM.getDataLayout()))
1673 return lowerConstant(C);
1675 // Otherwise report the problem to the user.
1678 raw_string_ostream OS(S);
1679 OS << "Unsupported expression in static initializer: ";
1680 CE->printAsOperand(OS, /*PrintType=*/false,
1681 !MF ? nullptr : MF->getFunction()->getParent());
1682 report_fatal_error(OS.str());
1684 case Instruction::GetElementPtr: {
1685 const DataLayout &DL = *TM.getDataLayout();
1687 // Generate a symbolic expression for the byte address
1688 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1689 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1691 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1695 int64_t Offset = OffsetAI.getSExtValue();
1696 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1700 case Instruction::Trunc:
1701 // We emit the value and depend on the assembler to truncate the generated
1702 // expression properly. This is important for differences between
1703 // blockaddress labels. Since the two labels are in the same function, it
1704 // is reasonable to treat their delta as a 32-bit value.
1706 case Instruction::BitCast:
1707 return lowerConstant(CE->getOperand(0));
1709 case Instruction::IntToPtr: {
1710 const DataLayout &DL = *TM.getDataLayout();
1712 // Handle casts to pointers by changing them into casts to the appropriate
1713 // integer type. This promotes constant folding and simplifies this code.
1714 Constant *Op = CE->getOperand(0);
1715 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1717 return lowerConstant(Op);
1720 case Instruction::PtrToInt: {
1721 const DataLayout &DL = *TM.getDataLayout();
1723 // Support only foldable casts to/from pointers that can be eliminated by
1724 // changing the pointer to the appropriately sized integer type.
1725 Constant *Op = CE->getOperand(0);
1726 Type *Ty = CE->getType();
1728 const MCExpr *OpExpr = lowerConstant(Op);
1730 // We can emit the pointer value into this slot if the slot is an
1731 // integer slot equal to the size of the pointer.
1732 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1735 // Otherwise the pointer is smaller than the resultant integer, mask off
1736 // the high bits so we are sure to get a proper truncation if the input is
1738 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1739 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1740 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1743 // The MC library also has a right-shift operator, but it isn't consistently
1744 // signed or unsigned between different targets.
1745 case Instruction::Add:
1746 case Instruction::Sub:
1747 case Instruction::Mul:
1748 case Instruction::SDiv:
1749 case Instruction::SRem:
1750 case Instruction::Shl:
1751 case Instruction::And:
1752 case Instruction::Or:
1753 case Instruction::Xor: {
1754 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1755 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1756 switch (CE->getOpcode()) {
1757 default: llvm_unreachable("Unknown binary operator constant cast expr");
1758 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1759 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1760 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1761 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1762 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1763 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1764 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1765 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1766 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1772 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1773 const Constant *BaseCV = nullptr,
1774 uint64_t Offset = 0);
1776 /// isRepeatedByteSequence - Determine whether the given value is
1777 /// composed of a repeated sequence of identical bytes and return the
1778 /// byte value. If it is not a repeated sequence, return -1.
1779 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1780 StringRef Data = V->getRawDataValues();
1781 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1783 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1784 if (Data[i] != C) return -1;
1785 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1789 /// isRepeatedByteSequence - Determine whether the given value is
1790 /// composed of a repeated sequence of identical bytes and return the
1791 /// byte value. If it is not a repeated sequence, return -1.
1792 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1794 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1795 if (CI->getBitWidth() > 64) return -1;
1798 TM.getDataLayout()->getTypeAllocSize(V->getType());
1799 uint64_t Value = CI->getZExtValue();
1801 // Make sure the constant is at least 8 bits long and has a power
1802 // of 2 bit width. This guarantees the constant bit width is
1803 // always a multiple of 8 bits, avoiding issues with padding out
1804 // to Size and other such corner cases.
1805 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1807 uint8_t Byte = static_cast<uint8_t>(Value);
1809 for (unsigned i = 1; i < Size; ++i) {
1811 if (static_cast<uint8_t>(Value) != Byte) return -1;
1815 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1816 // Make sure all array elements are sequences of the same repeated
1818 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1819 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1820 if (Byte == -1) return -1;
1822 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1823 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1824 if (ThisByte == -1) return -1;
1825 if (Byte != ThisByte) return -1;
1830 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1831 return isRepeatedByteSequence(CDS);
1836 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1839 // See if we can aggregate this into a .fill, if so, emit it as such.
1840 int Value = isRepeatedByteSequence(CDS, AP.TM);
1843 AP.TM.getDataLayout()->getTypeAllocSize(
1845 // Don't emit a 1-byte object as a .fill.
1847 return AP.OutStreamer.EmitFill(Bytes, Value);
1850 // If this can be emitted with .ascii/.asciz, emit it as such.
1851 if (CDS->isString())
1852 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1854 // Otherwise, emit the values in successive locations.
1855 unsigned ElementByteSize = CDS->getElementByteSize();
1856 if (isa<IntegerType>(CDS->getElementType())) {
1857 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1859 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1860 CDS->getElementAsInteger(i));
1861 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1864 } else if (ElementByteSize == 4) {
1865 // FP Constants are printed as integer constants to avoid losing
1867 assert(CDS->getElementType()->isFloatTy());
1868 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1874 F = CDS->getElementAsFloat(i);
1876 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1877 AP.OutStreamer.EmitIntValue(I, 4);
1880 assert(CDS->getElementType()->isDoubleTy());
1881 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1887 F = CDS->getElementAsDouble(i);
1889 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1890 AP.OutStreamer.EmitIntValue(I, 8);
1894 const DataLayout &DL = *AP.TM.getDataLayout();
1895 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1896 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1897 CDS->getNumElements();
1898 if (unsigned Padding = Size - EmittedSize)
1899 AP.OutStreamer.EmitZeros(Padding);
1903 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP,
1904 const Constant *BaseCV, uint64_t Offset) {
1905 // See if we can aggregate some values. Make sure it can be
1906 // represented as a series of bytes of the constant value.
1907 int Value = isRepeatedByteSequence(CA, AP.TM);
1908 const DataLayout &DL = *AP.TM.getDataLayout();
1911 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1912 AP.OutStreamer.EmitFill(Bytes, Value);
1915 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1916 emitGlobalConstantImpl(CA->getOperand(i), AP, BaseCV, Offset);
1917 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1922 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1923 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1924 emitGlobalConstantImpl(CV->getOperand(i), AP);
1926 const DataLayout &DL = *AP.TM.getDataLayout();
1927 unsigned Size = DL.getTypeAllocSize(CV->getType());
1928 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1929 CV->getType()->getNumElements();
1930 if (unsigned Padding = Size - EmittedSize)
1931 AP.OutStreamer.EmitZeros(Padding);
1934 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP,
1935 const Constant *BaseCV, uint64_t Offset) {
1936 // Print the fields in successive locations. Pad to align if needed!
1937 const DataLayout *DL = AP.TM.getDataLayout();
1938 unsigned Size = DL->getTypeAllocSize(CS->getType());
1939 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1940 uint64_t SizeSoFar = 0;
1941 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1942 const Constant *Field = CS->getOperand(i);
1944 // Print the actual field value.
1945 emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
1947 // Check if padding is needed and insert one or more 0s.
1948 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1949 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1950 - Layout->getElementOffset(i)) - FieldSize;
1951 SizeSoFar += FieldSize + PadSize;
1953 // Insert padding - this may include padding to increase the size of the
1954 // current field up to the ABI size (if the struct is not packed) as well
1955 // as padding to ensure that the next field starts at the right offset.
1956 AP.OutStreamer.EmitZeros(PadSize);
1958 assert(SizeSoFar == Layout->getSizeInBytes() &&
1959 "Layout of constant struct may be incorrect!");
1962 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1963 APInt API = CFP->getValueAPF().bitcastToAPInt();
1965 // First print a comment with what we think the original floating-point value
1966 // should have been.
1967 if (AP.isVerbose()) {
1968 SmallString<8> StrVal;
1969 CFP->getValueAPF().toString(StrVal);
1972 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1974 AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
1975 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1978 // Now iterate through the APInt chunks, emitting them in endian-correct
1979 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1981 unsigned NumBytes = API.getBitWidth() / 8;
1982 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1983 const uint64_t *p = API.getRawData();
1985 // PPC's long double has odd notions of endianness compared to how LLVM
1986 // handles it: p[0] goes first for *big* endian on PPC.
1987 if (AP.TM.getDataLayout()->isBigEndian() &&
1988 !CFP->getType()->isPPC_FP128Ty()) {
1989 int Chunk = API.getNumWords() - 1;
1992 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1994 for (; Chunk >= 0; --Chunk)
1995 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1998 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1999 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
2002 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
2005 // Emit the tail padding for the long double.
2006 const DataLayout &DL = *AP.TM.getDataLayout();
2007 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2008 DL.getTypeStoreSize(CFP->getType()));
2011 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2012 const DataLayout *DL = AP.TM.getDataLayout();
2013 unsigned BitWidth = CI->getBitWidth();
2015 // Copy the value as we may massage the layout for constants whose bit width
2016 // is not a multiple of 64-bits.
2017 APInt Realigned(CI->getValue());
2018 uint64_t ExtraBits = 0;
2019 unsigned ExtraBitsSize = BitWidth & 63;
2021 if (ExtraBitsSize) {
2022 // The bit width of the data is not a multiple of 64-bits.
2023 // The extra bits are expected to be at the end of the chunk of the memory.
2025 // * Nothing to be done, just record the extra bits to emit.
2027 // * Record the extra bits to emit.
2028 // * Realign the raw data to emit the chunks of 64-bits.
2029 if (DL->isBigEndian()) {
2030 // Basically the structure of the raw data is a chunk of 64-bits cells:
2031 // 0 1 BitWidth / 64
2032 // [chunk1][chunk2] ... [chunkN].
2033 // The most significant chunk is chunkN and it should be emitted first.
2034 // However, due to the alignment issue chunkN contains useless bits.
2035 // Realign the chunks so that they contain only useless information:
2036 // ExtraBits 0 1 (BitWidth / 64) - 1
2037 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2038 ExtraBits = Realigned.getRawData()[0] &
2039 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2040 Realigned = Realigned.lshr(ExtraBitsSize);
2042 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2045 // We don't expect assemblers to support integer data directives
2046 // for more than 64 bits, so we emit the data in at most 64-bit
2047 // quantities at a time.
2048 const uint64_t *RawData = Realigned.getRawData();
2049 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2050 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2051 AP.OutStreamer.EmitIntValue(Val, 8);
2054 if (ExtraBitsSize) {
2055 // Emit the extra bits after the 64-bits chunks.
2057 // Emit a directive that fills the expected size.
2058 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
2060 Size -= (BitWidth / 64) * 8;
2061 assert(Size && Size * 8 >= ExtraBitsSize &&
2062 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2063 == ExtraBits && "Directive too small for extra bits.");
2064 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
2068 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2069 /// equivalent global, by a target specific GOT pc relative access to the
2071 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2072 const Constant *BaseCst,
2074 // The global @foo below illustrates a global that uses a got equivalent.
2076 // @bar = global i32 42
2077 // @gotequiv = private unnamed_addr constant i32* @bar
2078 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2079 // i64 ptrtoint (i32* @foo to i64))
2082 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2083 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2086 // foo = cstexpr, where
2087 // cstexpr := <gotequiv> - "." + <cst>
2088 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2090 // After canonicalization by EvaluateAsRelocatable `ME` turns into:
2092 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2093 // gotpcrelcst := <offset from @foo base> + <cst>
2096 if (!(*ME)->EvaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2099 const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2100 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2103 const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2107 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2108 if (BaseSym != &MV.getSymB()->getSymbol())
2111 // Make sure to match:
2113 // gotpcrelcst := <offset from @foo base> + <cst>
2115 int64_t GOTPCRelCst = Offset + MV.getConstant();
2116 if (GOTPCRelCst < 0)
2119 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2126 // .long gotequiv - "." + <cst>
2128 // is replaced by the target specific equivalent to:
2133 // .long bar@GOTPCREL+<gotpcrelcst>
2135 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2136 const GlobalVariable *GV = Result.first;
2137 unsigned NumUses = Result.second;
2138 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2139 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2140 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(FinalSym,
2143 // Update GOT equivalent usage information
2146 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2148 AP.GlobalGOTEquivs.erase(GOTEquivSym);
2151 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2152 const Constant *BaseCV, uint64_t Offset) {
2153 const DataLayout *DL = AP.TM.getDataLayout();
2154 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2156 // Globals with sub-elements such as combinations of arrays and structs
2157 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2158 // constant symbol base and the current position with BaseCV and Offset.
2159 if (!BaseCV && CV->hasOneUse())
2160 BaseCV = dyn_cast<Constant>(CV->user_back());
2162 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2163 return AP.OutStreamer.EmitZeros(Size);
2165 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2172 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
2173 CI->getZExtValue());
2174 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
2177 emitGlobalConstantLargeInt(CI, AP);
2182 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2183 return emitGlobalConstantFP(CFP, AP);
2185 if (isa<ConstantPointerNull>(CV)) {
2186 AP.OutStreamer.EmitIntValue(0, Size);
2190 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2191 return emitGlobalConstantDataSequential(CDS, AP);
2193 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2194 return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2196 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2197 return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2199 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2200 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2202 if (CE->getOpcode() == Instruction::BitCast)
2203 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2206 // If the constant expression's size is greater than 64-bits, then we have
2207 // to emit the value in chunks. Try to constant fold the value and emit it
2209 Constant *New = ConstantFoldConstantExpression(CE, DL);
2210 if (New && New != CE)
2211 return emitGlobalConstantImpl(New, AP);
2215 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2216 return emitGlobalConstantVector(V, AP);
2218 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2219 // thread the streamer with EmitValue.
2220 const MCExpr *ME = AP.lowerConstant(CV);
2222 // Since lowerConstant already folded and got rid of all IR pointer and
2223 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2225 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2226 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2228 AP.OutStreamer.EmitValue(ME, Size);
2231 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2232 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2234 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2236 emitGlobalConstantImpl(CV, *this);
2237 else if (MAI->hasSubsectionsViaSymbols()) {
2238 // If the global has zero size, emit a single byte so that two labels don't
2239 // look like they are at the same location.
2240 OutStreamer.EmitIntValue(0, 1);
2244 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2245 // Target doesn't support this yet!
2246 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2249 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2251 OS << '+' << Offset;
2252 else if (Offset < 0)
2256 //===----------------------------------------------------------------------===//
2257 // Symbol Lowering Routines.
2258 //===----------------------------------------------------------------------===//
2260 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2261 /// temporary label with the specified stem and unique ID.
2262 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name, unsigned ID) const {
2263 const DataLayout *DL = TM.getDataLayout();
2264 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2268 /// GetTempSymbol - Return an assembler temporary label with the specified
2270 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name) const {
2271 const DataLayout *DL = TM.getDataLayout();
2272 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2277 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2278 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2281 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2282 return MMI->getAddrLabelSymbol(BB);
2285 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2286 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2287 const DataLayout *DL = TM.getDataLayout();
2288 return OutContext.GetOrCreateSymbol
2289 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2290 + "_" + Twine(CPID));
2293 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2294 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2295 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2298 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2299 /// FIXME: privatize to AsmPrinter.
2300 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2301 const DataLayout *DL = TM.getDataLayout();
2302 return OutContext.GetOrCreateSymbol
2303 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2304 Twine(UID) + "_set_" + Twine(MBBID));
2307 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2308 StringRef Suffix) const {
2309 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2313 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2315 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2316 SmallString<60> NameStr;
2317 Mang->getNameWithPrefix(NameStr, Sym);
2318 return OutContext.GetOrCreateSymbol(NameStr.str());
2323 /// PrintParentLoopComment - Print comments about parent loops of this one.
2324 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2325 unsigned FunctionNumber) {
2327 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2328 OS.indent(Loop->getLoopDepth()*2)
2329 << "Parent Loop BB" << FunctionNumber << "_"
2330 << Loop->getHeader()->getNumber()
2331 << " Depth=" << Loop->getLoopDepth() << '\n';
2335 /// PrintChildLoopComment - Print comments about child loops within
2336 /// the loop for this basic block, with nesting.
2337 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2338 unsigned FunctionNumber) {
2339 // Add child loop information
2340 for (const MachineLoop *CL : *Loop) {
2341 OS.indent(CL->getLoopDepth()*2)
2342 << "Child Loop BB" << FunctionNumber << "_"
2343 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2345 PrintChildLoopComment(OS, CL, FunctionNumber);
2349 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2350 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2351 const MachineLoopInfo *LI,
2352 const AsmPrinter &AP) {
2353 // Add loop depth information
2354 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2357 MachineBasicBlock *Header = Loop->getHeader();
2358 assert(Header && "No header for loop");
2360 // If this block is not a loop header, just print out what is the loop header
2362 if (Header != &MBB) {
2363 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2364 Twine(AP.getFunctionNumber())+"_" +
2365 Twine(Loop->getHeader()->getNumber())+
2366 " Depth="+Twine(Loop->getLoopDepth()));
2370 // Otherwise, it is a loop header. Print out information about child and
2372 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2374 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2377 OS.indent(Loop->getLoopDepth()*2-2);
2382 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2384 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2388 /// EmitBasicBlockStart - This method prints the label for the specified
2389 /// MachineBasicBlock, an alignment (if present) and a comment describing
2390 /// it if appropriate.
2391 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2392 // Emit an alignment directive for this block, if needed.
2393 if (unsigned Align = MBB.getAlignment())
2394 EmitAlignment(Align);
2396 // If the block has its address taken, emit any labels that were used to
2397 // reference the block. It is possible that there is more than one label
2398 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2399 // the references were generated.
2400 if (MBB.hasAddressTaken()) {
2401 const BasicBlock *BB = MBB.getBasicBlock();
2403 OutStreamer.AddComment("Block address taken");
2405 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2406 for (auto *Sym : Symbols)
2407 OutStreamer.EmitLabel(Sym);
2410 // Print some verbose block comments.
2412 if (const BasicBlock *BB = MBB.getBasicBlock())
2414 OutStreamer.AddComment("%" + BB->getName());
2415 emitBasicBlockLoopComments(MBB, LI, *this);
2418 // Print the main label for the block.
2419 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2421 // NOTE: Want this comment at start of line, don't emit with AddComment.
2422 OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2425 OutStreamer.EmitLabel(MBB.getSymbol());
2429 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2430 bool IsDefinition) const {
2431 MCSymbolAttr Attr = MCSA_Invalid;
2433 switch (Visibility) {
2435 case GlobalValue::HiddenVisibility:
2437 Attr = MAI->getHiddenVisibilityAttr();
2439 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2441 case GlobalValue::ProtectedVisibility:
2442 Attr = MAI->getProtectedVisibilityAttr();
2446 if (Attr != MCSA_Invalid)
2447 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2450 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2451 /// exactly one predecessor and the control transfer mechanism between
2452 /// the predecessor and this block is a fall-through.
2454 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2455 // If this is a landing pad, it isn't a fall through. If it has no preds,
2456 // then nothing falls through to it.
2457 if (MBB->isLandingPad() || MBB->pred_empty())
2460 // If there isn't exactly one predecessor, it can't be a fall through.
2461 if (MBB->pred_size() > 1)
2464 // The predecessor has to be immediately before this block.
2465 MachineBasicBlock *Pred = *MBB->pred_begin();
2466 if (!Pred->isLayoutSuccessor(MBB))
2469 // If the block is completely empty, then it definitely does fall through.
2473 // Check the terminators in the previous blocks
2474 for (const auto &MI : Pred->terminators()) {
2475 // If it is not a simple branch, we are in a table somewhere.
2476 if (!MI.isBranch() || MI.isIndirectBranch())
2479 // If we are the operands of one of the branches, this is not a fall
2480 // through. Note that targets with delay slots will usually bundle
2481 // terminators with the delay slot instruction.
2482 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2485 if (OP->isMBB() && OP->getMBB() == MBB)
2495 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2496 if (!S.usesMetadata())
2499 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2500 " stackmap formats, please see the documentation for a description of"
2501 " the default format. If you really need a custom serialized format,"
2502 " please file a bug");
2504 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2505 gcp_map_type::iterator GCPI = GCMap.find(&S);
2506 if (GCPI != GCMap.end())
2507 return GCPI->second.get();
2509 const char *Name = S.getName().c_str();
2511 for (GCMetadataPrinterRegistry::iterator
2512 I = GCMetadataPrinterRegistry::begin(),
2513 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2514 if (strcmp(Name, I->getName()) == 0) {
2515 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2517 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2518 return IterBool.first->second.get();
2521 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2524 /// Pin vtable to this file.
2525 AsmPrinterHandler::~AsmPrinterHandler() {}