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/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/DwarfWriter.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/Support/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.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"
46 #include "llvm/ADT/StringExtras.h"
50 static cl::opt<cl::boolOrDefault>
51 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52 cl::init(cl::BOU_UNSET));
54 char AsmPrinter::ID = 0;
55 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
56 const MCAsmInfo *T, bool VDef)
57 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
58 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
60 OutContext(*new MCContext()),
61 // FIXME: Pass instprinter to streamer.
62 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
64 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
67 case cl::BOU_UNSET: VerboseAsm = VDef; break;
68 case cl::BOU_TRUE: VerboseAsm = true; break;
69 case cl::BOU_FALSE: VerboseAsm = false; break;
73 AsmPrinter::~AsmPrinter() {
74 for (gcp_iterator I = GCMetadataPrinters.begin(),
75 E = GCMetadataPrinters.end(); I != E; ++I)
82 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
83 return TM.getTargetLowering()->getObjFileLowering();
86 /// getCurrentSection() - Return the current section we are emitting to.
87 const MCSection *AsmPrinter::getCurrentSection() const {
88 return OutStreamer.getCurrentSection();
92 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
94 MachineFunctionPass::getAnalysisUsage(AU);
95 AU.addRequired<GCModuleInfo>();
97 AU.addRequired<MachineLoopInfo>();
100 bool AsmPrinter::doInitialization(Module &M) {
101 // Initialize TargetLoweringObjectFile.
102 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
103 .Initialize(OutContext, TM);
105 Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(),
106 MAI->getLinkerPrivateGlobalPrefix());
108 if (MAI->doesAllowQuotesInName())
109 Mang->setUseQuotes(true);
111 if (MAI->doesAllowNameToStartWithDigit())
112 Mang->setSymbolsCanStartWithDigit(true);
114 // Allow the target to emit any magic that it wants at the start of the file.
115 EmitStartOfAsmFile(M);
117 if (MAI->hasSingleParameterDotFile()) {
118 /* Very minimal debug info. It is ignored if we emit actual
119 debug info. If we don't, this at least helps the user find where
120 a function came from. */
121 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
124 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
125 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
126 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
127 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
128 MP->beginAssembly(O, *this, *MAI);
130 if (!M.getModuleInlineAsm().empty())
131 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
132 << M.getModuleInlineAsm()
133 << '\n' << MAI->getCommentString()
134 << " End of file scope inline assembly\n";
136 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
138 MMI->AnalyzeModule(M);
139 DW = getAnalysisIfAvailable<DwarfWriter>();
141 DW->BeginModule(&M, MMI, O, this, MAI);
146 bool AsmPrinter::doFinalization(Module &M) {
147 // Emit global variables.
148 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
150 PrintGlobalVariable(I);
152 // Emit final debug information.
153 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
156 // If the target wants to know about weak references, print them all.
157 if (MAI->getWeakRefDirective()) {
158 // FIXME: This is not lazy, it would be nice to only print weak references
159 // to stuff that is actually used. Note that doing so would require targets
160 // to notice uses in operands (due to constant exprs etc). This should
161 // happen with the MC stuff eventually.
163 // Print out module-level global variables here.
164 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
166 if (!I->hasExternalWeakLinkage()) continue;
167 O << MAI->getWeakRefDirective();
168 GetGlobalValueSymbol(I)->print(O, MAI);
172 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
173 if (!I->hasExternalWeakLinkage()) continue;
174 O << MAI->getWeakRefDirective();
175 GetGlobalValueSymbol(I)->print(O, MAI);
180 if (MAI->getSetDirective()) {
182 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
184 MCSymbol *Name = GetGlobalValueSymbol(I);
186 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
187 MCSymbol *Target = GetGlobalValueSymbol(GV);
189 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) {
193 } else if (I->hasWeakLinkage()) {
194 O << MAI->getWeakRefDirective();
198 assert(I->hasLocalLinkage() && "Invalid alias linkage");
201 printVisibility(Name, I->getVisibility());
203 O << MAI->getSetDirective() << ' ';
206 Target->print(O, MAI);
211 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
212 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
213 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
214 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
215 MP->finishAssembly(O, *this, *MAI);
217 // If we don't have any trampolines, then we don't require stack memory
218 // to be executable. Some targets have a directive to declare this.
219 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
220 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
221 if (MAI->getNonexecutableStackDirective())
222 O << MAI->getNonexecutableStackDirective() << '\n';
225 // Allow the target to emit any magic that it wants at the end of the file,
226 // after everything else has gone out.
229 delete Mang; Mang = 0;
232 OutStreamer.Finish();
236 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
237 // Get the function symbol.
238 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
239 IncrementFunctionNumber();
242 LI = &getAnalysis<MachineLoopInfo>();
246 // SectionCPs - Keep track the alignment, constpool entries per Section.
250 SmallVector<unsigned, 4> CPEs;
251 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
255 /// EmitConstantPool - Print to the current output stream assembly
256 /// representations of the constants in the constant pool MCP. This is
257 /// used to print out constants which have been "spilled to memory" by
258 /// the code generator.
260 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
261 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
262 if (CP.empty()) return;
264 // Calculate sections for constant pool entries. We collect entries to go into
265 // the same section together to reduce amount of section switch statements.
266 SmallVector<SectionCPs, 4> CPSections;
267 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
268 const MachineConstantPoolEntry &CPE = CP[i];
269 unsigned Align = CPE.getAlignment();
272 switch (CPE.getRelocationInfo()) {
273 default: llvm_unreachable("Unknown section kind");
274 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
276 Kind = SectionKind::getReadOnlyWithRelLocal();
279 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
280 case 4: Kind = SectionKind::getMergeableConst4(); break;
281 case 8: Kind = SectionKind::getMergeableConst8(); break;
282 case 16: Kind = SectionKind::getMergeableConst16();break;
283 default: Kind = SectionKind::getMergeableConst(); break;
287 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
289 // The number of sections are small, just do a linear search from the
290 // last section to the first.
292 unsigned SecIdx = CPSections.size();
293 while (SecIdx != 0) {
294 if (CPSections[--SecIdx].S == S) {
300 SecIdx = CPSections.size();
301 CPSections.push_back(SectionCPs(S, Align));
304 if (Align > CPSections[SecIdx].Alignment)
305 CPSections[SecIdx].Alignment = Align;
306 CPSections[SecIdx].CPEs.push_back(i);
309 // Now print stuff into the calculated sections.
310 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
311 OutStreamer.SwitchSection(CPSections[i].S);
312 EmitAlignment(Log2_32(CPSections[i].Alignment));
315 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
316 unsigned CPI = CPSections[i].CPEs[j];
317 MachineConstantPoolEntry CPE = CP[CPI];
319 // Emit inter-object padding for alignment.
320 unsigned AlignMask = CPE.getAlignment() - 1;
321 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
322 EmitZeros(NewOffset - Offset);
324 const Type *Ty = CPE.getType();
325 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
327 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
330 O.PadToColumn(MAI->getCommentColumn());
331 O << MAI->getCommentString() << " constant ";
332 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
335 if (CPE.isMachineConstantPoolEntry())
336 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
338 EmitGlobalConstant(CPE.Val.ConstVal);
343 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
344 /// by the current function to the current output stream.
346 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
347 MachineFunction &MF) {
348 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
349 if (JT.empty()) return;
351 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
353 // Pick the directive to use to print the jump table entries, and switch to
354 // the appropriate section.
355 TargetLowering *LoweringInfo = TM.getTargetLowering();
357 const Function *F = MF.getFunction();
358 bool JTInDiffSection = false;
359 if (F->isWeakForLinker() ||
360 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
361 // In PIC mode, we need to emit the jump table to the same section as the
362 // function body itself, otherwise the label differences won't make sense.
363 // We should also do if the section name is NULL or function is declared in
364 // discardable section.
365 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
368 // Otherwise, drop it in the readonly section.
369 const MCSection *ReadOnlySection =
370 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
371 OutStreamer.SwitchSection(ReadOnlySection);
372 JTInDiffSection = true;
375 EmitAlignment(Log2_32(MJTI->getAlignment()));
377 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
378 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
380 // If this jump table was deleted, ignore it.
381 if (JTBBs.empty()) continue;
383 // For PIC codegen, if possible we want to use the SetDirective to reduce
384 // the number of relocations the assembler will generate for the jump table.
385 // Set directives are all printed before the jump table itself.
386 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
387 if (MAI->getSetDirective() && IsPic)
388 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
389 if (EmittedSets.insert(JTBBs[ii]))
390 printPICJumpTableSetLabel(i, JTBBs[ii]);
392 // On some targets (e.g. Darwin) we want to emit two consequtive labels
393 // before each jump table. The first label is never referenced, but tells
394 // the assembler and linker the extents of the jump table object. The
395 // second label is actually referenced by the code.
396 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
397 O << MAI->getLinkerPrivateGlobalPrefix()
398 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
401 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
402 << '_' << i << ":\n";
404 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
405 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
411 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
412 const MachineBasicBlock *MBB,
413 unsigned uid) const {
414 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
416 // Use JumpTableDirective otherwise honor the entry size from the jump table
418 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
419 bool HadJTEntryDirective = JTEntryDirective != NULL;
420 if (!HadJTEntryDirective) {
421 JTEntryDirective = MJTI->getEntrySize() == 4 ?
422 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
425 O << JTEntryDirective << ' ';
427 // If we have emitted set directives for the jump table entries, print
428 // them rather than the entries themselves. If we're emitting PIC, then
429 // emit the table entries as differences between two text section labels.
430 // If we're emitting non-PIC code, then emit the entries as direct
431 // references to the target basic blocks.
433 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
434 } else if (MAI->getSetDirective()) {
435 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
436 << '_' << uid << "_set_" << MBB->getNumber();
438 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
439 // If the arch uses custom Jump Table directives, don't calc relative to
441 if (!HadJTEntryDirective)
442 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
443 << getFunctionNumber() << '_' << uid;
448 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
449 /// special global used by LLVM. If so, emit it and return true, otherwise
450 /// do nothing and return false.
451 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
452 if (GV->getName() == "llvm.used") {
453 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
454 EmitLLVMUsedList(GV->getInitializer());
458 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
459 if (GV->getSection() == "llvm.metadata" ||
460 GV->hasAvailableExternallyLinkage())
463 if (!GV->hasAppendingLinkage()) return false;
465 assert(GV->hasInitializer() && "Not a special LLVM global!");
467 const TargetData *TD = TM.getTargetData();
468 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
469 if (GV->getName() == "llvm.global_ctors") {
470 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
471 EmitAlignment(Align, 0);
472 EmitXXStructorList(GV->getInitializer());
476 if (GV->getName() == "llvm.global_dtors") {
477 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
478 EmitAlignment(Align, 0);
479 EmitXXStructorList(GV->getInitializer());
486 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
487 /// global in the specified llvm.used list for which emitUsedDirectiveFor
488 /// is true, as being used with this directive.
489 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
490 const char *Directive = MAI->getUsedDirective();
492 // Should be an array of 'i8*'.
493 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
494 if (InitList == 0) return;
496 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
497 const GlobalValue *GV =
498 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
499 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
501 EmitConstantValueOnly(InitList->getOperand(i));
507 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
508 /// function pointers, ignoring the init priority.
509 void AsmPrinter::EmitXXStructorList(Constant *List) {
510 // Should be an array of '{ int, void ()* }' structs. The first value is the
511 // init priority, which we ignore.
512 if (!isa<ConstantArray>(List)) return;
513 ConstantArray *InitList = cast<ConstantArray>(List);
514 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
515 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
516 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
518 if (CS->getOperand(1)->isNullValue())
519 return; // Found a null terminator, exit printing.
520 // Emit the function pointer.
521 EmitGlobalConstant(CS->getOperand(1));
526 //===----------------------------------------------------------------------===//
527 /// LEB 128 number encoding.
529 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
530 /// representing an unsigned leb128 value.
531 void AsmPrinter::PrintULEB128(unsigned Value) const {
534 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
536 if (Value) Byte |= 0x80;
537 O << "0x" << utohex_buffer(Byte, Buffer+20);
538 if (Value) O << ", ";
542 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
543 /// representing a signed leb128 value.
544 void AsmPrinter::PrintSLEB128(int Value) const {
545 int Sign = Value >> (8 * sizeof(Value) - 1);
550 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
552 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
553 if (IsMore) Byte |= 0x80;
554 O << "0x" << utohex_buffer(Byte, Buffer+20);
555 if (IsMore) O << ", ";
559 //===--------------------------------------------------------------------===//
560 // Emission and print routines
563 /// PrintHex - Print a value as a hexadecimal value.
565 void AsmPrinter::PrintHex(int Value) const {
567 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
570 /// EOL - Print a newline character to asm stream. If a comment is present
571 /// then it will be printed first. Comments should not contain '\n'.
572 void AsmPrinter::EOL() const {
576 void AsmPrinter::EOL(const std::string &Comment) const {
577 if (VerboseAsm && !Comment.empty()) {
578 O.PadToColumn(MAI->getCommentColumn());
579 O << MAI->getCommentString()
586 void AsmPrinter::EOL(const char* Comment) const {
587 if (VerboseAsm && *Comment) {
588 O.PadToColumn(MAI->getCommentColumn());
589 O << MAI->getCommentString()
596 static const char *DecodeDWARFEncoding(unsigned Encoding) {
598 case dwarf::DW_EH_PE_absptr:
600 case dwarf::DW_EH_PE_omit:
602 case dwarf::DW_EH_PE_pcrel:
604 case dwarf::DW_EH_PE_udata4:
606 case dwarf::DW_EH_PE_udata8:
608 case dwarf::DW_EH_PE_sdata4:
610 case dwarf::DW_EH_PE_sdata8:
612 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
613 return "pcrel udata4";
614 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
615 return "pcrel sdata4";
616 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
617 return "pcrel udata8";
618 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
619 return "pcrel sdata8";
620 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
621 return "indirect pcrel udata4";
622 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
623 return "indirect pcrel sdata4";
624 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
625 return "indirect pcrel udata8";
626 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
627 return "indirect pcrel sdata8";
633 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
634 if (VerboseAsm && *Comment) {
635 O.PadToColumn(MAI->getCommentColumn());
636 O << MAI->getCommentString()
640 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
641 O << " (" << EncStr << ')';
646 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
647 /// unsigned leb128 value.
648 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
649 if (MAI->hasLEB128()) {
653 O << MAI->getData8bitsDirective();
658 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
659 /// signed leb128 value.
660 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
661 if (MAI->hasLEB128()) {
665 O << MAI->getData8bitsDirective();
670 /// EmitInt8 - Emit a byte directive and value.
672 void AsmPrinter::EmitInt8(int Value) const {
673 O << MAI->getData8bitsDirective();
674 PrintHex(Value & 0xFF);
677 /// EmitInt16 - Emit a short directive and value.
679 void AsmPrinter::EmitInt16(int Value) const {
680 O << MAI->getData16bitsDirective();
681 PrintHex(Value & 0xFFFF);
684 /// EmitInt32 - Emit a long directive and value.
686 void AsmPrinter::EmitInt32(int Value) const {
687 O << MAI->getData32bitsDirective();
691 /// EmitInt64 - Emit a long long directive and value.
693 void AsmPrinter::EmitInt64(uint64_t Value) const {
694 if (MAI->getData64bitsDirective()) {
695 O << MAI->getData64bitsDirective();
698 if (TM.getTargetData()->isBigEndian()) {
699 EmitInt32(unsigned(Value >> 32)); O << '\n';
700 EmitInt32(unsigned(Value));
702 EmitInt32(unsigned(Value)); O << '\n';
703 EmitInt32(unsigned(Value >> 32));
708 /// toOctal - Convert the low order bits of X into an octal digit.
710 static inline char toOctal(int X) {
714 /// printStringChar - Print a char, escaped if necessary.
716 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
719 } else if (C == '\\') {
721 } else if (isprint((unsigned char)C)) {
725 case '\b': O << "\\b"; break;
726 case '\f': O << "\\f"; break;
727 case '\n': O << "\\n"; break;
728 case '\r': O << "\\r"; break;
729 case '\t': O << "\\t"; break;
732 O << toOctal(C >> 6);
733 O << toOctal(C >> 3);
734 O << toOctal(C >> 0);
740 /// EmitString - Emit a string with quotes and a null terminator.
741 /// Special characters are emitted properly.
742 /// \literal (Eg. '\t') \endliteral
743 void AsmPrinter::EmitString(const StringRef String) const {
744 EmitString(String.data(), String.size());
747 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
748 const char* AscizDirective = MAI->getAscizDirective();
752 O << MAI->getAsciiDirective();
754 for (unsigned i = 0; i < Size; ++i)
755 printStringChar(O, String[i]);
763 /// EmitFile - Emit a .file directive.
764 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
765 O << "\t.file\t" << Number << " \"";
766 for (unsigned i = 0, N = Name.size(); i < N; ++i)
767 printStringChar(O, Name[i]);
772 //===----------------------------------------------------------------------===//
774 // EmitAlignment - Emit an alignment directive to the specified power of
775 // two boundary. For example, if you pass in 3 here, you will get an 8
776 // byte alignment. If a global value is specified, and if that global has
777 // an explicit alignment requested, it will unconditionally override the
778 // alignment request. However, if ForcedAlignBits is specified, this value
779 // has final say: the ultimate alignment will be the max of ForcedAlignBits
780 // and the alignment computed with NumBits and the global.
784 // if (GV && GV->hasalignment) Align = GV->getalignment();
785 // Align = std::max(Align, ForcedAlignBits);
787 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
788 unsigned ForcedAlignBits,
789 bool UseFillExpr) const {
790 if (GV && GV->getAlignment())
791 NumBits = Log2_32(GV->getAlignment());
792 NumBits = std::max(NumBits, ForcedAlignBits);
794 if (NumBits == 0) return; // No need to emit alignment.
796 unsigned FillValue = 0;
797 if (getCurrentSection()->getKind().isText())
798 FillValue = MAI->getTextAlignFillValue();
800 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
803 /// EmitZeros - Emit a block of zeros.
805 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
807 if (MAI->getZeroDirective()) {
808 O << MAI->getZeroDirective() << NumZeros;
809 if (MAI->getZeroDirectiveSuffix())
810 O << MAI->getZeroDirectiveSuffix();
813 for (; NumZeros; --NumZeros)
814 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
819 // Print out the specified constant, without a storage class. Only the
820 // constants valid in constant expressions can occur here.
821 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
822 if (CV->isNullValue() || isa<UndefValue>(CV)) {
827 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
828 O << CI->getZExtValue();
832 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
833 // This is a constant address for a global variable or function. Use the
834 // name of the variable or function as the address value.
835 GetGlobalValueSymbol(GV)->print(O, MAI);
839 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
840 GetBlockAddressSymbol(BA)->print(O, MAI);
844 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
846 llvm_unreachable("Unknown constant value!");
851 switch (CE->getOpcode()) {
852 case Instruction::ZExt:
853 case Instruction::SExt:
854 case Instruction::FPTrunc:
855 case Instruction::FPExt:
856 case Instruction::UIToFP:
857 case Instruction::SIToFP:
858 case Instruction::FPToUI:
859 case Instruction::FPToSI:
861 llvm_unreachable("FIXME: Don't support this constant cast expr");
862 case Instruction::GetElementPtr: {
863 // generate a symbolic expression for the byte address
864 const TargetData *TD = TM.getTargetData();
865 const Constant *ptrVal = CE->getOperand(0);
866 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
867 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
870 return EmitConstantValueOnly(ptrVal);
872 // Truncate/sext the offset to the pointer size.
873 if (TD->getPointerSizeInBits() != 64) {
874 int SExtAmount = 64-TD->getPointerSizeInBits();
875 Offset = (Offset << SExtAmount) >> SExtAmount;
880 EmitConstantValueOnly(ptrVal);
882 O << ") + " << Offset;
884 O << ") - " << -Offset;
887 case Instruction::BitCast:
888 return EmitConstantValueOnly(CE->getOperand(0));
890 case Instruction::IntToPtr: {
891 // Handle casts to pointers by changing them into casts to the appropriate
892 // integer type. This promotes constant folding and simplifies this code.
893 const TargetData *TD = TM.getTargetData();
894 Constant *Op = CE->getOperand(0);
895 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
897 return EmitConstantValueOnly(Op);
900 case Instruction::PtrToInt: {
901 // Support only foldable casts to/from pointers that can be eliminated by
902 // changing the pointer to the appropriately sized integer type.
903 Constant *Op = CE->getOperand(0);
904 const Type *Ty = CE->getType();
905 const TargetData *TD = TM.getTargetData();
907 // We can emit the pointer value into this slot if the slot is an
908 // integer slot greater or equal to the size of the pointer.
909 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
910 return EmitConstantValueOnly(Op);
913 EmitConstantValueOnly(Op);
915 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
918 ptrMask.toStringUnsigned(S);
919 O << ") & " << S.str() << ')';
923 case Instruction::Trunc:
924 // We emit the value and depend on the assembler to truncate the generated
925 // expression properly. This is important for differences between
926 // blockaddress labels. Since the two labels are in the same function, it
927 // is reasonable to treat their delta as a 32-bit value.
928 return EmitConstantValueOnly(CE->getOperand(0));
930 case Instruction::Add:
931 case Instruction::Sub:
932 case Instruction::And:
933 case Instruction::Or:
934 case Instruction::Xor:
936 EmitConstantValueOnly(CE->getOperand(0));
938 switch (CE->getOpcode()) {
939 case Instruction::Add:
942 case Instruction::Sub:
945 case Instruction::And:
948 case Instruction::Or:
951 case Instruction::Xor:
958 EmitConstantValueOnly(CE->getOperand(1));
964 /// printAsCString - Print the specified array as a C compatible string, only if
965 /// the predicate isString is true.
967 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
969 assert(CVA->isString() && "Array is not string compatible!");
972 for (unsigned i = 0; i != LastElt; ++i) {
974 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
975 printStringChar(O, C);
980 /// EmitString - Emit a zero-byte-terminated string constant.
982 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
983 unsigned NumElts = CVA->getNumOperands();
984 if (MAI->getAscizDirective() && NumElts &&
985 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
986 O << MAI->getAscizDirective();
987 printAsCString(O, CVA, NumElts-1);
989 O << MAI->getAsciiDirective();
990 printAsCString(O, CVA, NumElts);
995 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
996 unsigned AddrSpace) {
997 if (CVA->isString()) {
999 } else { // Not a string. Print the values in successive locations
1000 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
1001 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1005 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1006 const VectorType *PTy = CP->getType();
1008 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1009 EmitGlobalConstant(CP->getOperand(I));
1012 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1013 unsigned AddrSpace) {
1014 // Print the fields in successive locations. Pad to align if needed!
1015 const TargetData *TD = TM.getTargetData();
1016 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1017 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1018 uint64_t sizeSoFar = 0;
1019 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1020 const Constant* field = CVS->getOperand(i);
1022 // Check if padding is needed and insert one or more 0s.
1023 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1024 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1025 - cvsLayout->getElementOffset(i)) - fieldSize;
1026 sizeSoFar += fieldSize + padSize;
1028 // Now print the actual field value.
1029 EmitGlobalConstant(field, AddrSpace);
1031 // Insert padding - this may include padding to increase the size of the
1032 // current field up to the ABI size (if the struct is not packed) as well
1033 // as padding to ensure that the next field starts at the right offset.
1034 EmitZeros(padSize, AddrSpace);
1036 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1037 "Layout of constant struct may be incorrect!");
1040 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1041 unsigned AddrSpace) {
1042 // FP Constants are printed as integer constants to avoid losing
1044 LLVMContext &Context = CFP->getContext();
1045 const TargetData *TD = TM.getTargetData();
1046 if (CFP->getType()->isDoubleTy()) {
1047 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1048 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1049 if (MAI->getData64bitsDirective(AddrSpace)) {
1050 O << MAI->getData64bitsDirective(AddrSpace) << i;
1052 O.PadToColumn(MAI->getCommentColumn());
1053 O << MAI->getCommentString() << " double " << Val;
1056 } else if (TD->isBigEndian()) {
1057 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1059 O.PadToColumn(MAI->getCommentColumn());
1060 O << MAI->getCommentString()
1061 << " most significant word of double " << Val;
1064 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1066 O.PadToColumn(MAI->getCommentColumn());
1067 O << MAI->getCommentString()
1068 << " least significant word of double " << Val;
1072 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1074 O.PadToColumn(MAI->getCommentColumn());
1075 O << MAI->getCommentString()
1076 << " least significant word of double " << Val;
1079 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1081 O.PadToColumn(MAI->getCommentColumn());
1082 O << MAI->getCommentString()
1083 << " most significant word of double " << Val;
1090 if (CFP->getType()->isFloatTy()) {
1091 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1092 O << MAI->getData32bitsDirective(AddrSpace)
1093 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1095 O.PadToColumn(MAI->getCommentColumn());
1096 O << MAI->getCommentString() << " float " << Val;
1102 if (CFP->getType()->isX86_FP80Ty()) {
1103 // all long double variants are printed as hex
1104 // api needed to prevent premature destruction
1105 APInt api = CFP->getValueAPF().bitcastToAPInt();
1106 const uint64_t *p = api.getRawData();
1107 // Convert to double so we can print the approximate val as a comment.
1108 APFloat DoubleVal = CFP->getValueAPF();
1110 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1112 if (TD->isBigEndian()) {
1113 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1115 O.PadToColumn(MAI->getCommentColumn());
1116 O << MAI->getCommentString()
1117 << " most significant halfword of x86_fp80 ~"
1118 << DoubleVal.convertToDouble();
1121 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1123 O.PadToColumn(MAI->getCommentColumn());
1124 O << MAI->getCommentString() << " next halfword";
1127 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1129 O.PadToColumn(MAI->getCommentColumn());
1130 O << MAI->getCommentString() << " next halfword";
1133 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1135 O.PadToColumn(MAI->getCommentColumn());
1136 O << MAI->getCommentString() << " next halfword";
1139 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1141 O.PadToColumn(MAI->getCommentColumn());
1142 O << MAI->getCommentString()
1143 << " least significant halfword";
1147 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1149 O.PadToColumn(MAI->getCommentColumn());
1150 O << MAI->getCommentString()
1151 << " least significant halfword of x86_fp80 ~"
1152 << DoubleVal.convertToDouble();
1155 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1157 O.PadToColumn(MAI->getCommentColumn());
1158 O << MAI->getCommentString()
1159 << " next halfword";
1162 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1164 O.PadToColumn(MAI->getCommentColumn());
1165 O << MAI->getCommentString()
1166 << " next halfword";
1169 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1171 O.PadToColumn(MAI->getCommentColumn());
1172 O << MAI->getCommentString()
1173 << " next halfword";
1176 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1178 O.PadToColumn(MAI->getCommentColumn());
1179 O << MAI->getCommentString()
1180 << " most significant halfword";
1184 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1185 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1189 if (CFP->getType()->isPPC_FP128Ty()) {
1190 // all long double variants are printed as hex
1191 // api needed to prevent premature destruction
1192 APInt api = CFP->getValueAPF().bitcastToAPInt();
1193 const uint64_t *p = api.getRawData();
1194 if (TD->isBigEndian()) {
1195 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1197 O.PadToColumn(MAI->getCommentColumn());
1198 O << MAI->getCommentString()
1199 << " most significant word of ppc_fp128";
1202 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1204 O.PadToColumn(MAI->getCommentColumn());
1205 O << MAI->getCommentString()
1209 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1211 O.PadToColumn(MAI->getCommentColumn());
1212 O << MAI->getCommentString()
1216 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1218 O.PadToColumn(MAI->getCommentColumn());
1219 O << MAI->getCommentString()
1220 << " least significant word";
1224 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1226 O.PadToColumn(MAI->getCommentColumn());
1227 O << MAI->getCommentString()
1228 << " least significant word of ppc_fp128";
1231 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1233 O.PadToColumn(MAI->getCommentColumn());
1234 O << MAI->getCommentString()
1238 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1240 O.PadToColumn(MAI->getCommentColumn());
1241 O << MAI->getCommentString()
1245 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1247 O.PadToColumn(MAI->getCommentColumn());
1248 O << MAI->getCommentString()
1249 << " most significant word";
1254 } else llvm_unreachable("Floating point constant type not handled");
1257 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1258 unsigned AddrSpace) {
1259 const TargetData *TD = TM.getTargetData();
1260 unsigned BitWidth = CI->getBitWidth();
1261 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1263 // We don't expect assemblers to support integer data directives
1264 // for more than 64 bits, so we emit the data in at most 64-bit
1265 // quantities at a time.
1266 const uint64_t *RawData = CI->getValue().getRawData();
1267 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1269 if (TD->isBigEndian())
1270 Val = RawData[e - i - 1];
1274 if (MAI->getData64bitsDirective(AddrSpace)) {
1275 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1279 // Emit two 32-bit chunks, order depends on endianness.
1280 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1281 const char *FirstName = " least", *SecondName = " most";
1282 if (TD->isBigEndian()) {
1283 std::swap(FirstChunk, SecondChunk);
1284 std::swap(FirstName, SecondName);
1287 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1289 O.PadToColumn(MAI->getCommentColumn());
1290 O << MAI->getCommentString()
1291 << FirstName << " significant half of i64 " << Val;
1295 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1297 O.PadToColumn(MAI->getCommentColumn());
1298 O << MAI->getCommentString()
1299 << SecondName << " significant half of i64 " << Val;
1305 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1306 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1307 const TargetData *TD = TM.getTargetData();
1308 const Type *type = CV->getType();
1309 unsigned Size = TD->getTypeAllocSize(type);
1311 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1312 EmitZeros(Size, AddrSpace);
1316 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1317 EmitGlobalConstantArray(CVA , AddrSpace);
1321 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1322 EmitGlobalConstantStruct(CVS, AddrSpace);
1326 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1327 EmitGlobalConstantFP(CFP, AddrSpace);
1331 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1332 // If we can directly emit an 8-byte constant, do it.
1334 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1335 O << Data64Dir << CI->getZExtValue() << '\n';
1339 // Small integers are handled below; large integers are handled here.
1341 EmitGlobalConstantLargeInt(CI, AddrSpace);
1346 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1347 EmitGlobalConstantVector(CP);
1351 printDataDirective(type, AddrSpace);
1352 EmitConstantValueOnly(CV);
1354 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1356 CI->getValue().toStringUnsigned(S, 16);
1357 O.PadToColumn(MAI->getCommentColumn());
1358 O << MAI->getCommentString() << " 0x" << S.str();
1364 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1365 // Target doesn't support this yet!
1366 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1369 /// PrintSpecial - Print information related to the specified machine instr
1370 /// that is independent of the operand, and may be independent of the instr
1371 /// itself. This can be useful for portably encoding the comment character
1372 /// or other bits of target-specific knowledge into the asmstrings. The
1373 /// syntax used is ${:comment}. Targets can override this to add support
1374 /// for their own strange codes.
1375 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1376 if (!strcmp(Code, "private")) {
1377 O << MAI->getPrivateGlobalPrefix();
1378 } else if (!strcmp(Code, "comment")) {
1380 O << MAI->getCommentString();
1381 } else if (!strcmp(Code, "uid")) {
1382 // Comparing the address of MI isn't sufficient, because machineinstrs may
1383 // be allocated to the same address across functions.
1384 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1386 // If this is a new LastFn instruction, bump the counter.
1387 if (LastMI != MI || LastFn != ThisF) {
1395 raw_string_ostream Msg(msg);
1396 Msg << "Unknown special formatter '" << Code
1397 << "' for machine instr: " << *MI;
1398 llvm_report_error(Msg.str());
1402 /// processDebugLoc - Processes the debug information of each machine
1403 /// instruction's DebugLoc.
1404 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1405 bool BeforePrintingInsn) {
1406 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1407 || !DW->ShouldEmitDwarfDebug())
1409 DebugLoc DL = MI->getDebugLoc();
1412 DILocation CurDLT = MF->getDILocation(DL);
1413 if (CurDLT.getScope().isNull())
1416 if (BeforePrintingInsn) {
1417 if (CurDLT.getNode() != PrevDLT.getNode()) {
1418 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1419 CurDLT.getColumnNumber(),
1420 CurDLT.getScope().getNode());
1423 DW->BeginScope(MI, L);
1427 // After printing instruction
1433 /// printInlineAsm - This method formats and prints the specified machine
1434 /// instruction that is an inline asm.
1435 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1436 unsigned NumOperands = MI->getNumOperands();
1438 // Count the number of register definitions.
1439 unsigned NumDefs = 0;
1440 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1442 assert(NumDefs != NumOperands-1 && "No asm string?");
1444 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1446 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1447 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1451 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1452 // These are useful to see where empty asm's wound up.
1453 if (AsmStr[0] == 0) {
1454 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1455 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1459 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1461 // The variant of the current asmprinter.
1462 int AsmPrinterVariant = MAI->getAssemblerDialect();
1464 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1465 const char *LastEmitted = AsmStr; // One past the last character emitted.
1467 while (*LastEmitted) {
1468 switch (*LastEmitted) {
1470 // Not a special case, emit the string section literally.
1471 const char *LiteralEnd = LastEmitted+1;
1472 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1473 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1475 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1476 O.write(LastEmitted, LiteralEnd-LastEmitted);
1477 LastEmitted = LiteralEnd;
1481 ++LastEmitted; // Consume newline character.
1482 O << '\n'; // Indent code with newline.
1485 ++LastEmitted; // Consume '$' character.
1489 switch (*LastEmitted) {
1490 default: Done = false; break;
1491 case '$': // $$ -> $
1492 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1494 ++LastEmitted; // Consume second '$' character.
1496 case '(': // $( -> same as GCC's { character.
1497 ++LastEmitted; // Consume '(' character.
1498 if (CurVariant != -1) {
1499 llvm_report_error("Nested variants found in inline asm string: '"
1500 + std::string(AsmStr) + "'");
1502 CurVariant = 0; // We're in the first variant now.
1505 ++LastEmitted; // consume '|' character.
1506 if (CurVariant == -1)
1507 O << '|'; // this is gcc's behavior for | outside a variant
1509 ++CurVariant; // We're in the next variant.
1511 case ')': // $) -> same as GCC's } char.
1512 ++LastEmitted; // consume ')' character.
1513 if (CurVariant == -1)
1514 O << '}'; // this is gcc's behavior for } outside a variant
1521 bool HasCurlyBraces = false;
1522 if (*LastEmitted == '{') { // ${variable}
1523 ++LastEmitted; // Consume '{' character.
1524 HasCurlyBraces = true;
1527 // If we have ${:foo}, then this is not a real operand reference, it is a
1528 // "magic" string reference, just like in .td files. Arrange to call
1530 if (HasCurlyBraces && *LastEmitted == ':') {
1532 const char *StrStart = LastEmitted;
1533 const char *StrEnd = strchr(StrStart, '}');
1535 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1536 + std::string(AsmStr) + "'");
1539 std::string Val(StrStart, StrEnd);
1540 PrintSpecial(MI, Val.c_str());
1541 LastEmitted = StrEnd+1;
1545 const char *IDStart = LastEmitted;
1548 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1549 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1550 llvm_report_error("Bad $ operand number in inline asm string: '"
1551 + std::string(AsmStr) + "'");
1553 LastEmitted = IDEnd;
1555 char Modifier[2] = { 0, 0 };
1557 if (HasCurlyBraces) {
1558 // If we have curly braces, check for a modifier character. This
1559 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1560 if (*LastEmitted == ':') {
1561 ++LastEmitted; // Consume ':' character.
1562 if (*LastEmitted == 0) {
1563 llvm_report_error("Bad ${:} expression in inline asm string: '"
1564 + std::string(AsmStr) + "'");
1567 Modifier[0] = *LastEmitted;
1568 ++LastEmitted; // Consume modifier character.
1571 if (*LastEmitted != '}') {
1572 llvm_report_error("Bad ${} expression in inline asm string: '"
1573 + std::string(AsmStr) + "'");
1575 ++LastEmitted; // Consume '}' character.
1578 if ((unsigned)Val >= NumOperands-1) {
1579 llvm_report_error("Invalid $ operand number in inline asm string: '"
1580 + std::string(AsmStr) + "'");
1583 // Okay, we finally have a value number. Ask the target to print this
1585 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1590 // Scan to find the machine operand number for the operand.
1591 for (; Val; --Val) {
1592 if (OpNo >= MI->getNumOperands()) break;
1593 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1594 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1597 if (OpNo >= MI->getNumOperands()) {
1600 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1601 ++OpNo; // Skip over the ID number.
1603 if (Modifier[0]=='l') // labels are target independent
1604 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1605 ->getNumber())->print(O, MAI);
1607 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1608 if ((OpFlags & 7) == 4) {
1609 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1610 Modifier[0] ? Modifier : 0);
1612 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1613 Modifier[0] ? Modifier : 0);
1619 raw_string_ostream Msg(msg);
1620 Msg << "Invalid operand found in inline asm: '"
1623 llvm_report_error(Msg.str());
1630 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1633 /// printImplicitDef - This method prints the specified machine instruction
1634 /// that is an implicit def.
1635 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1636 if (!VerboseAsm) return;
1637 O.PadToColumn(MAI->getCommentColumn());
1638 O << MAI->getCommentString() << " implicit-def: "
1639 << TRI->getName(MI->getOperand(0).getReg());
1642 void AsmPrinter::printKill(const MachineInstr *MI) const {
1643 if (!VerboseAsm) return;
1644 O.PadToColumn(MAI->getCommentColumn());
1645 O << MAI->getCommentString() << " kill:";
1646 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1647 const MachineOperand &op = MI->getOperand(n);
1648 assert(op.isReg() && "KILL instruction must have only register operands");
1649 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1653 /// printLabel - This method prints a local label used by debug and
1654 /// exception handling tables.
1655 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1656 printLabel(MI->getOperand(0).getImm());
1659 void AsmPrinter::printLabel(unsigned Id) const {
1660 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1663 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1664 /// instruction, using the specified assembler variant. Targets should
1665 /// override this to format as appropriate.
1666 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1667 unsigned AsmVariant, const char *ExtraCode) {
1668 // Target doesn't support this yet!
1672 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1673 unsigned AsmVariant,
1674 const char *ExtraCode) {
1675 // Target doesn't support this yet!
1679 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1680 const char *Suffix) const {
1681 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1684 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1685 const BasicBlock *BB,
1686 const char *Suffix) const {
1687 assert(BB->hasName() &&
1688 "Address of anonymous basic block not supported yet!");
1690 // This code must use the function name itself, and not the function number,
1691 // since it must be possible to generate the label name from within other
1693 SmallString<60> FnName;
1694 Mang->getNameWithPrefix(FnName, F, false);
1696 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1697 SmallString<60> NameResult;
1698 Mang->getNameWithPrefix(NameResult,
1699 StringRef("BA") + Twine((unsigned)FnName.size()) +
1700 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1703 return OutContext.GetOrCreateSymbol(NameResult.str());
1706 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1707 SmallString<60> Name;
1708 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1709 << getFunctionNumber() << '_' << MBBID;
1711 return OutContext.GetOrCreateSymbol(Name.str());
1714 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1716 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1717 SmallString<60> NameStr;
1718 Mang->getNameWithPrefix(NameStr, GV, false);
1719 return OutContext.GetOrCreateSymbol(NameStr.str());
1722 /// GetPrivateGlobalValueSymbolStub - Return the MCSymbol for a symbol with
1723 /// global value name as its base, with the specified suffix, and where the
1724 /// symbol is forced to have private linkage.
1725 MCSymbol *AsmPrinter::GetPrivateGlobalValueSymbolStub(const GlobalValue *GV,
1726 StringRef Suffix) const {
1727 SmallString<60> NameStr;
1728 Mang->getNameWithPrefix(NameStr, GV, true);
1729 NameStr.append(Suffix.begin(), Suffix.end());
1730 return OutContext.GetOrCreateSymbol(NameStr.str());
1733 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1735 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1736 SmallString<60> NameStr;
1737 Mang->getNameWithPrefix(NameStr, Sym);
1738 return OutContext.GetOrCreateSymbol(NameStr.str());
1742 /// EmitBasicBlockStart - This method prints the label for the specified
1743 /// MachineBasicBlock, an alignment (if present) and a comment describing
1744 /// it if appropriate.
1745 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1746 // Emit an alignment directive for this block, if needed.
1747 if (unsigned Align = MBB->getAlignment())
1748 EmitAlignment(Log2_32(Align));
1750 // If the block has its address taken, emit a special label to satisfy
1751 // references to the block. This is done so that we don't need to
1752 // remember the number of this label, and so that we can make
1753 // forward references to labels without knowing what their numbers
1755 if (MBB->hasAddressTaken()) {
1756 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1757 MBB->getBasicBlock())->print(O, MAI);
1760 O.PadToColumn(MAI->getCommentColumn());
1761 O << MAI->getCommentString() << " Address Taken";
1766 // Print the main label for the block.
1767 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1769 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1771 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1777 // Print some comments to accompany the label.
1779 if (const BasicBlock *BB = MBB->getBasicBlock())
1780 if (BB->hasName()) {
1781 O.PadToColumn(MAI->getCommentColumn());
1782 O << MAI->getCommentString() << ' ';
1783 WriteAsOperand(O, BB, /*PrintType=*/false);
1791 /// printPICJumpTableSetLabel - This method prints a set label for the
1792 /// specified MachineBasicBlock for a jumptable entry.
1793 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1794 const MachineBasicBlock *MBB) const {
1795 if (!MAI->getSetDirective())
1798 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1799 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1800 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1801 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1802 << '_' << uid << '\n';
1805 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1806 const MachineBasicBlock *MBB) const {
1807 if (!MAI->getSetDirective())
1810 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1811 << getFunctionNumber() << '_' << uid << '_' << uid2
1812 << "_set_" << MBB->getNumber() << ',';
1813 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1814 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1815 << '_' << uid << '_' << uid2 << '\n';
1818 /// printDataDirective - This method prints the asm directive for the
1820 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1821 const TargetData *TD = TM.getTargetData();
1822 switch (type->getTypeID()) {
1823 case Type::FloatTyID: case Type::DoubleTyID:
1824 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1825 assert(0 && "Should have already output floating point constant.");
1827 assert(0 && "Can't handle printing this type of thing");
1828 case Type::IntegerTyID: {
1829 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1831 O << MAI->getData8bitsDirective(AddrSpace);
1832 else if (BitWidth <= 16)
1833 O << MAI->getData16bitsDirective(AddrSpace);
1834 else if (BitWidth <= 32)
1835 O << MAI->getData32bitsDirective(AddrSpace);
1836 else if (BitWidth <= 64) {
1837 assert(MAI->getData64bitsDirective(AddrSpace) &&
1838 "Target cannot handle 64-bit constant exprs!");
1839 O << MAI->getData64bitsDirective(AddrSpace);
1841 llvm_unreachable("Target cannot handle given data directive width!");
1845 case Type::PointerTyID:
1846 if (TD->getPointerSize() == 8) {
1847 assert(MAI->getData64bitsDirective(AddrSpace) &&
1848 "Target cannot handle 64-bit pointer exprs!");
1849 O << MAI->getData64bitsDirective(AddrSpace);
1850 } else if (TD->getPointerSize() == 2) {
1851 O << MAI->getData16bitsDirective(AddrSpace);
1852 } else if (TD->getPointerSize() == 1) {
1853 O << MAI->getData8bitsDirective(AddrSpace);
1855 O << MAI->getData32bitsDirective(AddrSpace);
1861 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1862 unsigned Visibility) const {
1863 if (Visibility == GlobalValue::HiddenVisibility) {
1864 if (const char *Directive = MAI->getHiddenDirective()) {
1869 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1870 if (const char *Directive = MAI->getProtectedDirective()) {
1878 void AsmPrinter::printOffset(int64_t Offset) const {
1881 else if (Offset < 0)
1885 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1886 if (!S->usesMetadata())
1889 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1890 if (GCPI != GCMetadataPrinters.end())
1891 return GCPI->second;
1893 const char *Name = S->getName().c_str();
1895 for (GCMetadataPrinterRegistry::iterator
1896 I = GCMetadataPrinterRegistry::begin(),
1897 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1898 if (strcmp(Name, I->getName()) == 0) {
1899 GCMetadataPrinter *GMP = I->instantiate();
1901 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1905 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1906 llvm_unreachable(0);
1909 /// EmitComments - Pretty-print comments for instructions
1910 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1914 bool Newline = false;
1916 if (!MI.getDebugLoc().isUnknown()) {
1917 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1919 // Print source line info.
1920 O.PadToColumn(MAI->getCommentColumn());
1921 O << MAI->getCommentString() << ' ';
1922 DIScope Scope = DLT.getScope();
1923 // Omit the directory, because it's likely to be long and uninteresting.
1924 if (!Scope.isNull())
1925 O << Scope.getFilename();
1928 O << ':' << DLT.getLineNumber();
1929 if (DLT.getColumnNumber() != 0)
1930 O << ':' << DLT.getColumnNumber();
1934 // Check for spills and reloads
1937 const MachineFrameInfo *FrameInfo =
1938 MI.getParent()->getParent()->getFrameInfo();
1940 // We assume a single instruction only has a spill or reload, not
1942 const MachineMemOperand *MMO;
1943 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1944 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1945 MMO = *MI.memoperands_begin();
1946 if (Newline) O << '\n';
1947 O.PadToColumn(MAI->getCommentColumn());
1948 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1952 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1953 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1954 if (Newline) O << '\n';
1955 O.PadToColumn(MAI->getCommentColumn());
1956 O << MAI->getCommentString() << ' '
1957 << MMO->getSize() << "-byte Folded Reload";
1961 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1962 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1963 MMO = *MI.memoperands_begin();
1964 if (Newline) O << '\n';
1965 O.PadToColumn(MAI->getCommentColumn());
1966 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1970 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1971 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1972 if (Newline) O << '\n';
1973 O.PadToColumn(MAI->getCommentColumn());
1974 O << MAI->getCommentString() << ' '
1975 << MMO->getSize() << "-byte Folded Spill";
1980 // Check for spill-induced copies
1981 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1982 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1983 SrcSubIdx, DstSubIdx)) {
1984 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1985 if (Newline) O << '\n';
1986 O.PadToColumn(MAI->getCommentColumn());
1987 O << MAI->getCommentString() << " Reload Reuse";
1992 /// PrintChildLoopComment - Print comments about child loops within
1993 /// the loop for this basic block, with nesting.
1995 static void PrintChildLoopComment(formatted_raw_ostream &O,
1996 const MachineLoop *loop,
1997 const MCAsmInfo *MAI,
1998 int FunctionNumber) {
1999 // Add child loop information
2000 for(MachineLoop::iterator cl = loop->begin(),
2001 clend = loop->end();
2004 MachineBasicBlock *Header = (*cl)->getHeader();
2005 assert(Header && "No header for loop");
2008 O.PadToColumn(MAI->getCommentColumn());
2010 O << MAI->getCommentString();
2011 O.indent(((*cl)->getLoopDepth()-1)*2)
2012 << " Child Loop BB" << FunctionNumber << "_"
2013 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2015 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2019 /// EmitComments - Pretty-print comments for basic blocks
2020 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2022 // Add loop depth information
2023 const MachineLoop *loop = LI->getLoopFor(&MBB);
2026 // Print a newline after bb# annotation.
2028 O.PadToColumn(MAI->getCommentColumn());
2029 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2032 O.PadToColumn(MAI->getCommentColumn());
2034 MachineBasicBlock *Header = loop->getHeader();
2035 assert(Header && "No header for loop");
2037 if (Header == &MBB) {
2038 O << MAI->getCommentString() << " Loop Header";
2039 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2042 O << MAI->getCommentString() << " Loop Header is BB"
2043 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2046 if (loop->empty()) {
2048 O.PadToColumn(MAI->getCommentColumn());
2049 O << MAI->getCommentString() << " Inner Loop";
2052 // Add parent loop information
2053 for (const MachineLoop *CurLoop = loop->getParentLoop();
2055 CurLoop = CurLoop->getParentLoop()) {
2056 MachineBasicBlock *Header = CurLoop->getHeader();
2057 assert(Header && "No header for loop");
2060 O.PadToColumn(MAI->getCommentColumn());
2061 O << MAI->getCommentString();
2062 O.indent((CurLoop->getLoopDepth()-1)*2)
2063 << " Inside Loop BB" << getFunctionNumber() << "_"
2064 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();