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());
174 if (GVKind.isCommon()) {
176 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
177 } else if (const char *LComm = MAI->getLCOMMDirective()) {
178 // .lcomm _foo, 42, 4
179 O << LComm << *GVSym << ',' << Size;
180 if (MAI->getLCOMMDirectiveTakesAlignment())
181 O << ',' << AlignLog;
185 O << "\t.local\t" << *GVSym << '\n';
187 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
192 const MCSection *TheSection =
193 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
195 // Handle the zerofill directive on darwin, which is a special form of BSS
197 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
199 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
200 // .zerofill __DATA, __common, _foo, 400, 5
201 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
205 OutStreamer.SwitchSection(TheSection);
207 // TODO: Factor into an 'emit linkage' thing that is shared with function
209 switch (GV->getLinkage()) {
210 case GlobalValue::CommonLinkage:
211 case GlobalValue::LinkOnceAnyLinkage:
212 case GlobalValue::LinkOnceODRLinkage:
213 case GlobalValue::WeakAnyLinkage:
214 case GlobalValue::WeakODRLinkage:
215 case GlobalValue::LinkerPrivateLinkage:
216 if (const char *WeakDef = MAI->getWeakDefDirective()) {
218 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
219 // .weak_definition _foo
220 O << WeakDef << *GVSym << '\n';
221 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
223 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
224 // .linkonce same_size
227 O << "\t.weak\t" << *GVSym << '\n';
229 case GlobalValue::DLLExportLinkage:
230 case GlobalValue::AppendingLinkage:
231 // FIXME: appending linkage variables should go into a section of
232 // their name or something. For now, just emit them as external.
233 case GlobalValue::ExternalLinkage:
234 // If external or appending, declare as a global symbol.
236 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
238 case GlobalValue::PrivateLinkage:
239 case GlobalValue::InternalLinkage:
242 llvm_unreachable("Unknown linkage type!");
245 EmitAlignment(AlignLog, GV);
248 O.PadToColumn(MAI->getCommentColumn());
249 O << MAI->getCommentString() << ' ';
250 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
254 EmitGlobalConstant(GV->getInitializer());
256 if (MAI->hasDotTypeDotSizeDirective())
257 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
261 bool AsmPrinter::doFinalization(Module &M) {
262 // Emit global variables.
263 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
265 EmitGlobalVariable(I);
267 // Emit final debug information.
268 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
271 // If the target wants to know about weak references, print them all.
272 if (MAI->getWeakRefDirective()) {
273 // FIXME: This is not lazy, it would be nice to only print weak references
274 // to stuff that is actually used. Note that doing so would require targets
275 // to notice uses in operands (due to constant exprs etc). This should
276 // happen with the MC stuff eventually.
278 // Print out module-level global variables here.
279 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
281 if (!I->hasExternalWeakLinkage()) continue;
282 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
285 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
286 if (!I->hasExternalWeakLinkage()) continue;
287 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
291 if (MAI->getSetDirective()) {
293 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
295 MCSymbol *Name = GetGlobalValueSymbol(I);
297 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
298 MCSymbol *Target = GetGlobalValueSymbol(GV);
300 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
301 O << "\t.globl\t" << *Name << '\n';
302 else if (I->hasWeakLinkage())
303 O << MAI->getWeakRefDirective() << *Name << '\n';
305 assert(I->hasLocalLinkage() && "Invalid alias linkage");
307 printVisibility(Name, I->getVisibility());
309 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
313 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
314 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
315 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
316 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
317 MP->finishAssembly(O, *this, *MAI);
319 // If we don't have any trampolines, then we don't require stack memory
320 // to be executable. Some targets have a directive to declare this.
321 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
322 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
323 if (MAI->getNonexecutableStackDirective())
324 O << MAI->getNonexecutableStackDirective() << '\n';
327 // Allow the target to emit any magic that it wants at the end of the file,
328 // after everything else has gone out.
331 delete Mang; Mang = 0;
334 OutStreamer.Finish();
338 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
339 // Get the function symbol.
340 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
341 IncrementFunctionNumber();
344 LI = &getAnalysis<MachineLoopInfo>();
348 // SectionCPs - Keep track the alignment, constpool entries per Section.
352 SmallVector<unsigned, 4> CPEs;
353 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
357 /// EmitConstantPool - Print to the current output stream assembly
358 /// representations of the constants in the constant pool MCP. This is
359 /// used to print out constants which have been "spilled to memory" by
360 /// the code generator.
362 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
363 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
364 if (CP.empty()) return;
366 // Calculate sections for constant pool entries. We collect entries to go into
367 // the same section together to reduce amount of section switch statements.
368 SmallVector<SectionCPs, 4> CPSections;
369 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
370 const MachineConstantPoolEntry &CPE = CP[i];
371 unsigned Align = CPE.getAlignment();
374 switch (CPE.getRelocationInfo()) {
375 default: llvm_unreachable("Unknown section kind");
376 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
378 Kind = SectionKind::getReadOnlyWithRelLocal();
381 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
382 case 4: Kind = SectionKind::getMergeableConst4(); break;
383 case 8: Kind = SectionKind::getMergeableConst8(); break;
384 case 16: Kind = SectionKind::getMergeableConst16();break;
385 default: Kind = SectionKind::getMergeableConst(); break;
389 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
391 // The number of sections are small, just do a linear search from the
392 // last section to the first.
394 unsigned SecIdx = CPSections.size();
395 while (SecIdx != 0) {
396 if (CPSections[--SecIdx].S == S) {
402 SecIdx = CPSections.size();
403 CPSections.push_back(SectionCPs(S, Align));
406 if (Align > CPSections[SecIdx].Alignment)
407 CPSections[SecIdx].Alignment = Align;
408 CPSections[SecIdx].CPEs.push_back(i);
411 // Now print stuff into the calculated sections.
412 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
413 OutStreamer.SwitchSection(CPSections[i].S);
414 EmitAlignment(Log2_32(CPSections[i].Alignment));
417 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
418 unsigned CPI = CPSections[i].CPEs[j];
419 MachineConstantPoolEntry CPE = CP[CPI];
421 // Emit inter-object padding for alignment.
422 unsigned AlignMask = CPE.getAlignment() - 1;
423 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
424 EmitZeros(NewOffset - Offset);
426 const Type *Ty = CPE.getType();
427 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
429 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
432 O.PadToColumn(MAI->getCommentColumn());
433 O << MAI->getCommentString() << " constant ";
434 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
437 if (CPE.isMachineConstantPoolEntry())
438 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
440 EmitGlobalConstant(CPE.Val.ConstVal);
445 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
446 /// by the current function to the current output stream.
448 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
449 MachineFunction &MF) {
450 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
451 if (JT.empty()) return;
453 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
455 // Pick the directive to use to print the jump table entries, and switch to
456 // the appropriate section.
457 TargetLowering *LoweringInfo = TM.getTargetLowering();
459 const Function *F = MF.getFunction();
460 bool JTInDiffSection = false;
461 if (F->isWeakForLinker() ||
462 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
463 // In PIC mode, we need to emit the jump table to the same section as the
464 // function body itself, otherwise the label differences won't make sense.
465 // We should also do if the section name is NULL or function is declared in
466 // discardable section.
467 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
470 // Otherwise, drop it in the readonly section.
471 const MCSection *ReadOnlySection =
472 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
473 OutStreamer.SwitchSection(ReadOnlySection);
474 JTInDiffSection = true;
477 EmitAlignment(Log2_32(MJTI->getAlignment()));
479 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
480 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
482 // If this jump table was deleted, ignore it.
483 if (JTBBs.empty()) continue;
485 // For PIC codegen, if possible we want to use the SetDirective to reduce
486 // the number of relocations the assembler will generate for the jump table.
487 // Set directives are all printed before the jump table itself.
488 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
489 if (MAI->getSetDirective() && IsPic)
490 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
491 if (EmittedSets.insert(JTBBs[ii]))
492 printPICJumpTableSetLabel(i, JTBBs[ii]);
494 // On some targets (e.g. Darwin) we want to emit two consequtive labels
495 // before each jump table. The first label is never referenced, but tells
496 // the assembler and linker the extents of the jump table object. The
497 // second label is actually referenced by the code.
498 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
499 O << MAI->getLinkerPrivateGlobalPrefix()
500 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
503 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
504 << '_' << i << ":\n";
506 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
507 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
513 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
514 const MachineBasicBlock *MBB,
515 unsigned uid) const {
516 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
518 // Use JumpTableDirective otherwise honor the entry size from the jump table
520 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
521 bool HadJTEntryDirective = JTEntryDirective != NULL;
522 if (!HadJTEntryDirective) {
523 JTEntryDirective = MJTI->getEntrySize() == 4 ?
524 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
527 O << JTEntryDirective << ' ';
529 // If we have emitted set directives for the jump table entries, print
530 // them rather than the entries themselves. If we're emitting PIC, then
531 // emit the table entries as differences between two text section labels.
532 // If we're emitting non-PIC code, then emit the entries as direct
533 // references to the target basic blocks.
535 O << *GetMBBSymbol(MBB->getNumber());
536 } else if (MAI->getSetDirective()) {
537 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
538 << '_' << uid << "_set_" << MBB->getNumber();
540 O << *GetMBBSymbol(MBB->getNumber());
541 // If the arch uses custom Jump Table directives, don't calc relative to
543 if (!HadJTEntryDirective)
544 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
545 << getFunctionNumber() << '_' << uid;
550 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
551 /// special global used by LLVM. If so, emit it and return true, otherwise
552 /// do nothing and return false.
553 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
554 if (GV->getName() == "llvm.used") {
555 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
556 EmitLLVMUsedList(GV->getInitializer());
560 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
561 if (GV->getSection() == "llvm.metadata" ||
562 GV->hasAvailableExternallyLinkage())
565 if (!GV->hasAppendingLinkage()) return false;
567 assert(GV->hasInitializer() && "Not a special LLVM global!");
569 const TargetData *TD = TM.getTargetData();
570 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
571 if (GV->getName() == "llvm.global_ctors") {
572 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
573 EmitAlignment(Align, 0);
574 EmitXXStructorList(GV->getInitializer());
576 if (TM.getRelocationModel() == Reloc::Static &&
577 MAI->hasStaticCtorDtorReferenceInStaticMode())
578 O << ".reference .constructors_used\n";
582 if (GV->getName() == "llvm.global_dtors") {
583 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
584 EmitAlignment(Align, 0);
585 EmitXXStructorList(GV->getInitializer());
587 if (TM.getRelocationModel() == Reloc::Static &&
588 MAI->hasStaticCtorDtorReferenceInStaticMode())
589 O << ".reference .destructors_used\n";
596 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
597 /// global in the specified llvm.used list for which emitUsedDirectiveFor
598 /// is true, as being used with this directive.
599 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
600 const char *Directive = MAI->getUsedDirective();
602 // Should be an array of 'i8*'.
603 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
604 if (InitList == 0) return;
606 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
607 const GlobalValue *GV =
608 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
609 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
611 EmitConstantValueOnly(InitList->getOperand(i));
617 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
618 /// function pointers, ignoring the init priority.
619 void AsmPrinter::EmitXXStructorList(Constant *List) {
620 // Should be an array of '{ int, void ()* }' structs. The first value is the
621 // init priority, which we ignore.
622 if (!isa<ConstantArray>(List)) return;
623 ConstantArray *InitList = cast<ConstantArray>(List);
624 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
625 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
626 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
628 if (CS->getOperand(1)->isNullValue())
629 return; // Found a null terminator, exit printing.
630 // Emit the function pointer.
631 EmitGlobalConstant(CS->getOperand(1));
636 //===----------------------------------------------------------------------===//
637 /// LEB 128 number encoding.
639 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
640 /// representing an unsigned leb128 value.
641 void AsmPrinter::PrintULEB128(unsigned Value) const {
643 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
645 if (Value) Byte |= 0x80;
647 if (Value) O << ", ";
651 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
652 /// representing a signed leb128 value.
653 void AsmPrinter::PrintSLEB128(int Value) const {
654 int Sign = Value >> (8 * sizeof(Value) - 1);
658 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
660 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
661 if (IsMore) Byte |= 0x80;
663 if (IsMore) O << ", ";
667 //===--------------------------------------------------------------------===//
668 // Emission and print routines
671 /// PrintHex - Print a value as a hexadecimal value.
673 void AsmPrinter::PrintHex(uint64_t Value) const {
678 /// EOL - Print a newline character to asm stream. If a comment is present
679 /// then it will be printed first. Comments should not contain '\n'.
680 void AsmPrinter::EOL() const {
684 void AsmPrinter::EOL(const Twine &Comment) const {
685 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
686 O.PadToColumn(MAI->getCommentColumn());
687 O << MAI->getCommentString()
694 static const char *DecodeDWARFEncoding(unsigned Encoding) {
696 case dwarf::DW_EH_PE_absptr:
698 case dwarf::DW_EH_PE_omit:
700 case dwarf::DW_EH_PE_pcrel:
702 case dwarf::DW_EH_PE_udata4:
704 case dwarf::DW_EH_PE_udata8:
706 case dwarf::DW_EH_PE_sdata4:
708 case dwarf::DW_EH_PE_sdata8:
710 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
711 return "pcrel udata4";
712 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
713 return "pcrel sdata4";
714 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
715 return "pcrel udata8";
716 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
717 return "pcrel sdata8";
718 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
719 return "indirect pcrel udata4";
720 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
721 return "indirect pcrel sdata4";
722 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
723 return "indirect pcrel udata8";
724 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
725 return "indirect pcrel sdata8";
731 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
732 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
733 O.PadToColumn(MAI->getCommentColumn());
734 O << MAI->getCommentString()
738 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
739 O << " (" << EncStr << ')';
744 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
745 /// unsigned leb128 value.
746 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
747 if (MAI->hasLEB128()) {
751 O << MAI->getData8bitsDirective();
756 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
757 /// signed leb128 value.
758 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
759 if (MAI->hasLEB128()) {
763 O << MAI->getData8bitsDirective();
768 /// EmitInt8 - Emit a byte directive and value.
770 void AsmPrinter::EmitInt8(int Value) const {
771 O << MAI->getData8bitsDirective();
772 PrintHex(Value & 0xFF);
775 /// EmitInt16 - Emit a short directive and value.
777 void AsmPrinter::EmitInt16(int Value) const {
778 O << MAI->getData16bitsDirective();
779 PrintHex(Value & 0xFFFF);
782 /// EmitInt32 - Emit a long directive and value.
784 void AsmPrinter::EmitInt32(int Value) const {
785 O << MAI->getData32bitsDirective();
789 /// EmitInt64 - Emit a long long directive and value.
791 void AsmPrinter::EmitInt64(uint64_t Value) const {
792 if (MAI->getData64bitsDirective()) {
793 O << MAI->getData64bitsDirective();
796 if (TM.getTargetData()->isBigEndian()) {
797 EmitInt32(unsigned(Value >> 32)); O << '\n';
798 EmitInt32(unsigned(Value));
800 EmitInt32(unsigned(Value)); O << '\n';
801 EmitInt32(unsigned(Value >> 32));
806 /// toOctal - Convert the low order bits of X into an octal digit.
808 static inline char toOctal(int X) {
812 /// printStringChar - Print a char, escaped if necessary.
814 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
817 } else if (C == '\\') {
819 } else if (isprint((unsigned char)C)) {
823 case '\b': O << "\\b"; break;
824 case '\f': O << "\\f"; break;
825 case '\n': O << "\\n"; break;
826 case '\r': O << "\\r"; break;
827 case '\t': O << "\\t"; break;
830 O << toOctal(C >> 6);
831 O << toOctal(C >> 3);
832 O << toOctal(C >> 0);
838 /// EmitString - Emit a string with quotes and a null terminator.
839 /// Special characters are emitted properly.
840 /// \literal (Eg. '\t') \endliteral
841 void AsmPrinter::EmitString(const StringRef String) const {
842 EmitString(String.data(), String.size());
845 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
846 const char* AscizDirective = MAI->getAscizDirective();
850 O << MAI->getAsciiDirective();
852 for (unsigned i = 0; i < Size; ++i)
853 printStringChar(O, String[i]);
861 /// EmitFile - Emit a .file directive.
862 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
863 O << "\t.file\t" << Number << " \"";
864 for (unsigned i = 0, N = Name.size(); i < N; ++i)
865 printStringChar(O, Name[i]);
870 //===----------------------------------------------------------------------===//
872 // EmitAlignment - Emit an alignment directive to the specified power of
873 // two boundary. For example, if you pass in 3 here, you will get an 8
874 // byte alignment. If a global value is specified, and if that global has
875 // an explicit alignment requested, it will unconditionally override the
876 // alignment request. However, if ForcedAlignBits is specified, this value
877 // has final say: the ultimate alignment will be the max of ForcedAlignBits
878 // and the alignment computed with NumBits and the global.
882 // if (GV && GV->hasalignment) Align = GV->getalignment();
883 // Align = std::max(Align, ForcedAlignBits);
885 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
886 unsigned ForcedAlignBits,
887 bool UseFillExpr) const {
888 if (GV && GV->getAlignment())
889 NumBits = Log2_32(GV->getAlignment());
890 NumBits = std::max(NumBits, ForcedAlignBits);
892 if (NumBits == 0) return; // No need to emit alignment.
894 unsigned FillValue = 0;
895 if (getCurrentSection()->getKind().isText())
896 FillValue = MAI->getTextAlignFillValue();
898 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
901 /// EmitZeros - Emit a block of zeros.
903 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
905 if (MAI->getZeroDirective()) {
906 O << MAI->getZeroDirective() << NumZeros;
907 if (MAI->getZeroDirectiveSuffix())
908 O << MAI->getZeroDirectiveSuffix();
911 for (; NumZeros; --NumZeros)
912 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
917 // Print out the specified constant, without a storage class. Only the
918 // constants valid in constant expressions can occur here.
919 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
920 if (CV->isNullValue() || isa<UndefValue>(CV)) {
925 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
926 O << CI->getZExtValue();
930 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
931 // This is a constant address for a global variable or function. Use the
932 // name of the variable or function as the address value.
933 O << *GetGlobalValueSymbol(GV);
937 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
938 O << *GetBlockAddressSymbol(BA);
942 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
944 llvm_unreachable("Unknown constant value!");
949 switch (CE->getOpcode()) {
950 case Instruction::ZExt:
951 case Instruction::SExt:
952 case Instruction::FPTrunc:
953 case Instruction::FPExt:
954 case Instruction::UIToFP:
955 case Instruction::SIToFP:
956 case Instruction::FPToUI:
957 case Instruction::FPToSI:
959 llvm_unreachable("FIXME: Don't support this constant cast expr");
960 case Instruction::GetElementPtr: {
961 // generate a symbolic expression for the byte address
962 const TargetData *TD = TM.getTargetData();
963 const Constant *ptrVal = CE->getOperand(0);
964 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
965 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
968 return EmitConstantValueOnly(ptrVal);
970 // Truncate/sext the offset to the pointer size.
971 if (TD->getPointerSizeInBits() != 64) {
972 int SExtAmount = 64-TD->getPointerSizeInBits();
973 Offset = (Offset << SExtAmount) >> SExtAmount;
978 EmitConstantValueOnly(ptrVal);
980 O << ") + " << Offset;
982 O << ") - " << -Offset;
985 case Instruction::BitCast:
986 return EmitConstantValueOnly(CE->getOperand(0));
988 case Instruction::IntToPtr: {
989 // Handle casts to pointers by changing them into casts to the appropriate
990 // integer type. This promotes constant folding and simplifies this code.
991 const TargetData *TD = TM.getTargetData();
992 Constant *Op = CE->getOperand(0);
993 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
995 return EmitConstantValueOnly(Op);
998 case Instruction::PtrToInt: {
999 // Support only foldable casts to/from pointers that can be eliminated by
1000 // changing the pointer to the appropriately sized integer type.
1001 Constant *Op = CE->getOperand(0);
1002 const Type *Ty = CE->getType();
1003 const TargetData *TD = TM.getTargetData();
1005 // We can emit the pointer value into this slot if the slot is an
1006 // integer slot greater or equal to the size of the pointer.
1007 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
1008 return EmitConstantValueOnly(Op);
1011 EmitConstantValueOnly(Op);
1013 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
1016 ptrMask.toStringUnsigned(S);
1017 O << ") & " << S.str() << ')';
1021 case Instruction::Trunc:
1022 // We emit the value and depend on the assembler to truncate the generated
1023 // expression properly. This is important for differences between
1024 // blockaddress labels. Since the two labels are in the same function, it
1025 // is reasonable to treat their delta as a 32-bit value.
1026 return EmitConstantValueOnly(CE->getOperand(0));
1028 case Instruction::Add:
1029 case Instruction::Sub:
1030 case Instruction::And:
1031 case Instruction::Or:
1032 case Instruction::Xor:
1034 EmitConstantValueOnly(CE->getOperand(0));
1036 switch (CE->getOpcode()) {
1037 case Instruction::Add:
1040 case Instruction::Sub:
1043 case Instruction::And:
1046 case Instruction::Or:
1049 case Instruction::Xor:
1056 EmitConstantValueOnly(CE->getOperand(1));
1062 /// printAsCString - Print the specified array as a C compatible string, only if
1063 /// the predicate isString is true.
1065 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
1067 assert(CVA->isString() && "Array is not string compatible!");
1070 for (unsigned i = 0; i != LastElt; ++i) {
1072 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
1073 printStringChar(O, C);
1078 /// EmitString - Emit a zero-byte-terminated string constant.
1080 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
1081 unsigned NumElts = CVA->getNumOperands();
1082 if (MAI->getAscizDirective() && NumElts &&
1083 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
1084 O << MAI->getAscizDirective();
1085 printAsCString(O, CVA, NumElts-1);
1087 O << MAI->getAsciiDirective();
1088 printAsCString(O, CVA, NumElts);
1093 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
1094 unsigned AddrSpace) {
1095 if (CVA->isString()) {
1097 } else { // Not a string. Print the values in successive locations
1098 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
1099 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1103 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1104 const VectorType *PTy = CP->getType();
1106 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1107 EmitGlobalConstant(CP->getOperand(I));
1110 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1111 unsigned AddrSpace) {
1112 // Print the fields in successive locations. Pad to align if needed!
1113 const TargetData *TD = TM.getTargetData();
1114 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1115 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1116 uint64_t sizeSoFar = 0;
1117 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1118 const Constant* field = CVS->getOperand(i);
1120 // Check if padding is needed and insert one or more 0s.
1121 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1122 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1123 - cvsLayout->getElementOffset(i)) - fieldSize;
1124 sizeSoFar += fieldSize + padSize;
1126 // Now print the actual field value.
1127 EmitGlobalConstant(field, AddrSpace);
1129 // Insert padding - this may include padding to increase the size of the
1130 // current field up to the ABI size (if the struct is not packed) as well
1131 // as padding to ensure that the next field starts at the right offset.
1132 EmitZeros(padSize, AddrSpace);
1134 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1135 "Layout of constant struct may be incorrect!");
1138 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1139 unsigned AddrSpace) {
1140 // FP Constants are printed as integer constants to avoid losing
1142 LLVMContext &Context = CFP->getContext();
1143 const TargetData *TD = TM.getTargetData();
1144 if (CFP->getType()->isDoubleTy()) {
1145 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1146 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1147 if (MAI->getData64bitsDirective(AddrSpace)) {
1148 O << MAI->getData64bitsDirective(AddrSpace) << i;
1150 O.PadToColumn(MAI->getCommentColumn());
1151 O << MAI->getCommentString() << " double " << Val;
1154 } else if (TD->isBigEndian()) {
1155 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1157 O.PadToColumn(MAI->getCommentColumn());
1158 O << MAI->getCommentString()
1159 << " most significant word of double " << Val;
1162 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1164 O.PadToColumn(MAI->getCommentColumn());
1165 O << MAI->getCommentString()
1166 << " least significant word of double " << Val;
1170 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1172 O.PadToColumn(MAI->getCommentColumn());
1173 O << MAI->getCommentString()
1174 << " least significant word of double " << Val;
1177 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1179 O.PadToColumn(MAI->getCommentColumn());
1180 O << MAI->getCommentString()
1181 << " most significant word of double " << Val;
1188 if (CFP->getType()->isFloatTy()) {
1189 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1190 O << MAI->getData32bitsDirective(AddrSpace)
1191 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1193 O.PadToColumn(MAI->getCommentColumn());
1194 O << MAI->getCommentString() << " float " << Val;
1200 if (CFP->getType()->isX86_FP80Ty()) {
1201 // all long double variants are printed as hex
1202 // api needed to prevent premature destruction
1203 APInt api = CFP->getValueAPF().bitcastToAPInt();
1204 const uint64_t *p = api.getRawData();
1205 // Convert to double so we can print the approximate val as a comment.
1206 APFloat DoubleVal = CFP->getValueAPF();
1208 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1210 if (TD->isBigEndian()) {
1211 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1213 O.PadToColumn(MAI->getCommentColumn());
1214 O << MAI->getCommentString()
1215 << " most significant halfword of x86_fp80 ~"
1216 << DoubleVal.convertToDouble();
1219 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1221 O.PadToColumn(MAI->getCommentColumn());
1222 O << MAI->getCommentString() << " next halfword";
1225 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1227 O.PadToColumn(MAI->getCommentColumn());
1228 O << MAI->getCommentString() << " next halfword";
1231 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1233 O.PadToColumn(MAI->getCommentColumn());
1234 O << MAI->getCommentString() << " next halfword";
1237 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1239 O.PadToColumn(MAI->getCommentColumn());
1240 O << MAI->getCommentString()
1241 << " least significant halfword";
1245 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1247 O.PadToColumn(MAI->getCommentColumn());
1248 O << MAI->getCommentString()
1249 << " least significant halfword of x86_fp80 ~"
1250 << DoubleVal.convertToDouble();
1253 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1255 O.PadToColumn(MAI->getCommentColumn());
1256 O << MAI->getCommentString()
1257 << " next halfword";
1260 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1262 O.PadToColumn(MAI->getCommentColumn());
1263 O << MAI->getCommentString()
1264 << " next halfword";
1267 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1269 O.PadToColumn(MAI->getCommentColumn());
1270 O << MAI->getCommentString()
1271 << " next halfword";
1274 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1276 O.PadToColumn(MAI->getCommentColumn());
1277 O << MAI->getCommentString()
1278 << " most significant halfword";
1282 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1283 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1287 if (CFP->getType()->isPPC_FP128Ty()) {
1288 // all long double variants are printed as hex
1289 // api needed to prevent premature destruction
1290 APInt api = CFP->getValueAPF().bitcastToAPInt();
1291 const uint64_t *p = api.getRawData();
1292 if (TD->isBigEndian()) {
1293 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1295 O.PadToColumn(MAI->getCommentColumn());
1296 O << MAI->getCommentString()
1297 << " most significant word of ppc_fp128";
1300 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1302 O.PadToColumn(MAI->getCommentColumn());
1303 O << MAI->getCommentString()
1307 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1309 O.PadToColumn(MAI->getCommentColumn());
1310 O << MAI->getCommentString()
1314 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1316 O.PadToColumn(MAI->getCommentColumn());
1317 O << MAI->getCommentString()
1318 << " least significant word";
1322 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1324 O.PadToColumn(MAI->getCommentColumn());
1325 O << MAI->getCommentString()
1326 << " least significant word of ppc_fp128";
1329 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1331 O.PadToColumn(MAI->getCommentColumn());
1332 O << MAI->getCommentString()
1336 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1338 O.PadToColumn(MAI->getCommentColumn());
1339 O << MAI->getCommentString()
1343 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1345 O.PadToColumn(MAI->getCommentColumn());
1346 O << MAI->getCommentString()
1347 << " most significant word";
1352 } else llvm_unreachable("Floating point constant type not handled");
1355 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1356 unsigned AddrSpace) {
1357 const TargetData *TD = TM.getTargetData();
1358 unsigned BitWidth = CI->getBitWidth();
1359 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1361 // We don't expect assemblers to support integer data directives
1362 // for more than 64 bits, so we emit the data in at most 64-bit
1363 // quantities at a time.
1364 const uint64_t *RawData = CI->getValue().getRawData();
1365 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1367 if (TD->isBigEndian())
1368 Val = RawData[e - i - 1];
1372 if (MAI->getData64bitsDirective(AddrSpace)) {
1373 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1377 // Emit two 32-bit chunks, order depends on endianness.
1378 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1379 const char *FirstName = " least", *SecondName = " most";
1380 if (TD->isBigEndian()) {
1381 std::swap(FirstChunk, SecondChunk);
1382 std::swap(FirstName, SecondName);
1385 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1387 O.PadToColumn(MAI->getCommentColumn());
1388 O << MAI->getCommentString()
1389 << FirstName << " significant half of i64 " << Val;
1393 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1395 O.PadToColumn(MAI->getCommentColumn());
1396 O << MAI->getCommentString()
1397 << SecondName << " significant half of i64 " << Val;
1403 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1404 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1405 const TargetData *TD = TM.getTargetData();
1406 const Type *type = CV->getType();
1407 unsigned Size = TD->getTypeAllocSize(type);
1409 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1410 EmitZeros(Size, AddrSpace);
1414 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1415 EmitGlobalConstantArray(CVA , AddrSpace);
1419 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1420 EmitGlobalConstantStruct(CVS, AddrSpace);
1424 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1425 EmitGlobalConstantFP(CFP, AddrSpace);
1429 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1430 // If we can directly emit an 8-byte constant, do it.
1432 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1433 O << Data64Dir << CI->getZExtValue() << '\n';
1437 // Small integers are handled below; large integers are handled here.
1439 EmitGlobalConstantLargeInt(CI, AddrSpace);
1444 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1445 EmitGlobalConstantVector(CP);
1449 printDataDirective(type, AddrSpace);
1450 EmitConstantValueOnly(CV);
1452 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1454 CI->getValue().toStringUnsigned(S, 16);
1455 O.PadToColumn(MAI->getCommentColumn());
1456 O << MAI->getCommentString() << " 0x" << S.str();
1462 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1463 // Target doesn't support this yet!
1464 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1467 /// PrintSpecial - Print information related to the specified machine instr
1468 /// that is independent of the operand, and may be independent of the instr
1469 /// itself. This can be useful for portably encoding the comment character
1470 /// or other bits of target-specific knowledge into the asmstrings. The
1471 /// syntax used is ${:comment}. Targets can override this to add support
1472 /// for their own strange codes.
1473 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1474 if (!strcmp(Code, "private")) {
1475 O << MAI->getPrivateGlobalPrefix();
1476 } else if (!strcmp(Code, "comment")) {
1478 O << MAI->getCommentString();
1479 } else if (!strcmp(Code, "uid")) {
1480 // Comparing the address of MI isn't sufficient, because machineinstrs may
1481 // be allocated to the same address across functions.
1482 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1484 // If this is a new LastFn instruction, bump the counter.
1485 if (LastMI != MI || LastFn != ThisF) {
1493 raw_string_ostream Msg(msg);
1494 Msg << "Unknown special formatter '" << Code
1495 << "' for machine instr: " << *MI;
1496 llvm_report_error(Msg.str());
1500 /// processDebugLoc - Processes the debug information of each machine
1501 /// instruction's DebugLoc.
1502 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1503 bool BeforePrintingInsn) {
1504 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1505 || !DW->ShouldEmitDwarfDebug())
1507 DebugLoc DL = MI->getDebugLoc();
1510 DILocation CurDLT = MF->getDILocation(DL);
1511 if (CurDLT.getScope().isNull())
1514 if (BeforePrintingInsn) {
1515 if (CurDLT.getNode() != PrevDLT.getNode()) {
1516 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1517 CurDLT.getColumnNumber(),
1518 CurDLT.getScope().getNode());
1521 DW->BeginScope(MI, L);
1525 // After printing instruction
1531 /// printInlineAsm - This method formats and prints the specified machine
1532 /// instruction that is an inline asm.
1533 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1534 unsigned NumOperands = MI->getNumOperands();
1536 // Count the number of register definitions.
1537 unsigned NumDefs = 0;
1538 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1540 assert(NumDefs != NumOperands-1 && "No asm string?");
1542 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1544 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1545 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1549 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1550 // These are useful to see where empty asm's wound up.
1551 if (AsmStr[0] == 0) {
1552 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1553 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1557 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1559 // The variant of the current asmprinter.
1560 int AsmPrinterVariant = MAI->getAssemblerDialect();
1562 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1563 const char *LastEmitted = AsmStr; // One past the last character emitted.
1565 while (*LastEmitted) {
1566 switch (*LastEmitted) {
1568 // Not a special case, emit the string section literally.
1569 const char *LiteralEnd = LastEmitted+1;
1570 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1571 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1573 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1574 O.write(LastEmitted, LiteralEnd-LastEmitted);
1575 LastEmitted = LiteralEnd;
1579 ++LastEmitted; // Consume newline character.
1580 O << '\n'; // Indent code with newline.
1583 ++LastEmitted; // Consume '$' character.
1587 switch (*LastEmitted) {
1588 default: Done = false; break;
1589 case '$': // $$ -> $
1590 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1592 ++LastEmitted; // Consume second '$' character.
1594 case '(': // $( -> same as GCC's { character.
1595 ++LastEmitted; // Consume '(' character.
1596 if (CurVariant != -1) {
1597 llvm_report_error("Nested variants found in inline asm string: '"
1598 + std::string(AsmStr) + "'");
1600 CurVariant = 0; // We're in the first variant now.
1603 ++LastEmitted; // consume '|' character.
1604 if (CurVariant == -1)
1605 O << '|'; // this is gcc's behavior for | outside a variant
1607 ++CurVariant; // We're in the next variant.
1609 case ')': // $) -> same as GCC's } char.
1610 ++LastEmitted; // consume ')' character.
1611 if (CurVariant == -1)
1612 O << '}'; // this is gcc's behavior for } outside a variant
1619 bool HasCurlyBraces = false;
1620 if (*LastEmitted == '{') { // ${variable}
1621 ++LastEmitted; // Consume '{' character.
1622 HasCurlyBraces = true;
1625 // If we have ${:foo}, then this is not a real operand reference, it is a
1626 // "magic" string reference, just like in .td files. Arrange to call
1628 if (HasCurlyBraces && *LastEmitted == ':') {
1630 const char *StrStart = LastEmitted;
1631 const char *StrEnd = strchr(StrStart, '}');
1633 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1634 + std::string(AsmStr) + "'");
1637 std::string Val(StrStart, StrEnd);
1638 PrintSpecial(MI, Val.c_str());
1639 LastEmitted = StrEnd+1;
1643 const char *IDStart = LastEmitted;
1646 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1647 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1648 llvm_report_error("Bad $ operand number in inline asm string: '"
1649 + std::string(AsmStr) + "'");
1651 LastEmitted = IDEnd;
1653 char Modifier[2] = { 0, 0 };
1655 if (HasCurlyBraces) {
1656 // If we have curly braces, check for a modifier character. This
1657 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1658 if (*LastEmitted == ':') {
1659 ++LastEmitted; // Consume ':' character.
1660 if (*LastEmitted == 0) {
1661 llvm_report_error("Bad ${:} expression in inline asm string: '"
1662 + std::string(AsmStr) + "'");
1665 Modifier[0] = *LastEmitted;
1666 ++LastEmitted; // Consume modifier character.
1669 if (*LastEmitted != '}') {
1670 llvm_report_error("Bad ${} expression in inline asm string: '"
1671 + std::string(AsmStr) + "'");
1673 ++LastEmitted; // Consume '}' character.
1676 if ((unsigned)Val >= NumOperands-1) {
1677 llvm_report_error("Invalid $ operand number in inline asm string: '"
1678 + std::string(AsmStr) + "'");
1681 // Okay, we finally have a value number. Ask the target to print this
1683 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1688 // Scan to find the machine operand number for the operand.
1689 for (; Val; --Val) {
1690 if (OpNo >= MI->getNumOperands()) break;
1691 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1692 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1695 if (OpNo >= MI->getNumOperands()) {
1698 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1699 ++OpNo; // Skip over the ID number.
1701 if (Modifier[0] == 'l') // labels are target independent
1702 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1704 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1705 if ((OpFlags & 7) == 4) {
1706 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1707 Modifier[0] ? Modifier : 0);
1709 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1710 Modifier[0] ? Modifier : 0);
1716 raw_string_ostream Msg(msg);
1717 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1719 llvm_report_error(Msg.str());
1726 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1729 /// printImplicitDef - This method prints the specified machine instruction
1730 /// that is an implicit def.
1731 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1732 if (!VerboseAsm) return;
1733 O.PadToColumn(MAI->getCommentColumn());
1734 O << MAI->getCommentString() << " implicit-def: "
1735 << TRI->getName(MI->getOperand(0).getReg());
1738 void AsmPrinter::printKill(const MachineInstr *MI) const {
1739 if (!VerboseAsm) return;
1740 O.PadToColumn(MAI->getCommentColumn());
1741 O << MAI->getCommentString() << " kill:";
1742 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1743 const MachineOperand &op = MI->getOperand(n);
1744 assert(op.isReg() && "KILL instruction must have only register operands");
1745 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1749 /// printLabel - This method prints a local label used by debug and
1750 /// exception handling tables.
1751 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1752 printLabel(MI->getOperand(0).getImm());
1755 void AsmPrinter::printLabel(unsigned Id) const {
1756 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1759 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1760 /// instruction, using the specified assembler variant. Targets should
1761 /// override this to format as appropriate.
1762 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1763 unsigned AsmVariant, const char *ExtraCode) {
1764 // Target doesn't support this yet!
1768 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1769 unsigned AsmVariant,
1770 const char *ExtraCode) {
1771 // Target doesn't support this yet!
1775 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1776 const char *Suffix) const {
1777 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1780 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1781 const BasicBlock *BB,
1782 const char *Suffix) const {
1783 assert(BB->hasName() &&
1784 "Address of anonymous basic block not supported yet!");
1786 // This code must use the function name itself, and not the function number,
1787 // since it must be possible to generate the label name from within other
1789 SmallString<60> FnName;
1790 Mang->getNameWithPrefix(FnName, F, false);
1792 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1793 SmallString<60> NameResult;
1794 Mang->getNameWithPrefix(NameResult,
1795 StringRef("BA") + Twine((unsigned)FnName.size()) +
1796 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1799 return OutContext.GetOrCreateSymbol(NameResult.str());
1802 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1803 SmallString<60> Name;
1804 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1805 << getFunctionNumber() << '_' << MBBID;
1807 return OutContext.GetOrCreateSymbol(Name.str());
1810 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1812 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1813 SmallString<60> NameStr;
1814 Mang->getNameWithPrefix(NameStr, GV, false);
1815 return OutContext.GetOrCreateSymbol(NameStr.str());
1818 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1819 /// global value name as its base, with the specified suffix, and where the
1820 /// symbol is forced to have private linkage if ForcePrivate is true.
1821 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1823 bool ForcePrivate) const {
1824 SmallString<60> NameStr;
1825 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1826 NameStr.append(Suffix.begin(), Suffix.end());
1827 return OutContext.GetOrCreateSymbol(NameStr.str());
1830 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1832 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1833 SmallString<60> NameStr;
1834 Mang->getNameWithPrefix(NameStr, Sym);
1835 return OutContext.GetOrCreateSymbol(NameStr.str());
1839 /// EmitBasicBlockStart - This method prints the label for the specified
1840 /// MachineBasicBlock, an alignment (if present) and a comment describing
1841 /// it if appropriate.
1842 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1843 // Emit an alignment directive for this block, if needed.
1844 if (unsigned Align = MBB->getAlignment())
1845 EmitAlignment(Log2_32(Align));
1847 // If the block has its address taken, emit a special label to satisfy
1848 // references to the block. This is done so that we don't need to
1849 // remember the number of this label, and so that we can make
1850 // forward references to labels without knowing what their numbers
1852 if (MBB->hasAddressTaken()) {
1853 O << *GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1854 MBB->getBasicBlock());
1857 O.PadToColumn(MAI->getCommentColumn());
1858 O << MAI->getCommentString() << " Address Taken";
1863 // Print the main label for the block.
1864 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1866 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1868 O << *GetMBBSymbol(MBB->getNumber()) << ':';
1873 // Print some comments to accompany the label.
1875 if (const BasicBlock *BB = MBB->getBasicBlock())
1876 if (BB->hasName()) {
1877 O.PadToColumn(MAI->getCommentColumn());
1878 O << MAI->getCommentString() << ' ';
1879 WriteAsOperand(O, BB, /*PrintType=*/false);
1887 /// printPICJumpTableSetLabel - This method prints a set label for the
1888 /// specified MachineBasicBlock for a jumptable entry.
1889 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1890 const MachineBasicBlock *MBB) const {
1891 if (!MAI->getSetDirective())
1894 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1895 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1896 << *GetMBBSymbol(MBB->getNumber())
1897 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1898 << '_' << uid << '\n';
1901 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1902 const MachineBasicBlock *MBB) const {
1903 if (!MAI->getSetDirective())
1906 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1907 << getFunctionNumber() << '_' << uid << '_' << uid2
1908 << "_set_" << MBB->getNumber() << ','
1909 << *GetMBBSymbol(MBB->getNumber())
1910 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1911 << '_' << uid << '_' << uid2 << '\n';
1914 /// printDataDirective - This method prints the asm directive for the
1916 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1917 const TargetData *TD = TM.getTargetData();
1918 switch (type->getTypeID()) {
1919 case Type::FloatTyID: case Type::DoubleTyID:
1920 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1921 assert(0 && "Should have already output floating point constant.");
1923 assert(0 && "Can't handle printing this type of thing");
1924 case Type::IntegerTyID: {
1925 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1927 O << MAI->getData8bitsDirective(AddrSpace);
1928 else if (BitWidth <= 16)
1929 O << MAI->getData16bitsDirective(AddrSpace);
1930 else if (BitWidth <= 32)
1931 O << MAI->getData32bitsDirective(AddrSpace);
1932 else if (BitWidth <= 64) {
1933 assert(MAI->getData64bitsDirective(AddrSpace) &&
1934 "Target cannot handle 64-bit constant exprs!");
1935 O << MAI->getData64bitsDirective(AddrSpace);
1937 llvm_unreachable("Target cannot handle given data directive width!");
1941 case Type::PointerTyID:
1942 if (TD->getPointerSize() == 8) {
1943 assert(MAI->getData64bitsDirective(AddrSpace) &&
1944 "Target cannot handle 64-bit pointer exprs!");
1945 O << MAI->getData64bitsDirective(AddrSpace);
1946 } else if (TD->getPointerSize() == 2) {
1947 O << MAI->getData16bitsDirective(AddrSpace);
1948 } else if (TD->getPointerSize() == 1) {
1949 O << MAI->getData8bitsDirective(AddrSpace);
1951 O << MAI->getData32bitsDirective(AddrSpace);
1957 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1958 unsigned Visibility) const {
1959 if (Visibility == GlobalValue::HiddenVisibility) {
1960 if (const char *Directive = MAI->getHiddenDirective())
1961 O << Directive << *Sym << '\n';
1962 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1963 if (const char *Directive = MAI->getProtectedDirective())
1964 O << Directive << *Sym << '\n';
1968 void AsmPrinter::printOffset(int64_t Offset) const {
1971 else if (Offset < 0)
1975 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1976 if (!S->usesMetadata())
1979 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1980 if (GCPI != GCMetadataPrinters.end())
1981 return GCPI->second;
1983 const char *Name = S->getName().c_str();
1985 for (GCMetadataPrinterRegistry::iterator
1986 I = GCMetadataPrinterRegistry::begin(),
1987 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1988 if (strcmp(Name, I->getName()) == 0) {
1989 GCMetadataPrinter *GMP = I->instantiate();
1991 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1995 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1996 llvm_unreachable(0);
1999 /// EmitComments - Pretty-print comments for instructions
2000 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
2004 bool Newline = false;
2006 if (!MI.getDebugLoc().isUnknown()) {
2007 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
2009 // Print source line info.
2010 O.PadToColumn(MAI->getCommentColumn());
2011 O << MAI->getCommentString() << ' ';
2012 DIScope Scope = DLT.getScope();
2013 // Omit the directory, because it's likely to be long and uninteresting.
2014 if (!Scope.isNull())
2015 O << Scope.getFilename();
2018 O << ':' << DLT.getLineNumber();
2019 if (DLT.getColumnNumber() != 0)
2020 O << ':' << DLT.getColumnNumber();
2024 // Check for spills and reloads
2027 const MachineFrameInfo *FrameInfo =
2028 MI.getParent()->getParent()->getFrameInfo();
2030 // We assume a single instruction only has a spill or reload, not
2032 const MachineMemOperand *MMO;
2033 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
2034 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2035 MMO = *MI.memoperands_begin();
2036 if (Newline) O << '\n';
2037 O.PadToColumn(MAI->getCommentColumn());
2038 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
2042 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
2043 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2044 if (Newline) O << '\n';
2045 O.PadToColumn(MAI->getCommentColumn());
2046 O << MAI->getCommentString() << ' '
2047 << MMO->getSize() << "-byte Folded Reload";
2051 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
2052 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2053 MMO = *MI.memoperands_begin();
2054 if (Newline) O << '\n';
2055 O.PadToColumn(MAI->getCommentColumn());
2056 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
2060 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
2061 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2062 if (Newline) O << '\n';
2063 O.PadToColumn(MAI->getCommentColumn());
2064 O << MAI->getCommentString() << ' '
2065 << MMO->getSize() << "-byte Folded Spill";
2070 // Check for spill-induced copies
2071 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2072 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
2073 SrcSubIdx, DstSubIdx)) {
2074 if (MI.getAsmPrinterFlag(ReloadReuse)) {
2075 if (Newline) O << '\n';
2076 O.PadToColumn(MAI->getCommentColumn());
2077 O << MAI->getCommentString() << " Reload Reuse";
2082 /// PrintChildLoopComment - Print comments about child loops within
2083 /// the loop for this basic block, with nesting.
2085 static void PrintChildLoopComment(formatted_raw_ostream &O,
2086 const MachineLoop *loop,
2087 const MCAsmInfo *MAI,
2088 int FunctionNumber) {
2089 // Add child loop information
2090 for(MachineLoop::iterator cl = loop->begin(),
2091 clend = loop->end();
2094 MachineBasicBlock *Header = (*cl)->getHeader();
2095 assert(Header && "No header for loop");
2098 O.PadToColumn(MAI->getCommentColumn());
2100 O << MAI->getCommentString();
2101 O.indent(((*cl)->getLoopDepth()-1)*2)
2102 << " Child Loop BB" << FunctionNumber << "_"
2103 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2105 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2109 /// EmitComments - Pretty-print comments for basic blocks
2110 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2112 // Add loop depth information
2113 const MachineLoop *loop = LI->getLoopFor(&MBB);
2116 // Print a newline after bb# annotation.
2118 O.PadToColumn(MAI->getCommentColumn());
2119 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2122 O.PadToColumn(MAI->getCommentColumn());
2124 MachineBasicBlock *Header = loop->getHeader();
2125 assert(Header && "No header for loop");
2127 if (Header == &MBB) {
2128 O << MAI->getCommentString() << " Loop Header";
2129 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2132 O << MAI->getCommentString() << " Loop Header is BB"
2133 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2136 if (loop->empty()) {
2138 O.PadToColumn(MAI->getCommentColumn());
2139 O << MAI->getCommentString() << " Inner Loop";
2142 // Add parent loop information
2143 for (const MachineLoop *CurLoop = loop->getParentLoop();
2145 CurLoop = CurLoop->getParentLoop()) {
2146 MachineBasicBlock *Header = CurLoop->getHeader();
2147 assert(Header && "No header for loop");
2150 O.PadToColumn(MAI->getCommentColumn());
2151 O << MAI->getCommentString();
2152 O.indent((CurLoop->getLoopDepth()-1)*2)
2153 << " Inside Loop BB" << getFunctionNumber() << "_"
2154 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();