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 #include "llvm/Assembly/Writer.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/DwarfWriter.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/DebugInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/FormattedStream.h"
54 STATISTIC(EmittedInsts, "Number of machine instrs printed");
56 char AsmPrinter::ID = 0;
57 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
58 const MCAsmInfo *T, bool VerboseAsm)
59 : MachineFunctionPass(&ID), O(o),
60 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
62 OutContext(*new MCContext()),
63 // FIXME: Pass instprinter to streamer.
64 OutStreamer(*createAsmStreamer(OutContext, O, *T,
65 TM.getTargetData()->isLittleEndian(),
68 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
70 this->VerboseAsm = VerboseAsm;
73 AsmPrinter::~AsmPrinter() {
74 for (gcp_iterator I = GCMetadataPrinters.begin(),
75 E = GCMetadataPrinters.end(); I != E; ++I)
82 /// getFunctionNumber - Return a unique ID for the current function.
84 unsigned AsmPrinter::getFunctionNumber() const {
85 return MF->getFunctionNumber();
88 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
89 return TM.getTargetLowering()->getObjFileLowering();
92 /// getCurrentSection() - Return the current section we are emitting to.
93 const MCSection *AsmPrinter::getCurrentSection() const {
94 return OutStreamer.getCurrentSection();
98 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
100 MachineFunctionPass::getAnalysisUsage(AU);
101 AU.addRequired<GCModuleInfo>();
103 AU.addRequired<MachineLoopInfo>();
106 bool AsmPrinter::doInitialization(Module &M) {
107 // Initialize TargetLoweringObjectFile.
108 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
109 .Initialize(OutContext, TM);
111 Mang = new Mangler(*MAI);
113 // Allow the target to emit any magic that it wants at the start of the file.
114 EmitStartOfAsmFile(M);
116 // Very minimal debug info. It is ignored if we emit actual debug info. If we
117 // don't, this at least helps the user find where a global came from.
118 if (MAI->hasSingleParameterDotFile()) {
120 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
123 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
124 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
125 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
126 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
127 MP->beginAssembly(O, *this, *MAI);
129 if (!M.getModuleInlineAsm().empty())
130 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
131 << M.getModuleInlineAsm()
132 << '\n' << MAI->getCommentString()
133 << " End of file scope inline assembly\n";
135 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137 MMI->AnalyzeModule(M);
138 DW = getAnalysisIfAvailable<DwarfWriter>();
140 DW->BeginModule(&M, MMI, O, this, MAI);
145 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
146 switch ((GlobalValue::LinkageTypes)Linkage) {
147 case GlobalValue::CommonLinkage:
148 case GlobalValue::LinkOnceAnyLinkage:
149 case GlobalValue::LinkOnceODRLinkage:
150 case GlobalValue::WeakAnyLinkage:
151 case GlobalValue::WeakODRLinkage:
152 case GlobalValue::LinkerPrivateLinkage:
153 if (MAI->getWeakDefDirective() != 0) {
155 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
156 // .weak_definition _foo
157 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
158 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
160 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
161 // FIXME: linkonce should be a section attribute, handled by COFF Section
163 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
165 // FIXME: It would be nice to use .linkonce samesize for non-common
170 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
173 case GlobalValue::DLLExportLinkage:
174 case GlobalValue::AppendingLinkage:
175 // FIXME: appending linkage variables should go into a section of
176 // their name or something. For now, just emit them as external.
177 case GlobalValue::ExternalLinkage:
178 // If external or appending, declare as a global symbol.
180 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
182 case GlobalValue::PrivateLinkage:
183 case GlobalValue::InternalLinkage:
186 llvm_unreachable("Unknown linkage type!");
191 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
192 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
193 if (!GV->hasInitializer()) // External globals require no code.
196 // Check to see if this is a special global used by LLVM, if so, emit it.
197 if (EmitSpecialLLVMGlobal(GV))
200 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
201 EmitVisibility(GVSym, GV->getVisibility());
203 if (MAI->hasDotTypeDotSizeDirective())
204 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
206 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
208 const TargetData *TD = TM.getTargetData();
209 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
210 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
212 // Handle common and BSS local symbols (.lcomm).
213 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
214 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
217 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
218 /*PrintType=*/false, GV->getParent());
219 OutStreamer.GetCommentOS() << '\n';
222 // Handle common symbols.
223 if (GVKind.isCommon()) {
225 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
229 // Handle local BSS symbols.
230 if (MAI->hasMachoZeroFillDirective()) {
231 const MCSection *TheSection =
232 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
233 // .zerofill __DATA, __bss, _foo, 400, 5
234 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
238 if (MAI->hasLCOMMDirective()) {
240 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
245 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
247 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
251 const MCSection *TheSection =
252 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
254 // Handle the zerofill directive on darwin, which is a special form of BSS
256 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
258 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
259 // .zerofill __DATA, __common, _foo, 400, 5
260 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
264 OutStreamer.SwitchSection(TheSection);
266 EmitLinkage(GV->getLinkage(), GVSym);
267 EmitAlignment(AlignLog, GV);
270 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
271 /*PrintType=*/false, GV->getParent());
272 OutStreamer.GetCommentOS() << '\n';
274 OutStreamer.EmitLabel(GVSym);
276 EmitGlobalConstant(GV->getInitializer());
278 if (MAI->hasDotTypeDotSizeDirective())
280 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
282 OutStreamer.AddBlankLine();
285 /// EmitFunctionHeader - This method emits the header for the current
287 void AsmPrinter::EmitFunctionHeader() {
288 // Print out constants referenced by the function
291 // Print the 'header' of function.
292 const Function *F = MF->getFunction();
294 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
295 EmitVisibility(CurrentFnSym, F->getVisibility());
297 EmitLinkage(F->getLinkage(), CurrentFnSym);
298 EmitAlignment(MF->getAlignment(), F);
300 if (MAI->hasDotTypeDotSizeDirective())
301 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
304 WriteAsOperand(OutStreamer.GetCommentOS(), F,
305 /*PrintType=*/false, F->getParent());
306 OutStreamer.GetCommentOS() << '\n';
309 // Emit the CurrentFnSym. This is is a virtual function to allow targets to
310 // do their wild and crazy things as required.
311 EmitFunctionEntryLabel();
313 // Add some workaround for linkonce linkage on Cygwin\MinGW.
314 if (MAI->getLinkOnceDirective() != 0 &&
315 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
316 // FIXME: What is this?
317 O << "Lllvm$workaround$fake$stub$" << *CurrentFnSym << ":\n";
319 // Emit pre-function debug and/or EH information.
320 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
321 DW->BeginFunction(MF);
324 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
325 /// function. This can be overridden by targets as required to do custom stuff.
326 void AsmPrinter::EmitFunctionEntryLabel() {
327 OutStreamer.EmitLabel(CurrentFnSym);
331 /// EmitFunctionBody - This method emits the body and trailer for a
333 void AsmPrinter::EmitFunctionBody() {
334 // Emit target-specific gunk before the function body.
335 EmitFunctionBodyStart();
337 // Print out code for the function.
338 bool HasAnyRealCode = false;
339 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
341 // Print a label for the basic block.
342 EmitBasicBlockStart(I);
343 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
345 // Print the assembly for the instruction.
347 HasAnyRealCode = true;
351 // FIXME: Clean up processDebugLoc.
352 processDebugLoc(II, true);
360 // FIXME: Clean up processDebugLoc.
361 processDebugLoc(II, false);
365 // If the function is empty and the object file uses .subsections_via_symbols,
366 // then we need to emit *something* to the function body to prevent the
367 // labels from collapsing together. Just emit a 0 byte.
368 if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)
369 OutStreamer.EmitIntValue(0, 1, 0/*addrspace*/);
371 // Emit target-specific gunk after the function body.
372 EmitFunctionBodyEnd();
374 if (MAI->hasDotTypeDotSizeDirective())
375 O << "\t.size\t" << *CurrentFnSym << ", .-" << *CurrentFnSym << '\n';
377 // Emit post-function debug information.
378 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
381 // Print out jump tables referenced by the function.
386 bool AsmPrinter::doFinalization(Module &M) {
387 // Emit global variables.
388 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
390 EmitGlobalVariable(I);
392 // Emit final debug information.
393 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
396 // If the target wants to know about weak references, print them all.
397 if (MAI->getWeakRefDirective()) {
398 // FIXME: This is not lazy, it would be nice to only print weak references
399 // to stuff that is actually used. Note that doing so would require targets
400 // to notice uses in operands (due to constant exprs etc). This should
401 // happen with the MC stuff eventually.
403 // Print out module-level global variables here.
404 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
406 if (!I->hasExternalWeakLinkage()) continue;
407 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
411 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
412 if (!I->hasExternalWeakLinkage()) continue;
413 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
418 if (MAI->hasSetDirective()) {
419 OutStreamer.AddBlankLine();
420 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
422 MCSymbol *Name = GetGlobalValueSymbol(I);
424 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
425 MCSymbol *Target = GetGlobalValueSymbol(GV);
427 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
428 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
429 else if (I->hasWeakLinkage())
430 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
432 assert(I->hasLocalLinkage() && "Invalid alias linkage");
434 EmitVisibility(Name, I->getVisibility());
436 // Emit the directives as assignments aka .set:
437 OutStreamer.EmitAssignment(Name,
438 MCSymbolRefExpr::Create(Target, OutContext));
442 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
443 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
444 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
445 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
446 MP->finishAssembly(O, *this, *MAI);
448 // If we don't have any trampolines, then we don't require stack memory
449 // to be executable. Some targets have a directive to declare this.
450 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
451 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
452 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
453 OutStreamer.SwitchSection(S);
455 // Allow the target to emit any magic that it wants at the end of the file,
456 // after everything else has gone out.
459 delete Mang; Mang = 0;
462 OutStreamer.Finish();
466 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
468 // Get the function symbol.
469 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
472 LI = &getAnalysis<MachineLoopInfo>();
476 // SectionCPs - Keep track the alignment, constpool entries per Section.
480 SmallVector<unsigned, 4> CPEs;
481 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
485 /// EmitConstantPool - Print to the current output stream assembly
486 /// representations of the constants in the constant pool MCP. This is
487 /// used to print out constants which have been "spilled to memory" by
488 /// the code generator.
490 void AsmPrinter::EmitConstantPool() {
491 const MachineConstantPool *MCP = MF->getConstantPool();
492 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
493 if (CP.empty()) return;
495 // Calculate sections for constant pool entries. We collect entries to go into
496 // the same section together to reduce amount of section switch statements.
497 SmallVector<SectionCPs, 4> CPSections;
498 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
499 const MachineConstantPoolEntry &CPE = CP[i];
500 unsigned Align = CPE.getAlignment();
503 switch (CPE.getRelocationInfo()) {
504 default: llvm_unreachable("Unknown section kind");
505 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
507 Kind = SectionKind::getReadOnlyWithRelLocal();
510 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
511 case 4: Kind = SectionKind::getMergeableConst4(); break;
512 case 8: Kind = SectionKind::getMergeableConst8(); break;
513 case 16: Kind = SectionKind::getMergeableConst16();break;
514 default: Kind = SectionKind::getMergeableConst(); break;
518 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
520 // The number of sections are small, just do a linear search from the
521 // last section to the first.
523 unsigned SecIdx = CPSections.size();
524 while (SecIdx != 0) {
525 if (CPSections[--SecIdx].S == S) {
531 SecIdx = CPSections.size();
532 CPSections.push_back(SectionCPs(S, Align));
535 if (Align > CPSections[SecIdx].Alignment)
536 CPSections[SecIdx].Alignment = Align;
537 CPSections[SecIdx].CPEs.push_back(i);
540 // Now print stuff into the calculated sections.
541 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
542 OutStreamer.SwitchSection(CPSections[i].S);
543 EmitAlignment(Log2_32(CPSections[i].Alignment));
546 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
547 unsigned CPI = CPSections[i].CPEs[j];
548 MachineConstantPoolEntry CPE = CP[CPI];
550 // Emit inter-object padding for alignment.
551 unsigned AlignMask = CPE.getAlignment() - 1;
552 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
553 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
555 const Type *Ty = CPE.getType();
556 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
558 // Emit the label with a comment on it.
560 OutStreamer.GetCommentOS() << "constant pool ";
561 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
562 MF->getFunction()->getParent());
563 OutStreamer.GetCommentOS() << '\n';
565 OutStreamer.EmitLabel(GetCPISymbol(CPI));
567 if (CPE.isMachineConstantPoolEntry())
568 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
570 EmitGlobalConstant(CPE.Val.ConstVal);
575 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
576 /// by the current function to the current output stream.
578 void AsmPrinter::EmitJumpTableInfo() {
579 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
580 if (MJTI == 0) return;
581 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
582 if (JT.empty()) return;
584 // Pick the directive to use to print the jump table entries, and switch to
585 // the appropriate section.
586 const Function *F = MF->getFunction();
587 bool JTInDiffSection = false;
588 if (// In PIC mode, we need to emit the jump table to the same section as the
589 // function body itself, otherwise the label differences won't make sense.
590 // FIXME: Need a better predicate for this: what about custom entries?
591 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
592 // We should also do if the section name is NULL or function is declared
593 // in discardable section
594 // FIXME: this isn't the right predicate, should be based on the MCSection
596 F->isWeakForLinker()) {
597 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
599 // Otherwise, drop it in the readonly section.
600 const MCSection *ReadOnlySection =
601 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
602 OutStreamer.SwitchSection(ReadOnlySection);
603 JTInDiffSection = true;
606 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
608 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
609 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
611 // If this jump table was deleted, ignore it.
612 if (JTBBs.empty()) continue;
614 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
615 // .set directive for each unique entry. This reduces the number of
616 // relocations the assembler will generate for the jump table.
617 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
618 MAI->hasSetDirective()) {
619 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
620 const TargetLowering *TLI = TM.getTargetLowering();
621 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
622 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
623 const MachineBasicBlock *MBB = JTBBs[ii];
624 if (!EmittedSets.insert(MBB)) continue;
626 // .set LJTSet, LBB32-base
628 MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
629 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
630 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
634 // On some targets (e.g. Darwin) we want to emit two consequtive labels
635 // before each jump table. The first label is never referenced, but tells
636 // the assembler and linker the extents of the jump table object. The
637 // second label is actually referenced by the code.
638 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
639 // FIXME: This doesn't have to have any specific name, just any randomly
640 // named and numbered 'l' label would work. Simplify GetJTISymbol.
641 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
643 OutStreamer.EmitLabel(GetJTISymbol(JTI));
645 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
646 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
650 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
652 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
653 const MachineBasicBlock *MBB,
654 unsigned UID) const {
655 const MCExpr *Value = 0;
656 switch (MJTI->getEntryKind()) {
657 case MachineJumpTableInfo::EK_Custom32:
658 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
661 case MachineJumpTableInfo::EK_BlockAddress:
662 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
664 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
666 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
667 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
668 // with a relocation as gp-relative, e.g.:
670 MCSymbol *MBBSym = MBB->getSymbol(OutContext);
671 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
675 case MachineJumpTableInfo::EK_LabelDifference32: {
676 // EK_LabelDifference32 - Each entry is the address of the block minus
677 // the address of the jump table. This is used for PIC jump tables where
678 // gprel32 is not supported. e.g.:
679 // .word LBB123 - LJTI1_2
680 // If the .set directive is supported, this is emitted as:
681 // .set L4_5_set_123, LBB123 - LJTI1_2
682 // .word L4_5_set_123
684 // If we have emitted set directives for the jump table entries, print
685 // them rather than the entries themselves. If we're emitting PIC, then
686 // emit the table entries as differences between two text section labels.
687 if (MAI->hasSetDirective()) {
688 // If we used .set, reference the .set's symbol.
689 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
693 // Otherwise, use the difference as the jump table entry.
694 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
695 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
696 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
701 assert(Value && "Unknown entry kind!");
703 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
704 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
708 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
709 /// special global used by LLVM. If so, emit it and return true, otherwise
710 /// do nothing and return false.
711 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
712 if (GV->getName() == "llvm.used") {
713 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
714 EmitLLVMUsedList(GV->getInitializer());
718 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
719 if (GV->getSection() == "llvm.metadata" ||
720 GV->hasAvailableExternallyLinkage())
723 if (!GV->hasAppendingLinkage()) return false;
725 assert(GV->hasInitializer() && "Not a special LLVM global!");
727 const TargetData *TD = TM.getTargetData();
728 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
729 if (GV->getName() == "llvm.global_ctors") {
730 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
731 EmitAlignment(Align, 0);
732 EmitXXStructorList(GV->getInitializer());
734 if (TM.getRelocationModel() == Reloc::Static &&
735 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
736 StringRef Sym(".constructors_used");
737 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
743 if (GV->getName() == "llvm.global_dtors") {
744 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
745 EmitAlignment(Align, 0);
746 EmitXXStructorList(GV->getInitializer());
748 if (TM.getRelocationModel() == Reloc::Static &&
749 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
750 StringRef Sym(".destructors_used");
751 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
760 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
761 /// global in the specified llvm.used list for which emitUsedDirectiveFor
762 /// is true, as being used with this directive.
763 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
764 // Should be an array of 'i8*'.
765 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
766 if (InitList == 0) return;
768 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
769 const GlobalValue *GV =
770 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
771 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
772 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
777 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
778 /// function pointers, ignoring the init priority.
779 void AsmPrinter::EmitXXStructorList(Constant *List) {
780 // Should be an array of '{ int, void ()* }' structs. The first value is the
781 // init priority, which we ignore.
782 if (!isa<ConstantArray>(List)) return;
783 ConstantArray *InitList = cast<ConstantArray>(List);
784 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
785 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
786 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
788 if (CS->getOperand(1)->isNullValue())
789 return; // Found a null terminator, exit printing.
790 // Emit the function pointer.
791 EmitGlobalConstant(CS->getOperand(1));
795 //===--------------------------------------------------------------------===//
796 // Emission and print routines
799 /// EmitInt8 - Emit a byte directive and value.
801 void AsmPrinter::EmitInt8(int Value) const {
802 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
805 /// EmitInt16 - Emit a short directive and value.
807 void AsmPrinter::EmitInt16(int Value) const {
808 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
811 /// EmitInt32 - Emit a long directive and value.
813 void AsmPrinter::EmitInt32(int Value) const {
814 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
817 /// EmitInt64 - Emit a long long directive and value.
819 void AsmPrinter::EmitInt64(uint64_t Value) const {
820 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
823 //===----------------------------------------------------------------------===//
825 // EmitAlignment - Emit an alignment directive to the specified power of
826 // two boundary. For example, if you pass in 3 here, you will get an 8
827 // byte alignment. If a global value is specified, and if that global has
828 // an explicit alignment requested, it will unconditionally override the
829 // alignment request. However, if ForcedAlignBits is specified, this value
830 // has final say: the ultimate alignment will be the max of ForcedAlignBits
831 // and the alignment computed with NumBits and the global.
835 // if (GV && GV->hasalignment) Align = GV->getalignment();
836 // Align = std::max(Align, ForcedAlignBits);
838 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
839 unsigned ForcedAlignBits,
840 bool UseFillExpr) const {
841 if (GV && GV->getAlignment())
842 NumBits = Log2_32(GV->getAlignment());
843 NumBits = std::max(NumBits, ForcedAlignBits);
845 if (NumBits == 0) return; // No need to emit alignment.
847 unsigned FillValue = 0;
848 if (getCurrentSection()->getKind().isText())
849 FillValue = MAI->getTextAlignFillValue();
851 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
854 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
856 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
857 MCContext &Ctx = AP.OutContext;
859 if (CV->isNullValue() || isa<UndefValue>(CV))
860 return MCConstantExpr::Create(0, Ctx);
862 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
863 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
865 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
866 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
867 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
868 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
870 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
872 llvm_unreachable("Unknown constant value to lower!");
873 return MCConstantExpr::Create(0, Ctx);
876 switch (CE->getOpcode()) {
877 case Instruction::ZExt:
878 case Instruction::SExt:
879 case Instruction::FPTrunc:
880 case Instruction::FPExt:
881 case Instruction::UIToFP:
882 case Instruction::SIToFP:
883 case Instruction::FPToUI:
884 case Instruction::FPToSI:
885 default: llvm_unreachable("FIXME: Don't support this constant cast expr");
886 case Instruction::GetElementPtr: {
887 const TargetData &TD = *AP.TM.getTargetData();
888 // Generate a symbolic expression for the byte address
889 const Constant *PtrVal = CE->getOperand(0);
890 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
891 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
894 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
898 // Truncate/sext the offset to the pointer size.
899 if (TD.getPointerSizeInBits() != 64) {
900 int SExtAmount = 64-TD.getPointerSizeInBits();
901 Offset = (Offset << SExtAmount) >> SExtAmount;
904 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
908 case Instruction::Trunc:
909 // We emit the value and depend on the assembler to truncate the generated
910 // expression properly. This is important for differences between
911 // blockaddress labels. Since the two labels are in the same function, it
912 // is reasonable to treat their delta as a 32-bit value.
914 case Instruction::BitCast:
915 return LowerConstant(CE->getOperand(0), AP);
917 case Instruction::IntToPtr: {
918 const TargetData &TD = *AP.TM.getTargetData();
919 // Handle casts to pointers by changing them into casts to the appropriate
920 // integer type. This promotes constant folding and simplifies this code.
921 Constant *Op = CE->getOperand(0);
922 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
924 return LowerConstant(Op, AP);
927 case Instruction::PtrToInt: {
928 const TargetData &TD = *AP.TM.getTargetData();
929 // Support only foldable casts to/from pointers that can be eliminated by
930 // changing the pointer to the appropriately sized integer type.
931 Constant *Op = CE->getOperand(0);
932 const Type *Ty = CE->getType();
934 const MCExpr *OpExpr = LowerConstant(Op, AP);
936 // We can emit the pointer value into this slot if the slot is an
937 // integer slot equal to the size of the pointer.
938 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
941 // Otherwise the pointer is smaller than the resultant integer, mask off
942 // the high bits so we are sure to get a proper truncation if the input is
944 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
945 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
946 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
949 case Instruction::Add:
950 case Instruction::Sub:
951 case Instruction::And:
952 case Instruction::Or:
953 case Instruction::Xor: {
954 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
955 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
956 switch (CE->getOpcode()) {
957 default: llvm_unreachable("Unknown binary operator constant cast expr");
958 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
959 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
960 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
961 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
962 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
968 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
970 if (AddrSpace != 0 || !CA->isString()) {
971 // Not a string. Print the values in successive locations
972 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
973 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
977 // Otherwise, it can be emitted as .ascii.
978 SmallVector<char, 128> TmpVec;
979 TmpVec.reserve(CA->getNumOperands());
980 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
981 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
983 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
986 static void EmitGlobalConstantVector(const ConstantVector *CV,
987 unsigned AddrSpace, AsmPrinter &AP) {
988 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
989 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
992 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
993 unsigned AddrSpace, AsmPrinter &AP) {
994 // Print the fields in successive locations. Pad to align if needed!
995 const TargetData *TD = AP.TM.getTargetData();
996 unsigned Size = TD->getTypeAllocSize(CS->getType());
997 const StructLayout *Layout = TD->getStructLayout(CS->getType());
998 uint64_t SizeSoFar = 0;
999 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1000 const Constant *Field = CS->getOperand(i);
1002 // Check if padding is needed and insert one or more 0s.
1003 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1004 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1005 - Layout->getElementOffset(i)) - FieldSize;
1006 SizeSoFar += FieldSize + PadSize;
1008 // Now print the actual field value.
1009 AP.EmitGlobalConstant(Field, AddrSpace);
1011 // Insert padding - this may include padding to increase the size of the
1012 // current field up to the ABI size (if the struct is not packed) as well
1013 // as padding to ensure that the next field starts at the right offset.
1014 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1016 assert(SizeSoFar == Layout->getSizeInBytes() &&
1017 "Layout of constant struct may be incorrect!");
1020 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1022 // FP Constants are printed as integer constants to avoid losing
1024 if (CFP->getType()->isDoubleTy()) {
1025 if (AP.VerboseAsm) {
1026 double Val = CFP->getValueAPF().convertToDouble();
1027 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1030 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1031 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1035 if (CFP->getType()->isFloatTy()) {
1036 if (AP.VerboseAsm) {
1037 float Val = CFP->getValueAPF().convertToFloat();
1038 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1040 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1041 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1045 if (CFP->getType()->isX86_FP80Ty()) {
1046 // all long double variants are printed as hex
1047 // api needed to prevent premature destruction
1048 APInt API = CFP->getValueAPF().bitcastToAPInt();
1049 const uint64_t *p = API.getRawData();
1050 if (AP.VerboseAsm) {
1051 // Convert to double so we can print the approximate val as a comment.
1052 APFloat DoubleVal = CFP->getValueAPF();
1054 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1056 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1057 << DoubleVal.convertToDouble() << '\n';
1060 if (AP.TM.getTargetData()->isBigEndian()) {
1061 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1062 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1064 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1065 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1068 // Emit the tail padding for the long double.
1069 const TargetData &TD = *AP.TM.getTargetData();
1070 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1071 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1075 assert(CFP->getType()->isPPC_FP128Ty() &&
1076 "Floating point constant type not handled");
1077 // All long double variants are printed as hex api needed to prevent
1078 // premature destruction.
1079 APInt API = CFP->getValueAPF().bitcastToAPInt();
1080 const uint64_t *p = API.getRawData();
1081 if (AP.TM.getTargetData()->isBigEndian()) {
1082 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1083 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1085 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1086 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1090 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1091 unsigned AddrSpace, AsmPrinter &AP) {
1092 const TargetData *TD = AP.TM.getTargetData();
1093 unsigned BitWidth = CI->getBitWidth();
1094 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1096 // We don't expect assemblers to support integer data directives
1097 // for more than 64 bits, so we emit the data in at most 64-bit
1098 // quantities at a time.
1099 const uint64_t *RawData = CI->getValue().getRawData();
1100 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1101 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1102 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1106 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1107 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1108 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1109 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1110 return OutStreamer.EmitZeros(Size, AddrSpace);
1113 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1114 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1121 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1122 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1125 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1130 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1131 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1133 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1134 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1136 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1137 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1139 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1140 return EmitGlobalConstantVector(V, AddrSpace, *this);
1142 if (isa<ConstantPointerNull>(CV)) {
1143 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1144 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1148 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1149 // thread the streamer with EmitValue.
1150 OutStreamer.EmitValue(LowerConstant(CV, *this),
1151 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1155 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1156 // Target doesn't support this yet!
1157 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1160 /// PrintSpecial - Print information related to the specified machine instr
1161 /// that is independent of the operand, and may be independent of the instr
1162 /// itself. This can be useful for portably encoding the comment character
1163 /// or other bits of target-specific knowledge into the asmstrings. The
1164 /// syntax used is ${:comment}. Targets can override this to add support
1165 /// for their own strange codes.
1166 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1167 if (!strcmp(Code, "private")) {
1168 O << MAI->getPrivateGlobalPrefix();
1169 } else if (!strcmp(Code, "comment")) {
1171 O << MAI->getCommentString();
1172 } else if (!strcmp(Code, "uid")) {
1173 // Comparing the address of MI isn't sufficient, because machineinstrs may
1174 // be allocated to the same address across functions.
1175 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1177 // If this is a new LastFn instruction, bump the counter.
1178 if (LastMI != MI || LastFn != ThisF) {
1186 raw_string_ostream Msg(msg);
1187 Msg << "Unknown special formatter '" << Code
1188 << "' for machine instr: " << *MI;
1189 llvm_report_error(Msg.str());
1193 /// processDebugLoc - Processes the debug information of each machine
1194 /// instruction's DebugLoc.
1195 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1196 bool BeforePrintingInsn) {
1197 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1198 || !DW->ShouldEmitDwarfDebug())
1200 DebugLoc DL = MI->getDebugLoc();
1203 DILocation CurDLT = MF->getDILocation(DL);
1204 if (CurDLT.getScope().isNull())
1207 if (!BeforePrintingInsn) {
1208 // After printing instruction
1210 } else if (CurDLT.getNode() != PrevDLT) {
1211 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1212 CurDLT.getColumnNumber(),
1213 CurDLT.getScope().getNode());
1216 DW->BeginScope(MI, L);
1217 PrevDLT = CurDLT.getNode();
1222 /// printInlineAsm - This method formats and prints the specified machine
1223 /// instruction that is an inline asm.
1224 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1225 unsigned NumOperands = MI->getNumOperands();
1227 // Count the number of register definitions.
1228 unsigned NumDefs = 0;
1229 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1231 assert(NumDefs != NumOperands-1 && "No asm string?");
1233 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1235 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1236 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1240 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1241 // These are useful to see where empty asm's wound up.
1242 if (AsmStr[0] == 0) {
1243 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1244 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1248 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1250 // The variant of the current asmprinter.
1251 int AsmPrinterVariant = MAI->getAssemblerDialect();
1253 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1254 const char *LastEmitted = AsmStr; // One past the last character emitted.
1256 while (*LastEmitted) {
1257 switch (*LastEmitted) {
1259 // Not a special case, emit the string section literally.
1260 const char *LiteralEnd = LastEmitted+1;
1261 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1262 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1264 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1265 O.write(LastEmitted, LiteralEnd-LastEmitted);
1266 LastEmitted = LiteralEnd;
1270 ++LastEmitted; // Consume newline character.
1271 O << '\n'; // Indent code with newline.
1274 ++LastEmitted; // Consume '$' character.
1278 switch (*LastEmitted) {
1279 default: Done = false; break;
1280 case '$': // $$ -> $
1281 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1283 ++LastEmitted; // Consume second '$' character.
1285 case '(': // $( -> same as GCC's { character.
1286 ++LastEmitted; // Consume '(' character.
1287 if (CurVariant != -1) {
1288 llvm_report_error("Nested variants found in inline asm string: '"
1289 + std::string(AsmStr) + "'");
1291 CurVariant = 0; // We're in the first variant now.
1294 ++LastEmitted; // consume '|' character.
1295 if (CurVariant == -1)
1296 O << '|'; // this is gcc's behavior for | outside a variant
1298 ++CurVariant; // We're in the next variant.
1300 case ')': // $) -> same as GCC's } char.
1301 ++LastEmitted; // consume ')' character.
1302 if (CurVariant == -1)
1303 O << '}'; // this is gcc's behavior for } outside a variant
1310 bool HasCurlyBraces = false;
1311 if (*LastEmitted == '{') { // ${variable}
1312 ++LastEmitted; // Consume '{' character.
1313 HasCurlyBraces = true;
1316 // If we have ${:foo}, then this is not a real operand reference, it is a
1317 // "magic" string reference, just like in .td files. Arrange to call
1319 if (HasCurlyBraces && *LastEmitted == ':') {
1321 const char *StrStart = LastEmitted;
1322 const char *StrEnd = strchr(StrStart, '}');
1324 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1325 + std::string(AsmStr) + "'");
1328 std::string Val(StrStart, StrEnd);
1329 PrintSpecial(MI, Val.c_str());
1330 LastEmitted = StrEnd+1;
1334 const char *IDStart = LastEmitted;
1337 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1338 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1339 llvm_report_error("Bad $ operand number in inline asm string: '"
1340 + std::string(AsmStr) + "'");
1342 LastEmitted = IDEnd;
1344 char Modifier[2] = { 0, 0 };
1346 if (HasCurlyBraces) {
1347 // If we have curly braces, check for a modifier character. This
1348 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1349 if (*LastEmitted == ':') {
1350 ++LastEmitted; // Consume ':' character.
1351 if (*LastEmitted == 0) {
1352 llvm_report_error("Bad ${:} expression in inline asm string: '"
1353 + std::string(AsmStr) + "'");
1356 Modifier[0] = *LastEmitted;
1357 ++LastEmitted; // Consume modifier character.
1360 if (*LastEmitted != '}') {
1361 llvm_report_error("Bad ${} expression in inline asm string: '"
1362 + std::string(AsmStr) + "'");
1364 ++LastEmitted; // Consume '}' character.
1367 if ((unsigned)Val >= NumOperands-1) {
1368 llvm_report_error("Invalid $ operand number in inline asm string: '"
1369 + std::string(AsmStr) + "'");
1372 // Okay, we finally have a value number. Ask the target to print this
1374 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1379 // Scan to find the machine operand number for the operand.
1380 for (; Val; --Val) {
1381 if (OpNo >= MI->getNumOperands()) break;
1382 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1383 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1386 if (OpNo >= MI->getNumOperands()) {
1389 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1390 ++OpNo; // Skip over the ID number.
1392 if (Modifier[0] == 'l') // labels are target independent
1393 O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1395 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1396 if ((OpFlags & 7) == 4) {
1397 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1398 Modifier[0] ? Modifier : 0);
1400 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1401 Modifier[0] ? Modifier : 0);
1407 raw_string_ostream Msg(msg);
1408 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1410 llvm_report_error(Msg.str());
1417 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1420 /// printImplicitDef - This method prints the specified machine instruction
1421 /// that is an implicit def.
1422 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1423 if (!VerboseAsm) return;
1424 O.PadToColumn(MAI->getCommentColumn());
1425 O << MAI->getCommentString() << " implicit-def: "
1426 << TRI->getName(MI->getOperand(0).getReg());
1429 void AsmPrinter::printKill(const MachineInstr *MI) const {
1430 if (!VerboseAsm) return;
1431 O.PadToColumn(MAI->getCommentColumn());
1432 O << MAI->getCommentString() << " kill:";
1433 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1434 const MachineOperand &op = MI->getOperand(n);
1435 assert(op.isReg() && "KILL instruction must have only register operands");
1436 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1440 /// printLabel - This method prints a local label used by debug and
1441 /// exception handling tables.
1442 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1443 printLabel(MI->getOperand(0).getImm());
1446 void AsmPrinter::printLabel(unsigned Id) const {
1447 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1450 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1451 /// instruction, using the specified assembler variant. Targets should
1452 /// override this to format as appropriate.
1453 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1454 unsigned AsmVariant, const char *ExtraCode) {
1455 // Target doesn't support this yet!
1459 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1460 unsigned AsmVariant,
1461 const char *ExtraCode) {
1462 // Target doesn't support this yet!
1466 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1467 const char *Suffix) const {
1468 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1471 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1472 const BasicBlock *BB,
1473 const char *Suffix) const {
1474 assert(BB->hasName() &&
1475 "Address of anonymous basic block not supported yet!");
1477 // This code must use the function name itself, and not the function number,
1478 // since it must be possible to generate the label name from within other
1480 SmallString<60> FnName;
1481 Mang->getNameWithPrefix(FnName, F, false);
1483 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1484 SmallString<60> NameResult;
1485 Mang->getNameWithPrefix(NameResult,
1486 StringRef("BA") + Twine((unsigned)FnName.size()) +
1487 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1490 return OutContext.GetOrCreateSymbol(NameResult.str());
1493 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1494 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1495 SmallString<60> Name;
1496 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1497 << getFunctionNumber() << '_' << CPID;
1498 return OutContext.GetOrCreateSymbol(Name.str());
1501 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1502 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1503 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1506 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1507 /// FIXME: privatize to AsmPrinter.
1508 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1509 SmallString<60> Name;
1510 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1511 << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1512 return OutContext.GetOrCreateSymbol(Name.str());
1515 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1517 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1518 SmallString<60> NameStr;
1519 Mang->getNameWithPrefix(NameStr, GV, false);
1520 return OutContext.GetOrCreateSymbol(NameStr.str());
1523 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1524 /// global value name as its base, with the specified suffix, and where the
1525 /// symbol is forced to have private linkage if ForcePrivate is true.
1526 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1528 bool ForcePrivate) const {
1529 SmallString<60> NameStr;
1530 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1531 NameStr.append(Suffix.begin(), Suffix.end());
1532 return OutContext.GetOrCreateSymbol(NameStr.str());
1535 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1537 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1538 SmallString<60> NameStr;
1539 Mang->getNameWithPrefix(NameStr, Sym);
1540 return OutContext.GetOrCreateSymbol(NameStr.str());
1545 /// PrintParentLoopComment - Print comments about parent loops of this one.
1546 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1547 unsigned FunctionNumber) {
1548 if (Loop == 0) return;
1549 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1550 OS.indent(Loop->getLoopDepth()*2)
1551 << "Parent Loop BB" << FunctionNumber << "_"
1552 << Loop->getHeader()->getNumber()
1553 << " Depth=" << Loop->getLoopDepth() << '\n';
1557 /// PrintChildLoopComment - Print comments about child loops within
1558 /// the loop for this basic block, with nesting.
1559 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1560 unsigned FunctionNumber) {
1561 // Add child loop information
1562 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1563 OS.indent((*CL)->getLoopDepth()*2)
1564 << "Child Loop BB" << FunctionNumber << "_"
1565 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1567 PrintChildLoopComment(OS, *CL, FunctionNumber);
1571 /// EmitComments - Pretty-print comments for basic blocks.
1572 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1573 const MachineLoopInfo *LI,
1574 const AsmPrinter &AP) {
1575 // Add loop depth information
1576 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1577 if (Loop == 0) return;
1579 MachineBasicBlock *Header = Loop->getHeader();
1580 assert(Header && "No header for loop");
1582 // If this block is not a loop header, just print out what is the loop header
1584 if (Header != &MBB) {
1585 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1586 Twine(AP.getFunctionNumber())+"_" +
1587 Twine(Loop->getHeader()->getNumber())+
1588 " Depth="+Twine(Loop->getLoopDepth()));
1592 // Otherwise, it is a loop header. Print out information about child and
1594 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1596 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1599 OS.indent(Loop->getLoopDepth()*2-2);
1604 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1606 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1610 /// EmitBasicBlockStart - This method prints the label for the specified
1611 /// MachineBasicBlock, an alignment (if present) and a comment describing
1612 /// it if appropriate.
1613 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1614 // Emit an alignment directive for this block, if needed.
1615 if (unsigned Align = MBB->getAlignment())
1616 EmitAlignment(Log2_32(Align));
1618 // If the block has its address taken, emit a special label to satisfy
1619 // references to the block. This is done so that we don't need to
1620 // remember the number of this label, and so that we can make
1621 // forward references to labels without knowing what their numbers
1623 if (MBB->hasAddressTaken()) {
1624 const BasicBlock *BB = MBB->getBasicBlock();
1626 OutStreamer.AddComment("Address Taken");
1627 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1630 // Print the main label for the block.
1631 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1633 // NOTE: Want this comment at start of line.
1634 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1635 if (const BasicBlock *BB = MBB->getBasicBlock())
1637 OutStreamer.AddComment("%" + BB->getName());
1639 PrintBasicBlockLoopComments(*MBB, LI, *this);
1640 OutStreamer.AddBlankLine();
1644 if (const BasicBlock *BB = MBB->getBasicBlock())
1646 OutStreamer.AddComment("%" + BB->getName());
1647 PrintBasicBlockLoopComments(*MBB, LI, *this);
1650 OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1654 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1655 MCSymbolAttr Attr = MCSA_Invalid;
1657 switch (Visibility) {
1659 case GlobalValue::HiddenVisibility:
1660 Attr = MAI->getHiddenVisibilityAttr();
1662 case GlobalValue::ProtectedVisibility:
1663 Attr = MAI->getProtectedVisibilityAttr();
1667 if (Attr != MCSA_Invalid)
1668 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1671 void AsmPrinter::printOffset(int64_t Offset) const {
1674 else if (Offset < 0)
1678 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1679 if (!S->usesMetadata())
1682 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1683 if (GCPI != GCMetadataPrinters.end())
1684 return GCPI->second;
1686 const char *Name = S->getName().c_str();
1688 for (GCMetadataPrinterRegistry::iterator
1689 I = GCMetadataPrinterRegistry::begin(),
1690 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1691 if (strcmp(Name, I->getName()) == 0) {
1692 GCMetadataPrinter *GMP = I->instantiate();
1694 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1698 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1702 /// EmitComments - Pretty-print comments for instructions
1703 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1707 bool Newline = false;
1709 if (!MI.getDebugLoc().isUnknown()) {
1710 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1712 // Print source line info.
1713 O.PadToColumn(MAI->getCommentColumn());
1714 O << MAI->getCommentString() << ' ';
1715 DIScope Scope = DLT.getScope();
1716 // Omit the directory, because it's likely to be long and uninteresting.
1717 if (!Scope.isNull())
1718 O << Scope.getFilename();
1721 O << ':' << DLT.getLineNumber();
1722 if (DLT.getColumnNumber() != 0)
1723 O << ':' << DLT.getColumnNumber();
1727 // Check for spills and reloads
1730 const MachineFrameInfo *FrameInfo =
1731 MI.getParent()->getParent()->getFrameInfo();
1733 // We assume a single instruction only has a spill or reload, not
1735 const MachineMemOperand *MMO;
1736 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1737 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1738 MMO = *MI.memoperands_begin();
1739 if (Newline) O << '\n';
1740 O.PadToColumn(MAI->getCommentColumn());
1741 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1745 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1746 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1747 if (Newline) O << '\n';
1748 O.PadToColumn(MAI->getCommentColumn());
1749 O << MAI->getCommentString() << ' '
1750 << MMO->getSize() << "-byte Folded Reload";
1754 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1755 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1756 MMO = *MI.memoperands_begin();
1757 if (Newline) O << '\n';
1758 O.PadToColumn(MAI->getCommentColumn());
1759 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1763 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1764 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1765 if (Newline) O << '\n';
1766 O.PadToColumn(MAI->getCommentColumn());
1767 O << MAI->getCommentString() << ' '
1768 << MMO->getSize() << "-byte Folded Spill";
1773 // Check for spill-induced copies
1774 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1775 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1776 SrcSubIdx, DstSubIdx)) {
1777 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1778 if (Newline) O << '\n';
1779 O.PadToColumn(MAI->getCommentColumn());
1780 O << MAI->getCommentString() << " Reload Reuse";