1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #ifndef ANDROID_TARGET_BUILD
17 # include "DwarfDebug.h"
18 # include "DwarfException.h"
19 #endif // ANDROID_TARGET_BUILD
20 #include "llvm/Module.h"
21 #include "llvm/CodeGen/GCMetadataPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Assembly/Writer.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/Timer.h"
54 static const char *DWARFGroupName = "DWARF Emission";
55 static const char *DbgTimerName = "DWARF Debug Writer";
56 static const char *EHTimerName = "DWARF Exception Writer";
58 STATISTIC(EmittedInsts, "Number of machine instrs printed");
60 char AsmPrinter::ID = 0;
62 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
63 static gcp_map_type &getGCMap(void *&P) {
65 P = new gcp_map_type();
66 return *(gcp_map_type*)P;
70 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
71 /// value in log2 form. This rounds up to the preferred alignment if possible
73 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
74 unsigned InBits = 0) {
76 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77 NumBits = TD.getPreferredAlignmentLog(GVar);
79 // If InBits is specified, round it to it.
83 // If the GV has a specified alignment, take it into account.
84 if (GV->getAlignment() == 0)
87 unsigned GVAlign = Log2_32(GV->getAlignment());
89 // If the GVAlign is larger than NumBits, or if we are required to obey
90 // NumBits because the GV has an assigned section, obey it.
91 if (GVAlign > NumBits || GV->hasSection())
99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
100 : MachineFunctionPass(ID),
101 TM(tm), MAI(tm.getMCAsmInfo()),
102 OutContext(Streamer.getContext()),
103 OutStreamer(Streamer),
104 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105 DD = 0; DE = 0; MMI = 0; LI = 0;
106 GCMetadataPrinters = 0;
107 VerboseAsm = Streamer.isVerboseAsm();
110 AsmPrinter::~AsmPrinter() {
111 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
113 if (GCMetadataPrinters != 0) {
114 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
116 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
119 GCMetadataPrinters = 0;
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.getTargetLowering()->getObjFileLowering();
136 /// getTargetData - Return information about data layout.
137 const TargetData &AsmPrinter::getTargetData() const {
138 return *TM.getTargetData();
141 /// getCurrentSection() - Return the current section we are emitting to.
142 const MCSection *AsmPrinter::getCurrentSection() const {
143 return OutStreamer.getCurrentSection();
148 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.setPreservesAll();
150 MachineFunctionPass::getAnalysisUsage(AU);
151 AU.addRequired<MachineModuleInfo>();
152 AU.addRequired<GCModuleInfo>();
154 AU.addRequired<MachineLoopInfo>();
157 bool AsmPrinter::doInitialization(Module &M) {
158 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
159 MMI->AnalyzeModule(M);
161 // Initialize TargetLoweringObjectFile.
162 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
163 .Initialize(OutContext, TM);
165 Mang = new Mangler(OutContext, *TM.getTargetData());
167 // Allow the target to emit any magic that it wants at the start of the file.
168 EmitStartOfAsmFile(M);
170 // Very minimal debug info. It is ignored if we emit actual debug info. If we
171 // don't, this at least helps the user find where a global came from.
172 if (MAI->hasSingleParameterDotFile()) {
174 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
177 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
178 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
179 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
180 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
181 MP->beginAssembly(*this);
183 // Emit module-level inline asm if it exists.
184 if (!M.getModuleInlineAsm().empty()) {
185 OutStreamer.AddComment("Start of file scope inline assembly");
186 OutStreamer.AddBlankLine();
187 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
188 OutStreamer.AddComment("End of file scope inline assembly");
189 OutStreamer.AddBlankLine();
192 #ifndef ANDROID_TARGET_BUILD
193 if (MAI->doesSupportDebugInformation())
194 DD = new DwarfDebug(this, &M);
196 switch (MAI->getExceptionHandlingType()) {
197 case ExceptionHandling::None:
199 case ExceptionHandling::SjLj:
200 case ExceptionHandling::DwarfCFI:
201 DE = new DwarfCFIException(this);
203 case ExceptionHandling::ARM:
204 DE = new ARMException(this);
206 case ExceptionHandling::Win64:
207 DE = new Win64Exception(this);
212 #endif // ANDROID_TARGET_BUILD
214 llvm_unreachable("Unknown exception type.");
217 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
218 switch ((GlobalValue::LinkageTypes)Linkage) {
219 case GlobalValue::CommonLinkage:
220 case GlobalValue::LinkOnceAnyLinkage:
221 case GlobalValue::LinkOnceODRLinkage:
222 case GlobalValue::WeakAnyLinkage:
223 case GlobalValue::WeakODRLinkage:
224 case GlobalValue::LinkerPrivateWeakLinkage:
225 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
226 if (MAI->getWeakDefDirective() != 0) {
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
230 if ((GlobalValue::LinkageTypes)Linkage !=
231 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
232 // .weak_definition _foo
233 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
235 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
236 } else if (MAI->getLinkOnceDirective() != 0) {
238 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
239 //NOTE: linkonce is handled by the section the symbol was assigned to.
242 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
245 case GlobalValue::DLLExportLinkage:
246 case GlobalValue::AppendingLinkage:
247 // FIXME: appending linkage variables should go into a section of
248 // their name or something. For now, just emit them as external.
249 case GlobalValue::ExternalLinkage:
250 // If external or appending, declare as a global symbol.
252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
254 case GlobalValue::PrivateLinkage:
255 case GlobalValue::InternalLinkage:
256 case GlobalValue::LinkerPrivateLinkage:
259 llvm_unreachable("Unknown linkage type!");
264 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
265 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
266 if (GV->hasInitializer()) {
267 // Check to see if this is a special global used by LLVM, if so, emit it.
268 if (EmitSpecialLLVMGlobal(GV))
272 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
273 /*PrintType=*/false, GV->getParent());
274 OutStreamer.GetCommentOS() << '\n';
278 MCSymbol *GVSym = Mang->getSymbol(GV);
279 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
281 if (!GV->hasInitializer()) // External globals require no extra code.
284 if (MAI->hasDotTypeDotSizeDirective())
285 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
287 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
289 const TargetData *TD = TM.getTargetData();
290 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
292 // If the alignment is specified, we *must* obey it. Overaligning a global
293 // with a specified alignment is a prompt way to break globals emitted to
294 // sections and expected to be contiguous (e.g. ObjC metadata).
295 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
297 // Handle common and BSS local symbols (.lcomm).
298 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
299 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
301 // Handle common symbols.
302 if (GVKind.isCommon()) {
303 unsigned Align = 1 << AlignLog;
304 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
308 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
312 // Handle local BSS symbols.
313 if (MAI->hasMachoZeroFillDirective()) {
314 const MCSection *TheSection =
315 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
316 // .zerofill __DATA, __bss, _foo, 400, 5
317 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
321 if (MAI->hasLCOMMDirective()) {
323 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
327 unsigned Align = 1 << AlignLog;
328 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
332 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
334 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
338 const MCSection *TheSection =
339 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
341 // Handle the zerofill directive on darwin, which is a special form of BSS
343 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
344 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
347 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
348 // .zerofill __DATA, __common, _foo, 400, 5
349 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
353 // Handle thread local data for mach-o which requires us to output an
354 // additional structure of data and mangle the original symbol so that we
355 // can reference it later.
357 // TODO: This should become an "emit thread local global" method on TLOF.
358 // All of this macho specific stuff should be sunk down into TLOFMachO and
359 // stuff like "TLSExtraDataSection" should no longer be part of the parent
360 // TLOF class. This will also make it more obvious that stuff like
361 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
363 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
364 // Emit the .tbss symbol
366 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
368 if (GVKind.isThreadBSS())
369 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
370 else if (GVKind.isThreadData()) {
371 OutStreamer.SwitchSection(TheSection);
373 EmitAlignment(AlignLog, GV);
374 OutStreamer.EmitLabel(MangSym);
376 EmitGlobalConstant(GV->getInitializer());
379 OutStreamer.AddBlankLine();
381 // Emit the variable struct for the runtime.
382 const MCSection *TLVSect
383 = getObjFileLowering().getTLSExtraDataSection();
385 OutStreamer.SwitchSection(TLVSect);
386 // Emit the linkage here.
387 EmitLinkage(GV->getLinkage(), GVSym);
388 OutStreamer.EmitLabel(GVSym);
390 // Three pointers in size:
391 // - __tlv_bootstrap - used to make sure support exists
392 // - spare pointer, used when mapped by the runtime
393 // - pointer to mangled symbol above with initializer
394 unsigned PtrSize = TD->getPointerSizeInBits()/8;
395 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
397 OutStreamer.EmitIntValue(0, PtrSize, 0);
398 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
400 OutStreamer.AddBlankLine();
404 OutStreamer.SwitchSection(TheSection);
406 EmitLinkage(GV->getLinkage(), GVSym);
407 EmitAlignment(AlignLog, GV);
409 OutStreamer.EmitLabel(GVSym);
411 EmitGlobalConstant(GV->getInitializer());
413 if (MAI->hasDotTypeDotSizeDirective())
415 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
417 OutStreamer.AddBlankLine();
420 /// EmitFunctionHeader - This method emits the header for the current
422 void AsmPrinter::EmitFunctionHeader() {
423 // Print out constants referenced by the function
426 // Print the 'header' of function.
427 const Function *F = MF->getFunction();
429 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
430 EmitVisibility(CurrentFnSym, F->getVisibility());
432 EmitLinkage(F->getLinkage(), CurrentFnSym);
433 EmitAlignment(MF->getAlignment(), F);
435 if (MAI->hasDotTypeDotSizeDirective())
436 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
439 WriteAsOperand(OutStreamer.GetCommentOS(), F,
440 /*PrintType=*/false, F->getParent());
441 OutStreamer.GetCommentOS() << '\n';
444 // Emit the CurrentFnSym. This is a virtual function to allow targets to
445 // do their wild and crazy things as required.
446 EmitFunctionEntryLabel();
448 // If the function had address-taken blocks that got deleted, then we have
449 // references to the dangling symbols. Emit them at the start of the function
450 // so that we don't get references to undefined symbols.
451 std::vector<MCSymbol*> DeadBlockSyms;
452 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
453 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
454 OutStreamer.AddComment("Address taken block that was later removed");
455 OutStreamer.EmitLabel(DeadBlockSyms[i]);
458 // Add some workaround for linkonce linkage on Cygwin\MinGW.
459 if (MAI->getLinkOnceDirective() != 0 &&
460 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
461 // FIXME: What is this?
463 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
464 CurrentFnSym->getName());
465 OutStreamer.EmitLabel(FakeStub);
468 // Emit pre-function debug and/or EH information.
469 #ifndef ANDROID_TARGET_BUILD
471 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
472 DE->BeginFunction(MF);
475 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
476 DD->beginFunction(MF);
478 #endif // ANDROID_TARGET_BUILD
481 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
482 /// function. This can be overridden by targets as required to do custom stuff.
483 void AsmPrinter::EmitFunctionEntryLabel() {
484 // The function label could have already been emitted if two symbols end up
485 // conflicting due to asm renaming. Detect this and emit an error.
486 if (CurrentFnSym->isUndefined())
487 return OutStreamer.EmitLabel(CurrentFnSym);
489 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
490 "' label emitted multiple times to assembly file");
494 /// EmitComments - Pretty-print comments for instructions.
495 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
496 const MachineFunction *MF = MI.getParent()->getParent();
497 const TargetMachine &TM = MF->getTarget();
499 // Check for spills and reloads
502 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
504 // We assume a single instruction only has a spill or reload, not
506 const MachineMemOperand *MMO;
507 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
508 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
509 MMO = *MI.memoperands_begin();
510 CommentOS << MMO->getSize() << "-byte Reload\n";
512 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
513 if (FrameInfo->isSpillSlotObjectIndex(FI))
514 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
515 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
516 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
517 MMO = *MI.memoperands_begin();
518 CommentOS << MMO->getSize() << "-byte Spill\n";
520 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
521 if (FrameInfo->isSpillSlotObjectIndex(FI))
522 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
525 // Check for spill-induced copies
526 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
527 CommentOS << " Reload Reuse\n";
530 /// EmitImplicitDef - This method emits the specified machine instruction
531 /// that is an implicit def.
532 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
533 unsigned RegNo = MI->getOperand(0).getReg();
534 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
535 AP.TM.getRegisterInfo()->getName(RegNo));
536 AP.OutStreamer.AddBlankLine();
539 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
540 std::string Str = "kill:";
541 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
542 const MachineOperand &Op = MI->getOperand(i);
543 assert(Op.isReg() && "KILL instruction must have only register operands");
545 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
546 Str += (Op.isDef() ? "<def>" : "<kill>");
548 AP.OutStreamer.AddComment(Str);
549 AP.OutStreamer.AddBlankLine();
552 /// EmitDebugValueComment - This method handles the target-independent form
553 /// of DBG_VALUE, returning true if it was able to do so. A false return
554 /// means the target will need to handle MI in EmitInstruction.
555 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
556 // This code handles only the 3-operand target-independent form.
557 if (MI->getNumOperands() != 3)
560 SmallString<128> Str;
561 raw_svector_ostream OS(Str);
562 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
564 // cast away const; DIetc do not take const operands for some reason.
565 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
566 if (V.getContext().isSubprogram())
567 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
568 OS << V.getName() << " <- ";
570 // Register or immediate value. Register 0 means undef.
571 if (MI->getOperand(0).isFPImm()) {
572 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
573 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
574 OS << (double)APF.convertToFloat();
575 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
576 OS << APF.convertToDouble();
578 // There is no good way to print long double. Convert a copy to
579 // double. Ah well, it's only a comment.
581 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
583 OS << "(long double) " << APF.convertToDouble();
585 } else if (MI->getOperand(0).isImm()) {
586 OS << MI->getOperand(0).getImm();
587 } else if (MI->getOperand(0).isCImm()) {
588 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
590 assert(MI->getOperand(0).isReg() && "Unknown operand type");
591 if (MI->getOperand(0).getReg() == 0) {
592 // Suppress offset, it is not meaningful here.
594 // NOTE: Want this comment at start of line, don't emit with AddComment.
595 AP.OutStreamer.EmitRawText(OS.str());
598 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
601 OS << '+' << MI->getOperand(1).getImm();
602 // NOTE: Want this comment at start of line, don't emit with AddComment.
603 AP.OutStreamer.EmitRawText(OS.str());
607 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
608 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
609 MF->getFunction()->needsUnwindTableEntry())
612 if (MMI->hasDebugInfo())
618 bool AsmPrinter::needsSEHMoves() {
619 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
620 MF->getFunction()->needsUnwindTableEntry();
623 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
624 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
626 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
629 if (needsCFIMoves() == CFI_M_None)
632 if (MMI->getCompactUnwindEncoding() != 0)
633 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
635 MachineModuleInfo &MMI = MF->getMMI();
636 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
637 bool FoundOne = false;
639 for (std::vector<MachineMove>::iterator I = Moves.begin(),
640 E = Moves.end(); I != E; ++I) {
641 if (I->getLabel() == Label) {
642 EmitCFIFrameMove(*I);
649 /// EmitFunctionBody - This method emits the body and trailer for a
651 void AsmPrinter::EmitFunctionBody() {
652 // Emit target-specific gunk before the function body.
653 EmitFunctionBodyStart();
655 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
657 // Print out code for the function.
658 bool HasAnyRealCode = false;
659 const MachineInstr *LastMI = 0;
660 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
662 // Print a label for the basic block.
663 EmitBasicBlockStart(I);
664 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
668 // Print the assembly for the instruction.
669 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
670 !II->isDebugValue()) {
671 HasAnyRealCode = true;
675 #ifndef ANDROID_TARGET_BUILD
676 if (ShouldPrintDebugScopes) {
677 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
678 DD->beginInstruction(II);
680 #endif // ANDROID_TARGET_BUILD
683 EmitComments(*II, OutStreamer.GetCommentOS());
685 switch (II->getOpcode()) {
686 case TargetOpcode::PROLOG_LABEL:
687 emitPrologLabel(*II);
690 case TargetOpcode::EH_LABEL:
691 case TargetOpcode::GC_LABEL:
692 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
694 case TargetOpcode::INLINEASM:
697 case TargetOpcode::DBG_VALUE:
699 if (!EmitDebugValueComment(II, *this))
703 case TargetOpcode::IMPLICIT_DEF:
704 if (isVerbose()) EmitImplicitDef(II, *this);
706 case TargetOpcode::KILL:
707 if (isVerbose()) EmitKill(II, *this);
710 if (!TM.hasMCUseLoc())
711 MCLineEntry::Make(&OutStreamer, getCurrentSection());
717 #ifndef ANDROID_TARGET_BUILD
718 if (ShouldPrintDebugScopes) {
719 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
720 DD->endInstruction(II);
722 #endif // ANDROID_TARGET_BUILD
726 // If the last instruction was a prolog label, then we have a situation where
727 // we emitted a prolog but no function body. This results in the ending prolog
728 // label equaling the end of function label and an invalid "row" in the
729 // FDE. We need to emit a noop in this situation so that the FDE's rows are
731 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
733 // If the function is empty and the object file uses .subsections_via_symbols,
734 // then we need to emit *something* to the function body to prevent the
735 // labels from collapsing together. Just emit a noop.
736 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
738 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
739 if (Noop.getOpcode()) {
740 OutStreamer.AddComment("avoids zero-length function");
741 OutStreamer.EmitInstruction(Noop);
742 } else // Target not mc-ized yet.
743 OutStreamer.EmitRawText(StringRef("\tnop\n"));
746 // Emit target-specific gunk after the function body.
747 EmitFunctionBodyEnd();
749 // If the target wants a .size directive for the size of the function, emit
751 if (MAI->hasDotTypeDotSizeDirective()) {
752 // Create a symbol for the end of function, so we can get the size as
753 // difference between the function label and the temp label.
754 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
755 OutStreamer.EmitLabel(FnEndLabel);
757 const MCExpr *SizeExp =
758 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
759 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
761 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
764 // Emit post-function debug information.
765 #ifndef ANDROID_TARGET_BUILD
767 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
771 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
774 #endif // ANDROID_TARGET_BUILD
777 // Print out jump tables referenced by the function.
780 OutStreamer.AddBlankLine();
783 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
785 MachineLocation AsmPrinter::
786 getDebugValueLocation(const MachineInstr *MI) const {
787 // Target specific DBG_VALUE instructions are handled by each target.
788 return MachineLocation();
791 /// EmitDwarfRegOp - Emit dwarf register operation.
792 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
793 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
794 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
796 for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
797 *SR && Reg < 0; ++SR) {
798 Reg = TRI->getDwarfRegNum(*SR, false);
799 // FIXME: Get the bit range this register uses of the superregister
800 // so that we can produce a DW_OP_bit_piece
803 // FIXME: Handle cases like a super register being encoded as
804 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
806 // FIXME: We have no reasonable way of handling errors in here. The
807 // caller might be in the middle of an dwarf expression. We should
808 // probably assert that Reg >= 0 once debug info generation is more mature.
810 if (int Offset = MLoc.getOffset()) {
812 OutStreamer.AddComment(
813 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
814 EmitInt8(dwarf::DW_OP_breg0 + Reg);
816 OutStreamer.AddComment("DW_OP_bregx");
817 EmitInt8(dwarf::DW_OP_bregx);
818 OutStreamer.AddComment(Twine(Reg));
824 OutStreamer.AddComment(
825 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
826 EmitInt8(dwarf::DW_OP_reg0 + Reg);
828 OutStreamer.AddComment("DW_OP_regx");
829 EmitInt8(dwarf::DW_OP_regx);
830 OutStreamer.AddComment(Twine(Reg));
835 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
838 bool AsmPrinter::doFinalization(Module &M) {
839 // Emit global variables.
840 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
842 EmitGlobalVariable(I);
844 // Emit visibility info for declarations
845 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
846 const Function &F = *I;
847 if (!F.isDeclaration())
849 GlobalValue::VisibilityTypes V = F.getVisibility();
850 if (V == GlobalValue::DefaultVisibility)
853 MCSymbol *Name = Mang->getSymbol(&F);
854 EmitVisibility(Name, V, false);
857 // Finalize debug and EH information.
858 #ifndef ANDROID_TARGET_BUILD
861 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
868 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
873 #endif // ANDROID_TARGET_BUILD
875 // If the target wants to know about weak references, print them all.
876 if (MAI->getWeakRefDirective()) {
877 // FIXME: This is not lazy, it would be nice to only print weak references
878 // to stuff that is actually used. Note that doing so would require targets
879 // to notice uses in operands (due to constant exprs etc). This should
880 // happen with the MC stuff eventually.
882 // Print out module-level global variables here.
883 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
885 if (!I->hasExternalWeakLinkage()) continue;
886 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
889 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
890 if (!I->hasExternalWeakLinkage()) continue;
891 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
895 if (MAI->hasSetDirective()) {
896 OutStreamer.AddBlankLine();
897 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
899 MCSymbol *Name = Mang->getSymbol(I);
901 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
902 MCSymbol *Target = Mang->getSymbol(GV);
904 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
905 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
906 else if (I->hasWeakLinkage())
907 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
909 assert(I->hasLocalLinkage() && "Invalid alias linkage");
911 EmitVisibility(Name, I->getVisibility());
913 // Emit the directives as assignments aka .set:
914 OutStreamer.EmitAssignment(Name,
915 MCSymbolRefExpr::Create(Target, OutContext));
919 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
920 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
921 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
922 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
923 MP->finishAssembly(*this);
925 // If we don't have any trampolines, then we don't require stack memory
926 // to be executable. Some targets have a directive to declare this.
927 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
928 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
929 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
930 OutStreamer.SwitchSection(S);
932 // Allow the target to emit any magic that it wants at the end of the file,
933 // after everything else has gone out.
936 delete Mang; Mang = 0;
939 OutStreamer.Finish();
943 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
945 // Get the function symbol.
946 CurrentFnSym = Mang->getSymbol(MF.getFunction());
949 LI = &getAnalysis<MachineLoopInfo>();
953 // SectionCPs - Keep track the alignment, constpool entries per Section.
957 SmallVector<unsigned, 4> CPEs;
958 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
962 /// EmitConstantPool - Print to the current output stream assembly
963 /// representations of the constants in the constant pool MCP. This is
964 /// used to print out constants which have been "spilled to memory" by
965 /// the code generator.
967 void AsmPrinter::EmitConstantPool() {
968 const MachineConstantPool *MCP = MF->getConstantPool();
969 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
970 if (CP.empty()) return;
972 // Calculate sections for constant pool entries. We collect entries to go into
973 // the same section together to reduce amount of section switch statements.
974 SmallVector<SectionCPs, 4> CPSections;
975 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
976 const MachineConstantPoolEntry &CPE = CP[i];
977 unsigned Align = CPE.getAlignment();
980 switch (CPE.getRelocationInfo()) {
981 default: llvm_unreachable("Unknown section kind");
982 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
984 Kind = SectionKind::getReadOnlyWithRelLocal();
987 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
988 case 4: Kind = SectionKind::getMergeableConst4(); break;
989 case 8: Kind = SectionKind::getMergeableConst8(); break;
990 case 16: Kind = SectionKind::getMergeableConst16();break;
991 default: Kind = SectionKind::getMergeableConst(); break;
995 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
997 // The number of sections are small, just do a linear search from the
998 // last section to the first.
1000 unsigned SecIdx = CPSections.size();
1001 while (SecIdx != 0) {
1002 if (CPSections[--SecIdx].S == S) {
1008 SecIdx = CPSections.size();
1009 CPSections.push_back(SectionCPs(S, Align));
1012 if (Align > CPSections[SecIdx].Alignment)
1013 CPSections[SecIdx].Alignment = Align;
1014 CPSections[SecIdx].CPEs.push_back(i);
1017 // Now print stuff into the calculated sections.
1018 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1019 OutStreamer.SwitchSection(CPSections[i].S);
1020 EmitAlignment(Log2_32(CPSections[i].Alignment));
1022 unsigned Offset = 0;
1023 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1024 unsigned CPI = CPSections[i].CPEs[j];
1025 MachineConstantPoolEntry CPE = CP[CPI];
1027 // Emit inter-object padding for alignment.
1028 unsigned AlignMask = CPE.getAlignment() - 1;
1029 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1030 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1032 Type *Ty = CPE.getType();
1033 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
1034 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1036 if (CPE.isMachineConstantPoolEntry())
1037 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1039 EmitGlobalConstant(CPE.Val.ConstVal);
1044 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1045 /// by the current function to the current output stream.
1047 void AsmPrinter::EmitJumpTableInfo() {
1048 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1049 if (MJTI == 0) return;
1050 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1051 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1052 if (JT.empty()) return;
1054 // Pick the directive to use to print the jump table entries, and switch to
1055 // the appropriate section.
1056 const Function *F = MF->getFunction();
1057 bool JTInDiffSection = false;
1058 if (// In PIC mode, we need to emit the jump table to the same section as the
1059 // function body itself, otherwise the label differences won't make sense.
1060 // FIXME: Need a better predicate for this: what about custom entries?
1061 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1062 // We should also do if the section name is NULL or function is declared
1063 // in discardable section
1064 // FIXME: this isn't the right predicate, should be based on the MCSection
1065 // for the function.
1066 F->isWeakForLinker()) {
1067 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1069 // Otherwise, drop it in the readonly section.
1070 const MCSection *ReadOnlySection =
1071 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1072 OutStreamer.SwitchSection(ReadOnlySection);
1073 JTInDiffSection = true;
1076 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1078 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1079 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1081 // If this jump table was deleted, ignore it.
1082 if (JTBBs.empty()) continue;
1084 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1085 // .set directive for each unique entry. This reduces the number of
1086 // relocations the assembler will generate for the jump table.
1087 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1088 MAI->hasSetDirective()) {
1089 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1090 const TargetLowering *TLI = TM.getTargetLowering();
1091 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1092 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1093 const MachineBasicBlock *MBB = JTBBs[ii];
1094 if (!EmittedSets.insert(MBB)) continue;
1096 // .set LJTSet, LBB32-base
1098 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1099 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1100 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1104 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1105 // before each jump table. The first label is never referenced, but tells
1106 // the assembler and linker the extents of the jump table object. The
1107 // second label is actually referenced by the code.
1108 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1109 // FIXME: This doesn't have to have any specific name, just any randomly
1110 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1111 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1113 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1115 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1116 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1120 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1122 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1123 const MachineBasicBlock *MBB,
1124 unsigned UID) const {
1125 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1126 const MCExpr *Value = 0;
1127 switch (MJTI->getEntryKind()) {
1128 case MachineJumpTableInfo::EK_Inline:
1129 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1130 case MachineJumpTableInfo::EK_Custom32:
1131 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1134 case MachineJumpTableInfo::EK_BlockAddress:
1135 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1137 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1139 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1140 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1141 // with a relocation as gp-relative, e.g.:
1143 MCSymbol *MBBSym = MBB->getSymbol();
1144 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1148 case MachineJumpTableInfo::EK_LabelDifference32: {
1149 // EK_LabelDifference32 - Each entry is the address of the block minus
1150 // the address of the jump table. This is used for PIC jump tables where
1151 // gprel32 is not supported. e.g.:
1152 // .word LBB123 - LJTI1_2
1153 // If the .set directive is supported, this is emitted as:
1154 // .set L4_5_set_123, LBB123 - LJTI1_2
1155 // .word L4_5_set_123
1157 // If we have emitted set directives for the jump table entries, print
1158 // them rather than the entries themselves. If we're emitting PIC, then
1159 // emit the table entries as differences between two text section labels.
1160 if (MAI->hasSetDirective()) {
1161 // If we used .set, reference the .set's symbol.
1162 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1166 // Otherwise, use the difference as the jump table entry.
1167 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1168 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1169 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1174 assert(Value && "Unknown entry kind!");
1176 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1177 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1181 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1182 /// special global used by LLVM. If so, emit it and return true, otherwise
1183 /// do nothing and return false.
1184 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1185 if (GV->getName() == "llvm.used") {
1186 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1187 EmitLLVMUsedList(GV->getInitializer());
1191 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1192 if (GV->getSection() == "llvm.metadata" ||
1193 GV->hasAvailableExternallyLinkage())
1196 if (!GV->hasAppendingLinkage()) return false;
1198 assert(GV->hasInitializer() && "Not a special LLVM global!");
1200 const TargetData *TD = TM.getTargetData();
1201 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1202 if (GV->getName() == "llvm.global_ctors") {
1203 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1204 EmitAlignment(Align);
1205 EmitXXStructorList(GV->getInitializer());
1207 if (TM.getRelocationModel() == Reloc::Static &&
1208 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1209 StringRef Sym(".constructors_used");
1210 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1216 if (GV->getName() == "llvm.global_dtors") {
1217 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1218 EmitAlignment(Align);
1219 EmitXXStructorList(GV->getInitializer());
1221 if (TM.getRelocationModel() == Reloc::Static &&
1222 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1223 StringRef Sym(".destructors_used");
1224 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1233 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1234 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1235 /// is true, as being used with this directive.
1236 void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
1237 // Should be an array of 'i8*'.
1238 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1239 if (InitList == 0) return;
1241 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1242 const GlobalValue *GV =
1243 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1244 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1245 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1249 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1250 /// function pointers, ignoring the init priority.
1251 void AsmPrinter::EmitXXStructorList(const Constant *List) {
1252 // Should be an array of '{ int, void ()* }' structs. The first value is the
1253 // init priority, which we ignore.
1254 if (!isa<ConstantArray>(List)) return;
1255 const ConstantArray *InitList = cast<ConstantArray>(List);
1256 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1257 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1258 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1260 if (CS->getOperand(1)->isNullValue())
1261 return; // Found a null terminator, exit printing.
1262 // Emit the function pointer.
1263 EmitGlobalConstant(CS->getOperand(1));
1267 //===--------------------------------------------------------------------===//
1268 // Emission and print routines
1271 /// EmitInt8 - Emit a byte directive and value.
1273 void AsmPrinter::EmitInt8(int Value) const {
1274 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1277 /// EmitInt16 - Emit a short directive and value.
1279 void AsmPrinter::EmitInt16(int Value) const {
1280 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1283 /// EmitInt32 - Emit a long directive and value.
1285 void AsmPrinter::EmitInt32(int Value) const {
1286 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1289 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1290 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1291 /// labels. This implicitly uses .set if it is available.
1292 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1293 unsigned Size) const {
1294 // Get the Hi-Lo expression.
1295 const MCExpr *Diff =
1296 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1297 MCSymbolRefExpr::Create(Lo, OutContext),
1300 if (!MAI->hasSetDirective()) {
1301 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1305 // Otherwise, emit with .set (aka assignment).
1306 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1307 OutStreamer.EmitAssignment(SetLabel, Diff);
1308 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1311 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1312 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1313 /// specify the labels. This implicitly uses .set if it is available.
1314 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1315 const MCSymbol *Lo, unsigned Size)
1318 // Emit Hi+Offset - Lo
1319 // Get the Hi+Offset expression.
1320 const MCExpr *Plus =
1321 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1322 MCConstantExpr::Create(Offset, OutContext),
1325 // Get the Hi+Offset-Lo expression.
1326 const MCExpr *Diff =
1327 MCBinaryExpr::CreateSub(Plus,
1328 MCSymbolRefExpr::Create(Lo, OutContext),
1331 if (!MAI->hasSetDirective())
1332 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1334 // Otherwise, emit with .set (aka assignment).
1335 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1336 OutStreamer.EmitAssignment(SetLabel, Diff);
1337 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1341 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1342 /// where the size in bytes of the directive is specified by Size and Label
1343 /// specifies the label. This implicitly uses .set if it is available.
1344 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1348 // Emit Label+Offset
1349 const MCExpr *Plus =
1350 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1351 MCConstantExpr::Create(Offset, OutContext),
1354 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1358 //===----------------------------------------------------------------------===//
1360 // EmitAlignment - Emit an alignment directive to the specified power of
1361 // two boundary. For example, if you pass in 3 here, you will get an 8
1362 // byte alignment. If a global value is specified, and if that global has
1363 // an explicit alignment requested, it will override the alignment request
1364 // if required for correctness.
1366 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1367 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1369 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1371 if (getCurrentSection()->getKind().isText())
1372 OutStreamer.EmitCodeAlignment(1 << NumBits);
1374 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1377 //===----------------------------------------------------------------------===//
1378 // Constant emission.
1379 //===----------------------------------------------------------------------===//
1381 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1383 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1384 MCContext &Ctx = AP.OutContext;
1386 if (CV->isNullValue() || isa<UndefValue>(CV))
1387 return MCConstantExpr::Create(0, Ctx);
1389 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1390 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1392 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1393 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1395 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1396 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1398 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1400 llvm_unreachable("Unknown constant value to lower!");
1401 return MCConstantExpr::Create(0, Ctx);
1404 switch (CE->getOpcode()) {
1406 // If the code isn't optimized, there may be outstanding folding
1407 // opportunities. Attempt to fold the expression using TargetData as a
1408 // last resort before giving up.
1410 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1412 return LowerConstant(C, AP);
1414 // Otherwise report the problem to the user.
1417 raw_string_ostream OS(S);
1418 OS << "Unsupported expression in static initializer: ";
1419 WriteAsOperand(OS, CE, /*PrintType=*/false,
1420 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1421 report_fatal_error(OS.str());
1423 return MCConstantExpr::Create(0, Ctx);
1424 case Instruction::GetElementPtr: {
1425 const TargetData &TD = *AP.TM.getTargetData();
1426 // Generate a symbolic expression for the byte address
1427 const Constant *PtrVal = CE->getOperand(0);
1428 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1429 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
1431 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1435 // Truncate/sext the offset to the pointer size.
1436 if (TD.getPointerSizeInBits() != 64) {
1437 int SExtAmount = 64-TD.getPointerSizeInBits();
1438 Offset = (Offset << SExtAmount) >> SExtAmount;
1441 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1445 case Instruction::Trunc:
1446 // We emit the value and depend on the assembler to truncate the generated
1447 // expression properly. This is important for differences between
1448 // blockaddress labels. Since the two labels are in the same function, it
1449 // is reasonable to treat their delta as a 32-bit value.
1451 case Instruction::BitCast:
1452 return LowerConstant(CE->getOperand(0), AP);
1454 case Instruction::IntToPtr: {
1455 const TargetData &TD = *AP.TM.getTargetData();
1456 // Handle casts to pointers by changing them into casts to the appropriate
1457 // integer type. This promotes constant folding and simplifies this code.
1458 Constant *Op = CE->getOperand(0);
1459 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1461 return LowerConstant(Op, AP);
1464 case Instruction::PtrToInt: {
1465 const TargetData &TD = *AP.TM.getTargetData();
1466 // Support only foldable casts to/from pointers that can be eliminated by
1467 // changing the pointer to the appropriately sized integer type.
1468 Constant *Op = CE->getOperand(0);
1469 Type *Ty = CE->getType();
1471 const MCExpr *OpExpr = LowerConstant(Op, AP);
1473 // We can emit the pointer value into this slot if the slot is an
1474 // integer slot equal to the size of the pointer.
1475 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1478 // Otherwise the pointer is smaller than the resultant integer, mask off
1479 // the high bits so we are sure to get a proper truncation if the input is
1481 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1482 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1483 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1486 // The MC library also has a right-shift operator, but it isn't consistently
1487 // signed or unsigned between different targets.
1488 case Instruction::Add:
1489 case Instruction::Sub:
1490 case Instruction::Mul:
1491 case Instruction::SDiv:
1492 case Instruction::SRem:
1493 case Instruction::Shl:
1494 case Instruction::And:
1495 case Instruction::Or:
1496 case Instruction::Xor: {
1497 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1498 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1499 switch (CE->getOpcode()) {
1500 default: llvm_unreachable("Unknown binary operator constant cast expr");
1501 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1502 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1503 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1504 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1505 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1506 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1507 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1508 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1509 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1515 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1518 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1520 if (AddrSpace != 0 || !CA->isString()) {
1521 // Not a string. Print the values in successive locations
1522 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1523 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1527 // Otherwise, it can be emitted as .ascii.
1528 SmallVector<char, 128> TmpVec;
1529 TmpVec.reserve(CA->getNumOperands());
1530 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1531 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1533 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1536 static void EmitGlobalConstantVector(const ConstantVector *CV,
1537 unsigned AddrSpace, AsmPrinter &AP) {
1538 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1539 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1541 const TargetData &TD = *AP.TM.getTargetData();
1542 unsigned Size = TD.getTypeAllocSize(CV->getType());
1543 unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1544 CV->getType()->getNumElements();
1545 if (unsigned Padding = Size - EmittedSize)
1546 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1549 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1550 unsigned AddrSpace, AsmPrinter &AP) {
1551 // Print the fields in successive locations. Pad to align if needed!
1552 const TargetData *TD = AP.TM.getTargetData();
1553 unsigned Size = TD->getTypeAllocSize(CS->getType());
1554 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1555 uint64_t SizeSoFar = 0;
1556 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1557 const Constant *Field = CS->getOperand(i);
1559 // Check if padding is needed and insert one or more 0s.
1560 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1561 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1562 - Layout->getElementOffset(i)) - FieldSize;
1563 SizeSoFar += FieldSize + PadSize;
1565 // Now print the actual field value.
1566 EmitGlobalConstantImpl(Field, AddrSpace, AP);
1568 // Insert padding - this may include padding to increase the size of the
1569 // current field up to the ABI size (if the struct is not packed) as well
1570 // as padding to ensure that the next field starts at the right offset.
1571 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1573 assert(SizeSoFar == Layout->getSizeInBytes() &&
1574 "Layout of constant struct may be incorrect!");
1577 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1579 // FP Constants are printed as integer constants to avoid losing
1581 if (CFP->getType()->isDoubleTy()) {
1582 if (AP.isVerbose()) {
1583 double Val = CFP->getValueAPF().convertToDouble();
1584 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1587 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1588 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1592 if (CFP->getType()->isFloatTy()) {
1593 if (AP.isVerbose()) {
1594 float Val = CFP->getValueAPF().convertToFloat();
1595 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1597 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1598 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1602 if (CFP->getType()->isX86_FP80Ty()) {
1603 // all long double variants are printed as hex
1604 // API needed to prevent premature destruction
1605 APInt API = CFP->getValueAPF().bitcastToAPInt();
1606 const uint64_t *p = API.getRawData();
1607 if (AP.isVerbose()) {
1608 // Convert to double so we can print the approximate val as a comment.
1609 APFloat DoubleVal = CFP->getValueAPF();
1611 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1613 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1614 << DoubleVal.convertToDouble() << '\n';
1617 if (AP.TM.getTargetData()->isBigEndian()) {
1618 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1619 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1621 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1622 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1625 // Emit the tail padding for the long double.
1626 const TargetData &TD = *AP.TM.getTargetData();
1627 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1628 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1632 assert(CFP->getType()->isPPC_FP128Ty() &&
1633 "Floating point constant type not handled");
1634 // All long double variants are printed as hex
1635 // API needed to prevent premature destruction.
1636 APInt API = CFP->getValueAPF().bitcastToAPInt();
1637 const uint64_t *p = API.getRawData();
1638 if (AP.TM.getTargetData()->isBigEndian()) {
1639 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1640 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1642 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1643 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1647 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1648 unsigned AddrSpace, AsmPrinter &AP) {
1649 const TargetData *TD = AP.TM.getTargetData();
1650 unsigned BitWidth = CI->getBitWidth();
1651 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1653 // We don't expect assemblers to support integer data directives
1654 // for more than 64 bits, so we emit the data in at most 64-bit
1655 // quantities at a time.
1656 const uint64_t *RawData = CI->getValue().getRawData();
1657 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1658 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1659 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1663 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1665 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1666 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1667 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1670 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1671 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1678 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1679 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1682 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1687 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1688 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1690 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1691 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1693 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1694 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1696 if (isa<ConstantPointerNull>(CV)) {
1697 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1698 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1702 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1703 return EmitGlobalConstantVector(V, AddrSpace, AP);
1705 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1706 // thread the streamer with EmitValue.
1707 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1708 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1712 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1713 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1714 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1716 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1717 else if (MAI->hasSubsectionsViaSymbols()) {
1718 // If the global has zero size, emit a single byte so that two labels don't
1719 // look like they are at the same location.
1720 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1724 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1725 // Target doesn't support this yet!
1726 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1729 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1731 OS << '+' << Offset;
1732 else if (Offset < 0)
1736 //===----------------------------------------------------------------------===//
1737 // Symbol Lowering Routines.
1738 //===----------------------------------------------------------------------===//
1740 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1741 /// temporary label with the specified stem and unique ID.
1742 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1743 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1747 /// GetTempSymbol - Return an assembler temporary label with the specified
1749 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1750 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1755 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1756 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1759 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1760 return MMI->getAddrLabelSymbol(BB);
1763 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1764 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1765 return OutContext.GetOrCreateSymbol
1766 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1767 + "_" + Twine(CPID));
1770 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1771 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1772 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1775 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1776 /// FIXME: privatize to AsmPrinter.
1777 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1778 return OutContext.GetOrCreateSymbol
1779 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1780 Twine(UID) + "_set_" + Twine(MBBID));
1783 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1784 /// global value name as its base, with the specified suffix, and where the
1785 /// symbol is forced to have private linkage if ForcePrivate is true.
1786 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1788 bool ForcePrivate) const {
1789 SmallString<60> NameStr;
1790 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1791 NameStr.append(Suffix.begin(), Suffix.end());
1792 return OutContext.GetOrCreateSymbol(NameStr.str());
1795 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1797 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1798 SmallString<60> NameStr;
1799 Mang->getNameWithPrefix(NameStr, Sym);
1800 return OutContext.GetOrCreateSymbol(NameStr.str());
1805 /// PrintParentLoopComment - Print comments about parent loops of this one.
1806 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1807 unsigned FunctionNumber) {
1808 if (Loop == 0) return;
1809 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1810 OS.indent(Loop->getLoopDepth()*2)
1811 << "Parent Loop BB" << FunctionNumber << "_"
1812 << Loop->getHeader()->getNumber()
1813 << " Depth=" << Loop->getLoopDepth() << '\n';
1817 /// PrintChildLoopComment - Print comments about child loops within
1818 /// the loop for this basic block, with nesting.
1819 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1820 unsigned FunctionNumber) {
1821 // Add child loop information
1822 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1823 OS.indent((*CL)->getLoopDepth()*2)
1824 << "Child Loop BB" << FunctionNumber << "_"
1825 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1827 PrintChildLoopComment(OS, *CL, FunctionNumber);
1831 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1832 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1833 const MachineLoopInfo *LI,
1834 const AsmPrinter &AP) {
1835 // Add loop depth information
1836 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1837 if (Loop == 0) return;
1839 MachineBasicBlock *Header = Loop->getHeader();
1840 assert(Header && "No header for loop");
1842 // If this block is not a loop header, just print out what is the loop header
1844 if (Header != &MBB) {
1845 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1846 Twine(AP.getFunctionNumber())+"_" +
1847 Twine(Loop->getHeader()->getNumber())+
1848 " Depth="+Twine(Loop->getLoopDepth()));
1852 // Otherwise, it is a loop header. Print out information about child and
1854 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1856 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1859 OS.indent(Loop->getLoopDepth()*2-2);
1864 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1866 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1870 /// EmitBasicBlockStart - This method prints the label for the specified
1871 /// MachineBasicBlock, an alignment (if present) and a comment describing
1872 /// it if appropriate.
1873 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1874 // Emit an alignment directive for this block, if needed.
1875 if (unsigned Align = MBB->getAlignment())
1876 EmitAlignment(Log2_32(Align));
1878 // If the block has its address taken, emit any labels that were used to
1879 // reference the block. It is possible that there is more than one label
1880 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1881 // the references were generated.
1882 if (MBB->hasAddressTaken()) {
1883 const BasicBlock *BB = MBB->getBasicBlock();
1885 OutStreamer.AddComment("Block address taken");
1887 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1889 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1890 OutStreamer.EmitLabel(Syms[i]);
1893 // Print the main label for the block.
1894 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1895 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1896 if (const BasicBlock *BB = MBB->getBasicBlock())
1898 OutStreamer.AddComment("%" + BB->getName());
1900 EmitBasicBlockLoopComments(*MBB, LI, *this);
1902 // NOTE: Want this comment at start of line, don't emit with AddComment.
1903 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1904 Twine(MBB->getNumber()) + ":");
1908 if (const BasicBlock *BB = MBB->getBasicBlock())
1910 OutStreamer.AddComment("%" + BB->getName());
1911 EmitBasicBlockLoopComments(*MBB, LI, *this);
1914 OutStreamer.EmitLabel(MBB->getSymbol());
1918 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
1919 bool IsDefinition) const {
1920 MCSymbolAttr Attr = MCSA_Invalid;
1922 switch (Visibility) {
1924 case GlobalValue::HiddenVisibility:
1926 Attr = MAI->getHiddenVisibilityAttr();
1928 Attr = MAI->getHiddenDeclarationVisibilityAttr();
1930 case GlobalValue::ProtectedVisibility:
1931 Attr = MAI->getProtectedVisibilityAttr();
1935 if (Attr != MCSA_Invalid)
1936 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1939 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1940 /// exactly one predecessor and the control transfer mechanism between
1941 /// the predecessor and this block is a fall-through.
1943 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1944 // If this is a landing pad, it isn't a fall through. If it has no preds,
1945 // then nothing falls through to it.
1946 if (MBB->isLandingPad() || MBB->pred_empty())
1949 // If there isn't exactly one predecessor, it can't be a fall through.
1950 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1952 if (PI2 != MBB->pred_end())
1955 // The predecessor has to be immediately before this block.
1956 MachineBasicBlock *Pred = *PI;
1958 if (!Pred->isLayoutSuccessor(MBB))
1961 // If the block is completely empty, then it definitely does fall through.
1965 // Check the terminators in the previous blocks
1966 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
1967 IE = Pred->end(); II != IE; ++II) {
1968 MachineInstr &MI = *II;
1970 // If it is not a simple branch, we are in a table somewhere.
1971 if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
1974 // If we are the operands of one of the branches, this is not
1976 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
1977 OE = MI.operands_end(); OI != OE; ++OI) {
1978 const MachineOperand& OP = *OI;
1981 if (OP.isMBB() && OP.getMBB() == MBB)
1991 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1992 if (!S->usesMetadata())
1995 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1996 gcp_map_type::iterator GCPI = GCMap.find(S);
1997 if (GCPI != GCMap.end())
1998 return GCPI->second;
2000 const char *Name = S->getName().c_str();
2002 for (GCMetadataPrinterRegistry::iterator
2003 I = GCMetadataPrinterRegistry::begin(),
2004 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2005 if (strcmp(Name, I->getName()) == 0) {
2006 GCMetadataPrinter *GMP = I->instantiate();
2008 GCMap.insert(std::make_pair(S, GMP));
2012 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));