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/MachineFunction.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/StringExtras.h"
48 static cl::opt<cl::boolOrDefault>
49 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
50 cl::init(cl::BOU_UNSET));
52 char AsmPrinter::ID = 0;
53 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
54 const MCAsmInfo *T, bool VDef)
55 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
56 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
58 OutContext(*new MCContext()),
59 // FIXME: Pass instprinter to streamer.
60 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
62 LastMI(0), LastFn(0), Counter(~0U),
63 PrevDLT(0, ~0U, ~0U) {
66 case cl::BOU_UNSET: VerboseAsm = VDef; break;
67 case cl::BOU_TRUE: VerboseAsm = true; break;
68 case cl::BOU_FALSE: VerboseAsm = false; break;
72 AsmPrinter::~AsmPrinter() {
73 for (gcp_iterator I = GCMetadataPrinters.begin(),
74 E = GCMetadataPrinters.end(); I != E; ++I)
81 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
82 return TM.getTargetLowering()->getObjFileLowering();
85 /// getCurrentSection() - Return the current section we are emitting to.
86 const MCSection *AsmPrinter::getCurrentSection() const {
87 return OutStreamer.getCurrentSection();
91 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
93 MachineFunctionPass::getAnalysisUsage(AU);
94 AU.addRequired<GCModuleInfo>();
96 AU.addRequired<MachineLoopInfo>();
99 bool AsmPrinter::doInitialization(Module &M) {
100 // Initialize TargetLoweringObjectFile.
101 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
102 .Initialize(OutContext, TM);
104 Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(),
105 MAI->getLinkerPrivateGlobalPrefix());
107 if (MAI->doesAllowQuotesInName())
108 Mang->setUseQuotes(true);
110 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
111 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
113 if (MAI->hasSingleParameterDotFile()) {
114 /* Very minimal debug info. It is ignored if we emit actual
115 debug info. If we don't, this at helps the user find where
116 a function came from. */
117 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
120 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
121 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
122 MP->beginAssembly(O, *this, *MAI);
124 if (!M.getModuleInlineAsm().empty())
125 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
126 << M.getModuleInlineAsm()
127 << '\n' << MAI->getCommentString()
128 << " End of file scope inline assembly\n";
130 if (MAI->doesSupportDebugInformation() ||
131 MAI->doesSupportExceptionHandling()) {
132 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
134 MMI->AnalyzeModule(M);
135 DW = getAnalysisIfAvailable<DwarfWriter>();
137 DW->BeginModule(&M, MMI, O, this, MAI);
143 bool AsmPrinter::doFinalization(Module &M) {
144 // Emit global variables.
145 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
147 PrintGlobalVariable(I);
149 // Emit final debug information.
150 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
153 // If the target wants to know about weak references, print them all.
154 if (MAI->getWeakRefDirective()) {
155 // FIXME: This is not lazy, it would be nice to only print weak references
156 // to stuff that is actually used. Note that doing so would require targets
157 // to notice uses in operands (due to constant exprs etc). This should
158 // happen with the MC stuff eventually.
160 // Print out module-level global variables here.
161 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
163 if (I->hasExternalWeakLinkage())
164 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
167 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
168 if (I->hasExternalWeakLinkage())
169 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
173 if (MAI->getSetDirective()) {
175 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
177 std::string Name = Mang->getMangledName(I);
179 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
180 std::string Target = Mang->getMangledName(GV);
182 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
183 O << "\t.globl\t" << Name << '\n';
184 else if (I->hasWeakLinkage())
185 O << MAI->getWeakRefDirective() << Name << '\n';
186 else if (!I->hasLocalLinkage())
187 llvm_unreachable("Invalid alias linkage");
189 printVisibility(Name, I->getVisibility());
191 O << MAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
195 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
196 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
197 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
198 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
199 MP->finishAssembly(O, *this, *MAI);
201 // If we don't have any trampolines, then we don't require stack memory
202 // to be executable. Some targets have a directive to declare this.
203 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
204 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
205 if (MAI->getNonexecutableStackDirective())
206 O << MAI->getNonexecutableStackDirective() << '\n';
208 delete Mang; Mang = 0;
211 OutStreamer.Finish();
216 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
217 assert(MF && "No machine function?");
218 return Mang->getMangledName(MF->getFunction(), ".eh",
219 MAI->is_EHSymbolPrivate());
222 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
223 // What's my mangled name?
224 CurrentFnName = Mang->getMangledName(MF.getFunction());
225 IncrementFunctionNumber();
228 LI = &getAnalysis<MachineLoopInfo>();
233 // SectionCPs - Keep track the alignment, constpool entries per Section.
237 SmallVector<unsigned, 4> CPEs;
238 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
242 /// EmitConstantPool - Print to the current output stream assembly
243 /// representations of the constants in the constant pool MCP. This is
244 /// used to print out constants which have been "spilled to memory" by
245 /// the code generator.
247 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
248 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
249 if (CP.empty()) return;
251 // Calculate sections for constant pool entries. We collect entries to go into
252 // the same section together to reduce amount of section switch statements.
253 SmallVector<SectionCPs, 4> CPSections;
254 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
255 const MachineConstantPoolEntry &CPE = CP[i];
256 unsigned Align = CPE.getAlignment();
259 switch (CPE.getRelocationInfo()) {
260 default: llvm_unreachable("Unknown section kind");
261 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
263 Kind = SectionKind::getReadOnlyWithRelLocal();
266 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
267 case 4: Kind = SectionKind::getMergeableConst4(); break;
268 case 8: Kind = SectionKind::getMergeableConst8(); break;
269 case 16: Kind = SectionKind::getMergeableConst16();break;
270 default: Kind = SectionKind::getMergeableConst(); break;
274 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
276 // The number of sections are small, just do a linear search from the
277 // last section to the first.
279 unsigned SecIdx = CPSections.size();
280 while (SecIdx != 0) {
281 if (CPSections[--SecIdx].S == S) {
287 SecIdx = CPSections.size();
288 CPSections.push_back(SectionCPs(S, Align));
291 if (Align > CPSections[SecIdx].Alignment)
292 CPSections[SecIdx].Alignment = Align;
293 CPSections[SecIdx].CPEs.push_back(i);
296 // Now print stuff into the calculated sections.
297 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
298 OutStreamer.SwitchSection(CPSections[i].S);
299 EmitAlignment(Log2_32(CPSections[i].Alignment));
302 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
303 unsigned CPI = CPSections[i].CPEs[j];
304 MachineConstantPoolEntry CPE = CP[CPI];
306 // Emit inter-object padding for alignment.
307 unsigned AlignMask = CPE.getAlignment() - 1;
308 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
309 EmitZeros(NewOffset - Offset);
311 const Type *Ty = CPE.getType();
312 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
314 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
317 O.PadToColumn(MAI->getCommentColumn());
318 O << MAI->getCommentString() << " constant ";
319 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
322 if (CPE.isMachineConstantPoolEntry())
323 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
325 EmitGlobalConstant(CPE.Val.ConstVal);
330 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
331 /// by the current function to the current output stream.
333 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
334 MachineFunction &MF) {
335 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
336 if (JT.empty()) return;
338 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
340 // Pick the directive to use to print the jump table entries, and switch to
341 // the appropriate section.
342 TargetLowering *LoweringInfo = TM.getTargetLowering();
344 const Function *F = MF.getFunction();
345 bool JTInDiffSection = false;
346 if (F->isWeakForLinker() ||
347 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
348 // In PIC mode, we need to emit the jump table to the same section as the
349 // function body itself, otherwise the label differences won't make sense.
350 // We should also do if the section name is NULL or function is declared in
351 // discardable section.
352 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
355 // Otherwise, drop it in the readonly section.
356 const MCSection *ReadOnlySection =
357 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
358 OutStreamer.SwitchSection(ReadOnlySection);
359 JTInDiffSection = true;
362 EmitAlignment(Log2_32(MJTI->getAlignment()));
364 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
365 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
367 // If this jump table was deleted, ignore it.
368 if (JTBBs.empty()) continue;
370 // For PIC codegen, if possible we want to use the SetDirective to reduce
371 // the number of relocations the assembler will generate for the jump table.
372 // Set directives are all printed before the jump table itself.
373 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
374 if (MAI->getSetDirective() && IsPic)
375 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
376 if (EmittedSets.insert(JTBBs[ii]))
377 printPICJumpTableSetLabel(i, JTBBs[ii]);
379 // On some targets (e.g. Darwin) we want to emit two consequtive labels
380 // before each jump table. The first label is never referenced, but tells
381 // the assembler and linker the extents of the jump table object. The
382 // second label is actually referenced by the code.
383 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
384 O << MAI->getLinkerPrivateGlobalPrefix()
385 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
388 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
389 << '_' << i << ":\n";
391 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
392 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
398 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
399 const MachineBasicBlock *MBB,
400 unsigned uid) const {
401 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
403 // Use JumpTableDirective otherwise honor the entry size from the jump table
405 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
406 bool HadJTEntryDirective = JTEntryDirective != NULL;
407 if (!HadJTEntryDirective) {
408 JTEntryDirective = MJTI->getEntrySize() == 4 ?
409 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
412 O << JTEntryDirective << ' ';
414 // If we have emitted set directives for the jump table entries, print
415 // them rather than the entries themselves. If we're emitting PIC, then
416 // emit the table entries as differences between two text section labels.
417 // If we're emitting non-PIC code, then emit the entries as direct
418 // references to the target basic blocks.
420 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
421 } else if (MAI->getSetDirective()) {
422 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
423 << '_' << uid << "_set_" << MBB->getNumber();
425 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
426 // If the arch uses custom Jump Table directives, don't calc relative to
428 if (!HadJTEntryDirective)
429 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
430 << getFunctionNumber() << '_' << uid;
435 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
436 /// special global used by LLVM. If so, emit it and return true, otherwise
437 /// do nothing and return false.
438 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
439 if (GV->getName() == "llvm.used") {
440 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
441 EmitLLVMUsedList(GV->getInitializer());
445 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
446 if (GV->getSection() == "llvm.metadata" ||
447 GV->hasAvailableExternallyLinkage())
450 if (!GV->hasAppendingLinkage()) return false;
452 assert(GV->hasInitializer() && "Not a special LLVM global!");
454 const TargetData *TD = TM.getTargetData();
455 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
456 if (GV->getName() == "llvm.global_ctors") {
457 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
458 EmitAlignment(Align, 0);
459 EmitXXStructorList(GV->getInitializer());
463 if (GV->getName() == "llvm.global_dtors") {
464 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
465 EmitAlignment(Align, 0);
466 EmitXXStructorList(GV->getInitializer());
473 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
474 /// global in the specified llvm.used list for which emitUsedDirectiveFor
475 /// is true, as being used with this directive.
476 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
477 const char *Directive = MAI->getUsedDirective();
479 // Should be an array of 'i8*'.
480 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
481 if (InitList == 0) return;
483 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
484 const GlobalValue *GV =
485 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
486 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
488 EmitConstantValueOnly(InitList->getOperand(i));
494 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
495 /// function pointers, ignoring the init priority.
496 void AsmPrinter::EmitXXStructorList(Constant *List) {
497 // Should be an array of '{ int, void ()* }' structs. The first value is the
498 // init priority, which we ignore.
499 if (!isa<ConstantArray>(List)) return;
500 ConstantArray *InitList = cast<ConstantArray>(List);
501 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
502 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
503 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
505 if (CS->getOperand(1)->isNullValue())
506 return; // Found a null terminator, exit printing.
507 // Emit the function pointer.
508 EmitGlobalConstant(CS->getOperand(1));
512 /// EmitExternalGlobal - Emit the external reference to a global variable.
513 /// Should be overridden if an indirect reference should be used.
514 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
515 O << Mang->getMangledName(GV);
520 //===----------------------------------------------------------------------===//
521 /// LEB 128 number encoding.
523 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
524 /// representing an unsigned leb128 value.
525 void AsmPrinter::PrintULEB128(unsigned Value) const {
528 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
530 if (Value) Byte |= 0x80;
531 O << "0x" << utohex_buffer(Byte, Buffer+20);
532 if (Value) O << ", ";
536 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
537 /// representing a signed leb128 value.
538 void AsmPrinter::PrintSLEB128(int Value) const {
539 int Sign = Value >> (8 * sizeof(Value) - 1);
544 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
546 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
547 if (IsMore) Byte |= 0x80;
548 O << "0x" << utohex_buffer(Byte, Buffer+20);
549 if (IsMore) O << ", ";
553 //===--------------------------------------------------------------------===//
554 // Emission and print routines
557 /// PrintHex - Print a value as a hexidecimal value.
559 void AsmPrinter::PrintHex(int Value) const {
561 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
564 /// EOL - Print a newline character to asm stream. If a comment is present
565 /// then it will be printed first. Comments should not contain '\n'.
566 void AsmPrinter::EOL() const {
570 void AsmPrinter::EOL(const std::string &Comment) const {
571 if (VerboseAsm && !Comment.empty()) {
572 O.PadToColumn(MAI->getCommentColumn());
573 O << MAI->getCommentString()
580 void AsmPrinter::EOL(const char* Comment) const {
581 if (VerboseAsm && *Comment) {
582 O.PadToColumn(MAI->getCommentColumn());
583 O << MAI->getCommentString()
590 static const char *DecodeDWARFEncoding(unsigned Encoding) {
592 case dwarf::DW_EH_PE_absptr:
594 case dwarf::DW_EH_PE_omit:
596 case dwarf::DW_EH_PE_pcrel:
598 case dwarf::DW_EH_PE_udata4:
600 case dwarf::DW_EH_PE_udata8:
602 case dwarf::DW_EH_PE_sdata4:
604 case dwarf::DW_EH_PE_sdata8:
606 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
607 return "pcrel udata4";
608 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
609 return "pcrel sdata4";
610 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
611 return "pcrel udata8";
612 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
613 return "pcrel sdata8";
614 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
615 return "indirect pcrel udata4";
616 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
617 return "indirect pcrel sdata4";
618 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
619 return "indirect pcrel udata8";
620 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
621 return "indirect pcrel sdata8";
627 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
628 if (VerboseAsm && *Comment) {
629 O.PadToColumn(MAI->getCommentColumn());
630 O << MAI->getCommentString()
634 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
635 O << " (" << EncStr << ')';
640 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
641 /// unsigned leb128 value.
642 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
643 if (MAI->hasLEB128()) {
647 O << MAI->getData8bitsDirective();
652 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
653 /// signed leb128 value.
654 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
655 if (MAI->hasLEB128()) {
659 O << MAI->getData8bitsDirective();
664 /// EmitInt8 - Emit a byte directive and value.
666 void AsmPrinter::EmitInt8(int Value) const {
667 O << MAI->getData8bitsDirective();
668 PrintHex(Value & 0xFF);
671 /// EmitInt16 - Emit a short directive and value.
673 void AsmPrinter::EmitInt16(int Value) const {
674 O << MAI->getData16bitsDirective();
675 PrintHex(Value & 0xFFFF);
678 /// EmitInt32 - Emit a long directive and value.
680 void AsmPrinter::EmitInt32(int Value) const {
681 O << MAI->getData32bitsDirective();
685 /// EmitInt64 - Emit a long long directive and value.
687 void AsmPrinter::EmitInt64(uint64_t Value) const {
688 if (MAI->getData64bitsDirective()) {
689 O << MAI->getData64bitsDirective();
692 if (TM.getTargetData()->isBigEndian()) {
693 EmitInt32(unsigned(Value >> 32)); O << '\n';
694 EmitInt32(unsigned(Value));
696 EmitInt32(unsigned(Value)); O << '\n';
697 EmitInt32(unsigned(Value >> 32));
702 /// toOctal - Convert the low order bits of X into an octal digit.
704 static inline char toOctal(int X) {
708 /// printStringChar - Print a char, escaped if necessary.
710 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
713 } else if (C == '\\') {
715 } else if (isprint((unsigned char)C)) {
719 case '\b': O << "\\b"; break;
720 case '\f': O << "\\f"; break;
721 case '\n': O << "\\n"; break;
722 case '\r': O << "\\r"; break;
723 case '\t': O << "\\t"; break;
726 O << toOctal(C >> 6);
727 O << toOctal(C >> 3);
728 O << toOctal(C >> 0);
734 /// EmitString - Emit a string with quotes and a null terminator.
735 /// Special characters are emitted properly.
736 /// \literal (Eg. '\t') \endliteral
737 void AsmPrinter::EmitString(const std::string &String) const {
738 EmitString(String.c_str(), String.size());
741 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
742 const char* AscizDirective = MAI->getAscizDirective();
746 O << MAI->getAsciiDirective();
748 for (unsigned i = 0; i < Size; ++i)
749 printStringChar(O, String[i]);
757 /// EmitFile - Emit a .file directive.
758 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
759 O << "\t.file\t" << Number << " \"";
760 for (unsigned i = 0, N = Name.size(); i < N; ++i)
761 printStringChar(O, Name[i]);
766 //===----------------------------------------------------------------------===//
768 // EmitAlignment - Emit an alignment directive to the specified power of
769 // two boundary. For example, if you pass in 3 here, you will get an 8
770 // byte alignment. If a global value is specified, and if that global has
771 // an explicit alignment requested, it will unconditionally override the
772 // alignment request. However, if ForcedAlignBits is specified, this value
773 // has final say: the ultimate alignment will be the max of ForcedAlignBits
774 // and the alignment computed with NumBits and the global.
778 // if (GV && GV->hasalignment) Align = GV->getalignment();
779 // Align = std::max(Align, ForcedAlignBits);
781 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
782 unsigned ForcedAlignBits,
783 bool UseFillExpr) const {
784 if (GV && GV->getAlignment())
785 NumBits = Log2_32(GV->getAlignment());
786 NumBits = std::max(NumBits, ForcedAlignBits);
788 if (NumBits == 0) return; // No need to emit alignment.
790 unsigned FillValue = 0;
791 if (getCurrentSection()->getKind().isText())
792 FillValue = MAI->getTextAlignFillValue();
794 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
797 /// EmitZeros - Emit a block of zeros.
799 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
801 if (MAI->getZeroDirective()) {
802 O << MAI->getZeroDirective() << NumZeros;
803 if (MAI->getZeroDirectiveSuffix())
804 O << MAI->getZeroDirectiveSuffix();
807 for (; NumZeros; --NumZeros)
808 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
813 // Print out the specified constant, without a storage class. Only the
814 // constants valid in constant expressions can occur here.
815 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
816 if (CV->isNullValue() || isa<UndefValue>(CV))
818 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
819 O << CI->getZExtValue();
820 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
821 // This is a constant address for a global variable or function. Use the
822 // name of the variable or function as the address value.
823 O << Mang->getMangledName(GV);
824 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
825 const TargetData *TD = TM.getTargetData();
826 unsigned Opcode = CE->getOpcode();
828 case Instruction::Trunc:
829 case Instruction::ZExt:
830 case Instruction::SExt:
831 case Instruction::FPTrunc:
832 case Instruction::FPExt:
833 case Instruction::UIToFP:
834 case Instruction::SIToFP:
835 case Instruction::FPToUI:
836 case Instruction::FPToSI:
837 llvm_unreachable("FIXME: Don't support this constant cast expr");
838 case Instruction::GetElementPtr: {
839 // generate a symbolic expression for the byte address
840 const Constant *ptrVal = CE->getOperand(0);
841 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
842 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
844 // Truncate/sext the offset to the pointer size.
845 if (TD->getPointerSizeInBits() != 64) {
846 int SExtAmount = 64-TD->getPointerSizeInBits();
847 Offset = (Offset << SExtAmount) >> SExtAmount;
852 EmitConstantValueOnly(ptrVal);
854 O << ") + " << Offset;
856 O << ") - " << -Offset;
858 EmitConstantValueOnly(ptrVal);
862 case Instruction::BitCast:
863 return EmitConstantValueOnly(CE->getOperand(0));
865 case Instruction::IntToPtr: {
866 // Handle casts to pointers by changing them into casts to the appropriate
867 // integer type. This promotes constant folding and simplifies this code.
868 Constant *Op = CE->getOperand(0);
869 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
871 return EmitConstantValueOnly(Op);
875 case Instruction::PtrToInt: {
876 // Support only foldable casts to/from pointers that can be eliminated by
877 // changing the pointer to the appropriately sized integer type.
878 Constant *Op = CE->getOperand(0);
879 const Type *Ty = CE->getType();
881 // We can emit the pointer value into this slot if the slot is an
882 // integer slot greater or equal to the size of the pointer.
883 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
884 return EmitConstantValueOnly(Op);
887 EmitConstantValueOnly(Op);
889 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
892 ptrMask.toStringUnsigned(S);
893 O << ") & " << S.str() << ')';
896 case Instruction::Add:
897 case Instruction::Sub:
898 case Instruction::And:
899 case Instruction::Or:
900 case Instruction::Xor:
902 EmitConstantValueOnly(CE->getOperand(0));
905 case Instruction::Add:
908 case Instruction::Sub:
911 case Instruction::And:
914 case Instruction::Or:
917 case Instruction::Xor:
924 EmitConstantValueOnly(CE->getOperand(1));
928 llvm_unreachable("Unsupported operator!");
931 llvm_unreachable("Unknown constant value!");
935 /// printAsCString - Print the specified array as a C compatible string, only if
936 /// the predicate isString is true.
938 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
940 assert(CVA->isString() && "Array is not string compatible!");
943 for (unsigned i = 0; i != LastElt; ++i) {
945 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
946 printStringChar(O, C);
951 /// EmitString - Emit a zero-byte-terminated string constant.
953 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
954 unsigned NumElts = CVA->getNumOperands();
955 if (MAI->getAscizDirective() && NumElts &&
956 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
957 O << MAI->getAscizDirective();
958 printAsCString(O, CVA, NumElts-1);
960 O << MAI->getAsciiDirective();
961 printAsCString(O, CVA, NumElts);
966 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
967 unsigned AddrSpace) {
968 if (CVA->isString()) {
970 } else { // Not a string. Print the values in successive locations
971 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
972 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
976 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
977 const VectorType *PTy = CP->getType();
979 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
980 EmitGlobalConstant(CP->getOperand(I));
983 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
984 unsigned AddrSpace) {
985 // Print the fields in successive locations. Pad to align if needed!
986 const TargetData *TD = TM.getTargetData();
987 unsigned Size = TD->getTypeAllocSize(CVS->getType());
988 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
989 uint64_t sizeSoFar = 0;
990 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
991 const Constant* field = CVS->getOperand(i);
993 // Check if padding is needed and insert one or more 0s.
994 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
995 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
996 - cvsLayout->getElementOffset(i)) - fieldSize;
997 sizeSoFar += fieldSize + padSize;
999 // Now print the actual field value.
1000 EmitGlobalConstant(field, AddrSpace);
1002 // Insert padding - this may include padding to increase the size of the
1003 // current field up to the ABI size (if the struct is not packed) as well
1004 // as padding to ensure that the next field starts at the right offset.
1005 EmitZeros(padSize, AddrSpace);
1007 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1008 "Layout of constant struct may be incorrect!");
1011 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1012 unsigned AddrSpace) {
1013 // FP Constants are printed as integer constants to avoid losing
1015 LLVMContext &Context = CFP->getContext();
1016 const TargetData *TD = TM.getTargetData();
1017 if (CFP->getType() == Type::getDoubleTy(Context)) {
1018 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1019 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1020 if (MAI->getData64bitsDirective(AddrSpace)) {
1021 O << MAI->getData64bitsDirective(AddrSpace) << i;
1023 O.PadToColumn(MAI->getCommentColumn());
1024 O << MAI->getCommentString() << " double " << Val;
1027 } else if (TD->isBigEndian()) {
1028 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1030 O.PadToColumn(MAI->getCommentColumn());
1031 O << MAI->getCommentString()
1032 << " most significant word of double " << Val;
1035 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1037 O.PadToColumn(MAI->getCommentColumn());
1038 O << MAI->getCommentString()
1039 << " least significant word of double " << Val;
1043 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1045 O.PadToColumn(MAI->getCommentColumn());
1046 O << MAI->getCommentString()
1047 << " least significant word of double " << Val;
1050 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1052 O.PadToColumn(MAI->getCommentColumn());
1053 O << MAI->getCommentString()
1054 << " most significant word of double " << Val;
1059 } else if (CFP->getType() == Type::getFloatTy(Context)) {
1060 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1061 O << MAI->getData32bitsDirective(AddrSpace)
1062 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1064 O.PadToColumn(MAI->getCommentColumn());
1065 O << MAI->getCommentString() << " float " << Val;
1069 } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1070 // all long double variants are printed as hex
1071 // api needed to prevent premature destruction
1072 APInt api = CFP->getValueAPF().bitcastToAPInt();
1073 const uint64_t *p = api.getRawData();
1074 // Convert to double so we can print the approximate val as a comment.
1075 APFloat DoubleVal = CFP->getValueAPF();
1077 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1079 if (TD->isBigEndian()) {
1080 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1082 O.PadToColumn(MAI->getCommentColumn());
1083 O << MAI->getCommentString()
1084 << " most significant halfword of x86_fp80 ~"
1085 << DoubleVal.convertToDouble();
1088 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1090 O.PadToColumn(MAI->getCommentColumn());
1091 O << MAI->getCommentString() << " next halfword";
1094 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1096 O.PadToColumn(MAI->getCommentColumn());
1097 O << MAI->getCommentString() << " next halfword";
1100 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1102 O.PadToColumn(MAI->getCommentColumn());
1103 O << MAI->getCommentString() << " next halfword";
1106 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1108 O.PadToColumn(MAI->getCommentColumn());
1109 O << MAI->getCommentString()
1110 << " least significant halfword";
1114 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1116 O.PadToColumn(MAI->getCommentColumn());
1117 O << MAI->getCommentString()
1118 << " least significant halfword of x86_fp80 ~"
1119 << DoubleVal.convertToDouble();
1122 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1124 O.PadToColumn(MAI->getCommentColumn());
1125 O << MAI->getCommentString()
1126 << " next halfword";
1129 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1131 O.PadToColumn(MAI->getCommentColumn());
1132 O << MAI->getCommentString()
1133 << " next halfword";
1136 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1138 O.PadToColumn(MAI->getCommentColumn());
1139 O << MAI->getCommentString()
1140 << " next halfword";
1143 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1145 O.PadToColumn(MAI->getCommentColumn());
1146 O << MAI->getCommentString()
1147 << " most significant halfword";
1151 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1152 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1154 } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1155 // all long double variants are printed as hex
1156 // api needed to prevent premature destruction
1157 APInt api = CFP->getValueAPF().bitcastToAPInt();
1158 const uint64_t *p = api.getRawData();
1159 if (TD->isBigEndian()) {
1160 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1162 O.PadToColumn(MAI->getCommentColumn());
1163 O << MAI->getCommentString()
1164 << " most significant word of ppc_fp128";
1167 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1169 O.PadToColumn(MAI->getCommentColumn());
1170 O << MAI->getCommentString()
1174 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1176 O.PadToColumn(MAI->getCommentColumn());
1177 O << MAI->getCommentString()
1181 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1183 O.PadToColumn(MAI->getCommentColumn());
1184 O << MAI->getCommentString()
1185 << " least significant word";
1189 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1191 O.PadToColumn(MAI->getCommentColumn());
1192 O << MAI->getCommentString()
1193 << " least significant word of ppc_fp128";
1196 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1198 O.PadToColumn(MAI->getCommentColumn());
1199 O << MAI->getCommentString()
1203 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1205 O.PadToColumn(MAI->getCommentColumn());
1206 O << MAI->getCommentString()
1210 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1212 O.PadToColumn(MAI->getCommentColumn());
1213 O << MAI->getCommentString()
1214 << " most significant word";
1219 } else llvm_unreachable("Floating point constant type not handled");
1222 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1223 unsigned AddrSpace) {
1224 const TargetData *TD = TM.getTargetData();
1225 unsigned BitWidth = CI->getBitWidth();
1226 assert(isPowerOf2_32(BitWidth) &&
1227 "Non-power-of-2-sized integers not handled!");
1229 // We don't expect assemblers to support integer data directives
1230 // for more than 64 bits, so we emit the data in at most 64-bit
1231 // quantities at a time.
1232 const uint64_t *RawData = CI->getValue().getRawData();
1233 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1235 if (TD->isBigEndian())
1236 Val = RawData[e - i - 1];
1240 if (MAI->getData64bitsDirective(AddrSpace))
1241 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1242 else if (TD->isBigEndian()) {
1243 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1245 O.PadToColumn(MAI->getCommentColumn());
1246 O << MAI->getCommentString()
1247 << " most significant half of i64 " << Val;
1250 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1252 O.PadToColumn(MAI->getCommentColumn());
1253 O << MAI->getCommentString()
1254 << " least significant half of i64 " << Val;
1258 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1260 O.PadToColumn(MAI->getCommentColumn());
1261 O << MAI->getCommentString()
1262 << " least significant half of i64 " << Val;
1265 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1267 O.PadToColumn(MAI->getCommentColumn());
1268 O << MAI->getCommentString()
1269 << " most significant half of i64 " << Val;
1276 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1277 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1278 const TargetData *TD = TM.getTargetData();
1279 const Type *type = CV->getType();
1280 unsigned Size = TD->getTypeAllocSize(type);
1282 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1283 EmitZeros(Size, AddrSpace);
1285 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1286 EmitGlobalConstantArray(CVA , AddrSpace);
1288 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1289 EmitGlobalConstantStruct(CVS, AddrSpace);
1291 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1292 EmitGlobalConstantFP(CFP, AddrSpace);
1294 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1295 // Small integers are handled below; large integers are handled here.
1297 EmitGlobalConstantLargeInt(CI, AddrSpace);
1300 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1301 EmitGlobalConstantVector(CP);
1305 printDataDirective(type, AddrSpace);
1306 EmitConstantValueOnly(CV);
1308 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1310 CI->getValue().toStringUnsigned(S, 16);
1311 O.PadToColumn(MAI->getCommentColumn());
1312 O << MAI->getCommentString() << " 0x" << S.str();
1318 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1319 // Target doesn't support this yet!
1320 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1323 /// PrintSpecial - Print information related to the specified machine instr
1324 /// that is independent of the operand, and may be independent of the instr
1325 /// itself. This can be useful for portably encoding the comment character
1326 /// or other bits of target-specific knowledge into the asmstrings. The
1327 /// syntax used is ${:comment}. Targets can override this to add support
1328 /// for their own strange codes.
1329 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1330 if (!strcmp(Code, "private")) {
1331 O << MAI->getPrivateGlobalPrefix();
1332 } else if (!strcmp(Code, "comment")) {
1334 O << MAI->getCommentString();
1335 } else if (!strcmp(Code, "uid")) {
1336 // Comparing the address of MI isn't sufficient, because machineinstrs may
1337 // be allocated to the same address across functions.
1338 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1340 // If this is a new LastFn instruction, bump the counter.
1341 if (LastMI != MI || LastFn != ThisF) {
1349 raw_string_ostream Msg(msg);
1350 Msg << "Unknown special formatter '" << Code
1351 << "' for machine instr: " << *MI;
1352 llvm_report_error(Msg.str());
1356 /// processDebugLoc - Processes the debug information of each machine
1357 /// instruction's DebugLoc.
1358 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1362 if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1363 if (!DL.isUnknown()) {
1364 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1366 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1367 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1368 DICompileUnit(CurDLT.CompileUnit)));
1377 /// printInlineAsm - This method formats and prints the specified machine
1378 /// instruction that is an inline asm.
1379 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1380 unsigned NumOperands = MI->getNumOperands();
1382 // Count the number of register definitions.
1383 unsigned NumDefs = 0;
1384 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1386 assert(NumDefs != NumOperands-1 && "No asm string?");
1388 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1390 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1391 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1393 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1394 // These are useful to see where empty asm's wound up.
1395 if (AsmStr[0] == 0) {
1396 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1397 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1401 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1403 // The variant of the current asmprinter.
1404 int AsmPrinterVariant = MAI->getAssemblerDialect();
1406 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1407 const char *LastEmitted = AsmStr; // One past the last character emitted.
1409 while (*LastEmitted) {
1410 switch (*LastEmitted) {
1412 // Not a special case, emit the string section literally.
1413 const char *LiteralEnd = LastEmitted+1;
1414 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1415 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1417 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1418 O.write(LastEmitted, LiteralEnd-LastEmitted);
1419 LastEmitted = LiteralEnd;
1423 ++LastEmitted; // Consume newline character.
1424 O << '\n'; // Indent code with newline.
1427 ++LastEmitted; // Consume '$' character.
1431 switch (*LastEmitted) {
1432 default: Done = false; break;
1433 case '$': // $$ -> $
1434 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1436 ++LastEmitted; // Consume second '$' character.
1438 case '(': // $( -> same as GCC's { character.
1439 ++LastEmitted; // Consume '(' character.
1440 if (CurVariant != -1) {
1441 llvm_report_error("Nested variants found in inline asm string: '"
1442 + std::string(AsmStr) + "'");
1444 CurVariant = 0; // We're in the first variant now.
1447 ++LastEmitted; // consume '|' character.
1448 if (CurVariant == -1)
1449 O << '|'; // this is gcc's behavior for | outside a variant
1451 ++CurVariant; // We're in the next variant.
1453 case ')': // $) -> same as GCC's } char.
1454 ++LastEmitted; // consume ')' character.
1455 if (CurVariant == -1)
1456 O << '}'; // this is gcc's behavior for } outside a variant
1463 bool HasCurlyBraces = false;
1464 if (*LastEmitted == '{') { // ${variable}
1465 ++LastEmitted; // Consume '{' character.
1466 HasCurlyBraces = true;
1469 // If we have ${:foo}, then this is not a real operand reference, it is a
1470 // "magic" string reference, just like in .td files. Arrange to call
1472 if (HasCurlyBraces && *LastEmitted == ':') {
1474 const char *StrStart = LastEmitted;
1475 const char *StrEnd = strchr(StrStart, '}');
1477 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1478 + std::string(AsmStr) + "'");
1481 std::string Val(StrStart, StrEnd);
1482 PrintSpecial(MI, Val.c_str());
1483 LastEmitted = StrEnd+1;
1487 const char *IDStart = LastEmitted;
1490 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1491 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1492 llvm_report_error("Bad $ operand number in inline asm string: '"
1493 + std::string(AsmStr) + "'");
1495 LastEmitted = IDEnd;
1497 char Modifier[2] = { 0, 0 };
1499 if (HasCurlyBraces) {
1500 // If we have curly braces, check for a modifier character. This
1501 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1502 if (*LastEmitted == ':') {
1503 ++LastEmitted; // Consume ':' character.
1504 if (*LastEmitted == 0) {
1505 llvm_report_error("Bad ${:} expression in inline asm string: '"
1506 + std::string(AsmStr) + "'");
1509 Modifier[0] = *LastEmitted;
1510 ++LastEmitted; // Consume modifier character.
1513 if (*LastEmitted != '}') {
1514 llvm_report_error("Bad ${} expression in inline asm string: '"
1515 + std::string(AsmStr) + "'");
1517 ++LastEmitted; // Consume '}' character.
1520 if ((unsigned)Val >= NumOperands-1) {
1521 llvm_report_error("Invalid $ operand number in inline asm string: '"
1522 + std::string(AsmStr) + "'");
1525 // Okay, we finally have a value number. Ask the target to print this
1527 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1532 // Scan to find the machine operand number for the operand.
1533 for (; Val; --Val) {
1534 if (OpNo >= MI->getNumOperands()) break;
1535 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1536 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1539 if (OpNo >= MI->getNumOperands()) {
1542 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1543 ++OpNo; // Skip over the ID number.
1545 if (Modifier[0]=='l') // labels are target independent
1546 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1547 ->getNumber())->print(O, MAI);
1549 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1550 if ((OpFlags & 7) == 4) {
1551 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1552 Modifier[0] ? Modifier : 0);
1554 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1555 Modifier[0] ? Modifier : 0);
1561 raw_string_ostream Msg(msg);
1562 Msg << "Invalid operand found in inline asm: '"
1565 llvm_report_error(Msg.str());
1572 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1575 /// printImplicitDef - This method prints the specified machine instruction
1576 /// that is an implicit def.
1577 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1578 if (!VerboseAsm) return;
1579 O.PadToColumn(MAI->getCommentColumn());
1580 O << MAI->getCommentString() << " implicit-def: "
1581 << TRI->getName(MI->getOperand(0).getReg());
1584 /// printLabel - This method prints a local label used by debug and
1585 /// exception handling tables.
1586 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1587 printLabel(MI->getOperand(0).getImm());
1590 void AsmPrinter::printLabel(unsigned Id) const {
1591 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1594 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1595 /// instruction, using the specified assembler variant. Targets should
1596 /// overried this to format as appropriate.
1597 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1598 unsigned AsmVariant, const char *ExtraCode) {
1599 // Target doesn't support this yet!
1603 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1604 unsigned AsmVariant,
1605 const char *ExtraCode) {
1606 // Target doesn't support this yet!
1610 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1611 SmallString<60> Name;
1612 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1613 << getFunctionNumber() << '_' << MBBID;
1615 return OutContext.GetOrCreateSymbol(Name.str());
1619 /// EmitBasicBlockStart - This method prints the label for the specified
1620 /// MachineBasicBlock, an alignment (if present) and a comment describing
1621 /// it if appropriate.
1622 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1623 if (unsigned Align = MBB->getAlignment())
1624 EmitAlignment(Log2_32(Align));
1626 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1630 if (const BasicBlock *BB = MBB->getBasicBlock())
1631 if (BB->hasName()) {
1632 O.PadToColumn(MAI->getCommentColumn());
1633 O << MAI->getCommentString() << ' ';
1634 WriteAsOperand(O, BB, /*PrintType=*/false);
1641 /// printPICJumpTableSetLabel - This method prints a set label for the
1642 /// specified MachineBasicBlock for a jumptable entry.
1643 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1644 const MachineBasicBlock *MBB) const {
1645 if (!MAI->getSetDirective())
1648 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1649 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1650 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1651 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1652 << '_' << uid << '\n';
1655 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1656 const MachineBasicBlock *MBB) const {
1657 if (!MAI->getSetDirective())
1660 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1661 << getFunctionNumber() << '_' << uid << '_' << uid2
1662 << "_set_" << MBB->getNumber() << ',';
1663 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1664 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1665 << '_' << uid << '_' << uid2 << '\n';
1668 /// printDataDirective - This method prints the asm directive for the
1670 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1671 const TargetData *TD = TM.getTargetData();
1672 switch (type->getTypeID()) {
1673 case Type::FloatTyID: case Type::DoubleTyID:
1674 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1675 assert(0 && "Should have already output floating point constant.");
1677 assert(0 && "Can't handle printing this type of thing");
1678 case Type::IntegerTyID: {
1679 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1681 O << MAI->getData8bitsDirective(AddrSpace);
1682 else if (BitWidth <= 16)
1683 O << MAI->getData16bitsDirective(AddrSpace);
1684 else if (BitWidth <= 32)
1685 O << MAI->getData32bitsDirective(AddrSpace);
1686 else if (BitWidth <= 64) {
1687 assert(MAI->getData64bitsDirective(AddrSpace) &&
1688 "Target cannot handle 64-bit constant exprs!");
1689 O << MAI->getData64bitsDirective(AddrSpace);
1691 llvm_unreachable("Target cannot handle given data directive width!");
1695 case Type::PointerTyID:
1696 if (TD->getPointerSize() == 8) {
1697 assert(MAI->getData64bitsDirective(AddrSpace) &&
1698 "Target cannot handle 64-bit pointer exprs!");
1699 O << MAI->getData64bitsDirective(AddrSpace);
1700 } else if (TD->getPointerSize() == 2) {
1701 O << MAI->getData16bitsDirective(AddrSpace);
1702 } else if (TD->getPointerSize() == 1) {
1703 O << MAI->getData8bitsDirective(AddrSpace);
1705 O << MAI->getData32bitsDirective(AddrSpace);
1711 void AsmPrinter::printVisibility(const std::string& Name,
1712 unsigned Visibility) const {
1713 if (Visibility == GlobalValue::HiddenVisibility) {
1714 if (const char *Directive = MAI->getHiddenDirective())
1715 O << Directive << Name << '\n';
1716 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1717 if (const char *Directive = MAI->getProtectedDirective())
1718 O << Directive << Name << '\n';
1722 void AsmPrinter::printOffset(int64_t Offset) const {
1725 else if (Offset < 0)
1729 void AsmPrinter::printMCInst(const MCInst *MI) {
1730 llvm_unreachable("MCInst printing unavailable on this target!");
1733 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1734 if (!S->usesMetadata())
1737 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1738 if (GCPI != GCMetadataPrinters.end())
1739 return GCPI->second;
1741 const char *Name = S->getName().c_str();
1743 for (GCMetadataPrinterRegistry::iterator
1744 I = GCMetadataPrinterRegistry::begin(),
1745 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1746 if (strcmp(Name, I->getName()) == 0) {
1747 GCMetadataPrinter *GMP = I->instantiate();
1749 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1753 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1754 llvm_unreachable(0);
1757 /// EmitComments - Pretty-print comments for instructions
1758 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1759 assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1761 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1763 // Print source line info.
1764 O.PadToColumn(MAI->getCommentColumn());
1765 O << MAI->getCommentString() << " SrcLine ";
1766 if (DLT.CompileUnit) {
1768 DICompileUnit CU(DLT.CompileUnit);
1769 O << CU.getFilename(Str) << " ";
1773 O << ":" << DLT.Col;
1776 /// PrintChildLoopComment - Print comments about child loops within
1777 /// the loop for this basic block, with nesting.
1779 static void PrintChildLoopComment(formatted_raw_ostream &O,
1780 const MachineLoop *loop,
1781 const MCAsmInfo *MAI,
1782 int FunctionNumber) {
1783 // Add child loop information
1784 for(MachineLoop::iterator cl = loop->begin(),
1785 clend = loop->end();
1788 MachineBasicBlock *Header = (*cl)->getHeader();
1789 assert(Header && "No header for loop");
1792 O.PadToColumn(MAI->getCommentColumn());
1794 O << MAI->getCommentString();
1795 O.indent(((*cl)->getLoopDepth()-1)*2)
1796 << " Child Loop BB" << FunctionNumber << "_"
1797 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1799 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1803 /// EmitComments - Pretty-print comments for basic blocks
1804 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1807 // Add loop depth information
1808 const MachineLoop *loop = LI->getLoopFor(&MBB);
1811 // Print a newline after bb# annotation.
1813 O.PadToColumn(MAI->getCommentColumn());
1814 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1817 O.PadToColumn(MAI->getCommentColumn());
1819 MachineBasicBlock *Header = loop->getHeader();
1820 assert(Header && "No header for loop");
1822 if (Header == &MBB) {
1823 O << MAI->getCommentString() << " Loop Header";
1824 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1827 O << MAI->getCommentString() << " Loop Header is BB"
1828 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1831 if (loop->empty()) {
1833 O.PadToColumn(MAI->getCommentColumn());
1834 O << MAI->getCommentString() << " Inner Loop";
1837 // Add parent loop information
1838 for (const MachineLoop *CurLoop = loop->getParentLoop();
1840 CurLoop = CurLoop->getParentLoop()) {
1841 MachineBasicBlock *Header = CurLoop->getHeader();
1842 assert(Header && "No header for loop");
1845 O.PadToColumn(MAI->getCommentColumn());
1846 O << MAI->getCommentString();
1847 O.indent((CurLoop->getLoopDepth()-1)*2)
1848 << " Inside Loop BB" << getFunctionNumber() << "_"
1849 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();