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/FormattedStream.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
49 static cl::opt<cl::boolOrDefault>
50 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
51 cl::init(cl::BOU_UNSET));
53 char AsmPrinter::ID = 0;
54 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
55 const MCAsmInfo *T, bool VDef)
56 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
57 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
59 OutContext(*new MCContext()),
60 // FIXME: Pass instprinter to streamer.
61 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
63 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
66 case cl::BOU_UNSET: VerboseAsm = VDef; break;
67 case cl::BOU_TRUE: VerboseAsm = true; break;
68 case cl::BOU_FALSE: VerboseAsm = false; break;
72 AsmPrinter::~AsmPrinter() {
73 for (gcp_iterator I = GCMetadataPrinters.begin(),
74 E = GCMetadataPrinters.end(); I != E; ++I)
81 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
82 return TM.getTargetLowering()->getObjFileLowering();
85 /// getCurrentSection() - Return the current section we are emitting to.
86 const MCSection *AsmPrinter::getCurrentSection() const {
87 return OutStreamer.getCurrentSection();
91 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
93 MachineFunctionPass::getAnalysisUsage(AU);
94 AU.addRequired<GCModuleInfo>();
96 AU.addRequired<MachineLoopInfo>();
99 bool AsmPrinter::doInitialization(Module &M) {
100 // Initialize TargetLoweringObjectFile.
101 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
102 .Initialize(OutContext, TM);
104 Mang = new Mangler(*MAI);
106 // Allow the target to emit any magic that it wants at the start of the file.
107 EmitStartOfAsmFile(M);
109 if (MAI->hasSingleParameterDotFile()) {
110 /* Very minimal debug info. It is ignored if we emit actual
111 debug info. If we don't, this at least helps the user find where
112 a function came from. */
113 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
116 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
117 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
118 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
119 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
120 MP->beginAssembly(O, *this, *MAI);
122 if (!M.getModuleInlineAsm().empty())
123 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
124 << M.getModuleInlineAsm()
125 << '\n' << MAI->getCommentString()
126 << " End of file scope inline assembly\n";
128 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
130 MMI->AnalyzeModule(M);
131 DW = getAnalysisIfAvailable<DwarfWriter>();
133 DW->BeginModule(&M, MMI, O, this, MAI);
138 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
139 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
140 if (!GV->hasInitializer()) // External globals require no code.
143 // Check to see if this is a special global used by LLVM, if so, emit it.
144 if (EmitSpecialLLVMGlobal(GV))
147 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
148 printVisibility(GVSym, GV->getVisibility());
150 if (MAI->hasDotTypeDotSizeDirective()) {
151 O << "\t.type\t" << *GVSym;
152 if (MAI->getCommentString()[0] != '@')
158 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
160 const TargetData *TD = TM.getTargetData();
161 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
162 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
164 // Handle common and BSS local symbols (.lcomm).
165 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
166 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
169 O.PadToColumn(MAI->getCommentColumn());
170 O << MAI->getCommentString() << ' ';
171 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
173 if (GVKind.isCommon()) {
175 O << MAI->getCOMMDirective() << *GVSym << ',' << Size;
176 if (MAI->getCOMMDirectiveTakesAlignment())
177 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << AlignLog) : AlignLog);
178 } else if (const char *LComm = MAI->getLCOMMDirective()) {
179 // .lcomm _foo, 42, 4
180 O << LComm << *GVSym << ',' << Size;
181 if (MAI->getLCOMMDirectiveTakesAlignment())
182 O << ',' << AlignLog;
185 O << "\t.local\t" << *GVSym << '\n';
187 O << MAI->getCOMMDirective() << *GVSym << ',' << Size;
188 if (MAI->getCOMMDirectiveTakesAlignment())
189 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << AlignLog) : AlignLog);
195 const MCSection *TheSection =
196 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
198 // Handle the zerofill directive on darwin, which is a special form of BSS
200 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
202 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
203 // .zerofill __DATA, __common, _foo, 400, 5
204 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
208 OutStreamer.SwitchSection(TheSection);
210 // TODO: Factor into an 'emit linkage' thing that is shared with function
212 switch (GV->getLinkage()) {
213 case GlobalValue::CommonLinkage:
214 case GlobalValue::LinkOnceAnyLinkage:
215 case GlobalValue::LinkOnceODRLinkage:
216 case GlobalValue::WeakAnyLinkage:
217 case GlobalValue::WeakODRLinkage:
218 case GlobalValue::LinkerPrivateLinkage:
219 if (const char *WeakDef = MAI->getWeakDefDirective()) {
221 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
222 // .weak_definition _foo
223 O << WeakDef << *GVSym << '\n';
224 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
226 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
227 // .linkonce same_size
230 O << "\t.weak\t" << *GVSym << '\n';
232 case GlobalValue::DLLExportLinkage:
233 case GlobalValue::AppendingLinkage:
234 // FIXME: appending linkage variables should go into a section of
235 // their name or something. For now, just emit them as external.
236 case GlobalValue::ExternalLinkage:
237 // If external or appending, declare as a global symbol.
239 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
241 case GlobalValue::PrivateLinkage:
242 case GlobalValue::InternalLinkage:
245 llvm_unreachable("Unknown linkage type!");
248 EmitAlignment(AlignLog, GV);
251 O.PadToColumn(MAI->getCommentColumn());
252 O << MAI->getCommentString() << ' ';
253 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
257 EmitGlobalConstant(GV->getInitializer());
259 if (MAI->hasDotTypeDotSizeDirective())
260 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
264 bool AsmPrinter::doFinalization(Module &M) {
265 // Emit global variables.
266 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
268 EmitGlobalVariable(I);
270 // Emit final debug information.
271 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
274 // If the target wants to know about weak references, print them all.
275 if (MAI->getWeakRefDirective()) {
276 // FIXME: This is not lazy, it would be nice to only print weak references
277 // to stuff that is actually used. Note that doing so would require targets
278 // to notice uses in operands (due to constant exprs etc). This should
279 // happen with the MC stuff eventually.
281 // Print out module-level global variables here.
282 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
284 if (!I->hasExternalWeakLinkage()) continue;
285 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
288 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
289 if (!I->hasExternalWeakLinkage()) continue;
290 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
294 if (MAI->getSetDirective()) {
296 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
298 MCSymbol *Name = GetGlobalValueSymbol(I);
300 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
301 MCSymbol *Target = GetGlobalValueSymbol(GV);
303 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
304 O << "\t.globl\t" << *Name << '\n';
305 else if (I->hasWeakLinkage())
306 O << MAI->getWeakRefDirective() << *Name << '\n';
308 assert(I->hasLocalLinkage() && "Invalid alias linkage");
310 printVisibility(Name, I->getVisibility());
312 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
316 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
317 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
318 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
319 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
320 MP->finishAssembly(O, *this, *MAI);
322 // If we don't have any trampolines, then we don't require stack memory
323 // to be executable. Some targets have a directive to declare this.
324 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
325 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
326 if (MAI->getNonexecutableStackDirective())
327 O << MAI->getNonexecutableStackDirective() << '\n';
330 // Allow the target to emit any magic that it wants at the end of the file,
331 // after everything else has gone out.
334 delete Mang; Mang = 0;
337 OutStreamer.Finish();
341 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
342 // Get the function symbol.
343 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
344 IncrementFunctionNumber();
347 LI = &getAnalysis<MachineLoopInfo>();
351 // SectionCPs - Keep track the alignment, constpool entries per Section.
355 SmallVector<unsigned, 4> CPEs;
356 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
360 /// EmitConstantPool - Print to the current output stream assembly
361 /// representations of the constants in the constant pool MCP. This is
362 /// used to print out constants which have been "spilled to memory" by
363 /// the code generator.
365 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
366 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
367 if (CP.empty()) return;
369 // Calculate sections for constant pool entries. We collect entries to go into
370 // the same section together to reduce amount of section switch statements.
371 SmallVector<SectionCPs, 4> CPSections;
372 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
373 const MachineConstantPoolEntry &CPE = CP[i];
374 unsigned Align = CPE.getAlignment();
377 switch (CPE.getRelocationInfo()) {
378 default: llvm_unreachable("Unknown section kind");
379 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
381 Kind = SectionKind::getReadOnlyWithRelLocal();
384 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
385 case 4: Kind = SectionKind::getMergeableConst4(); break;
386 case 8: Kind = SectionKind::getMergeableConst8(); break;
387 case 16: Kind = SectionKind::getMergeableConst16();break;
388 default: Kind = SectionKind::getMergeableConst(); break;
392 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
394 // The number of sections are small, just do a linear search from the
395 // last section to the first.
397 unsigned SecIdx = CPSections.size();
398 while (SecIdx != 0) {
399 if (CPSections[--SecIdx].S == S) {
405 SecIdx = CPSections.size();
406 CPSections.push_back(SectionCPs(S, Align));
409 if (Align > CPSections[SecIdx].Alignment)
410 CPSections[SecIdx].Alignment = Align;
411 CPSections[SecIdx].CPEs.push_back(i);
414 // Now print stuff into the calculated sections.
415 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
416 OutStreamer.SwitchSection(CPSections[i].S);
417 EmitAlignment(Log2_32(CPSections[i].Alignment));
420 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
421 unsigned CPI = CPSections[i].CPEs[j];
422 MachineConstantPoolEntry CPE = CP[CPI];
424 // Emit inter-object padding for alignment.
425 unsigned AlignMask = CPE.getAlignment() - 1;
426 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
427 EmitZeros(NewOffset - Offset);
429 const Type *Ty = CPE.getType();
430 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
432 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
435 O.PadToColumn(MAI->getCommentColumn());
436 O << MAI->getCommentString() << " constant ";
437 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
440 if (CPE.isMachineConstantPoolEntry())
441 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
443 EmitGlobalConstant(CPE.Val.ConstVal);
448 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
449 /// by the current function to the current output stream.
451 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
452 MachineFunction &MF) {
453 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
454 if (JT.empty()) return;
456 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
458 // Pick the directive to use to print the jump table entries, and switch to
459 // the appropriate section.
460 TargetLowering *LoweringInfo = TM.getTargetLowering();
462 const Function *F = MF.getFunction();
463 bool JTInDiffSection = false;
464 if (F->isWeakForLinker() ||
465 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
466 // In PIC mode, we need to emit the jump table to the same section as the
467 // function body itself, otherwise the label differences won't make sense.
468 // We should also do if the section name is NULL or function is declared in
469 // discardable section.
470 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
473 // Otherwise, drop it in the readonly section.
474 const MCSection *ReadOnlySection =
475 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
476 OutStreamer.SwitchSection(ReadOnlySection);
477 JTInDiffSection = true;
480 EmitAlignment(Log2_32(MJTI->getAlignment()));
482 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
483 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
485 // If this jump table was deleted, ignore it.
486 if (JTBBs.empty()) continue;
488 // For PIC codegen, if possible we want to use the SetDirective to reduce
489 // the number of relocations the assembler will generate for the jump table.
490 // Set directives are all printed before the jump table itself.
491 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
492 if (MAI->getSetDirective() && IsPic)
493 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
494 if (EmittedSets.insert(JTBBs[ii]))
495 printPICJumpTableSetLabel(i, JTBBs[ii]);
497 // On some targets (e.g. Darwin) we want to emit two consequtive labels
498 // before each jump table. The first label is never referenced, but tells
499 // the assembler and linker the extents of the jump table object. The
500 // second label is actually referenced by the code.
501 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
502 O << MAI->getLinkerPrivateGlobalPrefix()
503 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
506 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
507 << '_' << i << ":\n";
509 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
510 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
516 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
517 const MachineBasicBlock *MBB,
518 unsigned uid) const {
519 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
521 // Use JumpTableDirective otherwise honor the entry size from the jump table
523 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
524 bool HadJTEntryDirective = JTEntryDirective != NULL;
525 if (!HadJTEntryDirective) {
526 JTEntryDirective = MJTI->getEntrySize() == 4 ?
527 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
530 O << JTEntryDirective << ' ';
532 // If we have emitted set directives for the jump table entries, print
533 // them rather than the entries themselves. If we're emitting PIC, then
534 // emit the table entries as differences between two text section labels.
535 // If we're emitting non-PIC code, then emit the entries as direct
536 // references to the target basic blocks.
538 O << *GetMBBSymbol(MBB->getNumber());
539 } else if (MAI->getSetDirective()) {
540 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
541 << '_' << uid << "_set_" << MBB->getNumber();
543 O << *GetMBBSymbol(MBB->getNumber());
544 // If the arch uses custom Jump Table directives, don't calc relative to
546 if (!HadJTEntryDirective)
547 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
548 << getFunctionNumber() << '_' << uid;
553 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
554 /// special global used by LLVM. If so, emit it and return true, otherwise
555 /// do nothing and return false.
556 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
557 if (GV->getName() == "llvm.used") {
558 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
559 EmitLLVMUsedList(GV->getInitializer());
563 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
564 if (GV->getSection() == "llvm.metadata" ||
565 GV->hasAvailableExternallyLinkage())
568 if (!GV->hasAppendingLinkage()) return false;
570 assert(GV->hasInitializer() && "Not a special LLVM global!");
572 const TargetData *TD = TM.getTargetData();
573 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
574 if (GV->getName() == "llvm.global_ctors") {
575 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
576 EmitAlignment(Align, 0);
577 EmitXXStructorList(GV->getInitializer());
579 if (TM.getRelocationModel() == Reloc::Static &&
580 MAI->hasStaticCtorDtorReferenceInStaticMode())
581 O << ".reference .constructors_used\n";
585 if (GV->getName() == "llvm.global_dtors") {
586 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
587 EmitAlignment(Align, 0);
588 EmitXXStructorList(GV->getInitializer());
590 if (TM.getRelocationModel() == Reloc::Static &&
591 MAI->hasStaticCtorDtorReferenceInStaticMode())
592 O << ".reference .destructors_used\n";
599 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
600 /// global in the specified llvm.used list for which emitUsedDirectiveFor
601 /// is true, as being used with this directive.
602 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
603 const char *Directive = MAI->getUsedDirective();
605 // Should be an array of 'i8*'.
606 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
607 if (InitList == 0) return;
609 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
610 const GlobalValue *GV =
611 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
612 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
614 EmitConstantValueOnly(InitList->getOperand(i));
620 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
621 /// function pointers, ignoring the init priority.
622 void AsmPrinter::EmitXXStructorList(Constant *List) {
623 // Should be an array of '{ int, void ()* }' structs. The first value is the
624 // init priority, which we ignore.
625 if (!isa<ConstantArray>(List)) return;
626 ConstantArray *InitList = cast<ConstantArray>(List);
627 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
628 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
629 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
631 if (CS->getOperand(1)->isNullValue())
632 return; // Found a null terminator, exit printing.
633 // Emit the function pointer.
634 EmitGlobalConstant(CS->getOperand(1));
639 //===----------------------------------------------------------------------===//
640 /// LEB 128 number encoding.
642 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
643 /// representing an unsigned leb128 value.
644 void AsmPrinter::PrintULEB128(unsigned Value) const {
646 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
648 if (Value) Byte |= 0x80;
650 if (Value) O << ", ";
654 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
655 /// representing a signed leb128 value.
656 void AsmPrinter::PrintSLEB128(int Value) const {
657 int Sign = Value >> (8 * sizeof(Value) - 1);
661 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
663 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
664 if (IsMore) Byte |= 0x80;
666 if (IsMore) O << ", ";
670 //===--------------------------------------------------------------------===//
671 // Emission and print routines
674 /// PrintHex - Print a value as a hexadecimal value.
676 void AsmPrinter::PrintHex(uint64_t Value) const {
681 /// EOL - Print a newline character to asm stream. If a comment is present
682 /// then it will be printed first. Comments should not contain '\n'.
683 void AsmPrinter::EOL() const {
687 void AsmPrinter::EOL(const Twine &Comment) const {
688 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
689 O.PadToColumn(MAI->getCommentColumn());
690 O << MAI->getCommentString()
697 static const char *DecodeDWARFEncoding(unsigned Encoding) {
699 case dwarf::DW_EH_PE_absptr:
701 case dwarf::DW_EH_PE_omit:
703 case dwarf::DW_EH_PE_pcrel:
705 case dwarf::DW_EH_PE_udata4:
707 case dwarf::DW_EH_PE_udata8:
709 case dwarf::DW_EH_PE_sdata4:
711 case dwarf::DW_EH_PE_sdata8:
713 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
714 return "pcrel udata4";
715 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
716 return "pcrel sdata4";
717 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
718 return "pcrel udata8";
719 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
720 return "pcrel sdata8";
721 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
722 return "indirect pcrel udata4";
723 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
724 return "indirect pcrel sdata4";
725 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
726 return "indirect pcrel udata8";
727 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
728 return "indirect pcrel sdata8";
734 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
735 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
736 O.PadToColumn(MAI->getCommentColumn());
737 O << MAI->getCommentString()
741 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
742 O << " (" << EncStr << ')';
747 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
748 /// unsigned leb128 value.
749 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
750 if (MAI->hasLEB128()) {
754 O << MAI->getData8bitsDirective();
759 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
760 /// signed leb128 value.
761 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
762 if (MAI->hasLEB128()) {
766 O << MAI->getData8bitsDirective();
771 /// EmitInt8 - Emit a byte directive and value.
773 void AsmPrinter::EmitInt8(int Value) const {
774 O << MAI->getData8bitsDirective();
775 PrintHex(Value & 0xFF);
778 /// EmitInt16 - Emit a short directive and value.
780 void AsmPrinter::EmitInt16(int Value) const {
781 O << MAI->getData16bitsDirective();
782 PrintHex(Value & 0xFFFF);
785 /// EmitInt32 - Emit a long directive and value.
787 void AsmPrinter::EmitInt32(int Value) const {
788 O << MAI->getData32bitsDirective();
792 /// EmitInt64 - Emit a long long directive and value.
794 void AsmPrinter::EmitInt64(uint64_t Value) const {
795 if (MAI->getData64bitsDirective()) {
796 O << MAI->getData64bitsDirective();
799 if (TM.getTargetData()->isBigEndian()) {
800 EmitInt32(unsigned(Value >> 32)); O << '\n';
801 EmitInt32(unsigned(Value));
803 EmitInt32(unsigned(Value)); O << '\n';
804 EmitInt32(unsigned(Value >> 32));
809 /// toOctal - Convert the low order bits of X into an octal digit.
811 static inline char toOctal(int X) {
815 /// printStringChar - Print a char, escaped if necessary.
817 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
820 } else if (C == '\\') {
822 } else if (isprint((unsigned char)C)) {
826 case '\b': O << "\\b"; break;
827 case '\f': O << "\\f"; break;
828 case '\n': O << "\\n"; break;
829 case '\r': O << "\\r"; break;
830 case '\t': O << "\\t"; break;
833 O << toOctal(C >> 6);
834 O << toOctal(C >> 3);
835 O << toOctal(C >> 0);
841 /// EmitString - Emit a string with quotes and a null terminator.
842 /// Special characters are emitted properly.
843 /// \literal (Eg. '\t') \endliteral
844 void AsmPrinter::EmitString(const StringRef String) const {
845 EmitString(String.data(), String.size());
848 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
849 const char* AscizDirective = MAI->getAscizDirective();
853 O << MAI->getAsciiDirective();
855 for (unsigned i = 0; i < Size; ++i)
856 printStringChar(O, String[i]);
864 /// EmitFile - Emit a .file directive.
865 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
866 O << "\t.file\t" << Number << " \"";
867 for (unsigned i = 0, N = Name.size(); i < N; ++i)
868 printStringChar(O, Name[i]);
873 //===----------------------------------------------------------------------===//
875 // EmitAlignment - Emit an alignment directive to the specified power of
876 // two boundary. For example, if you pass in 3 here, you will get an 8
877 // byte alignment. If a global value is specified, and if that global has
878 // an explicit alignment requested, it will unconditionally override the
879 // alignment request. However, if ForcedAlignBits is specified, this value
880 // has final say: the ultimate alignment will be the max of ForcedAlignBits
881 // and the alignment computed with NumBits and the global.
885 // if (GV && GV->hasalignment) Align = GV->getalignment();
886 // Align = std::max(Align, ForcedAlignBits);
888 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
889 unsigned ForcedAlignBits,
890 bool UseFillExpr) const {
891 if (GV && GV->getAlignment())
892 NumBits = Log2_32(GV->getAlignment());
893 NumBits = std::max(NumBits, ForcedAlignBits);
895 if (NumBits == 0) return; // No need to emit alignment.
897 unsigned FillValue = 0;
898 if (getCurrentSection()->getKind().isText())
899 FillValue = MAI->getTextAlignFillValue();
901 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
904 /// EmitZeros - Emit a block of zeros.
906 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
908 if (MAI->getZeroDirective()) {
909 O << MAI->getZeroDirective() << NumZeros;
910 if (MAI->getZeroDirectiveSuffix())
911 O << MAI->getZeroDirectiveSuffix();
914 for (; NumZeros; --NumZeros)
915 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
920 // Print out the specified constant, without a storage class. Only the
921 // constants valid in constant expressions can occur here.
922 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
923 if (CV->isNullValue() || isa<UndefValue>(CV)) {
928 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
929 O << CI->getZExtValue();
933 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
934 // This is a constant address for a global variable or function. Use the
935 // name of the variable or function as the address value.
936 O << *GetGlobalValueSymbol(GV);
940 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
941 O << *GetBlockAddressSymbol(BA);
945 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
947 llvm_unreachable("Unknown constant value!");
952 switch (CE->getOpcode()) {
953 case Instruction::ZExt:
954 case Instruction::SExt:
955 case Instruction::FPTrunc:
956 case Instruction::FPExt:
957 case Instruction::UIToFP:
958 case Instruction::SIToFP:
959 case Instruction::FPToUI:
960 case Instruction::FPToSI:
962 llvm_unreachable("FIXME: Don't support this constant cast expr");
963 case Instruction::GetElementPtr: {
964 // generate a symbolic expression for the byte address
965 const TargetData *TD = TM.getTargetData();
966 const Constant *ptrVal = CE->getOperand(0);
967 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
968 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
971 return EmitConstantValueOnly(ptrVal);
973 // Truncate/sext the offset to the pointer size.
974 if (TD->getPointerSizeInBits() != 64) {
975 int SExtAmount = 64-TD->getPointerSizeInBits();
976 Offset = (Offset << SExtAmount) >> SExtAmount;
981 EmitConstantValueOnly(ptrVal);
983 O << ") + " << Offset;
985 O << ") - " << -Offset;
988 case Instruction::BitCast:
989 return EmitConstantValueOnly(CE->getOperand(0));
991 case Instruction::IntToPtr: {
992 // Handle casts to pointers by changing them into casts to the appropriate
993 // integer type. This promotes constant folding and simplifies this code.
994 const TargetData *TD = TM.getTargetData();
995 Constant *Op = CE->getOperand(0);
996 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
998 return EmitConstantValueOnly(Op);
1001 case Instruction::PtrToInt: {
1002 // Support only foldable casts to/from pointers that can be eliminated by
1003 // changing the pointer to the appropriately sized integer type.
1004 Constant *Op = CE->getOperand(0);
1005 const Type *Ty = CE->getType();
1006 const TargetData *TD = TM.getTargetData();
1008 // We can emit the pointer value into this slot if the slot is an
1009 // integer slot greater or equal to the size of the pointer.
1010 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
1011 return EmitConstantValueOnly(Op);
1014 EmitConstantValueOnly(Op);
1016 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
1019 ptrMask.toStringUnsigned(S);
1020 O << ") & " << S.str() << ')';
1024 case Instruction::Trunc:
1025 // We emit the value and depend on the assembler to truncate the generated
1026 // expression properly. This is important for differences between
1027 // blockaddress labels. Since the two labels are in the same function, it
1028 // is reasonable to treat their delta as a 32-bit value.
1029 return EmitConstantValueOnly(CE->getOperand(0));
1031 case Instruction::Add:
1032 case Instruction::Sub:
1033 case Instruction::And:
1034 case Instruction::Or:
1035 case Instruction::Xor:
1037 EmitConstantValueOnly(CE->getOperand(0));
1039 switch (CE->getOpcode()) {
1040 case Instruction::Add:
1043 case Instruction::Sub:
1046 case Instruction::And:
1049 case Instruction::Or:
1052 case Instruction::Xor:
1059 EmitConstantValueOnly(CE->getOperand(1));
1065 /// printAsCString - Print the specified array as a C compatible string, only if
1066 /// the predicate isString is true.
1068 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
1070 assert(CVA->isString() && "Array is not string compatible!");
1073 for (unsigned i = 0; i != LastElt; ++i) {
1075 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
1076 printStringChar(O, C);
1081 /// EmitString - Emit a zero-byte-terminated string constant.
1083 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
1084 unsigned NumElts = CVA->getNumOperands();
1085 if (MAI->getAscizDirective() && NumElts &&
1086 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
1087 O << MAI->getAscizDirective();
1088 printAsCString(O, CVA, NumElts-1);
1090 O << MAI->getAsciiDirective();
1091 printAsCString(O, CVA, NumElts);
1096 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
1097 unsigned AddrSpace) {
1098 if (CVA->isString()) {
1100 } else { // Not a string. Print the values in successive locations
1101 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
1102 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1106 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1107 const VectorType *PTy = CP->getType();
1109 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1110 EmitGlobalConstant(CP->getOperand(I));
1113 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1114 unsigned AddrSpace) {
1115 // Print the fields in successive locations. Pad to align if needed!
1116 const TargetData *TD = TM.getTargetData();
1117 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1118 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1119 uint64_t sizeSoFar = 0;
1120 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1121 const Constant* field = CVS->getOperand(i);
1123 // Check if padding is needed and insert one or more 0s.
1124 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1125 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1126 - cvsLayout->getElementOffset(i)) - fieldSize;
1127 sizeSoFar += fieldSize + padSize;
1129 // Now print the actual field value.
1130 EmitGlobalConstant(field, AddrSpace);
1132 // Insert padding - this may include padding to increase the size of the
1133 // current field up to the ABI size (if the struct is not packed) as well
1134 // as padding to ensure that the next field starts at the right offset.
1135 EmitZeros(padSize, AddrSpace);
1137 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1138 "Layout of constant struct may be incorrect!");
1141 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1142 unsigned AddrSpace) {
1143 // FP Constants are printed as integer constants to avoid losing
1145 LLVMContext &Context = CFP->getContext();
1146 const TargetData *TD = TM.getTargetData();
1147 if (CFP->getType()->isDoubleTy()) {
1148 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1149 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1150 if (MAI->getData64bitsDirective(AddrSpace)) {
1151 O << MAI->getData64bitsDirective(AddrSpace) << i;
1153 O.PadToColumn(MAI->getCommentColumn());
1154 O << MAI->getCommentString() << " double " << Val;
1157 } else if (TD->isBigEndian()) {
1158 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1160 O.PadToColumn(MAI->getCommentColumn());
1161 O << MAI->getCommentString()
1162 << " most significant word of double " << Val;
1165 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1167 O.PadToColumn(MAI->getCommentColumn());
1168 O << MAI->getCommentString()
1169 << " least significant word of double " << Val;
1173 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1175 O.PadToColumn(MAI->getCommentColumn());
1176 O << MAI->getCommentString()
1177 << " least significant word of double " << Val;
1180 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1182 O.PadToColumn(MAI->getCommentColumn());
1183 O << MAI->getCommentString()
1184 << " most significant word of double " << Val;
1191 if (CFP->getType()->isFloatTy()) {
1192 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1193 O << MAI->getData32bitsDirective(AddrSpace)
1194 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1196 O.PadToColumn(MAI->getCommentColumn());
1197 O << MAI->getCommentString() << " float " << Val;
1203 if (CFP->getType()->isX86_FP80Ty()) {
1204 // all long double variants are printed as hex
1205 // api needed to prevent premature destruction
1206 APInt api = CFP->getValueAPF().bitcastToAPInt();
1207 const uint64_t *p = api.getRawData();
1208 // Convert to double so we can print the approximate val as a comment.
1209 APFloat DoubleVal = CFP->getValueAPF();
1211 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1213 if (TD->isBigEndian()) {
1214 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1216 O.PadToColumn(MAI->getCommentColumn());
1217 O << MAI->getCommentString()
1218 << " most significant halfword of x86_fp80 ~"
1219 << DoubleVal.convertToDouble();
1222 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1224 O.PadToColumn(MAI->getCommentColumn());
1225 O << MAI->getCommentString() << " next halfword";
1228 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1230 O.PadToColumn(MAI->getCommentColumn());
1231 O << MAI->getCommentString() << " next halfword";
1234 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1236 O.PadToColumn(MAI->getCommentColumn());
1237 O << MAI->getCommentString() << " next halfword";
1240 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1242 O.PadToColumn(MAI->getCommentColumn());
1243 O << MAI->getCommentString()
1244 << " least significant halfword";
1248 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1250 O.PadToColumn(MAI->getCommentColumn());
1251 O << MAI->getCommentString()
1252 << " least significant halfword of x86_fp80 ~"
1253 << DoubleVal.convertToDouble();
1256 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1258 O.PadToColumn(MAI->getCommentColumn());
1259 O << MAI->getCommentString()
1260 << " next halfword";
1263 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1265 O.PadToColumn(MAI->getCommentColumn());
1266 O << MAI->getCommentString()
1267 << " next halfword";
1270 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1272 O.PadToColumn(MAI->getCommentColumn());
1273 O << MAI->getCommentString()
1274 << " next halfword";
1277 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1279 O.PadToColumn(MAI->getCommentColumn());
1280 O << MAI->getCommentString()
1281 << " most significant halfword";
1285 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1286 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1290 if (CFP->getType()->isPPC_FP128Ty()) {
1291 // all long double variants are printed as hex
1292 // api needed to prevent premature destruction
1293 APInt api = CFP->getValueAPF().bitcastToAPInt();
1294 const uint64_t *p = api.getRawData();
1295 if (TD->isBigEndian()) {
1296 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1298 O.PadToColumn(MAI->getCommentColumn());
1299 O << MAI->getCommentString()
1300 << " most significant word of ppc_fp128";
1303 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1305 O.PadToColumn(MAI->getCommentColumn());
1306 O << MAI->getCommentString()
1310 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1312 O.PadToColumn(MAI->getCommentColumn());
1313 O << MAI->getCommentString()
1317 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1319 O.PadToColumn(MAI->getCommentColumn());
1320 O << MAI->getCommentString()
1321 << " least significant word";
1325 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1327 O.PadToColumn(MAI->getCommentColumn());
1328 O << MAI->getCommentString()
1329 << " least significant word of ppc_fp128";
1332 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1334 O.PadToColumn(MAI->getCommentColumn());
1335 O << MAI->getCommentString()
1339 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1341 O.PadToColumn(MAI->getCommentColumn());
1342 O << MAI->getCommentString()
1346 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1348 O.PadToColumn(MAI->getCommentColumn());
1349 O << MAI->getCommentString()
1350 << " most significant word";
1355 } else llvm_unreachable("Floating point constant type not handled");
1358 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1359 unsigned AddrSpace) {
1360 const TargetData *TD = TM.getTargetData();
1361 unsigned BitWidth = CI->getBitWidth();
1362 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1364 // We don't expect assemblers to support integer data directives
1365 // for more than 64 bits, so we emit the data in at most 64-bit
1366 // quantities at a time.
1367 const uint64_t *RawData = CI->getValue().getRawData();
1368 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1370 if (TD->isBigEndian())
1371 Val = RawData[e - i - 1];
1375 if (MAI->getData64bitsDirective(AddrSpace)) {
1376 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1380 // Emit two 32-bit chunks, order depends on endianness.
1381 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1382 const char *FirstName = " least", *SecondName = " most";
1383 if (TD->isBigEndian()) {
1384 std::swap(FirstChunk, SecondChunk);
1385 std::swap(FirstName, SecondName);
1388 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1390 O.PadToColumn(MAI->getCommentColumn());
1391 O << MAI->getCommentString()
1392 << FirstName << " significant half of i64 " << Val;
1396 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1398 O.PadToColumn(MAI->getCommentColumn());
1399 O << MAI->getCommentString()
1400 << SecondName << " significant half of i64 " << Val;
1406 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1407 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1408 const TargetData *TD = TM.getTargetData();
1409 const Type *type = CV->getType();
1410 unsigned Size = TD->getTypeAllocSize(type);
1412 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1413 EmitZeros(Size, AddrSpace);
1417 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1418 EmitGlobalConstantArray(CVA , AddrSpace);
1422 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1423 EmitGlobalConstantStruct(CVS, AddrSpace);
1427 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1428 EmitGlobalConstantFP(CFP, AddrSpace);
1432 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1433 // If we can directly emit an 8-byte constant, do it.
1435 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1436 O << Data64Dir << CI->getZExtValue() << '\n';
1440 // Small integers are handled below; large integers are handled here.
1442 EmitGlobalConstantLargeInt(CI, AddrSpace);
1447 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1448 EmitGlobalConstantVector(CP);
1452 printDataDirective(type, AddrSpace);
1453 EmitConstantValueOnly(CV);
1455 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1457 CI->getValue().toStringUnsigned(S, 16);
1458 O.PadToColumn(MAI->getCommentColumn());
1459 O << MAI->getCommentString() << " 0x" << S.str();
1465 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1466 // Target doesn't support this yet!
1467 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1470 /// PrintSpecial - Print information related to the specified machine instr
1471 /// that is independent of the operand, and may be independent of the instr
1472 /// itself. This can be useful for portably encoding the comment character
1473 /// or other bits of target-specific knowledge into the asmstrings. The
1474 /// syntax used is ${:comment}. Targets can override this to add support
1475 /// for their own strange codes.
1476 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1477 if (!strcmp(Code, "private")) {
1478 O << MAI->getPrivateGlobalPrefix();
1479 } else if (!strcmp(Code, "comment")) {
1481 O << MAI->getCommentString();
1482 } else if (!strcmp(Code, "uid")) {
1483 // Comparing the address of MI isn't sufficient, because machineinstrs may
1484 // be allocated to the same address across functions.
1485 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1487 // If this is a new LastFn instruction, bump the counter.
1488 if (LastMI != MI || LastFn != ThisF) {
1496 raw_string_ostream Msg(msg);
1497 Msg << "Unknown special formatter '" << Code
1498 << "' for machine instr: " << *MI;
1499 llvm_report_error(Msg.str());
1503 /// processDebugLoc - Processes the debug information of each machine
1504 /// instruction's DebugLoc.
1505 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1506 bool BeforePrintingInsn) {
1507 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1508 || !DW->ShouldEmitDwarfDebug())
1510 DebugLoc DL = MI->getDebugLoc();
1513 DILocation CurDLT = MF->getDILocation(DL);
1514 if (CurDLT.getScope().isNull())
1517 if (BeforePrintingInsn) {
1518 if (CurDLT.getNode() != PrevDLT.getNode()) {
1519 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1520 CurDLT.getColumnNumber(),
1521 CurDLT.getScope().getNode());
1524 DW->BeginScope(MI, L);
1528 // After printing instruction
1534 /// printInlineAsm - This method formats and prints the specified machine
1535 /// instruction that is an inline asm.
1536 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1537 unsigned NumOperands = MI->getNumOperands();
1539 // Count the number of register definitions.
1540 unsigned NumDefs = 0;
1541 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1543 assert(NumDefs != NumOperands-1 && "No asm string?");
1545 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1547 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1548 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1552 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1553 // These are useful to see where empty asm's wound up.
1554 if (AsmStr[0] == 0) {
1555 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1556 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1560 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1562 // The variant of the current asmprinter.
1563 int AsmPrinterVariant = MAI->getAssemblerDialect();
1565 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1566 const char *LastEmitted = AsmStr; // One past the last character emitted.
1568 while (*LastEmitted) {
1569 switch (*LastEmitted) {
1571 // Not a special case, emit the string section literally.
1572 const char *LiteralEnd = LastEmitted+1;
1573 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1574 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1576 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1577 O.write(LastEmitted, LiteralEnd-LastEmitted);
1578 LastEmitted = LiteralEnd;
1582 ++LastEmitted; // Consume newline character.
1583 O << '\n'; // Indent code with newline.
1586 ++LastEmitted; // Consume '$' character.
1590 switch (*LastEmitted) {
1591 default: Done = false; break;
1592 case '$': // $$ -> $
1593 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1595 ++LastEmitted; // Consume second '$' character.
1597 case '(': // $( -> same as GCC's { character.
1598 ++LastEmitted; // Consume '(' character.
1599 if (CurVariant != -1) {
1600 llvm_report_error("Nested variants found in inline asm string: '"
1601 + std::string(AsmStr) + "'");
1603 CurVariant = 0; // We're in the first variant now.
1606 ++LastEmitted; // consume '|' character.
1607 if (CurVariant == -1)
1608 O << '|'; // this is gcc's behavior for | outside a variant
1610 ++CurVariant; // We're in the next variant.
1612 case ')': // $) -> same as GCC's } char.
1613 ++LastEmitted; // consume ')' character.
1614 if (CurVariant == -1)
1615 O << '}'; // this is gcc's behavior for } outside a variant
1622 bool HasCurlyBraces = false;
1623 if (*LastEmitted == '{') { // ${variable}
1624 ++LastEmitted; // Consume '{' character.
1625 HasCurlyBraces = true;
1628 // If we have ${:foo}, then this is not a real operand reference, it is a
1629 // "magic" string reference, just like in .td files. Arrange to call
1631 if (HasCurlyBraces && *LastEmitted == ':') {
1633 const char *StrStart = LastEmitted;
1634 const char *StrEnd = strchr(StrStart, '}');
1636 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1637 + std::string(AsmStr) + "'");
1640 std::string Val(StrStart, StrEnd);
1641 PrintSpecial(MI, Val.c_str());
1642 LastEmitted = StrEnd+1;
1646 const char *IDStart = LastEmitted;
1649 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1650 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1651 llvm_report_error("Bad $ operand number in inline asm string: '"
1652 + std::string(AsmStr) + "'");
1654 LastEmitted = IDEnd;
1656 char Modifier[2] = { 0, 0 };
1658 if (HasCurlyBraces) {
1659 // If we have curly braces, check for a modifier character. This
1660 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1661 if (*LastEmitted == ':') {
1662 ++LastEmitted; // Consume ':' character.
1663 if (*LastEmitted == 0) {
1664 llvm_report_error("Bad ${:} expression in inline asm string: '"
1665 + std::string(AsmStr) + "'");
1668 Modifier[0] = *LastEmitted;
1669 ++LastEmitted; // Consume modifier character.
1672 if (*LastEmitted != '}') {
1673 llvm_report_error("Bad ${} expression in inline asm string: '"
1674 + std::string(AsmStr) + "'");
1676 ++LastEmitted; // Consume '}' character.
1679 if ((unsigned)Val >= NumOperands-1) {
1680 llvm_report_error("Invalid $ operand number in inline asm string: '"
1681 + std::string(AsmStr) + "'");
1684 // Okay, we finally have a value number. Ask the target to print this
1686 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1691 // Scan to find the machine operand number for the operand.
1692 for (; Val; --Val) {
1693 if (OpNo >= MI->getNumOperands()) break;
1694 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1695 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1698 if (OpNo >= MI->getNumOperands()) {
1701 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1702 ++OpNo; // Skip over the ID number.
1704 if (Modifier[0] == 'l') // labels are target independent
1705 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1707 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1708 if ((OpFlags & 7) == 4) {
1709 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1710 Modifier[0] ? Modifier : 0);
1712 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1713 Modifier[0] ? Modifier : 0);
1719 raw_string_ostream Msg(msg);
1720 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1722 llvm_report_error(Msg.str());
1729 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1732 /// printImplicitDef - This method prints the specified machine instruction
1733 /// that is an implicit def.
1734 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1735 if (!VerboseAsm) return;
1736 O.PadToColumn(MAI->getCommentColumn());
1737 O << MAI->getCommentString() << " implicit-def: "
1738 << TRI->getName(MI->getOperand(0).getReg());
1741 void AsmPrinter::printKill(const MachineInstr *MI) const {
1742 if (!VerboseAsm) return;
1743 O.PadToColumn(MAI->getCommentColumn());
1744 O << MAI->getCommentString() << " kill:";
1745 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1746 const MachineOperand &op = MI->getOperand(n);
1747 assert(op.isReg() && "KILL instruction must have only register operands");
1748 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1752 /// printLabel - This method prints a local label used by debug and
1753 /// exception handling tables.
1754 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1755 printLabel(MI->getOperand(0).getImm());
1758 void AsmPrinter::printLabel(unsigned Id) const {
1759 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1762 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1763 /// instruction, using the specified assembler variant. Targets should
1764 /// override this to format as appropriate.
1765 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1766 unsigned AsmVariant, const char *ExtraCode) {
1767 // Target doesn't support this yet!
1771 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1772 unsigned AsmVariant,
1773 const char *ExtraCode) {
1774 // Target doesn't support this yet!
1778 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1779 const char *Suffix) const {
1780 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1783 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1784 const BasicBlock *BB,
1785 const char *Suffix) const {
1786 assert(BB->hasName() &&
1787 "Address of anonymous basic block not supported yet!");
1789 // This code must use the function name itself, and not the function number,
1790 // since it must be possible to generate the label name from within other
1792 SmallString<60> FnName;
1793 Mang->getNameWithPrefix(FnName, F, false);
1795 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1796 SmallString<60> NameResult;
1797 Mang->getNameWithPrefix(NameResult,
1798 StringRef("BA") + Twine((unsigned)FnName.size()) +
1799 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1802 return OutContext.GetOrCreateSymbol(NameResult.str());
1805 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1806 SmallString<60> Name;
1807 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1808 << getFunctionNumber() << '_' << MBBID;
1810 return OutContext.GetOrCreateSymbol(Name.str());
1813 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1815 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1816 SmallString<60> NameStr;
1817 Mang->getNameWithPrefix(NameStr, GV, false);
1818 return OutContext.GetOrCreateSymbol(NameStr.str());
1821 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1822 /// global value name as its base, with the specified suffix, and where the
1823 /// symbol is forced to have private linkage if ForcePrivate is true.
1824 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1826 bool ForcePrivate) const {
1827 SmallString<60> NameStr;
1828 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1829 NameStr.append(Suffix.begin(), Suffix.end());
1830 return OutContext.GetOrCreateSymbol(NameStr.str());
1833 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1835 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1836 SmallString<60> NameStr;
1837 Mang->getNameWithPrefix(NameStr, Sym);
1838 return OutContext.GetOrCreateSymbol(NameStr.str());
1842 /// EmitBasicBlockStart - This method prints the label for the specified
1843 /// MachineBasicBlock, an alignment (if present) and a comment describing
1844 /// it if appropriate.
1845 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1846 // Emit an alignment directive for this block, if needed.
1847 if (unsigned Align = MBB->getAlignment())
1848 EmitAlignment(Log2_32(Align));
1850 // If the block has its address taken, emit a special label to satisfy
1851 // references to the block. This is done so that we don't need to
1852 // remember the number of this label, and so that we can make
1853 // forward references to labels without knowing what their numbers
1855 if (MBB->hasAddressTaken()) {
1856 O << *GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1857 MBB->getBasicBlock());
1860 O.PadToColumn(MAI->getCommentColumn());
1861 O << MAI->getCommentString() << " Address Taken";
1866 // Print the main label for the block.
1867 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1869 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1871 O << *GetMBBSymbol(MBB->getNumber()) << ':';
1876 // Print some comments to accompany the label.
1878 if (const BasicBlock *BB = MBB->getBasicBlock())
1879 if (BB->hasName()) {
1880 O.PadToColumn(MAI->getCommentColumn());
1881 O << MAI->getCommentString() << ' ';
1882 WriteAsOperand(O, BB, /*PrintType=*/false);
1890 /// printPICJumpTableSetLabel - This method prints a set label for the
1891 /// specified MachineBasicBlock for a jumptable entry.
1892 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1893 const MachineBasicBlock *MBB) const {
1894 if (!MAI->getSetDirective())
1897 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1898 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1899 << *GetMBBSymbol(MBB->getNumber())
1900 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1901 << '_' << uid << '\n';
1904 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1905 const MachineBasicBlock *MBB) const {
1906 if (!MAI->getSetDirective())
1909 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1910 << getFunctionNumber() << '_' << uid << '_' << uid2
1911 << "_set_" << MBB->getNumber() << ','
1912 << *GetMBBSymbol(MBB->getNumber())
1913 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1914 << '_' << uid << '_' << uid2 << '\n';
1917 /// printDataDirective - This method prints the asm directive for the
1919 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1920 const TargetData *TD = TM.getTargetData();
1921 switch (type->getTypeID()) {
1922 case Type::FloatTyID: case Type::DoubleTyID:
1923 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1924 assert(0 && "Should have already output floating point constant.");
1926 assert(0 && "Can't handle printing this type of thing");
1927 case Type::IntegerTyID: {
1928 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1930 O << MAI->getData8bitsDirective(AddrSpace);
1931 else if (BitWidth <= 16)
1932 O << MAI->getData16bitsDirective(AddrSpace);
1933 else if (BitWidth <= 32)
1934 O << MAI->getData32bitsDirective(AddrSpace);
1935 else if (BitWidth <= 64) {
1936 assert(MAI->getData64bitsDirective(AddrSpace) &&
1937 "Target cannot handle 64-bit constant exprs!");
1938 O << MAI->getData64bitsDirective(AddrSpace);
1940 llvm_unreachable("Target cannot handle given data directive width!");
1944 case Type::PointerTyID:
1945 if (TD->getPointerSize() == 8) {
1946 assert(MAI->getData64bitsDirective(AddrSpace) &&
1947 "Target cannot handle 64-bit pointer exprs!");
1948 O << MAI->getData64bitsDirective(AddrSpace);
1949 } else if (TD->getPointerSize() == 2) {
1950 O << MAI->getData16bitsDirective(AddrSpace);
1951 } else if (TD->getPointerSize() == 1) {
1952 O << MAI->getData8bitsDirective(AddrSpace);
1954 O << MAI->getData32bitsDirective(AddrSpace);
1960 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1961 unsigned Visibility) const {
1962 if (Visibility == GlobalValue::HiddenVisibility) {
1963 if (const char *Directive = MAI->getHiddenDirective())
1964 O << Directive << *Sym << '\n';
1965 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1966 if (const char *Directive = MAI->getProtectedDirective())
1967 O << Directive << *Sym << '\n';
1971 void AsmPrinter::printOffset(int64_t Offset) const {
1974 else if (Offset < 0)
1978 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1979 if (!S->usesMetadata())
1982 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1983 if (GCPI != GCMetadataPrinters.end())
1984 return GCPI->second;
1986 const char *Name = S->getName().c_str();
1988 for (GCMetadataPrinterRegistry::iterator
1989 I = GCMetadataPrinterRegistry::begin(),
1990 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1991 if (strcmp(Name, I->getName()) == 0) {
1992 GCMetadataPrinter *GMP = I->instantiate();
1994 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1998 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1999 llvm_unreachable(0);
2002 /// EmitComments - Pretty-print comments for instructions
2003 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
2007 bool Newline = false;
2009 if (!MI.getDebugLoc().isUnknown()) {
2010 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
2012 // Print source line info.
2013 O.PadToColumn(MAI->getCommentColumn());
2014 O << MAI->getCommentString() << ' ';
2015 DIScope Scope = DLT.getScope();
2016 // Omit the directory, because it's likely to be long and uninteresting.
2017 if (!Scope.isNull())
2018 O << Scope.getFilename();
2021 O << ':' << DLT.getLineNumber();
2022 if (DLT.getColumnNumber() != 0)
2023 O << ':' << DLT.getColumnNumber();
2027 // Check for spills and reloads
2030 const MachineFrameInfo *FrameInfo =
2031 MI.getParent()->getParent()->getFrameInfo();
2033 // We assume a single instruction only has a spill or reload, not
2035 const MachineMemOperand *MMO;
2036 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
2037 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2038 MMO = *MI.memoperands_begin();
2039 if (Newline) O << '\n';
2040 O.PadToColumn(MAI->getCommentColumn());
2041 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
2045 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
2046 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2047 if (Newline) O << '\n';
2048 O.PadToColumn(MAI->getCommentColumn());
2049 O << MAI->getCommentString() << ' '
2050 << MMO->getSize() << "-byte Folded Reload";
2054 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
2055 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2056 MMO = *MI.memoperands_begin();
2057 if (Newline) O << '\n';
2058 O.PadToColumn(MAI->getCommentColumn());
2059 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
2063 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
2064 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2065 if (Newline) O << '\n';
2066 O.PadToColumn(MAI->getCommentColumn());
2067 O << MAI->getCommentString() << ' '
2068 << MMO->getSize() << "-byte Folded Spill";
2073 // Check for spill-induced copies
2074 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2075 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
2076 SrcSubIdx, DstSubIdx)) {
2077 if (MI.getAsmPrinterFlag(ReloadReuse)) {
2078 if (Newline) O << '\n';
2079 O.PadToColumn(MAI->getCommentColumn());
2080 O << MAI->getCommentString() << " Reload Reuse";
2085 /// PrintChildLoopComment - Print comments about child loops within
2086 /// the loop for this basic block, with nesting.
2088 static void PrintChildLoopComment(formatted_raw_ostream &O,
2089 const MachineLoop *loop,
2090 const MCAsmInfo *MAI,
2091 int FunctionNumber) {
2092 // Add child loop information
2093 for(MachineLoop::iterator cl = loop->begin(),
2094 clend = loop->end();
2097 MachineBasicBlock *Header = (*cl)->getHeader();
2098 assert(Header && "No header for loop");
2101 O.PadToColumn(MAI->getCommentColumn());
2103 O << MAI->getCommentString();
2104 O.indent(((*cl)->getLoopDepth()-1)*2)
2105 << " Child Loop BB" << FunctionNumber << "_"
2106 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2108 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2112 /// EmitComments - Pretty-print comments for basic blocks
2113 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2115 // Add loop depth information
2116 const MachineLoop *loop = LI->getLoopFor(&MBB);
2119 // Print a newline after bb# annotation.
2121 O.PadToColumn(MAI->getCommentColumn());
2122 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2125 O.PadToColumn(MAI->getCommentColumn());
2127 MachineBasicBlock *Header = loop->getHeader();
2128 assert(Header && "No header for loop");
2130 if (Header == &MBB) {
2131 O << MAI->getCommentString() << " Loop Header";
2132 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2135 O << MAI->getCommentString() << " Loop Header is BB"
2136 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2139 if (loop->empty()) {
2141 O.PadToColumn(MAI->getCommentColumn());
2142 O << MAI->getCommentString() << " Inner Loop";
2145 // Add parent loop information
2146 for (const MachineLoop *CurLoop = loop->getParentLoop();
2148 CurLoop = CurLoop->getParentLoop()) {
2149 MachineBasicBlock *Header = CurLoop->getHeader();
2150 assert(Header && "No header for loop");
2153 O.PadToColumn(MAI->getCommentColumn());
2154 O << MAI->getCommentString();
2155 O.indent((CurLoop->getLoopDepth()-1)*2)
2156 << " Inside Loop BB" << getFunctionNumber() << "_"
2157 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();