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())
167 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
170 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
171 if (I->hasExternalWeakLinkage())
172 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
176 if (MAI->getSetDirective()) {
178 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
180 MCSymbol *Name = GetGlobalValueSymbol(I);
182 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
183 MCSymbol *Target = GetGlobalValueSymbol(GV);
185 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) {
189 } else if (I->hasWeakLinkage()) {
190 O << MAI->getWeakRefDirective();
194 assert(I->hasLocalLinkage() && "Invalid alias linkage");
197 printVisibility(Name, I->getVisibility());
199 O << MAI->getSetDirective() << ' ';
202 Target->print(O, MAI);
207 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
208 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
209 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
210 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
211 MP->finishAssembly(O, *this, *MAI);
213 // If we don't have any trampolines, then we don't require stack memory
214 // to be executable. Some targets have a directive to declare this.
215 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
216 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
217 if (MAI->getNonexecutableStackDirective())
218 O << MAI->getNonexecutableStackDirective() << '\n';
221 // Allow the target to emit any magic that it wants at the end of the file,
222 // after everything else has gone out.
225 delete Mang; Mang = 0;
228 OutStreamer.Finish();
232 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
233 // Get the function symbol.
234 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
235 IncrementFunctionNumber();
238 LI = &getAnalysis<MachineLoopInfo>();
242 // SectionCPs - Keep track the alignment, constpool entries per Section.
246 SmallVector<unsigned, 4> CPEs;
247 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
251 /// EmitConstantPool - Print to the current output stream assembly
252 /// representations of the constants in the constant pool MCP. This is
253 /// used to print out constants which have been "spilled to memory" by
254 /// the code generator.
256 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
257 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
258 if (CP.empty()) return;
260 // Calculate sections for constant pool entries. We collect entries to go into
261 // the same section together to reduce amount of section switch statements.
262 SmallVector<SectionCPs, 4> CPSections;
263 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
264 const MachineConstantPoolEntry &CPE = CP[i];
265 unsigned Align = CPE.getAlignment();
268 switch (CPE.getRelocationInfo()) {
269 default: llvm_unreachable("Unknown section kind");
270 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
272 Kind = SectionKind::getReadOnlyWithRelLocal();
275 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
276 case 4: Kind = SectionKind::getMergeableConst4(); break;
277 case 8: Kind = SectionKind::getMergeableConst8(); break;
278 case 16: Kind = SectionKind::getMergeableConst16();break;
279 default: Kind = SectionKind::getMergeableConst(); break;
283 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
285 // The number of sections are small, just do a linear search from the
286 // last section to the first.
288 unsigned SecIdx = CPSections.size();
289 while (SecIdx != 0) {
290 if (CPSections[--SecIdx].S == S) {
296 SecIdx = CPSections.size();
297 CPSections.push_back(SectionCPs(S, Align));
300 if (Align > CPSections[SecIdx].Alignment)
301 CPSections[SecIdx].Alignment = Align;
302 CPSections[SecIdx].CPEs.push_back(i);
305 // Now print stuff into the calculated sections.
306 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
307 OutStreamer.SwitchSection(CPSections[i].S);
308 EmitAlignment(Log2_32(CPSections[i].Alignment));
311 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
312 unsigned CPI = CPSections[i].CPEs[j];
313 MachineConstantPoolEntry CPE = CP[CPI];
315 // Emit inter-object padding for alignment.
316 unsigned AlignMask = CPE.getAlignment() - 1;
317 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
318 EmitZeros(NewOffset - Offset);
320 const Type *Ty = CPE.getType();
321 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
323 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
326 O.PadToColumn(MAI->getCommentColumn());
327 O << MAI->getCommentString() << " constant ";
328 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
331 if (CPE.isMachineConstantPoolEntry())
332 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
334 EmitGlobalConstant(CPE.Val.ConstVal);
339 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
340 /// by the current function to the current output stream.
342 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
343 MachineFunction &MF) {
344 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
345 if (JT.empty()) return;
347 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
349 // Pick the directive to use to print the jump table entries, and switch to
350 // the appropriate section.
351 TargetLowering *LoweringInfo = TM.getTargetLowering();
353 const Function *F = MF.getFunction();
354 bool JTInDiffSection = false;
355 if (F->isWeakForLinker() ||
356 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
357 // In PIC mode, we need to emit the jump table to the same section as the
358 // function body itself, otherwise the label differences won't make sense.
359 // We should also do if the section name is NULL or function is declared in
360 // discardable section.
361 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
364 // Otherwise, drop it in the readonly section.
365 const MCSection *ReadOnlySection =
366 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
367 OutStreamer.SwitchSection(ReadOnlySection);
368 JTInDiffSection = true;
371 EmitAlignment(Log2_32(MJTI->getAlignment()));
373 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
374 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
376 // If this jump table was deleted, ignore it.
377 if (JTBBs.empty()) continue;
379 // For PIC codegen, if possible we want to use the SetDirective to reduce
380 // the number of relocations the assembler will generate for the jump table.
381 // Set directives are all printed before the jump table itself.
382 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
383 if (MAI->getSetDirective() && IsPic)
384 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
385 if (EmittedSets.insert(JTBBs[ii]))
386 printPICJumpTableSetLabel(i, JTBBs[ii]);
388 // On some targets (e.g. Darwin) we want to emit two consequtive labels
389 // before each jump table. The first label is never referenced, but tells
390 // the assembler and linker the extents of the jump table object. The
391 // second label is actually referenced by the code.
392 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
393 O << MAI->getLinkerPrivateGlobalPrefix()
394 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
397 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
398 << '_' << i << ":\n";
400 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
401 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
407 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
408 const MachineBasicBlock *MBB,
409 unsigned uid) const {
410 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
412 // Use JumpTableDirective otherwise honor the entry size from the jump table
414 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
415 bool HadJTEntryDirective = JTEntryDirective != NULL;
416 if (!HadJTEntryDirective) {
417 JTEntryDirective = MJTI->getEntrySize() == 4 ?
418 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
421 O << JTEntryDirective << ' ';
423 // If we have emitted set directives for the jump table entries, print
424 // them rather than the entries themselves. If we're emitting PIC, then
425 // emit the table entries as differences between two text section labels.
426 // If we're emitting non-PIC code, then emit the entries as direct
427 // references to the target basic blocks.
429 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
430 } else if (MAI->getSetDirective()) {
431 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
432 << '_' << uid << "_set_" << MBB->getNumber();
434 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
435 // If the arch uses custom Jump Table directives, don't calc relative to
437 if (!HadJTEntryDirective)
438 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
439 << getFunctionNumber() << '_' << uid;
444 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
445 /// special global used by LLVM. If so, emit it and return true, otherwise
446 /// do nothing and return false.
447 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
448 if (GV->getName() == "llvm.used") {
449 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
450 EmitLLVMUsedList(GV->getInitializer());
454 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
455 if (GV->getSection() == "llvm.metadata" ||
456 GV->hasAvailableExternallyLinkage())
459 if (!GV->hasAppendingLinkage()) return false;
461 assert(GV->hasInitializer() && "Not a special LLVM global!");
463 const TargetData *TD = TM.getTargetData();
464 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
465 if (GV->getName() == "llvm.global_ctors") {
466 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
467 EmitAlignment(Align, 0);
468 EmitXXStructorList(GV->getInitializer());
472 if (GV->getName() == "llvm.global_dtors") {
473 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
474 EmitAlignment(Align, 0);
475 EmitXXStructorList(GV->getInitializer());
482 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
483 /// global in the specified llvm.used list for which emitUsedDirectiveFor
484 /// is true, as being used with this directive.
485 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
486 const char *Directive = MAI->getUsedDirective();
488 // Should be an array of 'i8*'.
489 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
490 if (InitList == 0) return;
492 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
493 const GlobalValue *GV =
494 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
495 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
497 EmitConstantValueOnly(InitList->getOperand(i));
503 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
504 /// function pointers, ignoring the init priority.
505 void AsmPrinter::EmitXXStructorList(Constant *List) {
506 // Should be an array of '{ int, void ()* }' structs. The first value is the
507 // init priority, which we ignore.
508 if (!isa<ConstantArray>(List)) return;
509 ConstantArray *InitList = cast<ConstantArray>(List);
510 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
511 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
512 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
514 if (CS->getOperand(1)->isNullValue())
515 return; // Found a null terminator, exit printing.
516 // Emit the function pointer.
517 EmitGlobalConstant(CS->getOperand(1));
522 //===----------------------------------------------------------------------===//
523 /// LEB 128 number encoding.
525 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
526 /// representing an unsigned leb128 value.
527 void AsmPrinter::PrintULEB128(unsigned Value) const {
530 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
532 if (Value) Byte |= 0x80;
533 O << "0x" << utohex_buffer(Byte, Buffer+20);
534 if (Value) O << ", ";
538 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
539 /// representing a signed leb128 value.
540 void AsmPrinter::PrintSLEB128(int Value) const {
541 int Sign = Value >> (8 * sizeof(Value) - 1);
546 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
548 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
549 if (IsMore) Byte |= 0x80;
550 O << "0x" << utohex_buffer(Byte, Buffer+20);
551 if (IsMore) O << ", ";
555 //===--------------------------------------------------------------------===//
556 // Emission and print routines
559 /// PrintHex - Print a value as a hexadecimal value.
561 void AsmPrinter::PrintHex(int Value) const {
563 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
566 /// EOL - Print a newline character to asm stream. If a comment is present
567 /// then it will be printed first. Comments should not contain '\n'.
568 void AsmPrinter::EOL() const {
572 void AsmPrinter::EOL(const std::string &Comment) const {
573 if (VerboseAsm && !Comment.empty()) {
574 O.PadToColumn(MAI->getCommentColumn());
575 O << MAI->getCommentString()
582 void AsmPrinter::EOL(const char* Comment) const {
583 if (VerboseAsm && *Comment) {
584 O.PadToColumn(MAI->getCommentColumn());
585 O << MAI->getCommentString()
592 static const char *DecodeDWARFEncoding(unsigned Encoding) {
594 case dwarf::DW_EH_PE_absptr:
596 case dwarf::DW_EH_PE_omit:
598 case dwarf::DW_EH_PE_pcrel:
600 case dwarf::DW_EH_PE_udata4:
602 case dwarf::DW_EH_PE_udata8:
604 case dwarf::DW_EH_PE_sdata4:
606 case dwarf::DW_EH_PE_sdata8:
608 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
609 return "pcrel udata4";
610 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
611 return "pcrel sdata4";
612 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
613 return "pcrel udata8";
614 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
615 return "pcrel sdata8";
616 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
617 return "indirect pcrel udata4";
618 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
619 return "indirect pcrel sdata4";
620 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
621 return "indirect pcrel udata8";
622 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
623 return "indirect pcrel sdata8";
629 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
630 if (VerboseAsm && *Comment) {
631 O.PadToColumn(MAI->getCommentColumn());
632 O << MAI->getCommentString()
636 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
637 O << " (" << EncStr << ')';
642 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
643 /// unsigned leb128 value.
644 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
645 if (MAI->hasLEB128()) {
649 O << MAI->getData8bitsDirective();
654 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
655 /// signed leb128 value.
656 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
657 if (MAI->hasLEB128()) {
661 O << MAI->getData8bitsDirective();
666 /// EmitInt8 - Emit a byte directive and value.
668 void AsmPrinter::EmitInt8(int Value) const {
669 O << MAI->getData8bitsDirective();
670 PrintHex(Value & 0xFF);
673 /// EmitInt16 - Emit a short directive and value.
675 void AsmPrinter::EmitInt16(int Value) const {
676 O << MAI->getData16bitsDirective();
677 PrintHex(Value & 0xFFFF);
680 /// EmitInt32 - Emit a long directive and value.
682 void AsmPrinter::EmitInt32(int Value) const {
683 O << MAI->getData32bitsDirective();
687 /// EmitInt64 - Emit a long long directive and value.
689 void AsmPrinter::EmitInt64(uint64_t Value) const {
690 if (MAI->getData64bitsDirective()) {
691 O << MAI->getData64bitsDirective();
694 if (TM.getTargetData()->isBigEndian()) {
695 EmitInt32(unsigned(Value >> 32)); O << '\n';
696 EmitInt32(unsigned(Value));
698 EmitInt32(unsigned(Value)); O << '\n';
699 EmitInt32(unsigned(Value >> 32));
704 /// toOctal - Convert the low order bits of X into an octal digit.
706 static inline char toOctal(int X) {
710 /// printStringChar - Print a char, escaped if necessary.
712 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
715 } else if (C == '\\') {
717 } else if (isprint((unsigned char)C)) {
721 case '\b': O << "\\b"; break;
722 case '\f': O << "\\f"; break;
723 case '\n': O << "\\n"; break;
724 case '\r': O << "\\r"; break;
725 case '\t': O << "\\t"; break;
728 O << toOctal(C >> 6);
729 O << toOctal(C >> 3);
730 O << toOctal(C >> 0);
736 /// EmitString - Emit a string with quotes and a null terminator.
737 /// Special characters are emitted properly.
738 /// \literal (Eg. '\t') \endliteral
739 void AsmPrinter::EmitString(const StringRef String) const {
740 EmitString(String.data(), String.size());
743 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
744 const char* AscizDirective = MAI->getAscizDirective();
748 O << MAI->getAsciiDirective();
750 for (unsigned i = 0; i < Size; ++i)
751 printStringChar(O, String[i]);
759 /// EmitFile - Emit a .file directive.
760 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
761 O << "\t.file\t" << Number << " \"";
762 for (unsigned i = 0, N = Name.size(); i < N; ++i)
763 printStringChar(O, Name[i]);
768 //===----------------------------------------------------------------------===//
770 // EmitAlignment - Emit an alignment directive to the specified power of
771 // two boundary. For example, if you pass in 3 here, you will get an 8
772 // byte alignment. If a global value is specified, and if that global has
773 // an explicit alignment requested, it will unconditionally override the
774 // alignment request. However, if ForcedAlignBits is specified, this value
775 // has final say: the ultimate alignment will be the max of ForcedAlignBits
776 // and the alignment computed with NumBits and the global.
780 // if (GV && GV->hasalignment) Align = GV->getalignment();
781 // Align = std::max(Align, ForcedAlignBits);
783 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
784 unsigned ForcedAlignBits,
785 bool UseFillExpr) const {
786 if (GV && GV->getAlignment())
787 NumBits = Log2_32(GV->getAlignment());
788 NumBits = std::max(NumBits, ForcedAlignBits);
790 if (NumBits == 0) return; // No need to emit alignment.
792 unsigned FillValue = 0;
793 if (getCurrentSection()->getKind().isText())
794 FillValue = MAI->getTextAlignFillValue();
796 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
799 /// EmitZeros - Emit a block of zeros.
801 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
803 if (MAI->getZeroDirective()) {
804 O << MAI->getZeroDirective() << NumZeros;
805 if (MAI->getZeroDirectiveSuffix())
806 O << MAI->getZeroDirectiveSuffix();
809 for (; NumZeros; --NumZeros)
810 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
815 // Print out the specified constant, without a storage class. Only the
816 // constants valid in constant expressions can occur here.
817 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
818 if (CV->isNullValue() || isa<UndefValue>(CV)) {
823 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
824 O << CI->getZExtValue();
828 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
829 // This is a constant address for a global variable or function. Use the
830 // name of the variable or function as the address value.
831 O << Mang->getMangledName(GV);
835 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
836 GetBlockAddressSymbol(BA)->print(O, MAI);
840 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
842 llvm_unreachable("Unknown constant value!");
847 switch (CE->getOpcode()) {
848 case Instruction::ZExt:
849 case Instruction::SExt:
850 case Instruction::FPTrunc:
851 case Instruction::FPExt:
852 case Instruction::UIToFP:
853 case Instruction::SIToFP:
854 case Instruction::FPToUI:
855 case Instruction::FPToSI:
857 llvm_unreachable("FIXME: Don't support this constant cast expr");
858 case Instruction::GetElementPtr: {
859 // generate a symbolic expression for the byte address
860 const TargetData *TD = TM.getTargetData();
861 const Constant *ptrVal = CE->getOperand(0);
862 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
863 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
866 return EmitConstantValueOnly(ptrVal);
868 // Truncate/sext the offset to the pointer size.
869 if (TD->getPointerSizeInBits() != 64) {
870 int SExtAmount = 64-TD->getPointerSizeInBits();
871 Offset = (Offset << SExtAmount) >> SExtAmount;
876 EmitConstantValueOnly(ptrVal);
878 O << ") + " << Offset;
880 O << ") - " << -Offset;
883 case Instruction::BitCast:
884 return EmitConstantValueOnly(CE->getOperand(0));
886 case Instruction::IntToPtr: {
887 // Handle casts to pointers by changing them into casts to the appropriate
888 // integer type. This promotes constant folding and simplifies this code.
889 const TargetData *TD = TM.getTargetData();
890 Constant *Op = CE->getOperand(0);
891 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
893 return EmitConstantValueOnly(Op);
896 case Instruction::PtrToInt: {
897 // Support only foldable casts to/from pointers that can be eliminated by
898 // changing the pointer to the appropriately sized integer type.
899 Constant *Op = CE->getOperand(0);
900 const Type *Ty = CE->getType();
901 const TargetData *TD = TM.getTargetData();
903 // We can emit the pointer value into this slot if the slot is an
904 // integer slot greater or equal to the size of the pointer.
905 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
906 return EmitConstantValueOnly(Op);
909 EmitConstantValueOnly(Op);
911 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
914 ptrMask.toStringUnsigned(S);
915 O << ") & " << S.str() << ')';
919 case Instruction::Trunc:
920 // We emit the value and depend on the assembler to truncate the generated
921 // expression properly. This is important for differences between
922 // blockaddress labels. Since the two labels are in the same function, it
923 // is reasonable to treat their delta as a 32-bit value.
924 return EmitConstantValueOnly(CE->getOperand(0));
926 case Instruction::Add:
927 case Instruction::Sub:
928 case Instruction::And:
929 case Instruction::Or:
930 case Instruction::Xor:
932 EmitConstantValueOnly(CE->getOperand(0));
934 switch (CE->getOpcode()) {
935 case Instruction::Add:
938 case Instruction::Sub:
941 case Instruction::And:
944 case Instruction::Or:
947 case Instruction::Xor:
954 EmitConstantValueOnly(CE->getOperand(1));
960 /// printAsCString - Print the specified array as a C compatible string, only if
961 /// the predicate isString is true.
963 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
965 assert(CVA->isString() && "Array is not string compatible!");
968 for (unsigned i = 0; i != LastElt; ++i) {
970 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
971 printStringChar(O, C);
976 /// EmitString - Emit a zero-byte-terminated string constant.
978 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
979 unsigned NumElts = CVA->getNumOperands();
980 if (MAI->getAscizDirective() && NumElts &&
981 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
982 O << MAI->getAscizDirective();
983 printAsCString(O, CVA, NumElts-1);
985 O << MAI->getAsciiDirective();
986 printAsCString(O, CVA, NumElts);
991 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
992 unsigned AddrSpace) {
993 if (CVA->isString()) {
995 } else { // Not a string. Print the values in successive locations
996 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
997 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1001 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1002 const VectorType *PTy = CP->getType();
1004 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1005 EmitGlobalConstant(CP->getOperand(I));
1008 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1009 unsigned AddrSpace) {
1010 // Print the fields in successive locations. Pad to align if needed!
1011 const TargetData *TD = TM.getTargetData();
1012 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1013 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1014 uint64_t sizeSoFar = 0;
1015 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1016 const Constant* field = CVS->getOperand(i);
1018 // Check if padding is needed and insert one or more 0s.
1019 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1020 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1021 - cvsLayout->getElementOffset(i)) - fieldSize;
1022 sizeSoFar += fieldSize + padSize;
1024 // Now print the actual field value.
1025 EmitGlobalConstant(field, AddrSpace);
1027 // Insert padding - this may include padding to increase the size of the
1028 // current field up to the ABI size (if the struct is not packed) as well
1029 // as padding to ensure that the next field starts at the right offset.
1030 EmitZeros(padSize, AddrSpace);
1032 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1033 "Layout of constant struct may be incorrect!");
1036 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1037 unsigned AddrSpace) {
1038 // FP Constants are printed as integer constants to avoid losing
1040 LLVMContext &Context = CFP->getContext();
1041 const TargetData *TD = TM.getTargetData();
1042 if (CFP->getType()->isDoubleTy()) {
1043 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1044 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1045 if (MAI->getData64bitsDirective(AddrSpace)) {
1046 O << MAI->getData64bitsDirective(AddrSpace) << i;
1048 O.PadToColumn(MAI->getCommentColumn());
1049 O << MAI->getCommentString() << " double " << Val;
1052 } else if (TD->isBigEndian()) {
1053 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1055 O.PadToColumn(MAI->getCommentColumn());
1056 O << MAI->getCommentString()
1057 << " most significant word of double " << Val;
1060 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1062 O.PadToColumn(MAI->getCommentColumn());
1063 O << MAI->getCommentString()
1064 << " least significant word of double " << Val;
1068 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1070 O.PadToColumn(MAI->getCommentColumn());
1071 O << MAI->getCommentString()
1072 << " least significant word of double " << Val;
1075 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1077 O.PadToColumn(MAI->getCommentColumn());
1078 O << MAI->getCommentString()
1079 << " most significant word of double " << Val;
1086 if (CFP->getType()->isFloatTy()) {
1087 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1088 O << MAI->getData32bitsDirective(AddrSpace)
1089 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1091 O.PadToColumn(MAI->getCommentColumn());
1092 O << MAI->getCommentString() << " float " << Val;
1098 if (CFP->getType()->isX86_FP80Ty()) {
1099 // all long double variants are printed as hex
1100 // api needed to prevent premature destruction
1101 APInt api = CFP->getValueAPF().bitcastToAPInt();
1102 const uint64_t *p = api.getRawData();
1103 // Convert to double so we can print the approximate val as a comment.
1104 APFloat DoubleVal = CFP->getValueAPF();
1106 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1108 if (TD->isBigEndian()) {
1109 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1111 O.PadToColumn(MAI->getCommentColumn());
1112 O << MAI->getCommentString()
1113 << " most significant halfword of x86_fp80 ~"
1114 << DoubleVal.convertToDouble();
1117 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1119 O.PadToColumn(MAI->getCommentColumn());
1120 O << MAI->getCommentString() << " next halfword";
1123 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1125 O.PadToColumn(MAI->getCommentColumn());
1126 O << MAI->getCommentString() << " next halfword";
1129 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1131 O.PadToColumn(MAI->getCommentColumn());
1132 O << MAI->getCommentString() << " next halfword";
1135 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1137 O.PadToColumn(MAI->getCommentColumn());
1138 O << MAI->getCommentString()
1139 << " least significant halfword";
1143 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1145 O.PadToColumn(MAI->getCommentColumn());
1146 O << MAI->getCommentString()
1147 << " least significant halfword of x86_fp80 ~"
1148 << DoubleVal.convertToDouble();
1151 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1153 O.PadToColumn(MAI->getCommentColumn());
1154 O << MAI->getCommentString()
1155 << " next halfword";
1158 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1160 O.PadToColumn(MAI->getCommentColumn());
1161 O << MAI->getCommentString()
1162 << " next halfword";
1165 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1167 O.PadToColumn(MAI->getCommentColumn());
1168 O << MAI->getCommentString()
1169 << " next halfword";
1172 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1174 O.PadToColumn(MAI->getCommentColumn());
1175 O << MAI->getCommentString()
1176 << " most significant halfword";
1180 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1181 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1185 if (CFP->getType()->isPPC_FP128Ty()) {
1186 // all long double variants are printed as hex
1187 // api needed to prevent premature destruction
1188 APInt api = CFP->getValueAPF().bitcastToAPInt();
1189 const uint64_t *p = api.getRawData();
1190 if (TD->isBigEndian()) {
1191 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1193 O.PadToColumn(MAI->getCommentColumn());
1194 O << MAI->getCommentString()
1195 << " most significant word of ppc_fp128";
1198 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1200 O.PadToColumn(MAI->getCommentColumn());
1201 O << MAI->getCommentString()
1205 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1207 O.PadToColumn(MAI->getCommentColumn());
1208 O << MAI->getCommentString()
1212 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1214 O.PadToColumn(MAI->getCommentColumn());
1215 O << MAI->getCommentString()
1216 << " least significant word";
1220 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1222 O.PadToColumn(MAI->getCommentColumn());
1223 O << MAI->getCommentString()
1224 << " least significant word of ppc_fp128";
1227 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1229 O.PadToColumn(MAI->getCommentColumn());
1230 O << MAI->getCommentString()
1234 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1236 O.PadToColumn(MAI->getCommentColumn());
1237 O << MAI->getCommentString()
1241 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1243 O.PadToColumn(MAI->getCommentColumn());
1244 O << MAI->getCommentString()
1245 << " most significant word";
1250 } else llvm_unreachable("Floating point constant type not handled");
1253 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1254 unsigned AddrSpace) {
1255 const TargetData *TD = TM.getTargetData();
1256 unsigned BitWidth = CI->getBitWidth();
1257 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1259 // We don't expect assemblers to support integer data directives
1260 // for more than 64 bits, so we emit the data in at most 64-bit
1261 // quantities at a time.
1262 const uint64_t *RawData = CI->getValue().getRawData();
1263 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1265 if (TD->isBigEndian())
1266 Val = RawData[e - i - 1];
1270 if (MAI->getData64bitsDirective(AddrSpace)) {
1271 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1275 // Emit two 32-bit chunks, order depends on endianness.
1276 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1277 const char *FirstName = " least", *SecondName = " most";
1278 if (TD->isBigEndian()) {
1279 std::swap(FirstChunk, SecondChunk);
1280 std::swap(FirstName, SecondName);
1283 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1285 O.PadToColumn(MAI->getCommentColumn());
1286 O << MAI->getCommentString()
1287 << FirstName << " significant half of i64 " << Val;
1291 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1293 O.PadToColumn(MAI->getCommentColumn());
1294 O << MAI->getCommentString()
1295 << SecondName << " significant half of i64 " << Val;
1301 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1302 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1303 const TargetData *TD = TM.getTargetData();
1304 const Type *type = CV->getType();
1305 unsigned Size = TD->getTypeAllocSize(type);
1307 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1308 EmitZeros(Size, AddrSpace);
1312 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1313 EmitGlobalConstantArray(CVA , AddrSpace);
1317 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1318 EmitGlobalConstantStruct(CVS, AddrSpace);
1322 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1323 EmitGlobalConstantFP(CFP, AddrSpace);
1327 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1328 // If we can directly emit an 8-byte constant, do it.
1330 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1331 O << Data64Dir << CI->getZExtValue() << '\n';
1335 // Small integers are handled below; large integers are handled here.
1337 EmitGlobalConstantLargeInt(CI, AddrSpace);
1342 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1343 EmitGlobalConstantVector(CP);
1347 printDataDirective(type, AddrSpace);
1348 EmitConstantValueOnly(CV);
1350 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1352 CI->getValue().toStringUnsigned(S, 16);
1353 O.PadToColumn(MAI->getCommentColumn());
1354 O << MAI->getCommentString() << " 0x" << S.str();
1360 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1361 // Target doesn't support this yet!
1362 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1365 /// PrintSpecial - Print information related to the specified machine instr
1366 /// that is independent of the operand, and may be independent of the instr
1367 /// itself. This can be useful for portably encoding the comment character
1368 /// or other bits of target-specific knowledge into the asmstrings. The
1369 /// syntax used is ${:comment}. Targets can override this to add support
1370 /// for their own strange codes.
1371 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1372 if (!strcmp(Code, "private")) {
1373 O << MAI->getPrivateGlobalPrefix();
1374 } else if (!strcmp(Code, "comment")) {
1376 O << MAI->getCommentString();
1377 } else if (!strcmp(Code, "uid")) {
1378 // Comparing the address of MI isn't sufficient, because machineinstrs may
1379 // be allocated to the same address across functions.
1380 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1382 // If this is a new LastFn instruction, bump the counter.
1383 if (LastMI != MI || LastFn != ThisF) {
1391 raw_string_ostream Msg(msg);
1392 Msg << "Unknown special formatter '" << Code
1393 << "' for machine instr: " << *MI;
1394 llvm_report_error(Msg.str());
1398 /// processDebugLoc - Processes the debug information of each machine
1399 /// instruction's DebugLoc.
1400 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1401 bool BeforePrintingInsn) {
1402 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1403 || !DW->ShouldEmitDwarfDebug())
1405 DebugLoc DL = MI->getDebugLoc();
1408 DILocation CurDLT = MF->getDILocation(DL);
1409 if (CurDLT.getScope().isNull())
1412 if (BeforePrintingInsn) {
1413 if (CurDLT.getNode() != PrevDLT.getNode()) {
1414 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1415 CurDLT.getColumnNumber(),
1416 CurDLT.getScope().getNode());
1419 DW->BeginScope(MI, L);
1423 // After printing instruction
1429 /// printInlineAsm - This method formats and prints the specified machine
1430 /// instruction that is an inline asm.
1431 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1432 unsigned NumOperands = MI->getNumOperands();
1434 // Count the number of register definitions.
1435 unsigned NumDefs = 0;
1436 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1438 assert(NumDefs != NumOperands-1 && "No asm string?");
1440 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1442 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1443 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1447 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1448 // These are useful to see where empty asm's wound up.
1449 if (AsmStr[0] == 0) {
1450 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1451 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1455 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1457 // The variant of the current asmprinter.
1458 int AsmPrinterVariant = MAI->getAssemblerDialect();
1460 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1461 const char *LastEmitted = AsmStr; // One past the last character emitted.
1463 while (*LastEmitted) {
1464 switch (*LastEmitted) {
1466 // Not a special case, emit the string section literally.
1467 const char *LiteralEnd = LastEmitted+1;
1468 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1469 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1471 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1472 O.write(LastEmitted, LiteralEnd-LastEmitted);
1473 LastEmitted = LiteralEnd;
1477 ++LastEmitted; // Consume newline character.
1478 O << '\n'; // Indent code with newline.
1481 ++LastEmitted; // Consume '$' character.
1485 switch (*LastEmitted) {
1486 default: Done = false; break;
1487 case '$': // $$ -> $
1488 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1490 ++LastEmitted; // Consume second '$' character.
1492 case '(': // $( -> same as GCC's { character.
1493 ++LastEmitted; // Consume '(' character.
1494 if (CurVariant != -1) {
1495 llvm_report_error("Nested variants found in inline asm string: '"
1496 + std::string(AsmStr) + "'");
1498 CurVariant = 0; // We're in the first variant now.
1501 ++LastEmitted; // consume '|' character.
1502 if (CurVariant == -1)
1503 O << '|'; // this is gcc's behavior for | outside a variant
1505 ++CurVariant; // We're in the next variant.
1507 case ')': // $) -> same as GCC's } char.
1508 ++LastEmitted; // consume ')' character.
1509 if (CurVariant == -1)
1510 O << '}'; // this is gcc's behavior for } outside a variant
1517 bool HasCurlyBraces = false;
1518 if (*LastEmitted == '{') { // ${variable}
1519 ++LastEmitted; // Consume '{' character.
1520 HasCurlyBraces = true;
1523 // If we have ${:foo}, then this is not a real operand reference, it is a
1524 // "magic" string reference, just like in .td files. Arrange to call
1526 if (HasCurlyBraces && *LastEmitted == ':') {
1528 const char *StrStart = LastEmitted;
1529 const char *StrEnd = strchr(StrStart, '}');
1531 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1532 + std::string(AsmStr) + "'");
1535 std::string Val(StrStart, StrEnd);
1536 PrintSpecial(MI, Val.c_str());
1537 LastEmitted = StrEnd+1;
1541 const char *IDStart = LastEmitted;
1544 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1545 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1546 llvm_report_error("Bad $ operand number in inline asm string: '"
1547 + std::string(AsmStr) + "'");
1549 LastEmitted = IDEnd;
1551 char Modifier[2] = { 0, 0 };
1553 if (HasCurlyBraces) {
1554 // If we have curly braces, check for a modifier character. This
1555 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1556 if (*LastEmitted == ':') {
1557 ++LastEmitted; // Consume ':' character.
1558 if (*LastEmitted == 0) {
1559 llvm_report_error("Bad ${:} expression in inline asm string: '"
1560 + std::string(AsmStr) + "'");
1563 Modifier[0] = *LastEmitted;
1564 ++LastEmitted; // Consume modifier character.
1567 if (*LastEmitted != '}') {
1568 llvm_report_error("Bad ${} expression in inline asm string: '"
1569 + std::string(AsmStr) + "'");
1571 ++LastEmitted; // Consume '}' character.
1574 if ((unsigned)Val >= NumOperands-1) {
1575 llvm_report_error("Invalid $ operand number in inline asm string: '"
1576 + std::string(AsmStr) + "'");
1579 // Okay, we finally have a value number. Ask the target to print this
1581 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1586 // Scan to find the machine operand number for the operand.
1587 for (; Val; --Val) {
1588 if (OpNo >= MI->getNumOperands()) break;
1589 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1590 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1593 if (OpNo >= MI->getNumOperands()) {
1596 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1597 ++OpNo; // Skip over the ID number.
1599 if (Modifier[0]=='l') // labels are target independent
1600 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1601 ->getNumber())->print(O, MAI);
1603 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1604 if ((OpFlags & 7) == 4) {
1605 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1606 Modifier[0] ? Modifier : 0);
1608 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1609 Modifier[0] ? Modifier : 0);
1615 raw_string_ostream Msg(msg);
1616 Msg << "Invalid operand found in inline asm: '"
1619 llvm_report_error(Msg.str());
1626 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1629 /// printImplicitDef - This method prints the specified machine instruction
1630 /// that is an implicit def.
1631 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1632 if (!VerboseAsm) return;
1633 O.PadToColumn(MAI->getCommentColumn());
1634 O << MAI->getCommentString() << " implicit-def: "
1635 << TRI->getName(MI->getOperand(0).getReg());
1638 void AsmPrinter::printKill(const MachineInstr *MI) const {
1639 if (!VerboseAsm) return;
1640 O.PadToColumn(MAI->getCommentColumn());
1641 O << MAI->getCommentString() << " kill:";
1642 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1643 const MachineOperand &op = MI->getOperand(n);
1644 assert(op.isReg() && "KILL instruction must have only register operands");
1645 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1649 /// printLabel - This method prints a local label used by debug and
1650 /// exception handling tables.
1651 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1652 printLabel(MI->getOperand(0).getImm());
1655 void AsmPrinter::printLabel(unsigned Id) const {
1656 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1659 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1660 /// instruction, using the specified assembler variant. Targets should
1661 /// override this to format as appropriate.
1662 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1663 unsigned AsmVariant, const char *ExtraCode) {
1664 // Target doesn't support this yet!
1668 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1669 unsigned AsmVariant,
1670 const char *ExtraCode) {
1671 // Target doesn't support this yet!
1675 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1676 const char *Suffix) const {
1677 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1680 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1681 const BasicBlock *BB,
1682 const char *Suffix) const {
1683 assert(BB->hasName() &&
1684 "Address of anonymous basic block not supported yet!");
1686 // This code must use the function name itself, and not the function number,
1687 // since it must be possible to generate the label name from within other
1689 SmallString<60> FnName;
1690 Mang->getNameWithPrefix(FnName, F, false);
1692 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1693 SmallString<60> NameResult;
1694 Mang->getNameWithPrefix(NameResult,
1695 StringRef("BA") + Twine((unsigned)FnName.size()) +
1696 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1699 return OutContext.GetOrCreateSymbol(NameResult.str());
1702 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1703 SmallString<60> Name;
1704 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1705 << getFunctionNumber() << '_' << MBBID;
1707 return OutContext.GetOrCreateSymbol(Name.str());
1710 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1712 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1713 SmallString<60> NameStr;
1714 Mang->getNameWithPrefix(NameStr, GV, false);
1715 return OutContext.GetOrCreateSymbol(NameStr.str());
1718 /// GetPrivateGlobalValueSymbolStub - Return the MCSymbol for a symbol with
1719 /// global value name as its base, with the specified suffix, and where the
1720 /// symbol is forced to have private linkage.
1721 MCSymbol *AsmPrinter::GetPrivateGlobalValueSymbolStub(const GlobalValue *GV,
1722 StringRef Suffix) const {
1723 SmallString<60> NameStr;
1724 Mang->getNameWithPrefix(NameStr, GV, true);
1725 NameStr.append(Suffix.begin(), Suffix.end());
1726 return OutContext.GetOrCreateSymbol(NameStr.str());
1729 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1731 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1732 SmallString<60> NameStr;
1733 Mang->getNameWithPrefix(NameStr, Sym);
1734 return OutContext.GetOrCreateSymbol(NameStr.str());
1738 /// EmitBasicBlockStart - This method prints the label for the specified
1739 /// MachineBasicBlock, an alignment (if present) and a comment describing
1740 /// it if appropriate.
1741 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1742 // Emit an alignment directive for this block, if needed.
1743 if (unsigned Align = MBB->getAlignment())
1744 EmitAlignment(Log2_32(Align));
1746 // If the block has its address taken, emit a special label to satisfy
1747 // references to the block. This is done so that we don't need to
1748 // remember the number of this label, and so that we can make
1749 // forward references to labels without knowing what their numbers
1751 if (MBB->hasAddressTaken()) {
1752 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1753 MBB->getBasicBlock())->print(O, MAI);
1756 O.PadToColumn(MAI->getCommentColumn());
1757 O << MAI->getCommentString() << " Address Taken";
1762 // Print the main label for the block.
1763 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1765 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1767 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1773 // Print some comments to accompany the label.
1775 if (const BasicBlock *BB = MBB->getBasicBlock())
1776 if (BB->hasName()) {
1777 O.PadToColumn(MAI->getCommentColumn());
1778 O << MAI->getCommentString() << ' ';
1779 WriteAsOperand(O, BB, /*PrintType=*/false);
1787 /// printPICJumpTableSetLabel - This method prints a set label for the
1788 /// specified MachineBasicBlock for a jumptable entry.
1789 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1790 const MachineBasicBlock *MBB) const {
1791 if (!MAI->getSetDirective())
1794 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1795 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1796 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1797 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1798 << '_' << uid << '\n';
1801 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1802 const MachineBasicBlock *MBB) const {
1803 if (!MAI->getSetDirective())
1806 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1807 << getFunctionNumber() << '_' << uid << '_' << uid2
1808 << "_set_" << MBB->getNumber() << ',';
1809 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1810 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1811 << '_' << uid << '_' << uid2 << '\n';
1814 /// printDataDirective - This method prints the asm directive for the
1816 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1817 const TargetData *TD = TM.getTargetData();
1818 switch (type->getTypeID()) {
1819 case Type::FloatTyID: case Type::DoubleTyID:
1820 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1821 assert(0 && "Should have already output floating point constant.");
1823 assert(0 && "Can't handle printing this type of thing");
1824 case Type::IntegerTyID: {
1825 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1827 O << MAI->getData8bitsDirective(AddrSpace);
1828 else if (BitWidth <= 16)
1829 O << MAI->getData16bitsDirective(AddrSpace);
1830 else if (BitWidth <= 32)
1831 O << MAI->getData32bitsDirective(AddrSpace);
1832 else if (BitWidth <= 64) {
1833 assert(MAI->getData64bitsDirective(AddrSpace) &&
1834 "Target cannot handle 64-bit constant exprs!");
1835 O << MAI->getData64bitsDirective(AddrSpace);
1837 llvm_unreachable("Target cannot handle given data directive width!");
1841 case Type::PointerTyID:
1842 if (TD->getPointerSize() == 8) {
1843 assert(MAI->getData64bitsDirective(AddrSpace) &&
1844 "Target cannot handle 64-bit pointer exprs!");
1845 O << MAI->getData64bitsDirective(AddrSpace);
1846 } else if (TD->getPointerSize() == 2) {
1847 O << MAI->getData16bitsDirective(AddrSpace);
1848 } else if (TD->getPointerSize() == 1) {
1849 O << MAI->getData8bitsDirective(AddrSpace);
1851 O << MAI->getData32bitsDirective(AddrSpace);
1857 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1858 unsigned Visibility) const {
1859 if (Visibility == GlobalValue::HiddenVisibility) {
1860 if (const char *Directive = MAI->getHiddenDirective()) {
1865 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1866 if (const char *Directive = MAI->getProtectedDirective()) {
1874 void AsmPrinter::printOffset(int64_t Offset) const {
1877 else if (Offset < 0)
1881 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1882 if (!S->usesMetadata())
1885 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1886 if (GCPI != GCMetadataPrinters.end())
1887 return GCPI->second;
1889 const char *Name = S->getName().c_str();
1891 for (GCMetadataPrinterRegistry::iterator
1892 I = GCMetadataPrinterRegistry::begin(),
1893 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1894 if (strcmp(Name, I->getName()) == 0) {
1895 GCMetadataPrinter *GMP = I->instantiate();
1897 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1901 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1902 llvm_unreachable(0);
1905 /// EmitComments - Pretty-print comments for instructions
1906 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1910 bool Newline = false;
1912 if (!MI.getDebugLoc().isUnknown()) {
1913 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1915 // Print source line info.
1916 O.PadToColumn(MAI->getCommentColumn());
1917 O << MAI->getCommentString() << ' ';
1918 DIScope Scope = DLT.getScope();
1919 // Omit the directory, because it's likely to be long and uninteresting.
1920 if (!Scope.isNull())
1921 O << Scope.getFilename();
1924 O << ':' << DLT.getLineNumber();
1925 if (DLT.getColumnNumber() != 0)
1926 O << ':' << DLT.getColumnNumber();
1930 // Check for spills and reloads
1933 const MachineFrameInfo *FrameInfo =
1934 MI.getParent()->getParent()->getFrameInfo();
1936 // We assume a single instruction only has a spill or reload, not
1938 const MachineMemOperand *MMO;
1939 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1940 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1941 MMO = *MI.memoperands_begin();
1942 if (Newline) O << '\n';
1943 O.PadToColumn(MAI->getCommentColumn());
1944 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1948 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1949 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1950 if (Newline) O << '\n';
1951 O.PadToColumn(MAI->getCommentColumn());
1952 O << MAI->getCommentString() << ' '
1953 << MMO->getSize() << "-byte Folded Reload";
1957 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1958 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1959 MMO = *MI.memoperands_begin();
1960 if (Newline) O << '\n';
1961 O.PadToColumn(MAI->getCommentColumn());
1962 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1966 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1967 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1968 if (Newline) O << '\n';
1969 O.PadToColumn(MAI->getCommentColumn());
1970 O << MAI->getCommentString() << ' '
1971 << MMO->getSize() << "-byte Folded Spill";
1976 // Check for spill-induced copies
1977 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1978 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1979 SrcSubIdx, DstSubIdx)) {
1980 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1981 if (Newline) O << '\n';
1982 O.PadToColumn(MAI->getCommentColumn());
1983 O << MAI->getCommentString() << " Reload Reuse";
1988 /// PrintChildLoopComment - Print comments about child loops within
1989 /// the loop for this basic block, with nesting.
1991 static void PrintChildLoopComment(formatted_raw_ostream &O,
1992 const MachineLoop *loop,
1993 const MCAsmInfo *MAI,
1994 int FunctionNumber) {
1995 // Add child loop information
1996 for(MachineLoop::iterator cl = loop->begin(),
1997 clend = loop->end();
2000 MachineBasicBlock *Header = (*cl)->getHeader();
2001 assert(Header && "No header for loop");
2004 O.PadToColumn(MAI->getCommentColumn());
2006 O << MAI->getCommentString();
2007 O.indent(((*cl)->getLoopDepth()-1)*2)
2008 << " Child Loop BB" << FunctionNumber << "_"
2009 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2011 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2015 /// EmitComments - Pretty-print comments for basic blocks
2016 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2018 // Add loop depth information
2019 const MachineLoop *loop = LI->getLoopFor(&MBB);
2022 // Print a newline after bb# annotation.
2024 O.PadToColumn(MAI->getCommentColumn());
2025 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2028 O.PadToColumn(MAI->getCommentColumn());
2030 MachineBasicBlock *Header = loop->getHeader();
2031 assert(Header && "No header for loop");
2033 if (Header == &MBB) {
2034 O << MAI->getCommentString() << " Loop Header";
2035 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2038 O << MAI->getCommentString() << " Loop Header is BB"
2039 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2042 if (loop->empty()) {
2044 O.PadToColumn(MAI->getCommentColumn());
2045 O << MAI->getCommentString() << " Inner Loop";
2048 // Add parent loop information
2049 for (const MachineLoop *CurLoop = loop->getParentLoop();
2051 CurLoop = CurLoop->getParentLoop()) {
2052 MachineBasicBlock *Header = CurLoop->getHeader();
2053 assert(Header && "No header for loop");
2056 O.PadToColumn(MAI->getCommentColumn());
2057 O << MAI->getCommentString();
2058 O.indent((CurLoop->getLoopDepth()-1)*2)
2059 << " Inside Loop BB" << getFunctionNumber() << "_"
2060 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();