1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "Win64Exception.h"
18 #include "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/JumpInstrTableInfo.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/GCMetadataPrinter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBundle.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "asm-printer"
58 static const char *const DWARFGroupName = "DWARF Emission";
59 static const char *const DbgTimerName = "Debug Info Emission";
60 static const char *const EHTimerName = "DWARF Exception Writer";
61 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
63 STATISTIC(EmittedInsts, "Number of machine instrs printed");
65 char AsmPrinter::ID = 0;
67 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
68 static gcp_map_type &getGCMap(void *&P) {
70 P = new gcp_map_type();
71 return *(gcp_map_type*)P;
75 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
76 /// value in log2 form. This rounds up to the preferred alignment if possible
78 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
79 unsigned InBits = 0) {
81 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
82 NumBits = TD.getPreferredAlignmentLog(GVar);
84 // If InBits is specified, round it to it.
88 // If the GV has a specified alignment, take it into account.
89 if (GV->getAlignment() == 0)
92 unsigned GVAlign = Log2_32(GV->getAlignment());
94 // If the GVAlign is larger than NumBits, or if we are required to obey
95 // NumBits because the GV has an assigned section, obey it.
96 if (GVAlign > NumBits || GV->hasSection())
101 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
102 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
103 MII(tm.getSubtargetImpl()->getInstrInfo()),
104 OutContext(Streamer.getContext()), OutStreamer(Streamer), LastMI(nullptr),
105 LastFn(0), Counter(~0U), SetCounter(0) {
106 DD = nullptr; MMI = nullptr; LI = nullptr; MF = nullptr;
107 CurrentFnSym = CurrentFnSymForSize = nullptr;
108 GCMetadataPrinters = nullptr;
109 VerboseAsm = Streamer.isVerboseAsm();
112 AsmPrinter::~AsmPrinter() {
113 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
115 if (GCMetadataPrinters) {
116 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
119 GCMetadataPrinters = nullptr;
125 /// getFunctionNumber - Return a unique ID for the current function.
127 unsigned AsmPrinter::getFunctionNumber() const {
128 return MF->getFunctionNumber();
131 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
132 return TM.getSubtargetImpl()->getTargetLowering()->getObjFileLowering();
135 /// getDataLayout - Return information about data layout.
136 const DataLayout &AsmPrinter::getDataLayout() const {
137 return *TM.getSubtargetImpl()->getDataLayout();
140 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
141 return TM.getSubtarget<MCSubtargetInfo>();
144 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
145 S.EmitInstruction(Inst, getSubtargetInfo());
148 StringRef AsmPrinter::getTargetTriple() const {
149 return TM.getTargetTriple();
152 /// getCurrentSection() - Return the current section we are emitting to.
153 const MCSection *AsmPrinter::getCurrentSection() const {
154 return OutStreamer.getCurrentSection().first;
159 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
160 AU.setPreservesAll();
161 MachineFunctionPass::getAnalysisUsage(AU);
162 AU.addRequired<MachineModuleInfo>();
163 AU.addRequired<GCModuleInfo>();
165 AU.addRequired<MachineLoopInfo>();
168 bool AsmPrinter::doInitialization(Module &M) {
169 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
170 MMI->AnalyzeModule(M);
172 // Initialize TargetLoweringObjectFile.
173 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
174 .Initialize(OutContext, TM);
176 OutStreamer.InitSections();
178 Mang = new Mangler(TM.getSubtargetImpl()->getDataLayout());
180 // Emit the version-min deplyment target directive if needed.
182 // FIXME: If we end up with a collection of these sorts of Darwin-specific
183 // or ELF-specific things, it may make sense to have a platform helper class
184 // that will work with the target helper class. For now keep it here, as the
185 // alternative is duplicated code in each of the target asm printers that
186 // use the directive, where it would need the same conditionalization
188 Triple TT(getTargetTriple());
189 if (TT.isOSDarwin()) {
190 unsigned Major, Minor, Update;
191 TT.getOSVersion(Major, Minor, Update);
192 // If there is a version specified, Major will be non-zero.
194 OutStreamer.EmitVersionMin((TT.isMacOSX() ?
195 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
196 Major, Minor, Update);
199 // Allow the target to emit any magic that it wants at the start of the file.
200 EmitStartOfAsmFile(M);
202 // Very minimal debug info. It is ignored if we emit actual debug info. If we
203 // don't, this at least helps the user find where a global came from.
204 if (MAI->hasSingleParameterDotFile()) {
206 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
209 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
210 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
212 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
213 MP->beginAssembly(*this);
215 // Emit module-level inline asm if it exists.
216 if (!M.getModuleInlineAsm().empty()) {
217 OutStreamer.AddComment("Start of file scope inline assembly");
218 OutStreamer.AddBlankLine();
219 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
220 OutStreamer.AddComment("End of file scope inline assembly");
221 OutStreamer.AddBlankLine();
224 if (MAI->doesSupportDebugInformation()) {
225 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
226 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
228 CodeViewLineTablesGroupName));
230 DD = new DwarfDebug(this, &M);
231 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
235 EHStreamer *ES = nullptr;
236 switch (MAI->getExceptionHandlingType()) {
237 case ExceptionHandling::None:
239 case ExceptionHandling::SjLj:
240 case ExceptionHandling::DwarfCFI:
241 ES = new DwarfCFIException(this);
243 case ExceptionHandling::ARM:
244 ES = new ARMException(this);
246 case ExceptionHandling::WinEH:
247 ES = new Win64Exception(this);
251 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
255 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
256 if (!MAI.hasWeakDefCanBeHiddenDirective())
259 return canBeOmittedFromSymbolTable(GV);
262 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
263 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
265 case GlobalValue::CommonLinkage:
266 case GlobalValue::LinkOnceAnyLinkage:
267 case GlobalValue::LinkOnceODRLinkage:
268 case GlobalValue::WeakAnyLinkage:
269 case GlobalValue::WeakODRLinkage:
270 if (MAI->hasWeakDefDirective()) {
272 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
274 if (!canBeHidden(GV, *MAI))
275 // .weak_definition _foo
276 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
278 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
279 } else if (MAI->hasLinkOnceDirective()) {
281 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
282 //NOTE: linkonce is handled by the section the symbol was assigned to.
285 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
288 case GlobalValue::AppendingLinkage:
289 // FIXME: appending linkage variables should go into a section of
290 // their name or something. For now, just emit them as external.
291 case GlobalValue::ExternalLinkage:
292 // If external or appending, declare as a global symbol.
294 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
296 case GlobalValue::PrivateLinkage:
297 case GlobalValue::InternalLinkage:
299 case GlobalValue::AvailableExternallyLinkage:
300 llvm_unreachable("Should never emit this");
301 case GlobalValue::ExternalWeakLinkage:
302 llvm_unreachable("Don't know how to emit these");
304 llvm_unreachable("Unknown linkage type!");
307 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
308 const GlobalValue *GV) const {
309 TM.getNameWithPrefix(Name, GV, *Mang);
312 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
313 return TM.getSymbol(GV, *Mang);
316 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
317 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
318 if (GV->hasInitializer()) {
319 // Check to see if this is a special global used by LLVM, if so, emit it.
320 if (EmitSpecialLLVMGlobal(GV))
324 GV->printAsOperand(OutStreamer.GetCommentOS(),
325 /*PrintType=*/false, GV->getParent());
326 OutStreamer.GetCommentOS() << '\n';
330 MCSymbol *GVSym = getSymbol(GV);
331 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
333 if (!GV->hasInitializer()) // External globals require no extra code.
336 if (MAI->hasDotTypeDotSizeDirective())
337 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
339 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
341 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
342 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
344 // If the alignment is specified, we *must* obey it. Overaligning a global
345 // with a specified alignment is a prompt way to break globals emitted to
346 // sections and expected to be contiguous (e.g. ObjC metadata).
347 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
349 for (const HandlerInfo &HI : Handlers) {
350 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
351 HI.Handler->setSymbolSize(GVSym, Size);
354 // Handle common and BSS local symbols (.lcomm).
355 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
356 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
357 unsigned Align = 1 << AlignLog;
359 // Handle common symbols.
360 if (GVKind.isCommon()) {
361 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
365 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
369 // Handle local BSS symbols.
370 if (MAI->hasMachoZeroFillDirective()) {
371 const MCSection *TheSection =
372 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
373 // .zerofill __DATA, __bss, _foo, 400, 5
374 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
378 // Use .lcomm only if it supports user-specified alignment.
379 // Otherwise, while it would still be correct to use .lcomm in some
380 // cases (e.g. when Align == 1), the external assembler might enfore
381 // some -unknown- default alignment behavior, which could cause
382 // spurious differences between external and integrated assembler.
383 // Prefer to simply fall back to .local / .comm in this case.
384 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
386 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
390 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
394 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
396 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
400 const MCSection *TheSection =
401 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
403 // Handle the zerofill directive on darwin, which is a special form of BSS
405 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
406 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
409 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
410 // .zerofill __DATA, __common, _foo, 400, 5
411 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
415 // Handle thread local data for mach-o which requires us to output an
416 // additional structure of data and mangle the original symbol so that we
417 // can reference it later.
419 // TODO: This should become an "emit thread local global" method on TLOF.
420 // All of this macho specific stuff should be sunk down into TLOFMachO and
421 // stuff like "TLSExtraDataSection" should no longer be part of the parent
422 // TLOF class. This will also make it more obvious that stuff like
423 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
425 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
426 // Emit the .tbss symbol
428 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
430 if (GVKind.isThreadBSS()) {
431 TheSection = getObjFileLowering().getTLSBSSSection();
432 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
433 } else if (GVKind.isThreadData()) {
434 OutStreamer.SwitchSection(TheSection);
436 EmitAlignment(AlignLog, GV);
437 OutStreamer.EmitLabel(MangSym);
439 EmitGlobalConstant(GV->getInitializer());
442 OutStreamer.AddBlankLine();
444 // Emit the variable struct for the runtime.
445 const MCSection *TLVSect
446 = getObjFileLowering().getTLSExtraDataSection();
448 OutStreamer.SwitchSection(TLVSect);
449 // Emit the linkage here.
450 EmitLinkage(GV, GVSym);
451 OutStreamer.EmitLabel(GVSym);
453 // Three pointers in size:
454 // - __tlv_bootstrap - used to make sure support exists
455 // - spare pointer, used when mapped by the runtime
456 // - pointer to mangled symbol above with initializer
457 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
458 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
460 OutStreamer.EmitIntValue(0, PtrSize);
461 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
463 OutStreamer.AddBlankLine();
467 OutStreamer.SwitchSection(TheSection);
469 EmitLinkage(GV, GVSym);
470 EmitAlignment(AlignLog, GV);
472 OutStreamer.EmitLabel(GVSym);
474 EmitGlobalConstant(GV->getInitializer());
476 if (MAI->hasDotTypeDotSizeDirective())
478 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
480 OutStreamer.AddBlankLine();
483 /// EmitFunctionHeader - This method emits the header for the current
485 void AsmPrinter::EmitFunctionHeader() {
486 // Print out constants referenced by the function
489 // Print the 'header' of function.
490 const Function *F = MF->getFunction();
492 OutStreamer.SwitchSection(
493 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
494 EmitVisibility(CurrentFnSym, F->getVisibility());
496 EmitLinkage(F, CurrentFnSym);
497 EmitAlignment(MF->getAlignment(), F);
499 if (MAI->hasDotTypeDotSizeDirective())
500 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
503 F->printAsOperand(OutStreamer.GetCommentOS(),
504 /*PrintType=*/false, F->getParent());
505 OutStreamer.GetCommentOS() << '\n';
508 // Emit the CurrentFnSym. This is a virtual function to allow targets to
509 // do their wild and crazy things as required.
510 EmitFunctionEntryLabel();
512 // If the function had address-taken blocks that got deleted, then we have
513 // references to the dangling symbols. Emit them at the start of the function
514 // so that we don't get references to undefined symbols.
515 std::vector<MCSymbol*> DeadBlockSyms;
516 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
517 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
518 OutStreamer.AddComment("Address taken block that was later removed");
519 OutStreamer.EmitLabel(DeadBlockSyms[i]);
522 // Emit pre-function debug and/or EH information.
523 for (const HandlerInfo &HI : Handlers) {
524 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
525 HI.Handler->beginFunction(MF);
528 // Emit the prefix data.
529 if (F->hasPrefixData())
530 EmitGlobalConstant(F->getPrefixData());
533 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
534 /// function. This can be overridden by targets as required to do custom stuff.
535 void AsmPrinter::EmitFunctionEntryLabel() {
536 // The function label could have already been emitted if two symbols end up
537 // conflicting due to asm renaming. Detect this and emit an error.
538 if (CurrentFnSym->isUndefined())
539 return OutStreamer.EmitLabel(CurrentFnSym);
541 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
542 "' label emitted multiple times to assembly file");
545 /// emitComments - Pretty-print comments for instructions.
546 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
547 const MachineFunction *MF = MI.getParent()->getParent();
548 const TargetMachine &TM = MF->getTarget();
550 // Check for spills and reloads
553 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
555 // We assume a single instruction only has a spill or reload, not
557 const MachineMemOperand *MMO;
558 if (TM.getSubtargetImpl()->getInstrInfo()->isLoadFromStackSlotPostFE(&MI,
560 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
561 MMO = *MI.memoperands_begin();
562 CommentOS << MMO->getSize() << "-byte Reload\n";
564 } else if (TM.getSubtargetImpl()->getInstrInfo()->hasLoadFromStackSlot(
566 if (FrameInfo->isSpillSlotObjectIndex(FI))
567 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
568 } else if (TM.getSubtargetImpl()->getInstrInfo()->isStoreToStackSlotPostFE(
570 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
571 MMO = *MI.memoperands_begin();
572 CommentOS << MMO->getSize() << "-byte Spill\n";
574 } else if (TM.getSubtargetImpl()->getInstrInfo()->hasStoreToStackSlot(
576 if (FrameInfo->isSpillSlotObjectIndex(FI))
577 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
580 // Check for spill-induced copies
581 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
582 CommentOS << " Reload Reuse\n";
585 /// emitImplicitDef - This method emits the specified machine instruction
586 /// that is an implicit def.
587 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
588 unsigned RegNo = MI->getOperand(0).getReg();
589 OutStreamer.AddComment(
590 Twine("implicit-def: ") +
591 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
592 OutStreamer.AddBlankLine();
595 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
596 std::string Str = "kill:";
597 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
598 const MachineOperand &Op = MI->getOperand(i);
599 assert(Op.isReg() && "KILL instruction must have only register operands");
601 Str += AP.TM.getSubtargetImpl()->getRegisterInfo()->getName(Op.getReg());
602 Str += (Op.isDef() ? "<def>" : "<kill>");
604 AP.OutStreamer.AddComment(Str);
605 AP.OutStreamer.AddBlankLine();
608 /// emitDebugValueComment - This method handles the target-independent form
609 /// of DBG_VALUE, returning true if it was able to do so. A false return
610 /// means the target will need to handle MI in EmitInstruction.
611 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
612 // This code handles only the 3-operand target-independent form.
613 if (MI->getNumOperands() != 3)
616 SmallString<128> Str;
617 raw_svector_ostream OS(Str);
618 OS << "DEBUG_VALUE: ";
620 DIVariable V(MI->getOperand(2).getMetadata());
621 if (V.getContext().isSubprogram()) {
622 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
627 if (V.isVariablePiece())
628 OS << " [piece offset=" << V.getPieceOffset()
629 << " size="<<V.getPieceSize()<<"]";
632 // The second operand is only an offset if it's an immediate.
633 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
634 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
636 // Register or immediate value. Register 0 means undef.
637 if (MI->getOperand(0).isFPImm()) {
638 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
639 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
640 OS << (double)APF.convertToFloat();
641 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
642 OS << APF.convertToDouble();
644 // There is no good way to print long double. Convert a copy to
645 // double. Ah well, it's only a comment.
647 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
649 OS << "(long double) " << APF.convertToDouble();
651 } else if (MI->getOperand(0).isImm()) {
652 OS << MI->getOperand(0).getImm();
653 } else if (MI->getOperand(0).isCImm()) {
654 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
657 if (MI->getOperand(0).isReg()) {
658 Reg = MI->getOperand(0).getReg();
660 assert(MI->getOperand(0).isFI() && "Unknown operand type");
661 const TargetFrameLowering *TFI =
662 AP.TM.getSubtargetImpl()->getFrameLowering();
663 Offset += TFI->getFrameIndexReference(*AP.MF,
664 MI->getOperand(0).getIndex(), Reg);
668 // Suppress offset, it is not meaningful here.
670 // NOTE: Want this comment at start of line, don't emit with AddComment.
671 AP.OutStreamer.emitRawComment(OS.str());
676 OS << AP.TM.getSubtargetImpl()->getRegisterInfo()->getName(Reg);
680 OS << '+' << Offset << ']';
682 // NOTE: Want this comment at start of line, don't emit with AddComment.
683 AP.OutStreamer.emitRawComment(OS.str());
687 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
688 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
689 MF->getFunction()->needsUnwindTableEntry())
692 if (MMI->hasDebugInfo())
698 bool AsmPrinter::needsSEHMoves() {
699 return MAI->getExceptionHandlingType() == ExceptionHandling::WinEH &&
700 MF->getFunction()->needsUnwindTableEntry();
703 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
704 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
705 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
706 ExceptionHandlingType != ExceptionHandling::ARM)
709 if (needsCFIMoves() == CFI_M_None)
712 const MachineModuleInfo &MMI = MF->getMMI();
713 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
714 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
715 const MCCFIInstruction &CFI = Instrs[CFIIndex];
716 emitCFIInstruction(CFI);
719 /// EmitFunctionBody - This method emits the body and trailer for a
721 void AsmPrinter::EmitFunctionBody() {
722 // Emit target-specific gunk before the function body.
723 EmitFunctionBodyStart();
725 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
727 // Print out code for the function.
728 bool HasAnyRealCode = false;
729 const MachineInstr *LastMI = nullptr;
730 for (auto &MBB : *MF) {
731 // Print a label for the basic block.
732 EmitBasicBlockStart(MBB);
733 for (auto &MI : MBB) {
736 // Print the assembly for the instruction.
737 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
738 !MI.isDebugValue()) {
739 HasAnyRealCode = true;
743 if (ShouldPrintDebugScopes) {
744 for (const HandlerInfo &HI : Handlers) {
745 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
746 TimePassesIsEnabled);
747 HI.Handler->beginInstruction(&MI);
752 emitComments(MI, OutStreamer.GetCommentOS());
754 switch (MI.getOpcode()) {
755 case TargetOpcode::CFI_INSTRUCTION:
756 emitCFIInstruction(MI);
759 case TargetOpcode::EH_LABEL:
760 case TargetOpcode::GC_LABEL:
761 OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
763 case TargetOpcode::INLINEASM:
766 case TargetOpcode::DBG_VALUE:
768 if (!emitDebugValueComment(&MI, *this))
769 EmitInstruction(&MI);
772 case TargetOpcode::IMPLICIT_DEF:
773 if (isVerbose()) emitImplicitDef(&MI);
775 case TargetOpcode::KILL:
776 if (isVerbose()) emitKill(&MI, *this);
779 EmitInstruction(&MI);
783 if (ShouldPrintDebugScopes) {
784 for (const HandlerInfo &HI : Handlers) {
785 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
786 TimePassesIsEnabled);
787 HI.Handler->endInstruction();
792 EmitBasicBlockEnd(MBB);
795 // If the last instruction was a prolog label, then we have a situation where
796 // we emitted a prolog but no function body. This results in the ending prolog
797 // label equaling the end of function label and an invalid "row" in the
798 // FDE. We need to emit a noop in this situation so that the FDE's rows are
800 bool RequiresNoop = LastMI && LastMI->isCFIInstruction();
802 // If the function is empty and the object file uses .subsections_via_symbols,
803 // then we need to emit *something* to the function body to prevent the
804 // labels from collapsing together. Just emit a noop.
805 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
807 TM.getSubtargetImpl()->getInstrInfo()->getNoopForMachoTarget(Noop);
808 if (Noop.getOpcode()) {
809 OutStreamer.AddComment("avoids zero-length function");
810 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
811 } else // Target not mc-ized yet.
812 OutStreamer.EmitRawText(StringRef("\tnop\n"));
815 const Function *F = MF->getFunction();
816 for (const auto &BB : *F) {
817 if (!BB.hasAddressTaken())
819 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
820 if (Sym->isDefined())
822 OutStreamer.AddComment("Address of block that was removed by CodeGen");
823 OutStreamer.EmitLabel(Sym);
826 // Emit target-specific gunk after the function body.
827 EmitFunctionBodyEnd();
829 // If the target wants a .size directive for the size of the function, emit
831 if (MAI->hasDotTypeDotSizeDirective()) {
832 // Create a symbol for the end of function, so we can get the size as
833 // difference between the function label and the temp label.
834 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
835 OutStreamer.EmitLabel(FnEndLabel);
837 const MCExpr *SizeExp =
838 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
839 MCSymbolRefExpr::Create(CurrentFnSymForSize,
842 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
845 // Emit post-function debug and/or EH information.
846 for (const HandlerInfo &HI : Handlers) {
847 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
848 HI.Handler->endFunction(MF);
852 // Print out jump tables referenced by the function.
855 OutStreamer.AddBlankLine();
858 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP);
860 bool AsmPrinter::doFinalization(Module &M) {
861 // Emit global variables.
862 for (const auto &G : M.globals())
863 EmitGlobalVariable(&G);
865 // Emit visibility info for declarations
866 for (const Function &F : M) {
867 if (!F.isDeclaration())
869 GlobalValue::VisibilityTypes V = F.getVisibility();
870 if (V == GlobalValue::DefaultVisibility)
873 MCSymbol *Name = getSymbol(&F);
874 EmitVisibility(Name, V, false);
877 // Get information about jump-instruction tables to print.
878 JumpInstrTableInfo *JITI = getAnalysisIfAvailable<JumpInstrTableInfo>();
880 if (JITI && !JITI->getTables().empty()) {
881 unsigned Arch = Triple(getTargetTriple()).getArch();
882 bool IsThumb = (Arch == Triple::thumb || Arch == Triple::thumbeb);
884 TM.getSubtargetImpl()->getInstrInfo()->getTrap(TrapInst);
885 for (const auto &KV : JITI->getTables()) {
887 for (const auto &FunPair : KV.second) {
888 // Emit the function labels to make this be a function entry point.
890 OutContext.GetOrCreateSymbol(FunPair.second->getName());
891 OutStreamer.EmitSymbolAttribute(FunSym, MCSA_Global);
892 // FIXME: JumpTableInstrInfo should store information about the required
893 // alignment of table entries and the size of the padding instruction.
896 OutStreamer.EmitThumbFunc(FunSym);
897 if (MAI->hasDotTypeDotSizeDirective())
898 OutStreamer.EmitSymbolAttribute(FunSym, MCSA_ELF_TypeFunction);
899 OutStreamer.EmitLabel(FunSym);
901 // Emit the jump instruction to transfer control to the original
904 MCSymbol *TargetSymbol =
905 OutContext.GetOrCreateSymbol(FunPair.first->getName());
906 const MCSymbolRefExpr *TargetSymRef =
907 MCSymbolRefExpr::Create(TargetSymbol, MCSymbolRefExpr::VK_PLT,
909 TM.getSubtargetImpl()->getInstrInfo()->getUnconditionalBranch(
910 JumpToFun, TargetSymRef);
911 OutStreamer.EmitInstruction(JumpToFun, getSubtargetInfo());
915 // Emit enough padding instructions to fill up to the next power of two.
916 // This assumes that the trap instruction takes 8 bytes or fewer.
917 uint64_t Remaining = NextPowerOf2(Count) - Count;
918 for (uint64_t C = 0; C < Remaining; ++C) {
920 OutStreamer.EmitInstruction(TrapInst, getSubtargetInfo());
926 // Emit module flags.
927 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
928 M.getModuleFlagsMetadata(ModuleFlags);
929 if (!ModuleFlags.empty())
930 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
932 // Make sure we wrote out everything we need.
935 // Finalize debug and EH information.
936 for (const HandlerInfo &HI : Handlers) {
937 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
938 TimePassesIsEnabled);
939 HI.Handler->endModule();
945 // If the target wants to know about weak references, print them all.
946 if (MAI->getWeakRefDirective()) {
947 // FIXME: This is not lazy, it would be nice to only print weak references
948 // to stuff that is actually used. Note that doing so would require targets
949 // to notice uses in operands (due to constant exprs etc). This should
950 // happen with the MC stuff eventually.
952 // Print out module-level global variables here.
953 for (const auto &G : M.globals()) {
954 if (!G.hasExternalWeakLinkage())
956 OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
959 for (const auto &F : M) {
960 if (!F.hasExternalWeakLinkage())
962 OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
966 if (MAI->hasSetDirective()) {
967 OutStreamer.AddBlankLine();
968 for (const auto &Alias : M.aliases()) {
969 MCSymbol *Name = getSymbol(&Alias);
971 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
972 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
973 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
974 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
976 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
978 EmitVisibility(Name, Alias.getVisibility());
980 // Emit the directives as assignments aka .set:
981 OutStreamer.EmitAssignment(Name,
982 lowerConstant(Alias.getAliasee(), *this));
986 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
987 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
988 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
989 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
990 MP->finishAssembly(*this);
992 // Emit llvm.ident metadata in an '.ident' directive.
995 // If we don't have any trampolines, then we don't require stack memory
996 // to be executable. Some targets have a directive to declare this.
997 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
998 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
999 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1000 OutStreamer.SwitchSection(S);
1002 // Allow the target to emit any magic that it wants at the end of the file,
1003 // after everything else has gone out.
1004 EmitEndOfAsmFile(M);
1006 delete Mang; Mang = nullptr;
1009 OutStreamer.Finish();
1010 OutStreamer.reset();
1015 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1017 // Get the function symbol.
1018 CurrentFnSym = getSymbol(MF.getFunction());
1019 CurrentFnSymForSize = CurrentFnSym;
1022 LI = &getAnalysis<MachineLoopInfo>();
1026 // SectionCPs - Keep track the alignment, constpool entries per Section.
1030 SmallVector<unsigned, 4> CPEs;
1031 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1035 /// EmitConstantPool - Print to the current output stream assembly
1036 /// representations of the constants in the constant pool MCP. This is
1037 /// used to print out constants which have been "spilled to memory" by
1038 /// the code generator.
1040 void AsmPrinter::EmitConstantPool() {
1041 const MachineConstantPool *MCP = MF->getConstantPool();
1042 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1043 if (CP.empty()) return;
1045 // Calculate sections for constant pool entries. We collect entries to go into
1046 // the same section together to reduce amount of section switch statements.
1047 SmallVector<SectionCPs, 4> CPSections;
1048 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1049 const MachineConstantPoolEntry &CPE = CP[i];
1050 unsigned Align = CPE.getAlignment();
1053 CPE.getSectionKind(TM.getSubtargetImpl()->getDataLayout());
1055 const Constant *C = nullptr;
1056 if (!CPE.isMachineConstantPoolEntry())
1057 C = CPE.Val.ConstVal;
1059 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1061 // The number of sections are small, just do a linear search from the
1062 // last section to the first.
1064 unsigned SecIdx = CPSections.size();
1065 while (SecIdx != 0) {
1066 if (CPSections[--SecIdx].S == S) {
1072 SecIdx = CPSections.size();
1073 CPSections.push_back(SectionCPs(S, Align));
1076 if (Align > CPSections[SecIdx].Alignment)
1077 CPSections[SecIdx].Alignment = Align;
1078 CPSections[SecIdx].CPEs.push_back(i);
1081 // Now print stuff into the calculated sections.
1082 const MCSection *CurSection = nullptr;
1083 unsigned Offset = 0;
1084 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1085 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1086 unsigned CPI = CPSections[i].CPEs[j];
1087 MCSymbol *Sym = GetCPISymbol(CPI);
1088 if (!Sym->isUndefined())
1091 if (CurSection != CPSections[i].S) {
1092 OutStreamer.SwitchSection(CPSections[i].S);
1093 EmitAlignment(Log2_32(CPSections[i].Alignment));
1094 CurSection = CPSections[i].S;
1098 MachineConstantPoolEntry CPE = CP[CPI];
1100 // Emit inter-object padding for alignment.
1101 unsigned AlignMask = CPE.getAlignment() - 1;
1102 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1103 OutStreamer.EmitZeros(NewOffset - Offset);
1105 Type *Ty = CPE.getType();
1106 Offset = NewOffset +
1107 TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(Ty);
1109 OutStreamer.EmitLabel(Sym);
1110 if (CPE.isMachineConstantPoolEntry())
1111 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1113 EmitGlobalConstant(CPE.Val.ConstVal);
1118 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1119 /// by the current function to the current output stream.
1121 void AsmPrinter::EmitJumpTableInfo() {
1122 const DataLayout *DL = MF->getSubtarget().getDataLayout();
1123 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1125 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1126 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1127 if (JT.empty()) return;
1129 // Pick the directive to use to print the jump table entries, and switch to
1130 // the appropriate section.
1131 const Function *F = MF->getFunction();
1132 bool JTInDiffSection = false;
1133 if (// In PIC mode, we need to emit the jump table to the same section as the
1134 // function body itself, otherwise the label differences won't make sense.
1135 // FIXME: Need a better predicate for this: what about custom entries?
1136 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1137 // We should also do if the section name is NULL or function is declared
1138 // in discardable section
1139 // FIXME: this isn't the right predicate, should be based on the MCSection
1140 // for the function.
1141 F->isWeakForLinker()) {
1142 OutStreamer.SwitchSection(
1143 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
1145 // Otherwise, drop it in the readonly section.
1146 const MCSection *ReadOnlySection =
1147 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1149 OutStreamer.SwitchSection(ReadOnlySection);
1150 JTInDiffSection = true;
1153 EmitAlignment(Log2_32(
1154 MJTI->getEntryAlignment(*TM.getSubtargetImpl()->getDataLayout())));
1156 // Jump tables in code sections are marked with a data_region directive
1157 // where that's supported.
1158 if (!JTInDiffSection)
1159 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1161 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1162 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1164 // If this jump table was deleted, ignore it.
1165 if (JTBBs.empty()) continue;
1167 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1168 // .set directive for each unique entry. This reduces the number of
1169 // relocations the assembler will generate for the jump table.
1170 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1171 MAI->hasSetDirective()) {
1172 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1173 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1174 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1175 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1176 const MachineBasicBlock *MBB = JTBBs[ii];
1177 if (!EmittedSets.insert(MBB)) continue;
1179 // .set LJTSet, LBB32-base
1181 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1182 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1183 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1187 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1188 // before each jump table. The first label is never referenced, but tells
1189 // the assembler and linker the extents of the jump table object. The
1190 // second label is actually referenced by the code.
1191 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1192 // FIXME: This doesn't have to have any specific name, just any randomly
1193 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1194 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1196 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1198 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1199 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1201 if (!JTInDiffSection)
1202 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1205 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1207 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1208 const MachineBasicBlock *MBB,
1209 unsigned UID) const {
1210 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1211 const MCExpr *Value = nullptr;
1212 switch (MJTI->getEntryKind()) {
1213 case MachineJumpTableInfo::EK_Inline:
1214 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1215 case MachineJumpTableInfo::EK_Custom32:
1217 TM.getSubtargetImpl()->getTargetLowering()->LowerCustomJumpTableEntry(
1218 MJTI, MBB, UID, OutContext);
1220 case MachineJumpTableInfo::EK_BlockAddress:
1221 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1223 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1225 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1226 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1227 // with a relocation as gp-relative, e.g.:
1229 MCSymbol *MBBSym = MBB->getSymbol();
1230 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1234 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1235 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1236 // with a relocation as gp-relative, e.g.:
1238 MCSymbol *MBBSym = MBB->getSymbol();
1239 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1243 case MachineJumpTableInfo::EK_LabelDifference32: {
1244 // EK_LabelDifference32 - Each entry is the address of the block minus
1245 // the address of the jump table. This is used for PIC jump tables where
1246 // gprel32 is not supported. e.g.:
1247 // .word LBB123 - LJTI1_2
1248 // If the .set directive is supported, this is emitted as:
1249 // .set L4_5_set_123, LBB123 - LJTI1_2
1250 // .word L4_5_set_123
1252 // If we have emitted set directives for the jump table entries, print
1253 // them rather than the entries themselves. If we're emitting PIC, then
1254 // emit the table entries as differences between two text section labels.
1255 if (MAI->hasSetDirective()) {
1256 // If we used .set, reference the .set's symbol.
1257 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1261 // Otherwise, use the difference as the jump table entry.
1262 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1263 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1264 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1269 assert(Value && "Unknown entry kind!");
1271 unsigned EntrySize =
1272 MJTI->getEntrySize(*TM.getSubtargetImpl()->getDataLayout());
1273 OutStreamer.EmitValue(Value, EntrySize);
1277 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1278 /// special global used by LLVM. If so, emit it and return true, otherwise
1279 /// do nothing and return false.
1280 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1281 if (GV->getName() == "llvm.used") {
1282 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1283 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1287 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1288 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1289 GV->hasAvailableExternallyLinkage())
1292 if (!GV->hasAppendingLinkage()) return false;
1294 assert(GV->hasInitializer() && "Not a special LLVM global!");
1296 if (GV->getName() == "llvm.global_ctors") {
1297 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1299 if (TM.getRelocationModel() == Reloc::Static &&
1300 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1301 StringRef Sym(".constructors_used");
1302 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1308 if (GV->getName() == "llvm.global_dtors") {
1309 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1311 if (TM.getRelocationModel() == Reloc::Static &&
1312 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1313 StringRef Sym(".destructors_used");
1314 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1323 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1324 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1325 /// is true, as being used with this directive.
1326 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1327 // Should be an array of 'i8*'.
1328 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1329 const GlobalValue *GV =
1330 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1332 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1338 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1340 llvm::Constant *Func;
1341 llvm::GlobalValue *ComdatKey;
1345 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1347 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1348 // Should be an array of '{ int, void ()* }' structs. The first value is the
1350 if (!isa<ConstantArray>(List)) return;
1352 // Sanity check the structors list.
1353 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1354 if (!InitList) return; // Not an array!
1355 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1356 // FIXME: Only allow the 3-field form in LLVM 4.0.
1357 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1358 return; // Not an array of two or three elements!
1359 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1360 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1361 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1362 return; // Not (int, ptr, ptr).
1364 // Gather the structors in a form that's convenient for sorting by priority.
1365 SmallVector<Structor, 8> Structors;
1366 for (Value *O : InitList->operands()) {
1367 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1368 if (!CS) continue; // Malformed.
1369 if (CS->getOperand(1)->isNullValue())
1370 break; // Found a null terminator, skip the rest.
1371 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1372 if (!Priority) continue; // Malformed.
1373 Structors.push_back(Structor());
1374 Structor &S = Structors.back();
1375 S.Priority = Priority->getLimitedValue(65535);
1376 S.Func = CS->getOperand(1);
1377 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1378 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1381 // Emit the function pointers in the target-specific order
1382 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
1383 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1384 std::stable_sort(Structors.begin(), Structors.end(),
1385 [](const Structor &L,
1386 const Structor &R) { return L.Priority < R.Priority; });
1387 for (Structor &S : Structors) {
1388 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1389 const MCSymbol *KeySym = nullptr;
1390 if (GlobalValue *GV = S.ComdatKey) {
1391 if (GV->hasAvailableExternallyLinkage())
1392 // If the associated variable is available_externally, some other TU
1393 // will provide its dynamic initializer.
1396 KeySym = getSymbol(GV);
1398 const MCSection *OutputSection =
1399 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1400 : Obj.getStaticDtorSection(S.Priority, KeySym));
1401 OutStreamer.SwitchSection(OutputSection);
1402 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1403 EmitAlignment(Align);
1404 EmitXXStructor(S.Func);
1408 void AsmPrinter::EmitModuleIdents(Module &M) {
1409 if (!MAI->hasIdentDirective())
1412 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1413 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1414 const MDNode *N = NMD->getOperand(i);
1415 assert(N->getNumOperands() == 1 &&
1416 "llvm.ident metadata entry can have only one operand");
1417 const MDString *S = cast<MDString>(N->getOperand(0));
1418 OutStreamer.EmitIdent(S->getString());
1423 //===--------------------------------------------------------------------===//
1424 // Emission and print routines
1427 /// EmitInt8 - Emit a byte directive and value.
1429 void AsmPrinter::EmitInt8(int Value) const {
1430 OutStreamer.EmitIntValue(Value, 1);
1433 /// EmitInt16 - Emit a short directive and value.
1435 void AsmPrinter::EmitInt16(int Value) const {
1436 OutStreamer.EmitIntValue(Value, 2);
1439 /// EmitInt32 - Emit a long directive and value.
1441 void AsmPrinter::EmitInt32(int Value) const {
1442 OutStreamer.EmitIntValue(Value, 4);
1445 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1446 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1447 /// labels. This implicitly uses .set if it is available.
1448 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1449 unsigned Size) const {
1450 // Get the Hi-Lo expression.
1451 const MCExpr *Diff =
1452 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1453 MCSymbolRefExpr::Create(Lo, OutContext),
1456 if (!MAI->hasSetDirective()) {
1457 OutStreamer.EmitValue(Diff, Size);
1461 // Otherwise, emit with .set (aka assignment).
1462 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1463 OutStreamer.EmitAssignment(SetLabel, Diff);
1464 OutStreamer.EmitSymbolValue(SetLabel, Size);
1467 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1468 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1469 /// specify the labels. This implicitly uses .set if it is available.
1470 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1472 unsigned Size) const {
1474 // Emit Hi+Offset - Lo
1475 // Get the Hi+Offset expression.
1476 const MCExpr *Plus =
1477 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1478 MCConstantExpr::Create(Offset, OutContext),
1481 // Get the Hi+Offset-Lo expression.
1482 const MCExpr *Diff =
1483 MCBinaryExpr::CreateSub(Plus,
1484 MCSymbolRefExpr::Create(Lo, OutContext),
1487 if (!MAI->hasSetDirective())
1488 OutStreamer.EmitValue(Diff, Size);
1490 // Otherwise, emit with .set (aka assignment).
1491 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1492 OutStreamer.EmitAssignment(SetLabel, Diff);
1493 OutStreamer.EmitSymbolValue(SetLabel, Size);
1497 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1498 /// where the size in bytes of the directive is specified by Size and Label
1499 /// specifies the label. This implicitly uses .set if it is available.
1500 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1502 bool IsSectionRelative) const {
1503 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1504 OutStreamer.EmitCOFFSecRel32(Label);
1508 // Emit Label+Offset (or just Label if Offset is zero)
1509 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1511 Expr = MCBinaryExpr::CreateAdd(
1512 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1514 OutStreamer.EmitValue(Expr, Size);
1517 //===----------------------------------------------------------------------===//
1519 // EmitAlignment - Emit an alignment directive to the specified power of
1520 // two boundary. For example, if you pass in 3 here, you will get an 8
1521 // byte alignment. If a global value is specified, and if that global has
1522 // an explicit alignment requested, it will override the alignment request
1523 // if required for correctness.
1525 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1527 NumBits = getGVAlignmentLog2(GV, *TM.getSubtargetImpl()->getDataLayout(),
1530 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1532 if (getCurrentSection()->getKind().isText())
1533 OutStreamer.EmitCodeAlignment(1 << NumBits);
1535 OutStreamer.EmitValueToAlignment(1 << NumBits);
1538 //===----------------------------------------------------------------------===//
1539 // Constant emission.
1540 //===----------------------------------------------------------------------===//
1542 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1544 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1545 MCContext &Ctx = AP.OutContext;
1547 if (CV->isNullValue() || isa<UndefValue>(CV))
1548 return MCConstantExpr::Create(0, Ctx);
1550 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1551 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1553 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1554 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1556 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1557 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1559 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1561 llvm_unreachable("Unknown constant value to lower!");
1564 if (const MCExpr *RelocExpr =
1565 AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
1569 switch (CE->getOpcode()) {
1571 // If the code isn't optimized, there may be outstanding folding
1572 // opportunities. Attempt to fold the expression using DataLayout as a
1573 // last resort before giving up.
1574 if (Constant *C = ConstantFoldConstantExpression(
1575 CE, AP.TM.getSubtargetImpl()->getDataLayout()))
1577 return lowerConstant(C, AP);
1579 // Otherwise report the problem to the user.
1582 raw_string_ostream OS(S);
1583 OS << "Unsupported expression in static initializer: ";
1584 CE->printAsOperand(OS, /*PrintType=*/false,
1585 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
1586 report_fatal_error(OS.str());
1588 case Instruction::GetElementPtr: {
1589 const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
1590 // Generate a symbolic expression for the byte address
1591 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1592 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1594 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1598 int64_t Offset = OffsetAI.getSExtValue();
1599 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1603 case Instruction::Trunc:
1604 // We emit the value and depend on the assembler to truncate the generated
1605 // expression properly. This is important for differences between
1606 // blockaddress labels. Since the two labels are in the same function, it
1607 // is reasonable to treat their delta as a 32-bit value.
1609 case Instruction::BitCast:
1610 return lowerConstant(CE->getOperand(0), AP);
1612 case Instruction::IntToPtr: {
1613 const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
1614 // Handle casts to pointers by changing them into casts to the appropriate
1615 // integer type. This promotes constant folding and simplifies this code.
1616 Constant *Op = CE->getOperand(0);
1617 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1619 return lowerConstant(Op, AP);
1622 case Instruction::PtrToInt: {
1623 const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
1624 // Support only foldable casts to/from pointers that can be eliminated by
1625 // changing the pointer to the appropriately sized integer type.
1626 Constant *Op = CE->getOperand(0);
1627 Type *Ty = CE->getType();
1629 const MCExpr *OpExpr = lowerConstant(Op, AP);
1631 // We can emit the pointer value into this slot if the slot is an
1632 // integer slot equal to the size of the pointer.
1633 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1636 // Otherwise the pointer is smaller than the resultant integer, mask off
1637 // the high bits so we are sure to get a proper truncation if the input is
1639 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1640 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1641 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1644 // The MC library also has a right-shift operator, but it isn't consistently
1645 // signed or unsigned between different targets.
1646 case Instruction::Add:
1647 case Instruction::Sub:
1648 case Instruction::Mul:
1649 case Instruction::SDiv:
1650 case Instruction::SRem:
1651 case Instruction::Shl:
1652 case Instruction::And:
1653 case Instruction::Or:
1654 case Instruction::Xor: {
1655 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1656 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1657 switch (CE->getOpcode()) {
1658 default: llvm_unreachable("Unknown binary operator constant cast expr");
1659 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1660 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1661 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1662 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1663 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1664 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1665 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1666 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1667 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1673 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1675 /// isRepeatedByteSequence - Determine whether the given value is
1676 /// composed of a repeated sequence of identical bytes and return the
1677 /// byte value. If it is not a repeated sequence, return -1.
1678 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1679 StringRef Data = V->getRawDataValues();
1680 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1682 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1683 if (Data[i] != C) return -1;
1684 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1688 /// isRepeatedByteSequence - Determine whether the given value is
1689 /// composed of a repeated sequence of identical bytes and return the
1690 /// byte value. If it is not a repeated sequence, return -1.
1691 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1693 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1694 if (CI->getBitWidth() > 64) return -1;
1697 TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(V->getType());
1698 uint64_t Value = CI->getZExtValue();
1700 // Make sure the constant is at least 8 bits long and has a power
1701 // of 2 bit width. This guarantees the constant bit width is
1702 // always a multiple of 8 bits, avoiding issues with padding out
1703 // to Size and other such corner cases.
1704 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1706 uint8_t Byte = static_cast<uint8_t>(Value);
1708 for (unsigned i = 1; i < Size; ++i) {
1710 if (static_cast<uint8_t>(Value) != Byte) return -1;
1714 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1715 // Make sure all array elements are sequences of the same repeated
1717 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1718 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1719 if (Byte == -1) return -1;
1721 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1722 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1723 if (ThisByte == -1) return -1;
1724 if (Byte != ThisByte) return -1;
1729 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1730 return isRepeatedByteSequence(CDS);
1735 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1738 // See if we can aggregate this into a .fill, if so, emit it as such.
1739 int Value = isRepeatedByteSequence(CDS, AP.TM);
1742 AP.TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
1744 // Don't emit a 1-byte object as a .fill.
1746 return AP.OutStreamer.EmitFill(Bytes, Value);
1749 // If this can be emitted with .ascii/.asciz, emit it as such.
1750 if (CDS->isString())
1751 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1753 // Otherwise, emit the values in successive locations.
1754 unsigned ElementByteSize = CDS->getElementByteSize();
1755 if (isa<IntegerType>(CDS->getElementType())) {
1756 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1758 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1759 CDS->getElementAsInteger(i));
1760 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1763 } else if (ElementByteSize == 4) {
1764 // FP Constants are printed as integer constants to avoid losing
1766 assert(CDS->getElementType()->isFloatTy());
1767 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1773 F = CDS->getElementAsFloat(i);
1775 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1776 AP.OutStreamer.EmitIntValue(I, 4);
1779 assert(CDS->getElementType()->isDoubleTy());
1780 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1786 F = CDS->getElementAsDouble(i);
1788 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1789 AP.OutStreamer.EmitIntValue(I, 8);
1793 const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
1794 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1795 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1796 CDS->getNumElements();
1797 if (unsigned Padding = Size - EmittedSize)
1798 AP.OutStreamer.EmitZeros(Padding);
1802 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1803 // See if we can aggregate some values. Make sure it can be
1804 // represented as a series of bytes of the constant value.
1805 int Value = isRepeatedByteSequence(CA, AP.TM);
1809 AP.TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
1811 AP.OutStreamer.EmitFill(Bytes, Value);
1814 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1815 emitGlobalConstantImpl(CA->getOperand(i), AP);
1819 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1820 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1821 emitGlobalConstantImpl(CV->getOperand(i), AP);
1823 const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
1824 unsigned Size = DL.getTypeAllocSize(CV->getType());
1825 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1826 CV->getType()->getNumElements();
1827 if (unsigned Padding = Size - EmittedSize)
1828 AP.OutStreamer.EmitZeros(Padding);
1831 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1832 // Print the fields in successive locations. Pad to align if needed!
1833 const DataLayout *DL = AP.TM.getSubtargetImpl()->getDataLayout();
1834 unsigned Size = DL->getTypeAllocSize(CS->getType());
1835 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1836 uint64_t SizeSoFar = 0;
1837 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1838 const Constant *Field = CS->getOperand(i);
1840 // Check if padding is needed and insert one or more 0s.
1841 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1842 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1843 - Layout->getElementOffset(i)) - FieldSize;
1844 SizeSoFar += FieldSize + PadSize;
1846 // Now print the actual field value.
1847 emitGlobalConstantImpl(Field, AP);
1849 // Insert padding - this may include padding to increase the size of the
1850 // current field up to the ABI size (if the struct is not packed) as well
1851 // as padding to ensure that the next field starts at the right offset.
1852 AP.OutStreamer.EmitZeros(PadSize);
1854 assert(SizeSoFar == Layout->getSizeInBytes() &&
1855 "Layout of constant struct may be incorrect!");
1858 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1859 APInt API = CFP->getValueAPF().bitcastToAPInt();
1861 // First print a comment with what we think the original floating-point value
1862 // should have been.
1863 if (AP.isVerbose()) {
1864 SmallString<8> StrVal;
1865 CFP->getValueAPF().toString(StrVal);
1868 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1870 AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
1871 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1874 // Now iterate through the APInt chunks, emitting them in endian-correct
1875 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1877 unsigned NumBytes = API.getBitWidth() / 8;
1878 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1879 const uint64_t *p = API.getRawData();
1881 // PPC's long double has odd notions of endianness compared to how LLVM
1882 // handles it: p[0] goes first for *big* endian on PPC.
1883 if (AP.TM.getSubtargetImpl()->getDataLayout()->isBigEndian() &&
1884 !CFP->getType()->isPPC_FP128Ty()) {
1885 int Chunk = API.getNumWords() - 1;
1888 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1890 for (; Chunk >= 0; --Chunk)
1891 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1894 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1895 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1898 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1901 // Emit the tail padding for the long double.
1902 const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
1903 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1904 DL.getTypeStoreSize(CFP->getType()));
1907 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1908 const DataLayout *DL = AP.TM.getSubtargetImpl()->getDataLayout();
1909 unsigned BitWidth = CI->getBitWidth();
1911 // Copy the value as we may massage the layout for constants whose bit width
1912 // is not a multiple of 64-bits.
1913 APInt Realigned(CI->getValue());
1914 uint64_t ExtraBits = 0;
1915 unsigned ExtraBitsSize = BitWidth & 63;
1917 if (ExtraBitsSize) {
1918 // The bit width of the data is not a multiple of 64-bits.
1919 // The extra bits are expected to be at the end of the chunk of the memory.
1921 // * Nothing to be done, just record the extra bits to emit.
1923 // * Record the extra bits to emit.
1924 // * Realign the raw data to emit the chunks of 64-bits.
1925 if (DL->isBigEndian()) {
1926 // Basically the structure of the raw data is a chunk of 64-bits cells:
1927 // 0 1 BitWidth / 64
1928 // [chunk1][chunk2] ... [chunkN].
1929 // The most significant chunk is chunkN and it should be emitted first.
1930 // However, due to the alignment issue chunkN contains useless bits.
1931 // Realign the chunks so that they contain only useless information:
1932 // ExtraBits 0 1 (BitWidth / 64) - 1
1933 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1934 ExtraBits = Realigned.getRawData()[0] &
1935 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1936 Realigned = Realigned.lshr(ExtraBitsSize);
1938 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1941 // We don't expect assemblers to support integer data directives
1942 // for more than 64 bits, so we emit the data in at most 64-bit
1943 // quantities at a time.
1944 const uint64_t *RawData = Realigned.getRawData();
1945 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1946 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1947 AP.OutStreamer.EmitIntValue(Val, 8);
1950 if (ExtraBitsSize) {
1951 // Emit the extra bits after the 64-bits chunks.
1953 // Emit a directive that fills the expected size.
1954 uint64_t Size = AP.TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
1956 Size -= (BitWidth / 64) * 8;
1957 assert(Size && Size * 8 >= ExtraBitsSize &&
1958 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1959 == ExtraBits && "Directive too small for extra bits.");
1960 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1964 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1965 const DataLayout *DL = AP.TM.getSubtargetImpl()->getDataLayout();
1966 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1967 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1968 return AP.OutStreamer.EmitZeros(Size);
1970 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1977 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1978 CI->getZExtValue());
1979 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1982 emitGlobalConstantLargeInt(CI, AP);
1987 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1988 return emitGlobalConstantFP(CFP, AP);
1990 if (isa<ConstantPointerNull>(CV)) {
1991 AP.OutStreamer.EmitIntValue(0, Size);
1995 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1996 return emitGlobalConstantDataSequential(CDS, AP);
1998 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1999 return emitGlobalConstantArray(CVA, AP);
2001 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2002 return emitGlobalConstantStruct(CVS, AP);
2004 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2005 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2007 if (CE->getOpcode() == Instruction::BitCast)
2008 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2011 // If the constant expression's size is greater than 64-bits, then we have
2012 // to emit the value in chunks. Try to constant fold the value and emit it
2014 Constant *New = ConstantFoldConstantExpression(CE, DL);
2015 if (New && New != CE)
2016 return emitGlobalConstantImpl(New, AP);
2020 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2021 return emitGlobalConstantVector(V, AP);
2023 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2024 // thread the streamer with EmitValue.
2025 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
2028 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2029 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2031 TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(CV->getType());
2033 emitGlobalConstantImpl(CV, *this);
2034 else if (MAI->hasSubsectionsViaSymbols()) {
2035 // If the global has zero size, emit a single byte so that two labels don't
2036 // look like they are at the same location.
2037 OutStreamer.EmitIntValue(0, 1);
2041 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2042 // Target doesn't support this yet!
2043 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2046 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2048 OS << '+' << Offset;
2049 else if (Offset < 0)
2053 //===----------------------------------------------------------------------===//
2054 // Symbol Lowering Routines.
2055 //===----------------------------------------------------------------------===//
2057 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2058 /// temporary label with the specified stem and unique ID.
2059 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name, unsigned ID) const {
2060 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
2061 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2065 /// GetTempSymbol - Return an assembler temporary label with the specified
2067 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name) const {
2068 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
2069 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2074 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2075 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2078 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2079 return MMI->getAddrLabelSymbol(BB);
2082 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2083 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2084 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
2085 return OutContext.GetOrCreateSymbol
2086 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2087 + "_" + Twine(CPID));
2090 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2091 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2092 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2095 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2096 /// FIXME: privatize to AsmPrinter.
2097 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2098 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
2099 return OutContext.GetOrCreateSymbol
2100 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2101 Twine(UID) + "_set_" + Twine(MBBID));
2104 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2105 StringRef Suffix) const {
2106 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2110 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2112 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2113 SmallString<60> NameStr;
2114 Mang->getNameWithPrefix(NameStr, Sym);
2115 return OutContext.GetOrCreateSymbol(NameStr.str());
2120 /// PrintParentLoopComment - Print comments about parent loops of this one.
2121 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2122 unsigned FunctionNumber) {
2124 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2125 OS.indent(Loop->getLoopDepth()*2)
2126 << "Parent Loop BB" << FunctionNumber << "_"
2127 << Loop->getHeader()->getNumber()
2128 << " Depth=" << Loop->getLoopDepth() << '\n';
2132 /// PrintChildLoopComment - Print comments about child loops within
2133 /// the loop for this basic block, with nesting.
2134 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2135 unsigned FunctionNumber) {
2136 // Add child loop information
2137 for (const MachineLoop *CL : *Loop) {
2138 OS.indent(CL->getLoopDepth()*2)
2139 << "Child Loop BB" << FunctionNumber << "_"
2140 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2142 PrintChildLoopComment(OS, CL, FunctionNumber);
2146 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2147 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2148 const MachineLoopInfo *LI,
2149 const AsmPrinter &AP) {
2150 // Add loop depth information
2151 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2154 MachineBasicBlock *Header = Loop->getHeader();
2155 assert(Header && "No header for loop");
2157 // If this block is not a loop header, just print out what is the loop header
2159 if (Header != &MBB) {
2160 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2161 Twine(AP.getFunctionNumber())+"_" +
2162 Twine(Loop->getHeader()->getNumber())+
2163 " Depth="+Twine(Loop->getLoopDepth()));
2167 // Otherwise, it is a loop header. Print out information about child and
2169 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2171 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2174 OS.indent(Loop->getLoopDepth()*2-2);
2179 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2181 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2185 /// EmitBasicBlockStart - This method prints the label for the specified
2186 /// MachineBasicBlock, an alignment (if present) and a comment describing
2187 /// it if appropriate.
2188 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2189 // Emit an alignment directive for this block, if needed.
2190 if (unsigned Align = MBB.getAlignment())
2191 EmitAlignment(Align);
2193 // If the block has its address taken, emit any labels that were used to
2194 // reference the block. It is possible that there is more than one label
2195 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2196 // the references were generated.
2197 if (MBB.hasAddressTaken()) {
2198 const BasicBlock *BB = MBB.getBasicBlock();
2200 OutStreamer.AddComment("Block address taken");
2202 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2203 for (auto *Sym : Symbols)
2204 OutStreamer.EmitLabel(Sym);
2207 // Print some verbose block comments.
2209 if (const BasicBlock *BB = MBB.getBasicBlock())
2211 OutStreamer.AddComment("%" + BB->getName());
2212 emitBasicBlockLoopComments(MBB, LI, *this);
2215 // Print the main label for the block.
2216 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2218 // NOTE: Want this comment at start of line, don't emit with AddComment.
2219 OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2222 OutStreamer.EmitLabel(MBB.getSymbol());
2226 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2227 bool IsDefinition) const {
2228 MCSymbolAttr Attr = MCSA_Invalid;
2230 switch (Visibility) {
2232 case GlobalValue::HiddenVisibility:
2234 Attr = MAI->getHiddenVisibilityAttr();
2236 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2238 case GlobalValue::ProtectedVisibility:
2239 Attr = MAI->getProtectedVisibilityAttr();
2243 if (Attr != MCSA_Invalid)
2244 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2247 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2248 /// exactly one predecessor and the control transfer mechanism between
2249 /// the predecessor and this block is a fall-through.
2251 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2252 // If this is a landing pad, it isn't a fall through. If it has no preds,
2253 // then nothing falls through to it.
2254 if (MBB->isLandingPad() || MBB->pred_empty())
2257 // If there isn't exactly one predecessor, it can't be a fall through.
2258 if (MBB->pred_size() > 1)
2261 // The predecessor has to be immediately before this block.
2262 MachineBasicBlock *Pred = *MBB->pred_begin();
2263 if (!Pred->isLayoutSuccessor(MBB))
2266 // If the block is completely empty, then it definitely does fall through.
2270 // Check the terminators in the previous blocks
2271 for (const auto &MI : Pred->terminators()) {
2272 // If it is not a simple branch, we are in a table somewhere.
2273 if (!MI.isBranch() || MI.isIndirectBranch())
2276 // If we are the operands of one of the branches, this is not a fall
2277 // through. Note that targets with delay slots will usually bundle
2278 // terminators with the delay slot instruction.
2279 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2282 if (OP->isMBB() && OP->getMBB() == MBB)
2292 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2293 if (!S.usesMetadata())
2296 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2297 gcp_map_type::iterator GCPI = GCMap.find(&S);
2298 if (GCPI != GCMap.end())
2299 return GCPI->second.get();
2301 const char *Name = S.getName().c_str();
2303 for (GCMetadataPrinterRegistry::iterator
2304 I = GCMetadataPrinterRegistry::begin(),
2305 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2306 if (strcmp(Name, I->getName()) == 0) {
2307 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2309 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2310 return IterBool.first->second.get();
2313 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2316 /// Pin vtable to this file.
2317 AsmPrinterHandler::~AsmPrinterHandler() {}