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/TargetData.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Assembly/Writer.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/Timer.h"
52 static const char *DWARFGroupName = "DWARF Emission";
53 static const char *DbgTimerName = "DWARF Debug Writer";
54 static const char *EHTimerName = "DWARF Exception Writer";
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
58 char AsmPrinter::ID = 0;
60 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
61 static gcp_map_type &getGCMap(void *&P) {
63 P = new gcp_map_type();
64 return *(gcp_map_type*)P;
68 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
69 /// value in log2 form. This rounds up to the preferred alignment if possible
71 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
72 unsigned InBits = 0) {
74 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
75 NumBits = TD.getPreferredAlignmentLog(GVar);
77 // If InBits is specified, round it to it.
81 // If the GV has a specified alignment, take it into account.
82 if (GV->getAlignment() == 0)
85 unsigned GVAlign = Log2_32(GV->getAlignment());
87 // If the GVAlign is larger than NumBits, or if we are required to obey
88 // NumBits because the GV has an assigned section, obey it.
89 if (GVAlign > NumBits || GV->hasSection())
97 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
98 : MachineFunctionPass(ID),
99 TM(tm), MAI(tm.getMCAsmInfo()),
100 OutContext(Streamer.getContext()),
101 OutStreamer(Streamer),
102 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
103 DD = 0; DE = 0; MMI = 0; LI = 0;
104 GCMetadataPrinters = 0;
105 VerboseAsm = Streamer.isVerboseAsm();
108 AsmPrinter::~AsmPrinter() {
109 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
111 if (GCMetadataPrinters != 0) {
112 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
114 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
117 GCMetadataPrinters = 0;
123 /// getFunctionNumber - Return a unique ID for the current function.
125 unsigned AsmPrinter::getFunctionNumber() const {
126 return MF->getFunctionNumber();
129 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
130 return TM.getTargetLowering()->getObjFileLowering();
134 /// getTargetData - Return information about data layout.
135 const TargetData &AsmPrinter::getTargetData() const {
136 return *TM.getTargetData();
139 /// getCurrentSection() - Return the current section we are emitting to.
140 const MCSection *AsmPrinter::getCurrentSection() const {
141 return OutStreamer.getCurrentSection();
146 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.setPreservesAll();
148 MachineFunctionPass::getAnalysisUsage(AU);
149 AU.addRequired<MachineModuleInfo>();
150 AU.addRequired<GCModuleInfo>();
152 AU.addRequired<MachineLoopInfo>();
155 bool AsmPrinter::doInitialization(Module &M) {
156 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
157 MMI->AnalyzeModule(M);
159 // Initialize TargetLoweringObjectFile.
160 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
161 .Initialize(OutContext, TM);
163 Mang = new Mangler(OutContext, *TM.getTargetData());
165 // Allow the target to emit any magic that it wants at the start of the file.
166 EmitStartOfAsmFile(M);
168 // Very minimal debug info. It is ignored if we emit actual debug info. If we
169 // don't, this at least helps the user find where a global came from.
170 if (MAI->hasSingleParameterDotFile()) {
172 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
175 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
176 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
177 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
178 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
179 MP->beginAssembly(*this);
181 // Emit module-level inline asm if it exists.
182 if (!M.getModuleInlineAsm().empty()) {
183 OutStreamer.AddComment("Start of file scope inline assembly");
184 OutStreamer.AddBlankLine();
185 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
186 OutStreamer.AddComment("End of file scope inline assembly");
187 OutStreamer.AddBlankLine();
190 #ifndef ANDROID_TARGET_BUILD
191 if (MAI->doesSupportDebugInformation())
192 DD = new DwarfDebug(this, &M);
194 if (MAI->doesSupportExceptionHandling())
195 switch (MAI->getExceptionHandlingType()) {
197 case ExceptionHandling::DwarfTable:
198 DE = new DwarfTableException(this);
200 case ExceptionHandling::DwarfCFI:
201 DE = new DwarfCFIException(this);
203 case ExceptionHandling::ARM:
204 DE = new ARMException(this);
207 #endif // ANDROID_TARGET_BUILD
212 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
213 switch ((GlobalValue::LinkageTypes)Linkage) {
214 case GlobalValue::CommonLinkage:
215 case GlobalValue::LinkOnceAnyLinkage:
216 case GlobalValue::LinkOnceODRLinkage:
217 case GlobalValue::WeakAnyLinkage:
218 case GlobalValue::WeakODRLinkage:
219 case GlobalValue::LinkerPrivateWeakLinkage:
220 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
221 if (MAI->getWeakDefDirective() != 0) {
223 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
225 if ((GlobalValue::LinkageTypes)Linkage !=
226 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
227 // .weak_definition _foo
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
230 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
231 } else if (MAI->getLinkOnceDirective() != 0) {
233 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
234 //NOTE: linkonce is handled by the section the symbol was assigned to.
237 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
240 case GlobalValue::DLLExportLinkage:
241 case GlobalValue::AppendingLinkage:
242 // FIXME: appending linkage variables should go into a section of
243 // their name or something. For now, just emit them as external.
244 case GlobalValue::ExternalLinkage:
245 // If external or appending, declare as a global symbol.
247 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
249 case GlobalValue::PrivateLinkage:
250 case GlobalValue::InternalLinkage:
251 case GlobalValue::LinkerPrivateLinkage:
254 llvm_unreachable("Unknown linkage type!");
259 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
260 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
261 if (!GV->hasInitializer()) // External globals require no code.
264 // Check to see if this is a special global used by LLVM, if so, emit it.
265 if (EmitSpecialLLVMGlobal(GV))
269 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
270 /*PrintType=*/false, GV->getParent());
271 OutStreamer.GetCommentOS() << '\n';
274 MCSymbol *GVSym = Mang->getSymbol(GV);
275 EmitVisibility(GVSym, GV->getVisibility());
277 if (MAI->hasDotTypeDotSizeDirective())
278 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
280 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
282 const TargetData *TD = TM.getTargetData();
283 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
285 // If the alignment is specified, we *must* obey it. Overaligning a global
286 // with a specified alignment is a prompt way to break globals emitted to
287 // sections and expected to be contiguous (e.g. ObjC metadata).
288 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
290 // Handle common and BSS local symbols (.lcomm).
291 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
292 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
295 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
296 /*PrintType=*/false, GV->getParent());
297 OutStreamer.GetCommentOS() << '\n';
300 // Handle common symbols.
301 if (GVKind.isCommon()) {
302 unsigned Align = 1 << AlignLog;
303 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
307 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
311 // Handle local BSS symbols.
312 if (MAI->hasMachoZeroFillDirective()) {
313 const MCSection *TheSection =
314 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
315 // .zerofill __DATA, __bss, _foo, 400, 5
316 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
320 if (MAI->hasLCOMMDirective()) {
322 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
326 unsigned Align = 1 << AlignLog;
327 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
331 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
333 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
337 const MCSection *TheSection =
338 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
340 // Handle the zerofill directive on darwin, which is a special form of BSS
342 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
343 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
346 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
347 // .zerofill __DATA, __common, _foo, 400, 5
348 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
352 // Handle thread local data for mach-o which requires us to output an
353 // additional structure of data and mangle the original symbol so that we
354 // can reference it later.
356 // TODO: This should become an "emit thread local global" method on TLOF.
357 // All of this macho specific stuff should be sunk down into TLOFMachO and
358 // stuff like "TLSExtraDataSection" should no longer be part of the parent
359 // TLOF class. This will also make it more obvious that stuff like
360 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
362 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
363 // Emit the .tbss symbol
365 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
367 if (GVKind.isThreadBSS())
368 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
369 else if (GVKind.isThreadData()) {
370 OutStreamer.SwitchSection(TheSection);
372 EmitAlignment(AlignLog, GV);
373 OutStreamer.EmitLabel(MangSym);
375 EmitGlobalConstant(GV->getInitializer());
378 OutStreamer.AddBlankLine();
380 // Emit the variable struct for the runtime.
381 const MCSection *TLVSect
382 = getObjFileLowering().getTLSExtraDataSection();
384 OutStreamer.SwitchSection(TLVSect);
385 // Emit the linkage here.
386 EmitLinkage(GV->getLinkage(), GVSym);
387 OutStreamer.EmitLabel(GVSym);
389 // Three pointers in size:
390 // - __tlv_bootstrap - used to make sure support exists
391 // - spare pointer, used when mapped by the runtime
392 // - pointer to mangled symbol above with initializer
393 unsigned PtrSize = TD->getPointerSizeInBits()/8;
394 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
396 OutStreamer.EmitIntValue(0, PtrSize, 0);
397 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
399 OutStreamer.AddBlankLine();
403 OutStreamer.SwitchSection(TheSection);
405 EmitLinkage(GV->getLinkage(), GVSym);
406 EmitAlignment(AlignLog, GV);
408 OutStreamer.EmitLabel(GVSym);
410 EmitGlobalConstant(GV->getInitializer());
412 if (MAI->hasDotTypeDotSizeDirective())
414 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
416 OutStreamer.AddBlankLine();
419 /// EmitFunctionHeader - This method emits the header for the current
421 void AsmPrinter::EmitFunctionHeader() {
422 // Print out constants referenced by the function
425 // Print the 'header' of function.
426 const Function *F = MF->getFunction();
428 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
429 EmitVisibility(CurrentFnSym, F->getVisibility());
431 EmitLinkage(F->getLinkage(), CurrentFnSym);
432 EmitAlignment(MF->getAlignment(), F);
434 if (MAI->hasDotTypeDotSizeDirective())
435 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
438 WriteAsOperand(OutStreamer.GetCommentOS(), F,
439 /*PrintType=*/false, F->getParent());
440 OutStreamer.GetCommentOS() << '\n';
443 // Emit the CurrentFnSym. This is a virtual function to allow targets to
444 // do their wild and crazy things as required.
445 EmitFunctionEntryLabel();
447 // If the function had address-taken blocks that got deleted, then we have
448 // references to the dangling symbols. Emit them at the start of the function
449 // so that we don't get references to undefined symbols.
450 std::vector<MCSymbol*> DeadBlockSyms;
451 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
452 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
453 OutStreamer.AddComment("Address taken block that was later removed");
454 OutStreamer.EmitLabel(DeadBlockSyms[i]);
457 // Add some workaround for linkonce linkage on Cygwin\MinGW.
458 if (MAI->getLinkOnceDirective() != 0 &&
459 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
460 // FIXME: What is this?
462 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
463 CurrentFnSym->getName());
464 OutStreamer.EmitLabel(FakeStub);
467 // Emit pre-function debug and/or EH information.
468 #ifndef ANDROID_TARGET_BUILD
470 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
471 DE->BeginFunction(MF);
474 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
475 DD->beginFunction(MF);
477 #endif // ANDROID_TARGET_BUILD
480 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
481 /// function. This can be overridden by targets as required to do custom stuff.
482 void AsmPrinter::EmitFunctionEntryLabel() {
483 // The function label could have already been emitted if two symbols end up
484 // conflicting due to asm renaming. Detect this and emit an error.
485 if (CurrentFnSym->isUndefined())
486 return OutStreamer.EmitLabel(CurrentFnSym);
488 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
489 "' label emitted multiple times to assembly file");
493 static void EmitDebugLoc(DebugLoc DL, const MachineFunction *MF,
494 raw_ostream &CommentOS) {
495 const LLVMContext &Ctx = MF->getFunction()->getContext();
496 if (!DL.isUnknown()) { // Print source line info.
497 DIScope Scope(DL.getScope(Ctx));
498 // Omit the directory, because it's likely to be long and uninteresting.
500 CommentOS << Scope.getFilename();
502 CommentOS << "<unknown>";
503 CommentOS << ':' << DL.getLine();
504 if (DL.getCol() != 0)
505 CommentOS << ':' << DL.getCol();
506 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
507 if (!InlinedAtDL.isUnknown()) {
509 EmitDebugLoc(InlinedAtDL, MF, CommentOS);
515 /// EmitComments - Pretty-print comments for instructions.
516 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
517 const MachineFunction *MF = MI.getParent()->getParent();
518 const TargetMachine &TM = MF->getTarget();
520 DebugLoc DL = MI.getDebugLoc();
521 if (!DL.isUnknown()) { // Print source line info.
522 EmitDebugLoc(DL, MF, CommentOS);
526 // Check for spills and reloads
529 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
531 // We assume a single instruction only has a spill or reload, not
533 const MachineMemOperand *MMO;
534 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
535 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
536 MMO = *MI.memoperands_begin();
537 CommentOS << MMO->getSize() << "-byte Reload\n";
539 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
540 if (FrameInfo->isSpillSlotObjectIndex(FI))
541 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
542 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
543 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
544 MMO = *MI.memoperands_begin();
545 CommentOS << MMO->getSize() << "-byte Spill\n";
547 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
548 if (FrameInfo->isSpillSlotObjectIndex(FI))
549 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
552 // Check for spill-induced copies
553 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
554 CommentOS << " Reload Reuse\n";
557 /// EmitImplicitDef - This method emits the specified machine instruction
558 /// that is an implicit def.
559 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
560 unsigned RegNo = MI->getOperand(0).getReg();
561 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
562 AP.TM.getRegisterInfo()->getName(RegNo));
563 AP.OutStreamer.AddBlankLine();
566 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
567 std::string Str = "kill:";
568 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
569 const MachineOperand &Op = MI->getOperand(i);
570 assert(Op.isReg() && "KILL instruction must have only register operands");
572 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
573 Str += (Op.isDef() ? "<def>" : "<kill>");
575 AP.OutStreamer.AddComment(Str);
576 AP.OutStreamer.AddBlankLine();
579 /// EmitDebugValueComment - This method handles the target-independent form
580 /// of DBG_VALUE, returning true if it was able to do so. A false return
581 /// means the target will need to handle MI in EmitInstruction.
582 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
583 // This code handles only the 3-operand target-independent form.
584 if (MI->getNumOperands() != 3)
587 SmallString<128> Str;
588 raw_svector_ostream OS(Str);
589 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
591 // cast away const; DIetc do not take const operands for some reason.
592 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
593 if (V.getContext().isSubprogram())
594 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
595 OS << V.getName() << " <- ";
597 // Register or immediate value. Register 0 means undef.
598 if (MI->getOperand(0).isFPImm()) {
599 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
600 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
601 OS << (double)APF.convertToFloat();
602 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
603 OS << APF.convertToDouble();
605 // There is no good way to print long double. Convert a copy to
606 // double. Ah well, it's only a comment.
608 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
610 OS << "(long double) " << APF.convertToDouble();
612 } else if (MI->getOperand(0).isImm()) {
613 OS << MI->getOperand(0).getImm();
615 assert(MI->getOperand(0).isReg() && "Unknown operand type");
616 if (MI->getOperand(0).getReg() == 0) {
617 // Suppress offset, it is not meaningful here.
619 // NOTE: Want this comment at start of line, don't emit with AddComment.
620 AP.OutStreamer.EmitRawText(OS.str());
623 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
626 OS << '+' << MI->getOperand(1).getImm();
627 // NOTE: Want this comment at start of line, don't emit with AddComment.
628 AP.OutStreamer.EmitRawText(OS.str());
632 /// EmitFunctionBody - This method emits the body and trailer for a
634 void AsmPrinter::EmitFunctionBody() {
635 // Emit target-specific gunk before the function body.
636 EmitFunctionBodyStart();
638 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
640 // Print out code for the function.
641 bool HasAnyRealCode = false;
642 const MachineInstr *LastMI = 0;
643 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
645 // Print a label for the basic block.
646 EmitBasicBlockStart(I);
647 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
651 // Print the assembly for the instruction.
652 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
653 !II->isDebugValue()) {
654 HasAnyRealCode = true;
658 #ifndef ANDROID_TARGET_BUILD
659 if (ShouldPrintDebugScopes) {
660 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
661 DD->beginInstruction(II);
663 #endif // ANDROID_TARGET_BUILD
666 EmitComments(*II, OutStreamer.GetCommentOS());
668 switch (II->getOpcode()) {
669 case TargetOpcode::PROLOG_LABEL:
670 case TargetOpcode::EH_LABEL:
671 case TargetOpcode::GC_LABEL:
672 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
674 case TargetOpcode::INLINEASM:
677 case TargetOpcode::DBG_VALUE:
679 if (!EmitDebugValueComment(II, *this))
683 case TargetOpcode::IMPLICIT_DEF:
684 if (isVerbose()) EmitImplicitDef(II, *this);
686 case TargetOpcode::KILL:
687 if (isVerbose()) EmitKill(II, *this);
694 #ifndef ANDROID_TARGET_BUILD
695 if (ShouldPrintDebugScopes) {
696 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
697 DD->endInstruction(II);
699 #endif // ANDROID_TARGET_BUILD
703 // If the last instruction was a prolog label, then we have a situation where
704 // we emitted a prolog but no function body. This results in the ending prolog
705 // label equaling the end of function label and an invalid "row" in the
706 // FDE. We need to emit a noop in this situation so that the FDE's rows are
708 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
710 // If the function is empty and the object file uses .subsections_via_symbols,
711 // then we need to emit *something* to the function body to prevent the
712 // labels from collapsing together. Just emit a noop.
713 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
715 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
716 if (Noop.getOpcode()) {
717 OutStreamer.AddComment("avoids zero-length function");
718 OutStreamer.EmitInstruction(Noop);
719 } else // Target not mc-ized yet.
720 OutStreamer.EmitRawText(StringRef("\tnop\n"));
723 // Emit target-specific gunk after the function body.
724 EmitFunctionBodyEnd();
726 // If the target wants a .size directive for the size of the function, emit
728 if (MAI->hasDotTypeDotSizeDirective()) {
729 // Create a symbol for the end of function, so we can get the size as
730 // difference between the function label and the temp label.
731 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
732 OutStreamer.EmitLabel(FnEndLabel);
734 const MCExpr *SizeExp =
735 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
736 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
738 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
741 // Emit post-function debug information.
742 #ifndef ANDROID_TARGET_BUILD
744 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
748 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
751 #endif // ANDROID_TARGET_BUILD
754 // Print out jump tables referenced by the function.
757 OutStreamer.AddBlankLine();
760 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
762 MachineLocation AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
763 // Target specific DBG_VALUE instructions are handled by each target.
764 return MachineLocation();
767 bool AsmPrinter::doFinalization(Module &M) {
768 // Emit global variables.
769 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
771 EmitGlobalVariable(I);
773 // Emit visibility info for declarations
774 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
775 const Function &F = *I;
776 if (!F.isDeclaration())
778 GlobalValue::VisibilityTypes V = F.getVisibility();
779 if (V == GlobalValue::DefaultVisibility)
782 MCSymbol *Name = Mang->getSymbol(&F);
783 EmitVisibility(Name, V, false);
786 // Finalize debug and EH information.
787 #ifndef ANDROID_TARGET_BUILD
790 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
797 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
802 #endif // ANDROID_TARGET_BUILD
804 // If the target wants to know about weak references, print them all.
805 if (MAI->getWeakRefDirective()) {
806 // FIXME: This is not lazy, it would be nice to only print weak references
807 // to stuff that is actually used. Note that doing so would require targets
808 // to notice uses in operands (due to constant exprs etc). This should
809 // happen with the MC stuff eventually.
811 // Print out module-level global variables here.
812 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
814 if (!I->hasExternalWeakLinkage()) continue;
815 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
818 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
819 if (!I->hasExternalWeakLinkage()) continue;
820 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
824 if (MAI->hasSetDirective()) {
825 OutStreamer.AddBlankLine();
826 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
828 MCSymbol *Name = Mang->getSymbol(I);
830 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
831 MCSymbol *Target = Mang->getSymbol(GV);
833 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
834 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
835 else if (I->hasWeakLinkage())
836 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
838 assert(I->hasLocalLinkage() && "Invalid alias linkage");
840 EmitVisibility(Name, I->getVisibility());
842 // Emit the directives as assignments aka .set:
843 OutStreamer.EmitAssignment(Name,
844 MCSymbolRefExpr::Create(Target, OutContext));
848 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
849 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
850 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
851 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
852 MP->finishAssembly(*this);
854 // If we don't have any trampolines, then we don't require stack memory
855 // to be executable. Some targets have a directive to declare this.
856 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
857 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
858 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
859 OutStreamer.SwitchSection(S);
861 // Allow the target to emit any magic that it wants at the end of the file,
862 // after everything else has gone out.
865 delete Mang; Mang = 0;
868 OutStreamer.Finish();
872 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
874 // Get the function symbol.
875 CurrentFnSym = Mang->getSymbol(MF.getFunction());
878 LI = &getAnalysis<MachineLoopInfo>();
882 // SectionCPs - Keep track the alignment, constpool entries per Section.
886 SmallVector<unsigned, 4> CPEs;
887 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
891 /// EmitConstantPool - Print to the current output stream assembly
892 /// representations of the constants in the constant pool MCP. This is
893 /// used to print out constants which have been "spilled to memory" by
894 /// the code generator.
896 void AsmPrinter::EmitConstantPool() {
897 const MachineConstantPool *MCP = MF->getConstantPool();
898 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
899 if (CP.empty()) return;
901 // Calculate sections for constant pool entries. We collect entries to go into
902 // the same section together to reduce amount of section switch statements.
903 SmallVector<SectionCPs, 4> CPSections;
904 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
905 const MachineConstantPoolEntry &CPE = CP[i];
906 unsigned Align = CPE.getAlignment();
909 switch (CPE.getRelocationInfo()) {
910 default: llvm_unreachable("Unknown section kind");
911 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
913 Kind = SectionKind::getReadOnlyWithRelLocal();
916 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
917 case 4: Kind = SectionKind::getMergeableConst4(); break;
918 case 8: Kind = SectionKind::getMergeableConst8(); break;
919 case 16: Kind = SectionKind::getMergeableConst16();break;
920 default: Kind = SectionKind::getMergeableConst(); break;
924 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
926 // The number of sections are small, just do a linear search from the
927 // last section to the first.
929 unsigned SecIdx = CPSections.size();
930 while (SecIdx != 0) {
931 if (CPSections[--SecIdx].S == S) {
937 SecIdx = CPSections.size();
938 CPSections.push_back(SectionCPs(S, Align));
941 if (Align > CPSections[SecIdx].Alignment)
942 CPSections[SecIdx].Alignment = Align;
943 CPSections[SecIdx].CPEs.push_back(i);
946 // Now print stuff into the calculated sections.
947 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
948 OutStreamer.SwitchSection(CPSections[i].S);
949 EmitAlignment(Log2_32(CPSections[i].Alignment));
952 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
953 unsigned CPI = CPSections[i].CPEs[j];
954 MachineConstantPoolEntry CPE = CP[CPI];
956 // Emit inter-object padding for alignment.
957 unsigned AlignMask = CPE.getAlignment() - 1;
958 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
959 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
961 const Type *Ty = CPE.getType();
962 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
963 OutStreamer.EmitLabel(GetCPISymbol(CPI));
965 if (CPE.isMachineConstantPoolEntry())
966 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
968 EmitGlobalConstant(CPE.Val.ConstVal);
973 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
974 /// by the current function to the current output stream.
976 void AsmPrinter::EmitJumpTableInfo() {
977 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
978 if (MJTI == 0) return;
979 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
980 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
981 if (JT.empty()) return;
983 // Pick the directive to use to print the jump table entries, and switch to
984 // the appropriate section.
985 const Function *F = MF->getFunction();
986 bool JTInDiffSection = false;
987 if (// In PIC mode, we need to emit the jump table to the same section as the
988 // function body itself, otherwise the label differences won't make sense.
989 // FIXME: Need a better predicate for this: what about custom entries?
990 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
991 // We should also do if the section name is NULL or function is declared
992 // in discardable section
993 // FIXME: this isn't the right predicate, should be based on the MCSection
995 F->isWeakForLinker()) {
996 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
998 // Otherwise, drop it in the readonly section.
999 const MCSection *ReadOnlySection =
1000 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1001 OutStreamer.SwitchSection(ReadOnlySection);
1002 JTInDiffSection = true;
1005 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1007 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1008 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1010 // If this jump table was deleted, ignore it.
1011 if (JTBBs.empty()) continue;
1013 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1014 // .set directive for each unique entry. This reduces the number of
1015 // relocations the assembler will generate for the jump table.
1016 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1017 MAI->hasSetDirective()) {
1018 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1019 const TargetLowering *TLI = TM.getTargetLowering();
1020 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1021 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1022 const MachineBasicBlock *MBB = JTBBs[ii];
1023 if (!EmittedSets.insert(MBB)) continue;
1025 // .set LJTSet, LBB32-base
1027 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1028 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1029 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1033 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1034 // before each jump table. The first label is never referenced, but tells
1035 // the assembler and linker the extents of the jump table object. The
1036 // second label is actually referenced by the code.
1037 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1038 // FIXME: This doesn't have to have any specific name, just any randomly
1039 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1040 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1042 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1044 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1045 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1049 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1051 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1052 const MachineBasicBlock *MBB,
1053 unsigned UID) const {
1054 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1055 const MCExpr *Value = 0;
1056 switch (MJTI->getEntryKind()) {
1057 case MachineJumpTableInfo::EK_Inline:
1058 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1059 case MachineJumpTableInfo::EK_Custom32:
1060 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1063 case MachineJumpTableInfo::EK_BlockAddress:
1064 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1066 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1068 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1069 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1070 // with a relocation as gp-relative, e.g.:
1072 MCSymbol *MBBSym = MBB->getSymbol();
1073 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1077 case MachineJumpTableInfo::EK_LabelDifference32: {
1078 // EK_LabelDifference32 - Each entry is the address of the block minus
1079 // the address of the jump table. This is used for PIC jump tables where
1080 // gprel32 is not supported. e.g.:
1081 // .word LBB123 - LJTI1_2
1082 // If the .set directive is supported, this is emitted as:
1083 // .set L4_5_set_123, LBB123 - LJTI1_2
1084 // .word L4_5_set_123
1086 // If we have emitted set directives for the jump table entries, print
1087 // them rather than the entries themselves. If we're emitting PIC, then
1088 // emit the table entries as differences between two text section labels.
1089 if (MAI->hasSetDirective()) {
1090 // If we used .set, reference the .set's symbol.
1091 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1095 // Otherwise, use the difference as the jump table entry.
1096 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1097 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1098 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1103 assert(Value && "Unknown entry kind!");
1105 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1106 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1110 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1111 /// special global used by LLVM. If so, emit it and return true, otherwise
1112 /// do nothing and return false.
1113 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1114 if (GV->getName() == "llvm.used") {
1115 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1116 EmitLLVMUsedList(GV->getInitializer());
1120 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1121 if (GV->getSection() == "llvm.metadata" ||
1122 GV->hasAvailableExternallyLinkage())
1125 if (!GV->hasAppendingLinkage()) return false;
1127 assert(GV->hasInitializer() && "Not a special LLVM global!");
1129 const TargetData *TD = TM.getTargetData();
1130 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1131 if (GV->getName() == "llvm.global_ctors") {
1132 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1133 EmitAlignment(Align);
1134 EmitXXStructorList(GV->getInitializer());
1136 if (TM.getRelocationModel() == Reloc::Static &&
1137 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1138 StringRef Sym(".constructors_used");
1139 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1145 if (GV->getName() == "llvm.global_dtors") {
1146 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1147 EmitAlignment(Align);
1148 EmitXXStructorList(GV->getInitializer());
1150 if (TM.getRelocationModel() == Reloc::Static &&
1151 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1152 StringRef Sym(".destructors_used");
1153 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1162 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1163 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1164 /// is true, as being used with this directive.
1165 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
1166 // Should be an array of 'i8*'.
1167 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1168 if (InitList == 0) return;
1170 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1171 const GlobalValue *GV =
1172 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1173 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1174 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1178 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1179 /// function pointers, ignoring the init priority.
1180 void AsmPrinter::EmitXXStructorList(Constant *List) {
1181 // Should be an array of '{ int, void ()* }' structs. The first value is the
1182 // init priority, which we ignore.
1183 if (!isa<ConstantArray>(List)) return;
1184 ConstantArray *InitList = cast<ConstantArray>(List);
1185 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1186 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1187 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1189 if (CS->getOperand(1)->isNullValue())
1190 return; // Found a null terminator, exit printing.
1191 // Emit the function pointer.
1192 EmitGlobalConstant(CS->getOperand(1));
1196 //===--------------------------------------------------------------------===//
1197 // Emission and print routines
1200 /// EmitInt8 - Emit a byte directive and value.
1202 void AsmPrinter::EmitInt8(int Value) const {
1203 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1206 /// EmitInt16 - Emit a short directive and value.
1208 void AsmPrinter::EmitInt16(int Value) const {
1209 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1212 /// EmitInt32 - Emit a long directive and value.
1214 void AsmPrinter::EmitInt32(int Value) const {
1215 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1218 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1219 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1220 /// labels. This implicitly uses .set if it is available.
1221 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1222 unsigned Size) const {
1223 // Get the Hi-Lo expression.
1224 const MCExpr *Diff =
1225 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1226 MCSymbolRefExpr::Create(Lo, OutContext),
1229 if (!MAI->hasSetDirective()) {
1230 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1234 // Otherwise, emit with .set (aka assignment).
1235 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1236 OutStreamer.EmitAssignment(SetLabel, Diff);
1237 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1240 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1241 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1242 /// specify the labels. This implicitly uses .set if it is available.
1243 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1244 const MCSymbol *Lo, unsigned Size)
1247 // Emit Hi+Offset - Lo
1248 // Get the Hi+Offset expression.
1249 const MCExpr *Plus =
1250 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1251 MCConstantExpr::Create(Offset, OutContext),
1254 // Get the Hi+Offset-Lo expression.
1255 const MCExpr *Diff =
1256 MCBinaryExpr::CreateSub(Plus,
1257 MCSymbolRefExpr::Create(Lo, OutContext),
1260 if (!MAI->hasSetDirective())
1261 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1263 // Otherwise, emit with .set (aka assignment).
1264 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1265 OutStreamer.EmitAssignment(SetLabel, Diff);
1266 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1270 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1271 /// where the size in bytes of the directive is specified by Size and Label
1272 /// specifies the label. This implicitly uses .set if it is available.
1273 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1277 // Emit Label+Offset
1278 const MCExpr *Plus =
1279 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1280 MCConstantExpr::Create(Offset, OutContext),
1283 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1287 //===----------------------------------------------------------------------===//
1289 // EmitAlignment - Emit an alignment directive to the specified power of
1290 // two boundary. For example, if you pass in 3 here, you will get an 8
1291 // byte alignment. If a global value is specified, and if that global has
1292 // an explicit alignment requested, it will override the alignment request
1293 // if required for correctness.
1295 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1296 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1298 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1300 if (getCurrentSection()->getKind().isText())
1301 OutStreamer.EmitCodeAlignment(1 << NumBits);
1303 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1306 //===----------------------------------------------------------------------===//
1307 // Constant emission.
1308 //===----------------------------------------------------------------------===//
1310 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1312 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1313 MCContext &Ctx = AP.OutContext;
1315 if (CV->isNullValue() || isa<UndefValue>(CV))
1316 return MCConstantExpr::Create(0, Ctx);
1318 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1319 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1321 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1322 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1324 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1325 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1327 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1329 llvm_unreachable("Unknown constant value to lower!");
1330 return MCConstantExpr::Create(0, Ctx);
1333 switch (CE->getOpcode()) {
1335 // If the code isn't optimized, there may be outstanding folding
1336 // opportunities. Attempt to fold the expression using TargetData as a
1337 // last resort before giving up.
1339 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1341 return LowerConstant(C, AP);
1343 // Otherwise report the problem to the user.
1346 raw_string_ostream OS(S);
1347 OS << "Unsupported expression in static initializer: ";
1348 WriteAsOperand(OS, CE, /*PrintType=*/false,
1349 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1350 report_fatal_error(OS.str());
1352 return MCConstantExpr::Create(0, Ctx);
1353 case Instruction::GetElementPtr: {
1354 const TargetData &TD = *AP.TM.getTargetData();
1355 // Generate a symbolic expression for the byte address
1356 const Constant *PtrVal = CE->getOperand(0);
1357 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1358 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1361 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1365 // Truncate/sext the offset to the pointer size.
1366 if (TD.getPointerSizeInBits() != 64) {
1367 int SExtAmount = 64-TD.getPointerSizeInBits();
1368 Offset = (Offset << SExtAmount) >> SExtAmount;
1371 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1375 case Instruction::Trunc:
1376 // We emit the value and depend on the assembler to truncate the generated
1377 // expression properly. This is important for differences between
1378 // blockaddress labels. Since the two labels are in the same function, it
1379 // is reasonable to treat their delta as a 32-bit value.
1381 case Instruction::BitCast:
1382 return LowerConstant(CE->getOperand(0), AP);
1384 case Instruction::IntToPtr: {
1385 const TargetData &TD = *AP.TM.getTargetData();
1386 // Handle casts to pointers by changing them into casts to the appropriate
1387 // integer type. This promotes constant folding and simplifies this code.
1388 Constant *Op = CE->getOperand(0);
1389 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1391 return LowerConstant(Op, AP);
1394 case Instruction::PtrToInt: {
1395 const TargetData &TD = *AP.TM.getTargetData();
1396 // Support only foldable casts to/from pointers that can be eliminated by
1397 // changing the pointer to the appropriately sized integer type.
1398 Constant *Op = CE->getOperand(0);
1399 const Type *Ty = CE->getType();
1401 const MCExpr *OpExpr = LowerConstant(Op, AP);
1403 // We can emit the pointer value into this slot if the slot is an
1404 // integer slot equal to the size of the pointer.
1405 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1408 // Otherwise the pointer is smaller than the resultant integer, mask off
1409 // the high bits so we are sure to get a proper truncation if the input is
1411 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1412 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1413 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1416 // The MC library also has a right-shift operator, but it isn't consistently
1417 // signed or unsigned between different targets.
1418 case Instruction::Add:
1419 case Instruction::Sub:
1420 case Instruction::Mul:
1421 case Instruction::SDiv:
1422 case Instruction::SRem:
1423 case Instruction::Shl:
1424 case Instruction::And:
1425 case Instruction::Or:
1426 case Instruction::Xor: {
1427 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1428 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1429 switch (CE->getOpcode()) {
1430 default: llvm_unreachable("Unknown binary operator constant cast expr");
1431 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1432 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1433 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1434 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1435 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1436 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1437 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1438 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1439 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1445 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1448 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1450 if (AddrSpace != 0 || !CA->isString()) {
1451 // Not a string. Print the values in successive locations
1452 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1453 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1457 // Otherwise, it can be emitted as .ascii.
1458 SmallVector<char, 128> TmpVec;
1459 TmpVec.reserve(CA->getNumOperands());
1460 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1461 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1463 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1466 static void EmitGlobalConstantVector(const ConstantVector *CV,
1467 unsigned AddrSpace, AsmPrinter &AP) {
1468 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1469 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1472 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1473 unsigned AddrSpace, AsmPrinter &AP) {
1474 // Print the fields in successive locations. Pad to align if needed!
1475 const TargetData *TD = AP.TM.getTargetData();
1476 unsigned Size = TD->getTypeAllocSize(CS->getType());
1477 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1478 uint64_t SizeSoFar = 0;
1479 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1480 const Constant *Field = CS->getOperand(i);
1482 // Check if padding is needed and insert one or more 0s.
1483 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1484 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1485 - Layout->getElementOffset(i)) - FieldSize;
1486 SizeSoFar += FieldSize + PadSize;
1488 // Now print the actual field value.
1489 EmitGlobalConstantImpl(Field, AddrSpace, AP);
1491 // Insert padding - this may include padding to increase the size of the
1492 // current field up to the ABI size (if the struct is not packed) as well
1493 // as padding to ensure that the next field starts at the right offset.
1494 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1496 assert(SizeSoFar == Layout->getSizeInBytes() &&
1497 "Layout of constant struct may be incorrect!");
1500 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1502 // FP Constants are printed as integer constants to avoid losing
1504 if (CFP->getType()->isDoubleTy()) {
1505 if (AP.isVerbose()) {
1506 double Val = CFP->getValueAPF().convertToDouble();
1507 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1510 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1511 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1515 if (CFP->getType()->isFloatTy()) {
1516 if (AP.isVerbose()) {
1517 float Val = CFP->getValueAPF().convertToFloat();
1518 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1520 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1521 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1525 if (CFP->getType()->isX86_FP80Ty()) {
1526 // all long double variants are printed as hex
1527 // API needed to prevent premature destruction
1528 APInt API = CFP->getValueAPF().bitcastToAPInt();
1529 const uint64_t *p = API.getRawData();
1530 if (AP.isVerbose()) {
1531 // Convert to double so we can print the approximate val as a comment.
1532 APFloat DoubleVal = CFP->getValueAPF();
1534 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1536 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1537 << DoubleVal.convertToDouble() << '\n';
1540 if (AP.TM.getTargetData()->isBigEndian()) {
1541 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1542 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1544 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1545 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1548 // Emit the tail padding for the long double.
1549 const TargetData &TD = *AP.TM.getTargetData();
1550 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1551 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1555 assert(CFP->getType()->isPPC_FP128Ty() &&
1556 "Floating point constant type not handled");
1557 // All long double variants are printed as hex
1558 // API needed to prevent premature destruction.
1559 APInt API = CFP->getValueAPF().bitcastToAPInt();
1560 const uint64_t *p = API.getRawData();
1561 if (AP.TM.getTargetData()->isBigEndian()) {
1562 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1563 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1565 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1566 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1570 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1571 unsigned AddrSpace, AsmPrinter &AP) {
1572 const TargetData *TD = AP.TM.getTargetData();
1573 unsigned BitWidth = CI->getBitWidth();
1574 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1576 // We don't expect assemblers to support integer data directives
1577 // for more than 64 bits, so we emit the data in at most 64-bit
1578 // quantities at a time.
1579 const uint64_t *RawData = CI->getValue().getRawData();
1580 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1581 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1582 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1586 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1588 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1589 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1590 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1593 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1594 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1601 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1602 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1605 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1610 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1611 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1613 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1614 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1616 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1617 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1619 if (isa<ConstantPointerNull>(CV)) {
1620 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1621 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1625 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1626 return EmitGlobalConstantVector(V, AddrSpace, AP);
1628 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1629 // thread the streamer with EmitValue.
1630 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1631 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1635 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1636 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1637 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1639 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1640 else if (MAI->hasSubsectionsViaSymbols()) {
1641 // If the global has zero size, emit a single byte so that two labels don't
1642 // look like they are at the same location.
1643 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1647 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1648 // Target doesn't support this yet!
1649 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1652 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1654 OS << '+' << Offset;
1655 else if (Offset < 0)
1659 //===----------------------------------------------------------------------===//
1660 // Symbol Lowering Routines.
1661 //===----------------------------------------------------------------------===//
1663 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1664 /// temporary label with the specified stem and unique ID.
1665 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1666 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1670 /// GetTempSymbol - Return an assembler temporary label with the specified
1672 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1673 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1678 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1679 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1682 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1683 return MMI->getAddrLabelSymbol(BB);
1686 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1687 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1688 return OutContext.GetOrCreateSymbol
1689 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1690 + "_" + Twine(CPID));
1693 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1694 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1695 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1698 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1699 /// FIXME: privatize to AsmPrinter.
1700 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1701 return OutContext.GetOrCreateSymbol
1702 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1703 Twine(UID) + "_set_" + Twine(MBBID));
1706 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1707 /// global value name as its base, with the specified suffix, and where the
1708 /// symbol is forced to have private linkage if ForcePrivate is true.
1709 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1711 bool ForcePrivate) const {
1712 SmallString<60> NameStr;
1713 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1714 NameStr.append(Suffix.begin(), Suffix.end());
1715 return OutContext.GetOrCreateSymbol(NameStr.str());
1718 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1720 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1721 SmallString<60> NameStr;
1722 Mang->getNameWithPrefix(NameStr, Sym);
1723 return OutContext.GetOrCreateSymbol(NameStr.str());
1728 /// PrintParentLoopComment - Print comments about parent loops of this one.
1729 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1730 unsigned FunctionNumber) {
1731 if (Loop == 0) return;
1732 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1733 OS.indent(Loop->getLoopDepth()*2)
1734 << "Parent Loop BB" << FunctionNumber << "_"
1735 << Loop->getHeader()->getNumber()
1736 << " Depth=" << Loop->getLoopDepth() << '\n';
1740 /// PrintChildLoopComment - Print comments about child loops within
1741 /// the loop for this basic block, with nesting.
1742 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1743 unsigned FunctionNumber) {
1744 // Add child loop information
1745 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1746 OS.indent((*CL)->getLoopDepth()*2)
1747 << "Child Loop BB" << FunctionNumber << "_"
1748 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1750 PrintChildLoopComment(OS, *CL, FunctionNumber);
1754 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1755 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1756 const MachineLoopInfo *LI,
1757 const AsmPrinter &AP) {
1758 // Add loop depth information
1759 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1760 if (Loop == 0) return;
1762 MachineBasicBlock *Header = Loop->getHeader();
1763 assert(Header && "No header for loop");
1765 // If this block is not a loop header, just print out what is the loop header
1767 if (Header != &MBB) {
1768 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1769 Twine(AP.getFunctionNumber())+"_" +
1770 Twine(Loop->getHeader()->getNumber())+
1771 " Depth="+Twine(Loop->getLoopDepth()));
1775 // Otherwise, it is a loop header. Print out information about child and
1777 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1779 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1782 OS.indent(Loop->getLoopDepth()*2-2);
1787 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1789 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1793 /// EmitBasicBlockStart - This method prints the label for the specified
1794 /// MachineBasicBlock, an alignment (if present) and a comment describing
1795 /// it if appropriate.
1796 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1797 // Emit an alignment directive for this block, if needed.
1798 if (unsigned Align = MBB->getAlignment())
1799 EmitAlignment(Log2_32(Align));
1801 // If the block has its address taken, emit any labels that were used to
1802 // reference the block. It is possible that there is more than one label
1803 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1804 // the references were generated.
1805 if (MBB->hasAddressTaken()) {
1806 const BasicBlock *BB = MBB->getBasicBlock();
1808 OutStreamer.AddComment("Block address taken");
1810 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1812 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1813 OutStreamer.EmitLabel(Syms[i]);
1816 // Print the main label for the block.
1817 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1818 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1819 if (const BasicBlock *BB = MBB->getBasicBlock())
1821 OutStreamer.AddComment("%" + BB->getName());
1823 EmitBasicBlockLoopComments(*MBB, LI, *this);
1825 // NOTE: Want this comment at start of line, don't emit with AddComment.
1826 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1827 Twine(MBB->getNumber()) + ":");
1831 if (const BasicBlock *BB = MBB->getBasicBlock())
1833 OutStreamer.AddComment("%" + BB->getName());
1834 EmitBasicBlockLoopComments(*MBB, LI, *this);
1837 OutStreamer.EmitLabel(MBB->getSymbol());
1841 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
1842 bool IsDefinition) const {
1843 MCSymbolAttr Attr = MCSA_Invalid;
1845 switch (Visibility) {
1847 case GlobalValue::HiddenVisibility:
1849 Attr = MAI->getHiddenVisibilityAttr();
1851 Attr = MAI->getHiddenDeclarationVisibilityAttr();
1853 case GlobalValue::ProtectedVisibility:
1854 Attr = MAI->getProtectedVisibilityAttr();
1858 if (Attr != MCSA_Invalid)
1859 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1862 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1863 /// exactly one predecessor and the control transfer mechanism between
1864 /// the predecessor and this block is a fall-through.
1866 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1867 // If this is a landing pad, it isn't a fall through. If it has no preds,
1868 // then nothing falls through to it.
1869 if (MBB->isLandingPad() || MBB->pred_empty())
1872 // If there isn't exactly one predecessor, it can't be a fall through.
1873 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1875 if (PI2 != MBB->pred_end())
1878 // The predecessor has to be immediately before this block.
1879 const MachineBasicBlock *Pred = *PI;
1881 if (!Pred->isLayoutSuccessor(MBB))
1884 // If the block is completely empty, then it definitely does fall through.
1888 // Otherwise, check the last instruction.
1889 const MachineInstr &LastInst = Pred->back();
1890 return !LastInst.getDesc().isBarrier();
1895 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1896 if (!S->usesMetadata())
1899 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1900 gcp_map_type::iterator GCPI = GCMap.find(S);
1901 if (GCPI != GCMap.end())
1902 return GCPI->second;
1904 const char *Name = S->getName().c_str();
1906 for (GCMetadataPrinterRegistry::iterator
1907 I = GCMetadataPrinterRegistry::begin(),
1908 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1909 if (strcmp(Name, I->getName()) == 0) {
1910 GCMetadataPrinter *GMP = I->instantiate();
1912 GCMap.insert(std::make_pair(S, GMP));
1916 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));