1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/Mangler.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallString.h"
50 static cl::opt<cl::boolOrDefault>
51 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52 cl::init(cl::BOU_UNSET));
54 static bool getVerboseAsm(bool VDef) {
57 case cl::BOU_UNSET: return VDef;
58 case cl::BOU_TRUE: return true;
59 case cl::BOU_FALSE: return false;
63 char AsmPrinter::ID = 0;
64 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
65 const MCAsmInfo *T, bool VDef)
66 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
67 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
69 OutContext(*new MCContext()),
70 // FIXME: Pass instprinter to streamer.
71 OutStreamer(*createAsmStreamer(OutContext, O, *T,
72 TM.getTargetData()->isLittleEndian(),
73 getVerboseAsm(VDef), 0)),
75 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
77 VerboseAsm = getVerboseAsm(VDef);
80 AsmPrinter::~AsmPrinter() {
81 for (gcp_iterator I = GCMetadataPrinters.begin(),
82 E = GCMetadataPrinters.end(); I != E; ++I)
89 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
90 return TM.getTargetLowering()->getObjFileLowering();
93 /// getCurrentSection() - Return the current section we are emitting to.
94 const MCSection *AsmPrinter::getCurrentSection() const {
95 return OutStreamer.getCurrentSection();
99 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.setPreservesAll();
101 MachineFunctionPass::getAnalysisUsage(AU);
102 AU.addRequired<GCModuleInfo>();
104 AU.addRequired<MachineLoopInfo>();
107 bool AsmPrinter::doInitialization(Module &M) {
108 // Initialize TargetLoweringObjectFile.
109 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
110 .Initialize(OutContext, TM);
112 Mang = new Mangler(*MAI);
114 // Allow the target to emit any magic that it wants at the start of the file.
115 EmitStartOfAsmFile(M);
117 if (MAI->hasSingleParameterDotFile()) {
118 // Very minimal debug info. It is ignored if we emit actual
119 // debug info. If we don't, this at least helps the user find where
120 // a function came from.
121 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
124 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
125 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
126 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
127 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
128 MP->beginAssembly(O, *this, *MAI);
130 if (!M.getModuleInlineAsm().empty())
131 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
132 << M.getModuleInlineAsm()
133 << '\n' << MAI->getCommentString()
134 << " End of file scope inline assembly\n";
136 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
138 MMI->AnalyzeModule(M);
139 DW = getAnalysisIfAvailable<DwarfWriter>();
141 DW->BeginModule(&M, MMI, O, this, MAI);
146 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
147 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
148 if (!GV->hasInitializer()) // External globals require no code.
151 // Check to see if this is a special global used by LLVM, if so, emit it.
152 if (EmitSpecialLLVMGlobal(GV))
155 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
156 printVisibility(GVSym, GV->getVisibility());
158 if (MAI->hasDotTypeDotSizeDirective()) {
159 O << "\t.type\t" << *GVSym;
160 if (MAI->getCommentString()[0] != '@')
166 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
168 const TargetData *TD = TM.getTargetData();
169 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
170 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
172 // Handle common and BSS local symbols (.lcomm).
173 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
174 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
177 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
178 /*PrintType=*/false, GV->getParent());
179 OutStreamer.GetCommentOS() << '\n';
182 // Handle common symbols.
183 if (GVKind.isCommon()) {
185 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
189 // Handle local BSS symbols.
190 if (MAI->hasMachoZeroFillDirective()) {
191 const MCSection *TheSection =
192 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
193 // .zerofill __DATA, __bss, _foo, 400, 5
194 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
198 if (const char *LComm = MAI->getLCOMMDirective()) {
200 O << LComm << *GVSym << ',' << Size << '\n';
205 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Local);
207 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
211 const MCSection *TheSection =
212 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
214 // Handle the zerofill directive on darwin, which is a special form of BSS
216 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
218 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
219 // .zerofill __DATA, __common, _foo, 400, 5
220 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
224 OutStreamer.SwitchSection(TheSection);
226 // TODO: Factor into an 'emit linkage' thing that is shared with function
228 switch (GV->getLinkage()) {
229 case GlobalValue::CommonLinkage:
230 case GlobalValue::LinkOnceAnyLinkage:
231 case GlobalValue::LinkOnceODRLinkage:
232 case GlobalValue::WeakAnyLinkage:
233 case GlobalValue::WeakODRLinkage:
234 case GlobalValue::LinkerPrivateLinkage:
235 if (MAI->getWeakDefDirective() != 0) {
237 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
238 // .weak_definition _foo
239 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
240 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
242 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
243 // .linkonce same_size
247 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
250 case GlobalValue::DLLExportLinkage:
251 case GlobalValue::AppendingLinkage:
252 // FIXME: appending linkage variables should go into a section of
253 // their name or something. For now, just emit them as external.
254 case GlobalValue::ExternalLinkage:
255 // If external or appending, declare as a global symbol.
257 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
259 case GlobalValue::PrivateLinkage:
260 case GlobalValue::InternalLinkage:
263 llvm_unreachable("Unknown linkage type!");
266 EmitAlignment(AlignLog, GV);
268 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
269 /*PrintType=*/false, GV->getParent());
270 OutStreamer.GetCommentOS() << '\n';
272 OutStreamer.EmitLabel(GVSym);
274 EmitGlobalConstant(GV->getInitializer());
276 if (MAI->hasDotTypeDotSizeDirective())
277 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
279 OutStreamer.AddBlankLine();
283 bool AsmPrinter::doFinalization(Module &M) {
284 // Emit global variables.
285 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
287 EmitGlobalVariable(I);
289 // Emit final debug information.
290 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
293 // If the target wants to know about weak references, print them all.
294 if (MAI->getWeakRefDirective()) {
295 // FIXME: This is not lazy, it would be nice to only print weak references
296 // to stuff that is actually used. Note that doing so would require targets
297 // to notice uses in operands (due to constant exprs etc). This should
298 // happen with the MC stuff eventually.
300 // Print out module-level global variables here.
301 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
303 if (!I->hasExternalWeakLinkage()) continue;
304 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
305 MCStreamer::WeakReference);
308 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
309 if (!I->hasExternalWeakLinkage()) continue;
310 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
311 MCStreamer::WeakReference);
315 if (MAI->getSetDirective()) {
316 OutStreamer.AddBlankLine();
317 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
319 MCSymbol *Name = GetGlobalValueSymbol(I);
321 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
322 MCSymbol *Target = GetGlobalValueSymbol(GV);
324 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
325 OutStreamer.EmitSymbolAttribute(Name, MCStreamer::Global);
326 else if (I->hasWeakLinkage())
327 OutStreamer.EmitSymbolAttribute(Name, MCStreamer::WeakReference);
329 assert(I->hasLocalLinkage() && "Invalid alias linkage");
331 printVisibility(Name, I->getVisibility());
333 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
337 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
338 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
339 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
340 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
341 MP->finishAssembly(O, *this, *MAI);
343 // If we don't have any trampolines, then we don't require stack memory
344 // to be executable. Some targets have a directive to declare this.
345 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
346 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
347 // FIXME: This is actually a section switch on linux/x86 and systemz, use
349 if (MAI->getNonexecutableStackDirective())
350 O << MAI->getNonexecutableStackDirective() << '\n';
353 // Allow the target to emit any magic that it wants at the end of the file,
354 // after everything else has gone out.
357 delete Mang; Mang = 0;
360 OutStreamer.Finish();
364 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
365 // Get the function symbol.
366 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
367 IncrementFunctionNumber();
370 LI = &getAnalysis<MachineLoopInfo>();
374 // SectionCPs - Keep track the alignment, constpool entries per Section.
378 SmallVector<unsigned, 4> CPEs;
379 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
383 /// EmitConstantPool - Print to the current output stream assembly
384 /// representations of the constants in the constant pool MCP. This is
385 /// used to print out constants which have been "spilled to memory" by
386 /// the code generator.
388 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
389 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
390 if (CP.empty()) return;
392 // Calculate sections for constant pool entries. We collect entries to go into
393 // the same section together to reduce amount of section switch statements.
394 SmallVector<SectionCPs, 4> CPSections;
395 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
396 const MachineConstantPoolEntry &CPE = CP[i];
397 unsigned Align = CPE.getAlignment();
400 switch (CPE.getRelocationInfo()) {
401 default: llvm_unreachable("Unknown section kind");
402 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
404 Kind = SectionKind::getReadOnlyWithRelLocal();
407 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
408 case 4: Kind = SectionKind::getMergeableConst4(); break;
409 case 8: Kind = SectionKind::getMergeableConst8(); break;
410 case 16: Kind = SectionKind::getMergeableConst16();break;
411 default: Kind = SectionKind::getMergeableConst(); break;
415 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
417 // The number of sections are small, just do a linear search from the
418 // last section to the first.
420 unsigned SecIdx = CPSections.size();
421 while (SecIdx != 0) {
422 if (CPSections[--SecIdx].S == S) {
428 SecIdx = CPSections.size();
429 CPSections.push_back(SectionCPs(S, Align));
432 if (Align > CPSections[SecIdx].Alignment)
433 CPSections[SecIdx].Alignment = Align;
434 CPSections[SecIdx].CPEs.push_back(i);
437 // Now print stuff into the calculated sections.
438 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
439 OutStreamer.SwitchSection(CPSections[i].S);
440 EmitAlignment(Log2_32(CPSections[i].Alignment));
443 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
444 unsigned CPI = CPSections[i].CPEs[j];
445 MachineConstantPoolEntry CPE = CP[CPI];
447 // Emit inter-object padding for alignment.
448 unsigned AlignMask = CPE.getAlignment() - 1;
449 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
450 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
452 const Type *Ty = CPE.getType();
453 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
455 // Emit the label with a comment on it.
457 OutStreamer.GetCommentOS() << "constant pool ";
458 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
459 MF->getFunction()->getParent());
460 OutStreamer.GetCommentOS() << '\n';
462 OutStreamer.EmitLabel(GetCPISymbol(CPI));
464 if (CPE.isMachineConstantPoolEntry())
465 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
467 EmitGlobalConstant(CPE.Val.ConstVal);
472 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
473 /// by the current function to the current output stream.
475 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
476 MachineFunction &MF) {
477 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
478 if (JT.empty()) return;
480 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
482 // Pick the directive to use to print the jump table entries, and switch to
483 // the appropriate section.
484 TargetLowering *LoweringInfo = TM.getTargetLowering();
486 const Function *F = MF.getFunction();
487 bool JTInDiffSection = false;
488 if (F->isWeakForLinker() ||
489 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
490 // In PIC mode, we need to emit the jump table to the same section as the
491 // function body itself, otherwise the label differences won't make sense.
492 // We should also do if the section name is NULL or function is declared in
493 // discardable section.
494 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
497 // Otherwise, drop it in the readonly section.
498 const MCSection *ReadOnlySection =
499 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
500 OutStreamer.SwitchSection(ReadOnlySection);
501 JTInDiffSection = true;
504 EmitAlignment(Log2_32(MJTI->getAlignment()));
506 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
507 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
509 // If this jump table was deleted, ignore it.
510 if (JTBBs.empty()) continue;
512 // For PIC codegen, if possible we want to use the SetDirective to reduce
513 // the number of relocations the assembler will generate for the jump table.
514 // Set directives are all printed before the jump table itself.
515 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
516 if (MAI->getSetDirective() && IsPic)
517 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
518 if (EmittedSets.insert(JTBBs[ii]))
519 printPICJumpTableSetLabel(i, JTBBs[ii]);
521 // On some targets (e.g. Darwin) we want to emit two consequtive labels
522 // before each jump table. The first label is never referenced, but tells
523 // the assembler and linker the extents of the jump table object. The
524 // second label is actually referenced by the code.
525 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
526 OutStreamer.EmitLabel(GetJTISymbol(i, true));
528 OutStreamer.EmitLabel(GetJTISymbol(i));
530 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
531 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
537 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
538 const MachineBasicBlock *MBB,
539 unsigned uid) const {
540 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
542 // Use JumpTableDirective otherwise honor the entry size from the jump table
544 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
545 bool HadJTEntryDirective = JTEntryDirective != NULL;
546 if (!HadJTEntryDirective) {
547 JTEntryDirective = MJTI->getEntrySize() == 4 ?
548 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
551 O << JTEntryDirective << ' ';
553 // If we have emitted set directives for the jump table entries, print
554 // them rather than the entries themselves. If we're emitting PIC, then
555 // emit the table entries as differences between two text section labels.
556 // If we're emitting non-PIC code, then emit the entries as direct
557 // references to the target basic blocks.
559 O << *GetMBBSymbol(MBB->getNumber());
560 } else if (MAI->getSetDirective()) {
561 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
562 << '_' << uid << "_set_" << MBB->getNumber();
564 O << *GetMBBSymbol(MBB->getNumber());
565 // If the arch uses custom Jump Table directives, don't calc relative to
567 if (!HadJTEntryDirective)
568 O << '-' << *GetJTISymbol(uid);
573 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
574 /// special global used by LLVM. If so, emit it and return true, otherwise
575 /// do nothing and return false.
576 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
577 if (GV->getName() == "llvm.used") {
578 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
579 EmitLLVMUsedList(GV->getInitializer());
583 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
584 if (GV->getSection() == "llvm.metadata" ||
585 GV->hasAvailableExternallyLinkage())
588 if (!GV->hasAppendingLinkage()) return false;
590 assert(GV->hasInitializer() && "Not a special LLVM global!");
592 const TargetData *TD = TM.getTargetData();
593 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
594 if (GV->getName() == "llvm.global_ctors") {
595 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
596 EmitAlignment(Align, 0);
597 EmitXXStructorList(GV->getInitializer());
599 if (TM.getRelocationModel() == Reloc::Static &&
600 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
601 StringRef Sym(".constructors_used");
602 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
603 MCStreamer::Reference);
608 if (GV->getName() == "llvm.global_dtors") {
609 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
610 EmitAlignment(Align, 0);
611 EmitXXStructorList(GV->getInitializer());
613 if (TM.getRelocationModel() == Reloc::Static &&
614 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
615 StringRef Sym(".destructors_used");
616 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
617 MCStreamer::Reference);
625 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
626 /// global in the specified llvm.used list for which emitUsedDirectiveFor
627 /// is true, as being used with this directive.
628 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
629 // Should be an array of 'i8*'.
630 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
631 if (InitList == 0) return;
633 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
634 const GlobalValue *GV =
635 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
636 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
637 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
638 MCStreamer::NoDeadStrip);
642 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
643 /// function pointers, ignoring the init priority.
644 void AsmPrinter::EmitXXStructorList(Constant *List) {
645 // Should be an array of '{ int, void ()* }' structs. The first value is the
646 // init priority, which we ignore.
647 if (!isa<ConstantArray>(List)) return;
648 ConstantArray *InitList = cast<ConstantArray>(List);
649 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
650 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
651 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
653 if (CS->getOperand(1)->isNullValue())
654 return; // Found a null terminator, exit printing.
655 // Emit the function pointer.
656 EmitGlobalConstant(CS->getOperand(1));
660 //===--------------------------------------------------------------------===//
661 // Emission and print routines
664 /// EmitInt8 - Emit a byte directive and value.
666 void AsmPrinter::EmitInt8(int Value) const {
667 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
670 /// EmitInt16 - Emit a short directive and value.
672 void AsmPrinter::EmitInt16(int Value) const {
673 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
676 /// EmitInt32 - Emit a long directive and value.
678 void AsmPrinter::EmitInt32(int Value) const {
679 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
682 /// EmitInt64 - Emit a long long directive and value.
684 void AsmPrinter::EmitInt64(uint64_t Value) const {
685 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
689 /// toOctal - Convert the low order bits of X into an octal digit.
691 static inline char toOctal(int X) {
695 /// printStringChar - Print a char, escaped if necessary.
697 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
700 } else if (C == '\\') {
702 } else if (isprint((unsigned char)C)) {
706 case '\b': O << "\\b"; break;
707 case '\f': O << "\\f"; break;
708 case '\n': O << "\\n"; break;
709 case '\r': O << "\\r"; break;
710 case '\t': O << "\\t"; break;
713 O << toOctal(C >> 6);
714 O << toOctal(C >> 3);
715 O << toOctal(C >> 0);
721 /// EmitFile - Emit a .file directive.
722 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
723 O << "\t.file\t" << Number << " \"";
724 for (unsigned i = 0, N = Name.size(); i < N; ++i)
725 printStringChar(O, Name[i]);
730 //===----------------------------------------------------------------------===//
732 // EmitAlignment - Emit an alignment directive to the specified power of
733 // two boundary. For example, if you pass in 3 here, you will get an 8
734 // byte alignment. If a global value is specified, and if that global has
735 // an explicit alignment requested, it will unconditionally override the
736 // alignment request. However, if ForcedAlignBits is specified, this value
737 // has final say: the ultimate alignment will be the max of ForcedAlignBits
738 // and the alignment computed with NumBits and the global.
742 // if (GV && GV->hasalignment) Align = GV->getalignment();
743 // Align = std::max(Align, ForcedAlignBits);
745 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
746 unsigned ForcedAlignBits,
747 bool UseFillExpr) const {
748 if (GV && GV->getAlignment())
749 NumBits = Log2_32(GV->getAlignment());
750 NumBits = std::max(NumBits, ForcedAlignBits);
752 if (NumBits == 0) return; // No need to emit alignment.
754 unsigned FillValue = 0;
755 if (getCurrentSection()->getKind().isText())
756 FillValue = MAI->getTextAlignFillValue();
758 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
761 // Print out the specified constant, without a storage class. Only the
762 // constants valid in constant expressions can occur here.
763 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
764 if (CV->isNullValue() || isa<UndefValue>(CV)) {
769 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
770 O << CI->getZExtValue();
774 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
775 // This is a constant address for a global variable or function. Use the
776 // name of the variable or function as the address value.
777 O << *GetGlobalValueSymbol(GV);
781 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
782 O << *GetBlockAddressSymbol(BA);
786 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
788 llvm_unreachable("Unknown constant value!");
793 switch (CE->getOpcode()) {
794 case Instruction::ZExt:
795 case Instruction::SExt:
796 case Instruction::FPTrunc:
797 case Instruction::FPExt:
798 case Instruction::UIToFP:
799 case Instruction::SIToFP:
800 case Instruction::FPToUI:
801 case Instruction::FPToSI:
803 llvm_unreachable("FIXME: Don't support this constant cast expr");
804 case Instruction::GetElementPtr: {
805 // generate a symbolic expression for the byte address
806 const TargetData *TD = TM.getTargetData();
807 const Constant *ptrVal = CE->getOperand(0);
808 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
809 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
812 return EmitConstantValueOnly(ptrVal);
814 // Truncate/sext the offset to the pointer size.
815 if (TD->getPointerSizeInBits() != 64) {
816 int SExtAmount = 64-TD->getPointerSizeInBits();
817 Offset = (Offset << SExtAmount) >> SExtAmount;
822 EmitConstantValueOnly(ptrVal);
824 O << ") + " << Offset;
826 O << ") - " << -Offset;
829 case Instruction::BitCast:
830 return EmitConstantValueOnly(CE->getOperand(0));
832 case Instruction::IntToPtr: {
833 // Handle casts to pointers by changing them into casts to the appropriate
834 // integer type. This promotes constant folding and simplifies this code.
835 const TargetData *TD = TM.getTargetData();
836 Constant *Op = CE->getOperand(0);
837 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
839 return EmitConstantValueOnly(Op);
842 case Instruction::PtrToInt: {
843 // Support only foldable casts to/from pointers that can be eliminated by
844 // changing the pointer to the appropriately sized integer type.
845 Constant *Op = CE->getOperand(0);
846 const Type *Ty = CE->getType();
847 const TargetData *TD = TM.getTargetData();
849 // We can emit the pointer value into this slot if the slot is an
850 // integer slot greater or equal to the size of the pointer.
851 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
852 return EmitConstantValueOnly(Op);
855 EmitConstantValueOnly(Op);
857 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
860 ptrMask.toStringUnsigned(S);
861 O << ") & " << S.str() << ')';
865 case Instruction::Trunc:
866 // We emit the value and depend on the assembler to truncate the generated
867 // expression properly. This is important for differences between
868 // blockaddress labels. Since the two labels are in the same function, it
869 // is reasonable to treat their delta as a 32-bit value.
870 return EmitConstantValueOnly(CE->getOperand(0));
872 case Instruction::Add:
873 case Instruction::Sub:
874 case Instruction::And:
875 case Instruction::Or:
876 case Instruction::Xor:
878 EmitConstantValueOnly(CE->getOperand(0));
880 switch (CE->getOpcode()) {
881 case Instruction::Add:
884 case Instruction::Sub:
887 case Instruction::And:
890 case Instruction::Or:
893 case Instruction::Xor:
900 EmitConstantValueOnly(CE->getOperand(1));
906 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
908 if (AddrSpace != 0 || !CA->isString()) {
909 // Not a string. Print the values in successive locations
910 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
911 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
915 // Otherwise, it can be emitted as .ascii.
916 SmallVector<char, 128> TmpVec;
917 TmpVec.reserve(CA->getNumOperands());
918 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
919 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
921 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
924 static void EmitGlobalConstantVector(const ConstantVector *CV,
925 unsigned AddrSpace, AsmPrinter &AP) {
926 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
927 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
930 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
931 unsigned AddrSpace, AsmPrinter &AP) {
932 // Print the fields in successive locations. Pad to align if needed!
933 const TargetData *TD = AP.TM.getTargetData();
934 unsigned Size = TD->getTypeAllocSize(CS->getType());
935 const StructLayout *Layout = TD->getStructLayout(CS->getType());
936 uint64_t SizeSoFar = 0;
937 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
938 const Constant *Field = CS->getOperand(i);
940 // Check if padding is needed and insert one or more 0s.
941 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
942 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
943 - Layout->getElementOffset(i)) - FieldSize;
944 SizeSoFar += FieldSize + PadSize;
946 // Now print the actual field value.
947 AP.EmitGlobalConstant(Field, AddrSpace);
949 // Insert padding - this may include padding to increase the size of the
950 // current field up to the ABI size (if the struct is not packed) as well
951 // as padding to ensure that the next field starts at the right offset.
952 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
954 assert(SizeSoFar == Layout->getSizeInBytes() &&
955 "Layout of constant struct may be incorrect!");
958 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
960 // FP Constants are printed as integer constants to avoid losing
962 if (CFP->getType()->isDoubleTy()) {
964 double Val = CFP->getValueAPF().convertToDouble();
965 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
968 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
969 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
973 if (CFP->getType()->isFloatTy()) {
975 float Val = CFP->getValueAPF().convertToFloat();
976 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
978 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
979 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
983 if (CFP->getType()->isX86_FP80Ty()) {
984 // all long double variants are printed as hex
985 // api needed to prevent premature destruction
986 APInt API = CFP->getValueAPF().bitcastToAPInt();
987 const uint64_t *p = API.getRawData();
989 // Convert to double so we can print the approximate val as a comment.
990 APFloat DoubleVal = CFP->getValueAPF();
992 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
994 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
995 << DoubleVal.convertToDouble() << '\n';
998 if (AP.TM.getTargetData()->isBigEndian()) {
999 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1000 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1002 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1003 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1006 // Emit the tail padding for the long double.
1007 const TargetData &TD = *AP.TM.getTargetData();
1008 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1009 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1013 assert(CFP->getType()->isPPC_FP128Ty() &&
1014 "Floating point constant type not handled");
1015 // All long double variants are printed as hex api needed to prevent
1016 // premature destruction.
1017 APInt API = CFP->getValueAPF().bitcastToAPInt();
1018 const uint64_t *p = API.getRawData();
1019 if (AP.TM.getTargetData()->isBigEndian()) {
1020 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1021 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1023 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1024 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1028 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1029 unsigned AddrSpace, AsmPrinter &AP) {
1030 const TargetData *TD = AP.TM.getTargetData();
1031 unsigned BitWidth = CI->getBitWidth();
1032 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1034 // We don't expect assemblers to support integer data directives
1035 // for more than 64 bits, so we emit the data in at most 64-bit
1036 // quantities at a time.
1037 const uint64_t *RawData = CI->getValue().getRawData();
1038 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1039 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1040 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1044 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1045 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1046 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1047 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1048 return OutStreamer.EmitZeros(Size, AddrSpace);
1051 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1052 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1059 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1060 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1063 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1068 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1069 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1071 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1072 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1074 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1075 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1077 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1078 return EmitGlobalConstantVector(V, AddrSpace, *this);
1080 if (isa<ConstantPointerNull>(CV)) {
1081 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1082 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1086 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit
1087 // the expression value.
1088 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) {
1090 case 1: O << MAI->getData8bitsDirective(AddrSpace); break;
1091 case 2: O << MAI->getData16bitsDirective(AddrSpace); break;
1092 case 4: O << MAI->getData32bitsDirective(AddrSpace); break;
1094 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) {
1100 llvm_unreachable("Target cannot handle given data directive width!");
1104 EmitConstantValueOnly(CV);
1108 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1109 // Target doesn't support this yet!
1110 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1113 /// PrintSpecial - Print information related to the specified machine instr
1114 /// that is independent of the operand, and may be independent of the instr
1115 /// itself. This can be useful for portably encoding the comment character
1116 /// or other bits of target-specific knowledge into the asmstrings. The
1117 /// syntax used is ${:comment}. Targets can override this to add support
1118 /// for their own strange codes.
1119 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1120 if (!strcmp(Code, "private")) {
1121 O << MAI->getPrivateGlobalPrefix();
1122 } else if (!strcmp(Code, "comment")) {
1124 O << MAI->getCommentString();
1125 } else if (!strcmp(Code, "uid")) {
1126 // Comparing the address of MI isn't sufficient, because machineinstrs may
1127 // be allocated to the same address across functions.
1128 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1130 // If this is a new LastFn instruction, bump the counter.
1131 if (LastMI != MI || LastFn != ThisF) {
1139 raw_string_ostream Msg(msg);
1140 Msg << "Unknown special formatter '" << Code
1141 << "' for machine instr: " << *MI;
1142 llvm_report_error(Msg.str());
1146 /// processDebugLoc - Processes the debug information of each machine
1147 /// instruction's DebugLoc.
1148 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1149 bool BeforePrintingInsn) {
1150 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1151 || !DW->ShouldEmitDwarfDebug())
1153 DebugLoc DL = MI->getDebugLoc();
1156 DILocation CurDLT = MF->getDILocation(DL);
1157 if (CurDLT.getScope().isNull())
1160 if (!BeforePrintingInsn) {
1161 // After printing instruction
1163 } else if (CurDLT.getNode() != PrevDLT) {
1164 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1165 CurDLT.getColumnNumber(),
1166 CurDLT.getScope().getNode());
1169 DW->BeginScope(MI, L);
1170 PrevDLT = CurDLT.getNode();
1175 /// printInlineAsm - This method formats and prints the specified machine
1176 /// instruction that is an inline asm.
1177 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1178 unsigned NumOperands = MI->getNumOperands();
1180 // Count the number of register definitions.
1181 unsigned NumDefs = 0;
1182 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1184 assert(NumDefs != NumOperands-1 && "No asm string?");
1186 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1188 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1189 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1193 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1194 // These are useful to see where empty asm's wound up.
1195 if (AsmStr[0] == 0) {
1196 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1197 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1201 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1203 // The variant of the current asmprinter.
1204 int AsmPrinterVariant = MAI->getAssemblerDialect();
1206 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1207 const char *LastEmitted = AsmStr; // One past the last character emitted.
1209 while (*LastEmitted) {
1210 switch (*LastEmitted) {
1212 // Not a special case, emit the string section literally.
1213 const char *LiteralEnd = LastEmitted+1;
1214 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1215 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1217 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1218 O.write(LastEmitted, LiteralEnd-LastEmitted);
1219 LastEmitted = LiteralEnd;
1223 ++LastEmitted; // Consume newline character.
1224 O << '\n'; // Indent code with newline.
1227 ++LastEmitted; // Consume '$' character.
1231 switch (*LastEmitted) {
1232 default: Done = false; break;
1233 case '$': // $$ -> $
1234 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1236 ++LastEmitted; // Consume second '$' character.
1238 case '(': // $( -> same as GCC's { character.
1239 ++LastEmitted; // Consume '(' character.
1240 if (CurVariant != -1) {
1241 llvm_report_error("Nested variants found in inline asm string: '"
1242 + std::string(AsmStr) + "'");
1244 CurVariant = 0; // We're in the first variant now.
1247 ++LastEmitted; // consume '|' character.
1248 if (CurVariant == -1)
1249 O << '|'; // this is gcc's behavior for | outside a variant
1251 ++CurVariant; // We're in the next variant.
1253 case ')': // $) -> same as GCC's } char.
1254 ++LastEmitted; // consume ')' character.
1255 if (CurVariant == -1)
1256 O << '}'; // this is gcc's behavior for } outside a variant
1263 bool HasCurlyBraces = false;
1264 if (*LastEmitted == '{') { // ${variable}
1265 ++LastEmitted; // Consume '{' character.
1266 HasCurlyBraces = true;
1269 // If we have ${:foo}, then this is not a real operand reference, it is a
1270 // "magic" string reference, just like in .td files. Arrange to call
1272 if (HasCurlyBraces && *LastEmitted == ':') {
1274 const char *StrStart = LastEmitted;
1275 const char *StrEnd = strchr(StrStart, '}');
1277 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1278 + std::string(AsmStr) + "'");
1281 std::string Val(StrStart, StrEnd);
1282 PrintSpecial(MI, Val.c_str());
1283 LastEmitted = StrEnd+1;
1287 const char *IDStart = LastEmitted;
1290 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1291 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1292 llvm_report_error("Bad $ operand number in inline asm string: '"
1293 + std::string(AsmStr) + "'");
1295 LastEmitted = IDEnd;
1297 char Modifier[2] = { 0, 0 };
1299 if (HasCurlyBraces) {
1300 // If we have curly braces, check for a modifier character. This
1301 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1302 if (*LastEmitted == ':') {
1303 ++LastEmitted; // Consume ':' character.
1304 if (*LastEmitted == 0) {
1305 llvm_report_error("Bad ${:} expression in inline asm string: '"
1306 + std::string(AsmStr) + "'");
1309 Modifier[0] = *LastEmitted;
1310 ++LastEmitted; // Consume modifier character.
1313 if (*LastEmitted != '}') {
1314 llvm_report_error("Bad ${} expression in inline asm string: '"
1315 + std::string(AsmStr) + "'");
1317 ++LastEmitted; // Consume '}' character.
1320 if ((unsigned)Val >= NumOperands-1) {
1321 llvm_report_error("Invalid $ operand number in inline asm string: '"
1322 + std::string(AsmStr) + "'");
1325 // Okay, we finally have a value number. Ask the target to print this
1327 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1332 // Scan to find the machine operand number for the operand.
1333 for (; Val; --Val) {
1334 if (OpNo >= MI->getNumOperands()) break;
1335 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1336 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1339 if (OpNo >= MI->getNumOperands()) {
1342 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1343 ++OpNo; // Skip over the ID number.
1345 if (Modifier[0] == 'l') // labels are target independent
1346 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1348 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1349 if ((OpFlags & 7) == 4) {
1350 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1351 Modifier[0] ? Modifier : 0);
1353 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1354 Modifier[0] ? Modifier : 0);
1360 raw_string_ostream Msg(msg);
1361 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1363 llvm_report_error(Msg.str());
1370 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1373 /// printImplicitDef - This method prints the specified machine instruction
1374 /// that is an implicit def.
1375 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1376 if (!VerboseAsm) return;
1377 O.PadToColumn(MAI->getCommentColumn());
1378 O << MAI->getCommentString() << " implicit-def: "
1379 << TRI->getName(MI->getOperand(0).getReg());
1382 void AsmPrinter::printKill(const MachineInstr *MI) const {
1383 if (!VerboseAsm) return;
1384 O.PadToColumn(MAI->getCommentColumn());
1385 O << MAI->getCommentString() << " kill:";
1386 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1387 const MachineOperand &op = MI->getOperand(n);
1388 assert(op.isReg() && "KILL instruction must have only register operands");
1389 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1393 /// printLabel - This method prints a local label used by debug and
1394 /// exception handling tables.
1395 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1396 printLabel(MI->getOperand(0).getImm());
1399 void AsmPrinter::printLabel(unsigned Id) const {
1400 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1403 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1404 /// instruction, using the specified assembler variant. Targets should
1405 /// override this to format as appropriate.
1406 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1407 unsigned AsmVariant, const char *ExtraCode) {
1408 // Target doesn't support this yet!
1412 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1413 unsigned AsmVariant,
1414 const char *ExtraCode) {
1415 // Target doesn't support this yet!
1419 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1420 const char *Suffix) const {
1421 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1424 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1425 const BasicBlock *BB,
1426 const char *Suffix) const {
1427 assert(BB->hasName() &&
1428 "Address of anonymous basic block not supported yet!");
1430 // This code must use the function name itself, and not the function number,
1431 // since it must be possible to generate the label name from within other
1433 SmallString<60> FnName;
1434 Mang->getNameWithPrefix(FnName, F, false);
1436 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1437 SmallString<60> NameResult;
1438 Mang->getNameWithPrefix(NameResult,
1439 StringRef("BA") + Twine((unsigned)FnName.size()) +
1440 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1443 return OutContext.GetOrCreateSymbol(NameResult.str());
1446 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1447 SmallString<60> Name;
1448 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1449 << getFunctionNumber() << '_' << MBBID;
1450 return OutContext.GetOrCreateSymbol(Name.str());
1453 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1454 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1455 SmallString<60> Name;
1456 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1457 << getFunctionNumber() << '_' << CPID;
1458 return OutContext.GetOrCreateSymbol(Name.str());
1461 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1462 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1463 const char *Prefix = isLinkerPrivate ? MAI->getLinkerPrivateGlobalPrefix() :
1464 MAI->getPrivateGlobalPrefix();
1465 SmallString<60> Name;
1466 raw_svector_ostream(Name) << Prefix << "JTI" << getFunctionNumber() << '_'
1468 return OutContext.GetOrCreateSymbol(Name.str());
1471 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1473 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1474 SmallString<60> NameStr;
1475 Mang->getNameWithPrefix(NameStr, GV, false);
1476 return OutContext.GetOrCreateSymbol(NameStr.str());
1479 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1480 /// global value name as its base, with the specified suffix, and where the
1481 /// symbol is forced to have private linkage if ForcePrivate is true.
1482 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1484 bool ForcePrivate) const {
1485 SmallString<60> NameStr;
1486 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1487 NameStr.append(Suffix.begin(), Suffix.end());
1488 return OutContext.GetOrCreateSymbol(NameStr.str());
1491 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1493 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1494 SmallString<60> NameStr;
1495 Mang->getNameWithPrefix(NameStr, Sym);
1496 return OutContext.GetOrCreateSymbol(NameStr.str());
1501 /// PrintParentLoopComment - Print comments about parent loops of this one.
1502 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1503 unsigned FunctionNumber) {
1504 if (Loop == 0) return;
1505 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1506 OS.indent(Loop->getLoopDepth()*2)
1507 << "Parent Loop BB" << FunctionNumber << "_"
1508 << Loop->getHeader()->getNumber()
1509 << " Depth=" << Loop->getLoopDepth() << '\n';
1513 /// PrintChildLoopComment - Print comments about child loops within
1514 /// the loop for this basic block, with nesting.
1515 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1516 unsigned FunctionNumber) {
1517 // Add child loop information
1518 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1519 OS.indent((*CL)->getLoopDepth()*2)
1520 << "Child Loop BB" << FunctionNumber << "_"
1521 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1523 PrintChildLoopComment(OS, *CL, FunctionNumber);
1527 /// EmitComments - Pretty-print comments for basic blocks.
1528 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1529 const MachineLoopInfo *LI,
1530 const AsmPrinter &AP) {
1531 // Add loop depth information
1532 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1533 if (Loop == 0) return;
1535 MachineBasicBlock *Header = Loop->getHeader();
1536 assert(Header && "No header for loop");
1538 // If this block is not a loop header, just print out what is the loop header
1540 if (Header != &MBB) {
1541 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1542 Twine(AP.getFunctionNumber())+"_" +
1543 Twine(Loop->getHeader()->getNumber())+
1544 " Depth="+Twine(Loop->getLoopDepth()));
1548 // Otherwise, it is a loop header. Print out information about child and
1550 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1552 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1555 OS.indent(Loop->getLoopDepth()*2-2);
1560 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1562 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1566 /// EmitBasicBlockStart - This method prints the label for the specified
1567 /// MachineBasicBlock, an alignment (if present) and a comment describing
1568 /// it if appropriate.
1569 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1570 // Emit an alignment directive for this block, if needed.
1571 if (unsigned Align = MBB->getAlignment())
1572 EmitAlignment(Log2_32(Align));
1574 // If the block has its address taken, emit a special label to satisfy
1575 // references to the block. This is done so that we don't need to
1576 // remember the number of this label, and so that we can make
1577 // forward references to labels without knowing what their numbers
1579 if (MBB->hasAddressTaken()) {
1580 const BasicBlock *BB = MBB->getBasicBlock();
1582 OutStreamer.AddComment("Address Taken");
1583 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1586 // Print the main label for the block.
1587 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1589 // NOTE: Want this comment at start of line.
1590 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1591 if (const BasicBlock *BB = MBB->getBasicBlock())
1593 OutStreamer.AddComment("%" + BB->getName());
1595 PrintBasicBlockLoopComments(*MBB, LI, *this);
1596 OutStreamer.AddBlankLine();
1600 if (const BasicBlock *BB = MBB->getBasicBlock())
1602 OutStreamer.AddComment("%" + BB->getName());
1603 PrintBasicBlockLoopComments(*MBB, LI, *this);
1606 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
1610 /// printPICJumpTableSetLabel - This method prints a set label for the
1611 /// specified MachineBasicBlock for a jumptable entry.
1612 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1613 const MachineBasicBlock *MBB) const {
1614 if (!MAI->getSetDirective())
1617 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1618 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1619 << *GetMBBSymbol(MBB->getNumber())
1620 << '-' << *GetJTISymbol(uid) << '\n';
1623 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1624 const MachineBasicBlock *MBB) const {
1625 if (!MAI->getSetDirective())
1628 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1629 << getFunctionNumber() << '_' << uid << '_' << uid2
1630 << "_set_" << MBB->getNumber() << ','
1631 << *GetMBBSymbol(MBB->getNumber())
1632 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1633 << '_' << uid << '_' << uid2 << '\n';
1636 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1637 unsigned Visibility) const {
1638 if (Visibility == GlobalValue::HiddenVisibility) {
1639 if (const char *Directive = MAI->getHiddenDirective())
1640 O << Directive << *Sym << '\n';
1641 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1642 if (const char *Directive = MAI->getProtectedDirective())
1643 O << Directive << *Sym << '\n';
1647 void AsmPrinter::printOffset(int64_t Offset) const {
1650 else if (Offset < 0)
1654 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1655 if (!S->usesMetadata())
1658 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1659 if (GCPI != GCMetadataPrinters.end())
1660 return GCPI->second;
1662 const char *Name = S->getName().c_str();
1664 for (GCMetadataPrinterRegistry::iterator
1665 I = GCMetadataPrinterRegistry::begin(),
1666 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1667 if (strcmp(Name, I->getName()) == 0) {
1668 GCMetadataPrinter *GMP = I->instantiate();
1670 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1674 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1675 llvm_unreachable(0);
1678 /// EmitComments - Pretty-print comments for instructions
1679 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1683 bool Newline = false;
1685 if (!MI.getDebugLoc().isUnknown()) {
1686 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1688 // Print source line info.
1689 O.PadToColumn(MAI->getCommentColumn());
1690 O << MAI->getCommentString() << ' ';
1691 DIScope Scope = DLT.getScope();
1692 // Omit the directory, because it's likely to be long and uninteresting.
1693 if (!Scope.isNull())
1694 O << Scope.getFilename();
1697 O << ':' << DLT.getLineNumber();
1698 if (DLT.getColumnNumber() != 0)
1699 O << ':' << DLT.getColumnNumber();
1703 // Check for spills and reloads
1706 const MachineFrameInfo *FrameInfo =
1707 MI.getParent()->getParent()->getFrameInfo();
1709 // We assume a single instruction only has a spill or reload, not
1711 const MachineMemOperand *MMO;
1712 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1713 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1714 MMO = *MI.memoperands_begin();
1715 if (Newline) O << '\n';
1716 O.PadToColumn(MAI->getCommentColumn());
1717 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1721 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1722 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1723 if (Newline) O << '\n';
1724 O.PadToColumn(MAI->getCommentColumn());
1725 O << MAI->getCommentString() << ' '
1726 << MMO->getSize() << "-byte Folded Reload";
1730 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1731 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1732 MMO = *MI.memoperands_begin();
1733 if (Newline) O << '\n';
1734 O.PadToColumn(MAI->getCommentColumn());
1735 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1739 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1740 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1741 if (Newline) O << '\n';
1742 O.PadToColumn(MAI->getCommentColumn());
1743 O << MAI->getCommentString() << ' '
1744 << MMO->getSize() << "-byte Folded Spill";
1749 // Check for spill-induced copies
1750 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1751 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1752 SrcSubIdx, DstSubIdx)) {
1753 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1754 if (Newline) O << '\n';
1755 O.PadToColumn(MAI->getCommentColumn());
1756 O << MAI->getCommentString() << " Reload Reuse";