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 // Allow the target to emit any magic that it wants at the start of the file.
109 EmitStartOfAsmFile(M);
111 if (MAI->hasSingleParameterDotFile()) {
112 /* Very minimal debug info. It is ignored if we emit actual
113 debug info. If we don't, this at least helps the user find where
114 a function came from. */
115 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
118 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
119 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
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 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
132 MMI->AnalyzeModule(M);
133 DW = getAnalysisIfAvailable<DwarfWriter>();
135 DW->BeginModule(&M, MMI, O, this, MAI);
140 bool AsmPrinter::doFinalization(Module &M) {
141 // Emit global variables.
142 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
144 PrintGlobalVariable(I);
146 // Emit final debug information.
147 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
150 // If the target wants to know about weak references, print them all.
151 if (MAI->getWeakRefDirective()) {
152 // FIXME: This is not lazy, it would be nice to only print weak references
153 // to stuff that is actually used. Note that doing so would require targets
154 // to notice uses in operands (due to constant exprs etc). This should
155 // happen with the MC stuff eventually.
157 // Print out module-level global variables here.
158 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
160 if (!I->hasExternalWeakLinkage()) continue;
161 O << MAI->getWeakRefDirective();
162 GetGlobalValueSymbol(I)->print(O, MAI);
166 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
167 if (!I->hasExternalWeakLinkage()) continue;
168 O << MAI->getWeakRefDirective();
169 GetGlobalValueSymbol(I)->print(O, MAI);
174 if (MAI->getSetDirective()) {
176 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
178 MCSymbol *Name = GetGlobalValueSymbol(I);
180 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
181 MCSymbol *Target = GetGlobalValueSymbol(GV);
183 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) {
187 } else if (I->hasWeakLinkage()) {
188 O << MAI->getWeakRefDirective();
192 assert(I->hasLocalLinkage() && "Invalid alias linkage");
195 printVisibility(Name, I->getVisibility());
197 O << MAI->getSetDirective() << ' ';
200 Target->print(O, MAI);
205 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
206 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
207 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
208 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
209 MP->finishAssembly(O, *this, *MAI);
211 // If we don't have any trampolines, then we don't require stack memory
212 // to be executable. Some targets have a directive to declare this.
213 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
214 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
215 if (MAI->getNonexecutableStackDirective())
216 O << MAI->getNonexecutableStackDirective() << '\n';
219 // Allow the target to emit any magic that it wants at the end of the file,
220 // after everything else has gone out.
223 delete Mang; Mang = 0;
226 OutStreamer.Finish();
230 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
231 // Get the function symbol.
232 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
233 IncrementFunctionNumber();
236 LI = &getAnalysis<MachineLoopInfo>();
240 // SectionCPs - Keep track the alignment, constpool entries per Section.
244 SmallVector<unsigned, 4> CPEs;
245 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
249 /// EmitConstantPool - Print to the current output stream assembly
250 /// representations of the constants in the constant pool MCP. This is
251 /// used to print out constants which have been "spilled to memory" by
252 /// the code generator.
254 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
255 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
256 if (CP.empty()) return;
258 // Calculate sections for constant pool entries. We collect entries to go into
259 // the same section together to reduce amount of section switch statements.
260 SmallVector<SectionCPs, 4> CPSections;
261 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
262 const MachineConstantPoolEntry &CPE = CP[i];
263 unsigned Align = CPE.getAlignment();
266 switch (CPE.getRelocationInfo()) {
267 default: llvm_unreachable("Unknown section kind");
268 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
270 Kind = SectionKind::getReadOnlyWithRelLocal();
273 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
274 case 4: Kind = SectionKind::getMergeableConst4(); break;
275 case 8: Kind = SectionKind::getMergeableConst8(); break;
276 case 16: Kind = SectionKind::getMergeableConst16();break;
277 default: Kind = SectionKind::getMergeableConst(); break;
281 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
283 // The number of sections are small, just do a linear search from the
284 // last section to the first.
286 unsigned SecIdx = CPSections.size();
287 while (SecIdx != 0) {
288 if (CPSections[--SecIdx].S == S) {
294 SecIdx = CPSections.size();
295 CPSections.push_back(SectionCPs(S, Align));
298 if (Align > CPSections[SecIdx].Alignment)
299 CPSections[SecIdx].Alignment = Align;
300 CPSections[SecIdx].CPEs.push_back(i);
303 // Now print stuff into the calculated sections.
304 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
305 OutStreamer.SwitchSection(CPSections[i].S);
306 EmitAlignment(Log2_32(CPSections[i].Alignment));
309 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
310 unsigned CPI = CPSections[i].CPEs[j];
311 MachineConstantPoolEntry CPE = CP[CPI];
313 // Emit inter-object padding for alignment.
314 unsigned AlignMask = CPE.getAlignment() - 1;
315 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
316 EmitZeros(NewOffset - Offset);
318 const Type *Ty = CPE.getType();
319 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
321 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
324 O.PadToColumn(MAI->getCommentColumn());
325 O << MAI->getCommentString() << " constant ";
326 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
329 if (CPE.isMachineConstantPoolEntry())
330 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
332 EmitGlobalConstant(CPE.Val.ConstVal);
337 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
338 /// by the current function to the current output stream.
340 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
341 MachineFunction &MF) {
342 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
343 if (JT.empty()) return;
345 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
347 // Pick the directive to use to print the jump table entries, and switch to
348 // the appropriate section.
349 TargetLowering *LoweringInfo = TM.getTargetLowering();
351 const Function *F = MF.getFunction();
352 bool JTInDiffSection = false;
353 if (F->isWeakForLinker() ||
354 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
355 // In PIC mode, we need to emit the jump table to the same section as the
356 // function body itself, otherwise the label differences won't make sense.
357 // We should also do if the section name is NULL or function is declared in
358 // discardable section.
359 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
362 // Otherwise, drop it in the readonly section.
363 const MCSection *ReadOnlySection =
364 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
365 OutStreamer.SwitchSection(ReadOnlySection);
366 JTInDiffSection = true;
369 EmitAlignment(Log2_32(MJTI->getAlignment()));
371 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
372 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
374 // If this jump table was deleted, ignore it.
375 if (JTBBs.empty()) continue;
377 // For PIC codegen, if possible we want to use the SetDirective to reduce
378 // the number of relocations the assembler will generate for the jump table.
379 // Set directives are all printed before the jump table itself.
380 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
381 if (MAI->getSetDirective() && IsPic)
382 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
383 if (EmittedSets.insert(JTBBs[ii]))
384 printPICJumpTableSetLabel(i, JTBBs[ii]);
386 // On some targets (e.g. Darwin) we want to emit two consequtive labels
387 // before each jump table. The first label is never referenced, but tells
388 // the assembler and linker the extents of the jump table object. The
389 // second label is actually referenced by the code.
390 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
391 O << MAI->getLinkerPrivateGlobalPrefix()
392 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
395 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
396 << '_' << i << ":\n";
398 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
399 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
405 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
406 const MachineBasicBlock *MBB,
407 unsigned uid) const {
408 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
410 // Use JumpTableDirective otherwise honor the entry size from the jump table
412 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
413 bool HadJTEntryDirective = JTEntryDirective != NULL;
414 if (!HadJTEntryDirective) {
415 JTEntryDirective = MJTI->getEntrySize() == 4 ?
416 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
419 O << JTEntryDirective << ' ';
421 // If we have emitted set directives for the jump table entries, print
422 // them rather than the entries themselves. If we're emitting PIC, then
423 // emit the table entries as differences between two text section labels.
424 // If we're emitting non-PIC code, then emit the entries as direct
425 // references to the target basic blocks.
427 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
428 } else if (MAI->getSetDirective()) {
429 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
430 << '_' << uid << "_set_" << MBB->getNumber();
432 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
433 // If the arch uses custom Jump Table directives, don't calc relative to
435 if (!HadJTEntryDirective)
436 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
437 << getFunctionNumber() << '_' << uid;
442 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
443 /// special global used by LLVM. If so, emit it and return true, otherwise
444 /// do nothing and return false.
445 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
446 if (GV->getName() == "llvm.used") {
447 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
448 EmitLLVMUsedList(GV->getInitializer());
452 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
453 if (GV->getSection() == "llvm.metadata" ||
454 GV->hasAvailableExternallyLinkage())
457 if (!GV->hasAppendingLinkage()) return false;
459 assert(GV->hasInitializer() && "Not a special LLVM global!");
461 const TargetData *TD = TM.getTargetData();
462 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
463 if (GV->getName() == "llvm.global_ctors") {
464 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
465 EmitAlignment(Align, 0);
466 EmitXXStructorList(GV->getInitializer());
470 if (GV->getName() == "llvm.global_dtors") {
471 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
472 EmitAlignment(Align, 0);
473 EmitXXStructorList(GV->getInitializer());
480 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
481 /// global in the specified llvm.used list for which emitUsedDirectiveFor
482 /// is true, as being used with this directive.
483 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
484 const char *Directive = MAI->getUsedDirective();
486 // Should be an array of 'i8*'.
487 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
488 if (InitList == 0) return;
490 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
491 const GlobalValue *GV =
492 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
493 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
495 EmitConstantValueOnly(InitList->getOperand(i));
501 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
502 /// function pointers, ignoring the init priority.
503 void AsmPrinter::EmitXXStructorList(Constant *List) {
504 // Should be an array of '{ int, void ()* }' structs. The first value is the
505 // init priority, which we ignore.
506 if (!isa<ConstantArray>(List)) return;
507 ConstantArray *InitList = cast<ConstantArray>(List);
508 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
509 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
510 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
512 if (CS->getOperand(1)->isNullValue())
513 return; // Found a null terminator, exit printing.
514 // Emit the function pointer.
515 EmitGlobalConstant(CS->getOperand(1));
520 //===----------------------------------------------------------------------===//
521 /// LEB 128 number encoding.
523 /// PrintULEB128 - Print a series of hexadecimal 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 hexadecimal 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 hexadecimal 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 StringRef String) const {
738 EmitString(String.data(), 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)) {
821 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
822 O << CI->getZExtValue();
826 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
827 // This is a constant address for a global variable or function. Use the
828 // name of the variable or function as the address value.
829 GetGlobalValueSymbol(GV)->print(O, MAI);
833 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
834 GetBlockAddressSymbol(BA)->print(O, MAI);
838 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
840 llvm_unreachable("Unknown constant value!");
845 switch (CE->getOpcode()) {
846 case Instruction::ZExt:
847 case Instruction::SExt:
848 case Instruction::FPTrunc:
849 case Instruction::FPExt:
850 case Instruction::UIToFP:
851 case Instruction::SIToFP:
852 case Instruction::FPToUI:
853 case Instruction::FPToSI:
855 llvm_unreachable("FIXME: Don't support this constant cast expr");
856 case Instruction::GetElementPtr: {
857 // generate a symbolic expression for the byte address
858 const TargetData *TD = TM.getTargetData();
859 const Constant *ptrVal = CE->getOperand(0);
860 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
861 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
864 return EmitConstantValueOnly(ptrVal);
866 // Truncate/sext the offset to the pointer size.
867 if (TD->getPointerSizeInBits() != 64) {
868 int SExtAmount = 64-TD->getPointerSizeInBits();
869 Offset = (Offset << SExtAmount) >> SExtAmount;
874 EmitConstantValueOnly(ptrVal);
876 O << ") + " << Offset;
878 O << ") - " << -Offset;
881 case Instruction::BitCast:
882 return EmitConstantValueOnly(CE->getOperand(0));
884 case Instruction::IntToPtr: {
885 // Handle casts to pointers by changing them into casts to the appropriate
886 // integer type. This promotes constant folding and simplifies this code.
887 const TargetData *TD = TM.getTargetData();
888 Constant *Op = CE->getOperand(0);
889 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
891 return EmitConstantValueOnly(Op);
894 case Instruction::PtrToInt: {
895 // Support only foldable casts to/from pointers that can be eliminated by
896 // changing the pointer to the appropriately sized integer type.
897 Constant *Op = CE->getOperand(0);
898 const Type *Ty = CE->getType();
899 const TargetData *TD = TM.getTargetData();
901 // We can emit the pointer value into this slot if the slot is an
902 // integer slot greater or equal to the size of the pointer.
903 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
904 return EmitConstantValueOnly(Op);
907 EmitConstantValueOnly(Op);
909 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
912 ptrMask.toStringUnsigned(S);
913 O << ") & " << S.str() << ')';
917 case Instruction::Trunc:
918 // We emit the value and depend on the assembler to truncate the generated
919 // expression properly. This is important for differences between
920 // blockaddress labels. Since the two labels are in the same function, it
921 // is reasonable to treat their delta as a 32-bit value.
922 return EmitConstantValueOnly(CE->getOperand(0));
924 case Instruction::Add:
925 case Instruction::Sub:
926 case Instruction::And:
927 case Instruction::Or:
928 case Instruction::Xor:
930 EmitConstantValueOnly(CE->getOperand(0));
932 switch (CE->getOpcode()) {
933 case Instruction::Add:
936 case Instruction::Sub:
939 case Instruction::And:
942 case Instruction::Or:
945 case Instruction::Xor:
952 EmitConstantValueOnly(CE->getOperand(1));
958 /// printAsCString - Print the specified array as a C compatible string, only if
959 /// the predicate isString is true.
961 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
963 assert(CVA->isString() && "Array is not string compatible!");
966 for (unsigned i = 0; i != LastElt; ++i) {
968 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
969 printStringChar(O, C);
974 /// EmitString - Emit a zero-byte-terminated string constant.
976 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
977 unsigned NumElts = CVA->getNumOperands();
978 if (MAI->getAscizDirective() && NumElts &&
979 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
980 O << MAI->getAscizDirective();
981 printAsCString(O, CVA, NumElts-1);
983 O << MAI->getAsciiDirective();
984 printAsCString(O, CVA, NumElts);
989 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
990 unsigned AddrSpace) {
991 if (CVA->isString()) {
993 } else { // Not a string. Print the values in successive locations
994 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
995 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
999 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1000 const VectorType *PTy = CP->getType();
1002 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1003 EmitGlobalConstant(CP->getOperand(I));
1006 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1007 unsigned AddrSpace) {
1008 // Print the fields in successive locations. Pad to align if needed!
1009 const TargetData *TD = TM.getTargetData();
1010 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1011 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1012 uint64_t sizeSoFar = 0;
1013 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1014 const Constant* field = CVS->getOperand(i);
1016 // Check if padding is needed and insert one or more 0s.
1017 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1018 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1019 - cvsLayout->getElementOffset(i)) - fieldSize;
1020 sizeSoFar += fieldSize + padSize;
1022 // Now print the actual field value.
1023 EmitGlobalConstant(field, AddrSpace);
1025 // Insert padding - this may include padding to increase the size of the
1026 // current field up to the ABI size (if the struct is not packed) as well
1027 // as padding to ensure that the next field starts at the right offset.
1028 EmitZeros(padSize, AddrSpace);
1030 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1031 "Layout of constant struct may be incorrect!");
1034 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1035 unsigned AddrSpace) {
1036 // FP Constants are printed as integer constants to avoid losing
1038 LLVMContext &Context = CFP->getContext();
1039 const TargetData *TD = TM.getTargetData();
1040 if (CFP->getType()->isDoubleTy()) {
1041 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1042 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1043 if (MAI->getData64bitsDirective(AddrSpace)) {
1044 O << MAI->getData64bitsDirective(AddrSpace) << i;
1046 O.PadToColumn(MAI->getCommentColumn());
1047 O << MAI->getCommentString() << " double " << Val;
1050 } else if (TD->isBigEndian()) {
1051 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1053 O.PadToColumn(MAI->getCommentColumn());
1054 O << MAI->getCommentString()
1055 << " most significant word of double " << Val;
1058 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1060 O.PadToColumn(MAI->getCommentColumn());
1061 O << MAI->getCommentString()
1062 << " least significant word of double " << Val;
1066 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1068 O.PadToColumn(MAI->getCommentColumn());
1069 O << MAI->getCommentString()
1070 << " least significant word of double " << Val;
1073 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1075 O.PadToColumn(MAI->getCommentColumn());
1076 O << MAI->getCommentString()
1077 << " most significant word of double " << Val;
1084 if (CFP->getType()->isFloatTy()) {
1085 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1086 O << MAI->getData32bitsDirective(AddrSpace)
1087 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1089 O.PadToColumn(MAI->getCommentColumn());
1090 O << MAI->getCommentString() << " float " << Val;
1096 if (CFP->getType()->isX86_FP80Ty()) {
1097 // all long double variants are printed as hex
1098 // api needed to prevent premature destruction
1099 APInt api = CFP->getValueAPF().bitcastToAPInt();
1100 const uint64_t *p = api.getRawData();
1101 // Convert to double so we can print the approximate val as a comment.
1102 APFloat DoubleVal = CFP->getValueAPF();
1104 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1106 if (TD->isBigEndian()) {
1107 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1109 O.PadToColumn(MAI->getCommentColumn());
1110 O << MAI->getCommentString()
1111 << " most significant halfword of x86_fp80 ~"
1112 << DoubleVal.convertToDouble();
1115 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1117 O.PadToColumn(MAI->getCommentColumn());
1118 O << MAI->getCommentString() << " next halfword";
1121 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1123 O.PadToColumn(MAI->getCommentColumn());
1124 O << MAI->getCommentString() << " next halfword";
1127 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1129 O.PadToColumn(MAI->getCommentColumn());
1130 O << MAI->getCommentString() << " next halfword";
1133 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1135 O.PadToColumn(MAI->getCommentColumn());
1136 O << MAI->getCommentString()
1137 << " least significant halfword";
1141 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1143 O.PadToColumn(MAI->getCommentColumn());
1144 O << MAI->getCommentString()
1145 << " least significant halfword of x86_fp80 ~"
1146 << DoubleVal.convertToDouble();
1149 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1151 O.PadToColumn(MAI->getCommentColumn());
1152 O << MAI->getCommentString()
1153 << " next halfword";
1156 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1158 O.PadToColumn(MAI->getCommentColumn());
1159 O << MAI->getCommentString()
1160 << " next halfword";
1163 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1165 O.PadToColumn(MAI->getCommentColumn());
1166 O << MAI->getCommentString()
1167 << " next halfword";
1170 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1172 O.PadToColumn(MAI->getCommentColumn());
1173 O << MAI->getCommentString()
1174 << " most significant halfword";
1178 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1179 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1183 if (CFP->getType()->isPPC_FP128Ty()) {
1184 // all long double variants are printed as hex
1185 // api needed to prevent premature destruction
1186 APInt api = CFP->getValueAPF().bitcastToAPInt();
1187 const uint64_t *p = api.getRawData();
1188 if (TD->isBigEndian()) {
1189 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1191 O.PadToColumn(MAI->getCommentColumn());
1192 O << MAI->getCommentString()
1193 << " most significant word of ppc_fp128";
1196 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1198 O.PadToColumn(MAI->getCommentColumn());
1199 O << MAI->getCommentString()
1203 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1205 O.PadToColumn(MAI->getCommentColumn());
1206 O << MAI->getCommentString()
1210 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1212 O.PadToColumn(MAI->getCommentColumn());
1213 O << MAI->getCommentString()
1214 << " least significant word";
1218 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1220 O.PadToColumn(MAI->getCommentColumn());
1221 O << MAI->getCommentString()
1222 << " least significant word of ppc_fp128";
1225 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1227 O.PadToColumn(MAI->getCommentColumn());
1228 O << MAI->getCommentString()
1232 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1234 O.PadToColumn(MAI->getCommentColumn());
1235 O << MAI->getCommentString()
1239 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1241 O.PadToColumn(MAI->getCommentColumn());
1242 O << MAI->getCommentString()
1243 << " most significant word";
1248 } else llvm_unreachable("Floating point constant type not handled");
1251 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1252 unsigned AddrSpace) {
1253 const TargetData *TD = TM.getTargetData();
1254 unsigned BitWidth = CI->getBitWidth();
1255 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1257 // We don't expect assemblers to support integer data directives
1258 // for more than 64 bits, so we emit the data in at most 64-bit
1259 // quantities at a time.
1260 const uint64_t *RawData = CI->getValue().getRawData();
1261 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1263 if (TD->isBigEndian())
1264 Val = RawData[e - i - 1];
1268 if (MAI->getData64bitsDirective(AddrSpace)) {
1269 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1273 // Emit two 32-bit chunks, order depends on endianness.
1274 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1275 const char *FirstName = " least", *SecondName = " most";
1276 if (TD->isBigEndian()) {
1277 std::swap(FirstChunk, SecondChunk);
1278 std::swap(FirstName, SecondName);
1281 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1283 O.PadToColumn(MAI->getCommentColumn());
1284 O << MAI->getCommentString()
1285 << FirstName << " significant half of i64 " << Val;
1289 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1291 O.PadToColumn(MAI->getCommentColumn());
1292 O << MAI->getCommentString()
1293 << SecondName << " significant half of i64 " << Val;
1299 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1300 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1301 const TargetData *TD = TM.getTargetData();
1302 const Type *type = CV->getType();
1303 unsigned Size = TD->getTypeAllocSize(type);
1305 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1306 EmitZeros(Size, AddrSpace);
1310 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1311 EmitGlobalConstantArray(CVA , AddrSpace);
1315 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1316 EmitGlobalConstantStruct(CVS, AddrSpace);
1320 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1321 EmitGlobalConstantFP(CFP, AddrSpace);
1325 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1326 // If we can directly emit an 8-byte constant, do it.
1328 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1329 O << Data64Dir << CI->getZExtValue() << '\n';
1333 // Small integers are handled below; large integers are handled here.
1335 EmitGlobalConstantLargeInt(CI, AddrSpace);
1340 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1341 EmitGlobalConstantVector(CP);
1345 printDataDirective(type, AddrSpace);
1346 EmitConstantValueOnly(CV);
1348 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1350 CI->getValue().toStringUnsigned(S, 16);
1351 O.PadToColumn(MAI->getCommentColumn());
1352 O << MAI->getCommentString() << " 0x" << S.str();
1358 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1359 // Target doesn't support this yet!
1360 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1363 /// PrintSpecial - Print information related to the specified machine instr
1364 /// that is independent of the operand, and may be independent of the instr
1365 /// itself. This can be useful for portably encoding the comment character
1366 /// or other bits of target-specific knowledge into the asmstrings. The
1367 /// syntax used is ${:comment}. Targets can override this to add support
1368 /// for their own strange codes.
1369 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1370 if (!strcmp(Code, "private")) {
1371 O << MAI->getPrivateGlobalPrefix();
1372 } else if (!strcmp(Code, "comment")) {
1374 O << MAI->getCommentString();
1375 } else if (!strcmp(Code, "uid")) {
1376 // Comparing the address of MI isn't sufficient, because machineinstrs may
1377 // be allocated to the same address across functions.
1378 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1380 // If this is a new LastFn instruction, bump the counter.
1381 if (LastMI != MI || LastFn != ThisF) {
1389 raw_string_ostream Msg(msg);
1390 Msg << "Unknown special formatter '" << Code
1391 << "' for machine instr: " << *MI;
1392 llvm_report_error(Msg.str());
1396 /// processDebugLoc - Processes the debug information of each machine
1397 /// instruction's DebugLoc.
1398 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1399 bool BeforePrintingInsn) {
1400 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1401 || !DW->ShouldEmitDwarfDebug())
1403 DebugLoc DL = MI->getDebugLoc();
1406 DILocation CurDLT = MF->getDILocation(DL);
1407 if (CurDLT.getScope().isNull())
1410 if (BeforePrintingInsn) {
1411 if (CurDLT.getNode() != PrevDLT.getNode()) {
1412 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1413 CurDLT.getColumnNumber(),
1414 CurDLT.getScope().getNode());
1417 DW->BeginScope(MI, L);
1421 // After printing instruction
1427 /// printInlineAsm - This method formats and prints the specified machine
1428 /// instruction that is an inline asm.
1429 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1430 unsigned NumOperands = MI->getNumOperands();
1432 // Count the number of register definitions.
1433 unsigned NumDefs = 0;
1434 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1436 assert(NumDefs != NumOperands-1 && "No asm string?");
1438 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1440 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1441 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1445 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1446 // These are useful to see where empty asm's wound up.
1447 if (AsmStr[0] == 0) {
1448 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1449 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1453 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1455 // The variant of the current asmprinter.
1456 int AsmPrinterVariant = MAI->getAssemblerDialect();
1458 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1459 const char *LastEmitted = AsmStr; // One past the last character emitted.
1461 while (*LastEmitted) {
1462 switch (*LastEmitted) {
1464 // Not a special case, emit the string section literally.
1465 const char *LiteralEnd = LastEmitted+1;
1466 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1467 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1469 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1470 O.write(LastEmitted, LiteralEnd-LastEmitted);
1471 LastEmitted = LiteralEnd;
1475 ++LastEmitted; // Consume newline character.
1476 O << '\n'; // Indent code with newline.
1479 ++LastEmitted; // Consume '$' character.
1483 switch (*LastEmitted) {
1484 default: Done = false; break;
1485 case '$': // $$ -> $
1486 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1488 ++LastEmitted; // Consume second '$' character.
1490 case '(': // $( -> same as GCC's { character.
1491 ++LastEmitted; // Consume '(' character.
1492 if (CurVariant != -1) {
1493 llvm_report_error("Nested variants found in inline asm string: '"
1494 + std::string(AsmStr) + "'");
1496 CurVariant = 0; // We're in the first variant now.
1499 ++LastEmitted; // consume '|' character.
1500 if (CurVariant == -1)
1501 O << '|'; // this is gcc's behavior for | outside a variant
1503 ++CurVariant; // We're in the next variant.
1505 case ')': // $) -> same as GCC's } char.
1506 ++LastEmitted; // consume ')' character.
1507 if (CurVariant == -1)
1508 O << '}'; // this is gcc's behavior for } outside a variant
1515 bool HasCurlyBraces = false;
1516 if (*LastEmitted == '{') { // ${variable}
1517 ++LastEmitted; // Consume '{' character.
1518 HasCurlyBraces = true;
1521 // If we have ${:foo}, then this is not a real operand reference, it is a
1522 // "magic" string reference, just like in .td files. Arrange to call
1524 if (HasCurlyBraces && *LastEmitted == ':') {
1526 const char *StrStart = LastEmitted;
1527 const char *StrEnd = strchr(StrStart, '}');
1529 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1530 + std::string(AsmStr) + "'");
1533 std::string Val(StrStart, StrEnd);
1534 PrintSpecial(MI, Val.c_str());
1535 LastEmitted = StrEnd+1;
1539 const char *IDStart = LastEmitted;
1542 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1543 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1544 llvm_report_error("Bad $ operand number in inline asm string: '"
1545 + std::string(AsmStr) + "'");
1547 LastEmitted = IDEnd;
1549 char Modifier[2] = { 0, 0 };
1551 if (HasCurlyBraces) {
1552 // If we have curly braces, check for a modifier character. This
1553 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1554 if (*LastEmitted == ':') {
1555 ++LastEmitted; // Consume ':' character.
1556 if (*LastEmitted == 0) {
1557 llvm_report_error("Bad ${:} expression in inline asm string: '"
1558 + std::string(AsmStr) + "'");
1561 Modifier[0] = *LastEmitted;
1562 ++LastEmitted; // Consume modifier character.
1565 if (*LastEmitted != '}') {
1566 llvm_report_error("Bad ${} expression in inline asm string: '"
1567 + std::string(AsmStr) + "'");
1569 ++LastEmitted; // Consume '}' character.
1572 if ((unsigned)Val >= NumOperands-1) {
1573 llvm_report_error("Invalid $ operand number in inline asm string: '"
1574 + std::string(AsmStr) + "'");
1577 // Okay, we finally have a value number. Ask the target to print this
1579 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1584 // Scan to find the machine operand number for the operand.
1585 for (; Val; --Val) {
1586 if (OpNo >= MI->getNumOperands()) break;
1587 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1588 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1591 if (OpNo >= MI->getNumOperands()) {
1594 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1595 ++OpNo; // Skip over the ID number.
1597 if (Modifier[0]=='l') // labels are target independent
1598 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1599 ->getNumber())->print(O, MAI);
1601 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1602 if ((OpFlags & 7) == 4) {
1603 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1604 Modifier[0] ? Modifier : 0);
1606 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1607 Modifier[0] ? Modifier : 0);
1613 raw_string_ostream Msg(msg);
1614 Msg << "Invalid operand found in inline asm: '"
1617 llvm_report_error(Msg.str());
1624 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1627 /// printImplicitDef - This method prints the specified machine instruction
1628 /// that is an implicit def.
1629 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1630 if (!VerboseAsm) return;
1631 O.PadToColumn(MAI->getCommentColumn());
1632 O << MAI->getCommentString() << " implicit-def: "
1633 << TRI->getName(MI->getOperand(0).getReg());
1636 void AsmPrinter::printKill(const MachineInstr *MI) const {
1637 if (!VerboseAsm) return;
1638 O.PadToColumn(MAI->getCommentColumn());
1639 O << MAI->getCommentString() << " kill:";
1640 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1641 const MachineOperand &op = MI->getOperand(n);
1642 assert(op.isReg() && "KILL instruction must have only register operands");
1643 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1647 /// printLabel - This method prints a local label used by debug and
1648 /// exception handling tables.
1649 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1650 printLabel(MI->getOperand(0).getImm());
1653 void AsmPrinter::printLabel(unsigned Id) const {
1654 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1657 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1658 /// instruction, using the specified assembler variant. Targets should
1659 /// override this to format as appropriate.
1660 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1661 unsigned AsmVariant, const char *ExtraCode) {
1662 // Target doesn't support this yet!
1666 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1667 unsigned AsmVariant,
1668 const char *ExtraCode) {
1669 // Target doesn't support this yet!
1673 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1674 const char *Suffix) const {
1675 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1678 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1679 const BasicBlock *BB,
1680 const char *Suffix) const {
1681 assert(BB->hasName() &&
1682 "Address of anonymous basic block not supported yet!");
1684 // This code must use the function name itself, and not the function number,
1685 // since it must be possible to generate the label name from within other
1687 SmallString<60> FnName;
1688 Mang->getNameWithPrefix(FnName, F, false);
1690 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1691 SmallString<60> NameResult;
1692 Mang->getNameWithPrefix(NameResult,
1693 StringRef("BA") + Twine((unsigned)FnName.size()) +
1694 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1697 return OutContext.GetOrCreateSymbol(NameResult.str());
1700 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1701 SmallString<60> Name;
1702 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1703 << getFunctionNumber() << '_' << MBBID;
1705 return OutContext.GetOrCreateSymbol(Name.str());
1708 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1710 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1711 SmallString<60> NameStr;
1712 Mang->getNameWithPrefix(NameStr, GV, false);
1713 return OutContext.GetOrCreateSymbol(NameStr.str());
1716 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1717 /// global value name as its base, with the specified suffix, and where the
1718 /// symbol is forced to have private linkage if ForcePrivate is true.
1719 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1721 bool ForcePrivate) const {
1722 SmallString<60> NameStr;
1723 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1724 NameStr.append(Suffix.begin(), Suffix.end());
1725 return OutContext.GetOrCreateSymbol(NameStr.str());
1728 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1730 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1731 SmallString<60> NameStr;
1732 Mang->getNameWithPrefix(NameStr, Sym);
1733 return OutContext.GetOrCreateSymbol(NameStr.str());
1737 /// EmitBasicBlockStart - This method prints the label for the specified
1738 /// MachineBasicBlock, an alignment (if present) and a comment describing
1739 /// it if appropriate.
1740 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1741 // Emit an alignment directive for this block, if needed.
1742 if (unsigned Align = MBB->getAlignment())
1743 EmitAlignment(Log2_32(Align));
1745 // If the block has its address taken, emit a special label to satisfy
1746 // references to the block. This is done so that we don't need to
1747 // remember the number of this label, and so that we can make
1748 // forward references to labels without knowing what their numbers
1750 if (MBB->hasAddressTaken()) {
1751 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1752 MBB->getBasicBlock())->print(O, MAI);
1755 O.PadToColumn(MAI->getCommentColumn());
1756 O << MAI->getCommentString() << " Address Taken";
1761 // Print the main label for the block.
1762 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1764 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1766 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1772 // Print some comments to accompany the label.
1774 if (const BasicBlock *BB = MBB->getBasicBlock())
1775 if (BB->hasName()) {
1776 O.PadToColumn(MAI->getCommentColumn());
1777 O << MAI->getCommentString() << ' ';
1778 WriteAsOperand(O, BB, /*PrintType=*/false);
1786 /// printPICJumpTableSetLabel - This method prints a set label for the
1787 /// specified MachineBasicBlock for a jumptable entry.
1788 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1789 const MachineBasicBlock *MBB) const {
1790 if (!MAI->getSetDirective())
1793 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1794 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1795 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1796 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1797 << '_' << uid << '\n';
1800 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1801 const MachineBasicBlock *MBB) const {
1802 if (!MAI->getSetDirective())
1805 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1806 << getFunctionNumber() << '_' << uid << '_' << uid2
1807 << "_set_" << MBB->getNumber() << ',';
1808 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1809 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1810 << '_' << uid << '_' << uid2 << '\n';
1813 /// printDataDirective - This method prints the asm directive for the
1815 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1816 const TargetData *TD = TM.getTargetData();
1817 switch (type->getTypeID()) {
1818 case Type::FloatTyID: case Type::DoubleTyID:
1819 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1820 assert(0 && "Should have already output floating point constant.");
1822 assert(0 && "Can't handle printing this type of thing");
1823 case Type::IntegerTyID: {
1824 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1826 O << MAI->getData8bitsDirective(AddrSpace);
1827 else if (BitWidth <= 16)
1828 O << MAI->getData16bitsDirective(AddrSpace);
1829 else if (BitWidth <= 32)
1830 O << MAI->getData32bitsDirective(AddrSpace);
1831 else if (BitWidth <= 64) {
1832 assert(MAI->getData64bitsDirective(AddrSpace) &&
1833 "Target cannot handle 64-bit constant exprs!");
1834 O << MAI->getData64bitsDirective(AddrSpace);
1836 llvm_unreachable("Target cannot handle given data directive width!");
1840 case Type::PointerTyID:
1841 if (TD->getPointerSize() == 8) {
1842 assert(MAI->getData64bitsDirective(AddrSpace) &&
1843 "Target cannot handle 64-bit pointer exprs!");
1844 O << MAI->getData64bitsDirective(AddrSpace);
1845 } else if (TD->getPointerSize() == 2) {
1846 O << MAI->getData16bitsDirective(AddrSpace);
1847 } else if (TD->getPointerSize() == 1) {
1848 O << MAI->getData8bitsDirective(AddrSpace);
1850 O << MAI->getData32bitsDirective(AddrSpace);
1856 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1857 unsigned Visibility) const {
1858 if (Visibility == GlobalValue::HiddenVisibility) {
1859 if (const char *Directive = MAI->getHiddenDirective()) {
1864 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1865 if (const char *Directive = MAI->getProtectedDirective()) {
1873 void AsmPrinter::printOffset(int64_t Offset) const {
1876 else if (Offset < 0)
1880 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1881 if (!S->usesMetadata())
1884 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1885 if (GCPI != GCMetadataPrinters.end())
1886 return GCPI->second;
1888 const char *Name = S->getName().c_str();
1890 for (GCMetadataPrinterRegistry::iterator
1891 I = GCMetadataPrinterRegistry::begin(),
1892 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1893 if (strcmp(Name, I->getName()) == 0) {
1894 GCMetadataPrinter *GMP = I->instantiate();
1896 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1900 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1901 llvm_unreachable(0);
1904 /// EmitComments - Pretty-print comments for instructions
1905 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1909 bool Newline = false;
1911 if (!MI.getDebugLoc().isUnknown()) {
1912 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1914 // Print source line info.
1915 O.PadToColumn(MAI->getCommentColumn());
1916 O << MAI->getCommentString() << ' ';
1917 DIScope Scope = DLT.getScope();
1918 // Omit the directory, because it's likely to be long and uninteresting.
1919 if (!Scope.isNull())
1920 O << Scope.getFilename();
1923 O << ':' << DLT.getLineNumber();
1924 if (DLT.getColumnNumber() != 0)
1925 O << ':' << DLT.getColumnNumber();
1929 // Check for spills and reloads
1932 const MachineFrameInfo *FrameInfo =
1933 MI.getParent()->getParent()->getFrameInfo();
1935 // We assume a single instruction only has a spill or reload, not
1937 const MachineMemOperand *MMO;
1938 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1939 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1940 MMO = *MI.memoperands_begin();
1941 if (Newline) O << '\n';
1942 O.PadToColumn(MAI->getCommentColumn());
1943 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1947 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1948 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1949 if (Newline) O << '\n';
1950 O.PadToColumn(MAI->getCommentColumn());
1951 O << MAI->getCommentString() << ' '
1952 << MMO->getSize() << "-byte Folded Reload";
1956 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1957 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1958 MMO = *MI.memoperands_begin();
1959 if (Newline) O << '\n';
1960 O.PadToColumn(MAI->getCommentColumn());
1961 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1965 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1966 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1967 if (Newline) O << '\n';
1968 O.PadToColumn(MAI->getCommentColumn());
1969 O << MAI->getCommentString() << ' '
1970 << MMO->getSize() << "-byte Folded Spill";
1975 // Check for spill-induced copies
1976 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1977 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1978 SrcSubIdx, DstSubIdx)) {
1979 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1980 if (Newline) O << '\n';
1981 O.PadToColumn(MAI->getCommentColumn());
1982 O << MAI->getCommentString() << " Reload Reuse";
1987 /// PrintChildLoopComment - Print comments about child loops within
1988 /// the loop for this basic block, with nesting.
1990 static void PrintChildLoopComment(formatted_raw_ostream &O,
1991 const MachineLoop *loop,
1992 const MCAsmInfo *MAI,
1993 int FunctionNumber) {
1994 // Add child loop information
1995 for(MachineLoop::iterator cl = loop->begin(),
1996 clend = loop->end();
1999 MachineBasicBlock *Header = (*cl)->getHeader();
2000 assert(Header && "No header for loop");
2003 O.PadToColumn(MAI->getCommentColumn());
2005 O << MAI->getCommentString();
2006 O.indent(((*cl)->getLoopDepth()-1)*2)
2007 << " Child Loop BB" << FunctionNumber << "_"
2008 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2010 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2014 /// EmitComments - Pretty-print comments for basic blocks
2015 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2017 // Add loop depth information
2018 const MachineLoop *loop = LI->getLoopFor(&MBB);
2021 // Print a newline after bb# annotation.
2023 O.PadToColumn(MAI->getCommentColumn());
2024 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2027 O.PadToColumn(MAI->getCommentColumn());
2029 MachineBasicBlock *Header = loop->getHeader();
2030 assert(Header && "No header for loop");
2032 if (Header == &MBB) {
2033 O << MAI->getCommentString() << " Loop Header";
2034 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2037 O << MAI->getCommentString() << " Loop Header is BB"
2038 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2041 if (loop->empty()) {
2043 O.PadToColumn(MAI->getCommentColumn());
2044 O << MAI->getCommentString() << " Inner Loop";
2047 // Add parent loop information
2048 for (const MachineLoop *CurLoop = loop->getParentLoop();
2050 CurLoop = CurLoop->getParentLoop()) {
2051 MachineBasicBlock *Header = CurLoop->getHeader();
2052 assert(Header && "No header for loop");
2055 O.PadToColumn(MAI->getCommentColumn());
2056 O << MAI->getCommentString();
2057 O.indent((CurLoop->getLoopDepth()-1)*2)
2058 << " Inside Loop BB" << getFunctionNumber() << "_"
2059 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();