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 if (MAI->doesAllowNameToStartWithDigit())
111 Mang->setSymbolsCanStartWithDigit(true);
113 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
114 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
116 if (MAI->hasSingleParameterDotFile()) {
117 /* Very minimal debug info. It is ignored if we emit actual
118 debug info. If we don't, this at helps the user find where
119 a function came from. */
120 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
123 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
124 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
125 MP->beginAssembly(O, *this, *MAI);
127 if (!M.getModuleInlineAsm().empty())
128 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
129 << M.getModuleInlineAsm()
130 << '\n' << MAI->getCommentString()
131 << " End of file scope inline assembly\n";
133 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
135 MMI->AnalyzeModule(M);
136 DW = getAnalysisIfAvailable<DwarfWriter>();
138 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';
209 // Allow the target to emit any magic that it wants at the end of the file,
210 // after everything else has gone out.
213 delete Mang; Mang = 0;
216 OutStreamer.Finish();
220 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
221 // What's my mangled name?
222 CurrentFnName = Mang->getMangledName(MF.getFunction());
223 IncrementFunctionNumber();
226 LI = &getAnalysis<MachineLoopInfo>();
230 // SectionCPs - Keep track the alignment, constpool entries per Section.
234 SmallVector<unsigned, 4> CPEs;
235 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
239 /// EmitConstantPool - Print to the current output stream assembly
240 /// representations of the constants in the constant pool MCP. This is
241 /// used to print out constants which have been "spilled to memory" by
242 /// the code generator.
244 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
245 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
246 if (CP.empty()) return;
248 // Calculate sections for constant pool entries. We collect entries to go into
249 // the same section together to reduce amount of section switch statements.
250 SmallVector<SectionCPs, 4> CPSections;
251 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
252 const MachineConstantPoolEntry &CPE = CP[i];
253 unsigned Align = CPE.getAlignment();
256 switch (CPE.getRelocationInfo()) {
257 default: llvm_unreachable("Unknown section kind");
258 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
260 Kind = SectionKind::getReadOnlyWithRelLocal();
263 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
264 case 4: Kind = SectionKind::getMergeableConst4(); break;
265 case 8: Kind = SectionKind::getMergeableConst8(); break;
266 case 16: Kind = SectionKind::getMergeableConst16();break;
267 default: Kind = SectionKind::getMergeableConst(); break;
271 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
273 // The number of sections are small, just do a linear search from the
274 // last section to the first.
276 unsigned SecIdx = CPSections.size();
277 while (SecIdx != 0) {
278 if (CPSections[--SecIdx].S == S) {
284 SecIdx = CPSections.size();
285 CPSections.push_back(SectionCPs(S, Align));
288 if (Align > CPSections[SecIdx].Alignment)
289 CPSections[SecIdx].Alignment = Align;
290 CPSections[SecIdx].CPEs.push_back(i);
293 // Now print stuff into the calculated sections.
294 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
295 OutStreamer.SwitchSection(CPSections[i].S);
296 EmitAlignment(Log2_32(CPSections[i].Alignment));
299 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
300 unsigned CPI = CPSections[i].CPEs[j];
301 MachineConstantPoolEntry CPE = CP[CPI];
303 // Emit inter-object padding for alignment.
304 unsigned AlignMask = CPE.getAlignment() - 1;
305 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
306 EmitZeros(NewOffset - Offset);
308 const Type *Ty = CPE.getType();
309 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
311 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
314 O.PadToColumn(MAI->getCommentColumn());
315 O << MAI->getCommentString() << " constant ";
316 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
319 if (CPE.isMachineConstantPoolEntry())
320 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
322 EmitGlobalConstant(CPE.Val.ConstVal);
327 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
328 /// by the current function to the current output stream.
330 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
331 MachineFunction &MF) {
332 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
333 if (JT.empty()) return;
335 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
337 // Pick the directive to use to print the jump table entries, and switch to
338 // the appropriate section.
339 TargetLowering *LoweringInfo = TM.getTargetLowering();
341 const Function *F = MF.getFunction();
342 bool JTInDiffSection = false;
343 if (F->isWeakForLinker() ||
344 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
345 // In PIC mode, we need to emit the jump table to the same section as the
346 // function body itself, otherwise the label differences won't make sense.
347 // We should also do if the section name is NULL or function is declared in
348 // discardable section.
349 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
352 // Otherwise, drop it in the readonly section.
353 const MCSection *ReadOnlySection =
354 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
355 OutStreamer.SwitchSection(ReadOnlySection);
356 JTInDiffSection = true;
359 EmitAlignment(Log2_32(MJTI->getAlignment()));
361 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
362 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
364 // If this jump table was deleted, ignore it.
365 if (JTBBs.empty()) continue;
367 // For PIC codegen, if possible we want to use the SetDirective to reduce
368 // the number of relocations the assembler will generate for the jump table.
369 // Set directives are all printed before the jump table itself.
370 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
371 if (MAI->getSetDirective() && IsPic)
372 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
373 if (EmittedSets.insert(JTBBs[ii]))
374 printPICJumpTableSetLabel(i, JTBBs[ii]);
376 // On some targets (e.g. Darwin) we want to emit two consequtive labels
377 // before each jump table. The first label is never referenced, but tells
378 // the assembler and linker the extents of the jump table object. The
379 // second label is actually referenced by the code.
380 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
381 O << MAI->getLinkerPrivateGlobalPrefix()
382 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
385 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
386 << '_' << i << ":\n";
388 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
389 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
395 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
396 const MachineBasicBlock *MBB,
397 unsigned uid) const {
398 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
400 // Use JumpTableDirective otherwise honor the entry size from the jump table
402 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
403 bool HadJTEntryDirective = JTEntryDirective != NULL;
404 if (!HadJTEntryDirective) {
405 JTEntryDirective = MJTI->getEntrySize() == 4 ?
406 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
409 O << JTEntryDirective << ' ';
411 // If we have emitted set directives for the jump table entries, print
412 // them rather than the entries themselves. If we're emitting PIC, then
413 // emit the table entries as differences between two text section labels.
414 // If we're emitting non-PIC code, then emit the entries as direct
415 // references to the target basic blocks.
417 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
418 } else if (MAI->getSetDirective()) {
419 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
420 << '_' << uid << "_set_" << MBB->getNumber();
422 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
423 // If the arch uses custom Jump Table directives, don't calc relative to
425 if (!HadJTEntryDirective)
426 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
427 << getFunctionNumber() << '_' << uid;
432 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
433 /// special global used by LLVM. If so, emit it and return true, otherwise
434 /// do nothing and return false.
435 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
436 if (GV->getName() == "llvm.used") {
437 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
438 EmitLLVMUsedList(GV->getInitializer());
442 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
443 if (GV->getSection() == "llvm.metadata" ||
444 GV->hasAvailableExternallyLinkage())
447 if (!GV->hasAppendingLinkage()) return false;
449 assert(GV->hasInitializer() && "Not a special LLVM global!");
451 const TargetData *TD = TM.getTargetData();
452 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
453 if (GV->getName() == "llvm.global_ctors") {
454 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
455 EmitAlignment(Align, 0);
456 EmitXXStructorList(GV->getInitializer());
460 if (GV->getName() == "llvm.global_dtors") {
461 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
462 EmitAlignment(Align, 0);
463 EmitXXStructorList(GV->getInitializer());
470 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
471 /// global in the specified llvm.used list for which emitUsedDirectiveFor
472 /// is true, as being used with this directive.
473 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
474 const char *Directive = MAI->getUsedDirective();
476 // Should be an array of 'i8*'.
477 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
478 if (InitList == 0) return;
480 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
481 const GlobalValue *GV =
482 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
483 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
485 EmitConstantValueOnly(InitList->getOperand(i));
491 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
492 /// function pointers, ignoring the init priority.
493 void AsmPrinter::EmitXXStructorList(Constant *List) {
494 // Should be an array of '{ int, void ()* }' structs. The first value is the
495 // init priority, which we ignore.
496 if (!isa<ConstantArray>(List)) return;
497 ConstantArray *InitList = cast<ConstantArray>(List);
498 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
499 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
500 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
502 if (CS->getOperand(1)->isNullValue())
503 return; // Found a null terminator, exit printing.
504 // Emit the function pointer.
505 EmitGlobalConstant(CS->getOperand(1));
510 //===----------------------------------------------------------------------===//
511 /// LEB 128 number encoding.
513 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
514 /// representing an unsigned leb128 value.
515 void AsmPrinter::PrintULEB128(unsigned Value) const {
518 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
520 if (Value) Byte |= 0x80;
521 O << "0x" << utohex_buffer(Byte, Buffer+20);
522 if (Value) O << ", ";
526 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
527 /// representing a signed leb128 value.
528 void AsmPrinter::PrintSLEB128(int Value) const {
529 int Sign = Value >> (8 * sizeof(Value) - 1);
534 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
536 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
537 if (IsMore) Byte |= 0x80;
538 O << "0x" << utohex_buffer(Byte, Buffer+20);
539 if (IsMore) O << ", ";
543 //===--------------------------------------------------------------------===//
544 // Emission and print routines
547 /// PrintHex - Print a value as a hexidecimal value.
549 void AsmPrinter::PrintHex(int Value) const {
551 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
554 /// EOL - Print a newline character to asm stream. If a comment is present
555 /// then it will be printed first. Comments should not contain '\n'.
556 void AsmPrinter::EOL() const {
560 void AsmPrinter::EOL(const std::string &Comment) const {
561 if (VerboseAsm && !Comment.empty()) {
562 O.PadToColumn(MAI->getCommentColumn());
563 O << MAI->getCommentString()
570 void AsmPrinter::EOL(const char* Comment) const {
571 if (VerboseAsm && *Comment) {
572 O.PadToColumn(MAI->getCommentColumn());
573 O << MAI->getCommentString()
580 static const char *DecodeDWARFEncoding(unsigned Encoding) {
582 case dwarf::DW_EH_PE_absptr:
584 case dwarf::DW_EH_PE_omit:
586 case dwarf::DW_EH_PE_pcrel:
588 case dwarf::DW_EH_PE_udata4:
590 case dwarf::DW_EH_PE_udata8:
592 case dwarf::DW_EH_PE_sdata4:
594 case dwarf::DW_EH_PE_sdata8:
596 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
597 return "pcrel udata4";
598 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
599 return "pcrel sdata4";
600 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
601 return "pcrel udata8";
602 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
603 return "pcrel sdata8";
604 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
605 return "indirect pcrel udata4";
606 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
607 return "indirect pcrel sdata4";
608 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
609 return "indirect pcrel udata8";
610 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
611 return "indirect pcrel sdata8";
617 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
618 if (VerboseAsm && *Comment) {
619 O.PadToColumn(MAI->getCommentColumn());
620 O << MAI->getCommentString()
624 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
625 O << " (" << EncStr << ')';
630 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
631 /// unsigned leb128 value.
632 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
633 if (MAI->hasLEB128()) {
637 O << MAI->getData8bitsDirective();
642 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
643 /// signed leb128 value.
644 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
645 if (MAI->hasLEB128()) {
649 O << MAI->getData8bitsDirective();
654 /// EmitInt8 - Emit a byte directive and value.
656 void AsmPrinter::EmitInt8(int Value) const {
657 O << MAI->getData8bitsDirective();
658 PrintHex(Value & 0xFF);
661 /// EmitInt16 - Emit a short directive and value.
663 void AsmPrinter::EmitInt16(int Value) const {
664 O << MAI->getData16bitsDirective();
665 PrintHex(Value & 0xFFFF);
668 /// EmitInt32 - Emit a long directive and value.
670 void AsmPrinter::EmitInt32(int Value) const {
671 O << MAI->getData32bitsDirective();
675 /// EmitInt64 - Emit a long long directive and value.
677 void AsmPrinter::EmitInt64(uint64_t Value) const {
678 if (MAI->getData64bitsDirective()) {
679 O << MAI->getData64bitsDirective();
682 if (TM.getTargetData()->isBigEndian()) {
683 EmitInt32(unsigned(Value >> 32)); O << '\n';
684 EmitInt32(unsigned(Value));
686 EmitInt32(unsigned(Value)); O << '\n';
687 EmitInt32(unsigned(Value >> 32));
692 /// toOctal - Convert the low order bits of X into an octal digit.
694 static inline char toOctal(int X) {
698 /// printStringChar - Print a char, escaped if necessary.
700 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
703 } else if (C == '\\') {
705 } else if (isprint((unsigned char)C)) {
709 case '\b': O << "\\b"; break;
710 case '\f': O << "\\f"; break;
711 case '\n': O << "\\n"; break;
712 case '\r': O << "\\r"; break;
713 case '\t': O << "\\t"; break;
716 O << toOctal(C >> 6);
717 O << toOctal(C >> 3);
718 O << toOctal(C >> 0);
724 /// EmitString - Emit a string with quotes and a null terminator.
725 /// Special characters are emitted properly.
726 /// \literal (Eg. '\t') \endliteral
727 void AsmPrinter::EmitString(const std::string &String) const {
728 EmitString(String.c_str(), String.size());
731 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
732 const char* AscizDirective = MAI->getAscizDirective();
736 O << MAI->getAsciiDirective();
738 for (unsigned i = 0; i < Size; ++i)
739 printStringChar(O, String[i]);
747 /// EmitFile - Emit a .file directive.
748 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
749 O << "\t.file\t" << Number << " \"";
750 for (unsigned i = 0, N = Name.size(); i < N; ++i)
751 printStringChar(O, Name[i]);
756 //===----------------------------------------------------------------------===//
758 // EmitAlignment - Emit an alignment directive to the specified power of
759 // two boundary. For example, if you pass in 3 here, you will get an 8
760 // byte alignment. If a global value is specified, and if that global has
761 // an explicit alignment requested, it will unconditionally override the
762 // alignment request. However, if ForcedAlignBits is specified, this value
763 // has final say: the ultimate alignment will be the max of ForcedAlignBits
764 // and the alignment computed with NumBits and the global.
768 // if (GV && GV->hasalignment) Align = GV->getalignment();
769 // Align = std::max(Align, ForcedAlignBits);
771 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
772 unsigned ForcedAlignBits,
773 bool UseFillExpr) const {
774 if (GV && GV->getAlignment())
775 NumBits = Log2_32(GV->getAlignment());
776 NumBits = std::max(NumBits, ForcedAlignBits);
778 if (NumBits == 0) return; // No need to emit alignment.
780 unsigned FillValue = 0;
781 if (getCurrentSection()->getKind().isText())
782 FillValue = MAI->getTextAlignFillValue();
784 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
787 /// EmitZeros - Emit a block of zeros.
789 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
791 if (MAI->getZeroDirective()) {
792 O << MAI->getZeroDirective() << NumZeros;
793 if (MAI->getZeroDirectiveSuffix())
794 O << MAI->getZeroDirectiveSuffix();
797 for (; NumZeros; --NumZeros)
798 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
803 // Print out the specified constant, without a storage class. Only the
804 // constants valid in constant expressions can occur here.
805 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
806 if (CV->isNullValue() || isa<UndefValue>(CV))
808 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
809 O << CI->getZExtValue();
810 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
811 // This is a constant address for a global variable or function. Use the
812 // name of the variable or function as the address value.
813 O << Mang->getMangledName(GV);
814 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
815 const TargetData *TD = TM.getTargetData();
816 unsigned Opcode = CE->getOpcode();
818 case Instruction::Trunc:
819 case Instruction::ZExt:
820 case Instruction::SExt:
821 case Instruction::FPTrunc:
822 case Instruction::FPExt:
823 case Instruction::UIToFP:
824 case Instruction::SIToFP:
825 case Instruction::FPToUI:
826 case Instruction::FPToSI:
827 llvm_unreachable("FIXME: Don't support this constant cast expr");
828 case Instruction::GetElementPtr: {
829 // generate a symbolic expression for the byte address
830 const Constant *ptrVal = CE->getOperand(0);
831 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
832 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
834 // Truncate/sext the offset to the pointer size.
835 if (TD->getPointerSizeInBits() != 64) {
836 int SExtAmount = 64-TD->getPointerSizeInBits();
837 Offset = (Offset << SExtAmount) >> SExtAmount;
842 EmitConstantValueOnly(ptrVal);
844 O << ") + " << Offset;
846 O << ") - " << -Offset;
848 EmitConstantValueOnly(ptrVal);
852 case Instruction::BitCast:
853 return EmitConstantValueOnly(CE->getOperand(0));
855 case Instruction::IntToPtr: {
856 // Handle casts to pointers by changing them into casts to the appropriate
857 // integer type. This promotes constant folding and simplifies this code.
858 Constant *Op = CE->getOperand(0);
859 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
861 return EmitConstantValueOnly(Op);
865 case Instruction::PtrToInt: {
866 // Support only foldable casts to/from pointers that can be eliminated by
867 // changing the pointer to the appropriately sized integer type.
868 Constant *Op = CE->getOperand(0);
869 const Type *Ty = CE->getType();
871 // We can emit the pointer value into this slot if the slot is an
872 // integer slot greater or equal to the size of the pointer.
873 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
874 return EmitConstantValueOnly(Op);
877 EmitConstantValueOnly(Op);
879 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
882 ptrMask.toStringUnsigned(S);
883 O << ") & " << S.str() << ')';
886 case Instruction::Add:
887 case Instruction::Sub:
888 case Instruction::And:
889 case Instruction::Or:
890 case Instruction::Xor:
892 EmitConstantValueOnly(CE->getOperand(0));
895 case Instruction::Add:
898 case Instruction::Sub:
901 case Instruction::And:
904 case Instruction::Or:
907 case Instruction::Xor:
914 EmitConstantValueOnly(CE->getOperand(1));
918 llvm_unreachable("Unsupported operator!");
921 llvm_unreachable("Unknown constant value!");
925 /// printAsCString - Print the specified array as a C compatible string, only if
926 /// the predicate isString is true.
928 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
930 assert(CVA->isString() && "Array is not string compatible!");
933 for (unsigned i = 0; i != LastElt; ++i) {
935 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
936 printStringChar(O, C);
941 /// EmitString - Emit a zero-byte-terminated string constant.
943 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
944 unsigned NumElts = CVA->getNumOperands();
945 if (MAI->getAscizDirective() && NumElts &&
946 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
947 O << MAI->getAscizDirective();
948 printAsCString(O, CVA, NumElts-1);
950 O << MAI->getAsciiDirective();
951 printAsCString(O, CVA, NumElts);
956 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
957 unsigned AddrSpace) {
958 if (CVA->isString()) {
960 } else { // Not a string. Print the values in successive locations
961 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
962 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
966 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
967 const VectorType *PTy = CP->getType();
969 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
970 EmitGlobalConstant(CP->getOperand(I));
973 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
974 unsigned AddrSpace) {
975 // Print the fields in successive locations. Pad to align if needed!
976 const TargetData *TD = TM.getTargetData();
977 unsigned Size = TD->getTypeAllocSize(CVS->getType());
978 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
979 uint64_t sizeSoFar = 0;
980 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
981 const Constant* field = CVS->getOperand(i);
983 // Check if padding is needed and insert one or more 0s.
984 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
985 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
986 - cvsLayout->getElementOffset(i)) - fieldSize;
987 sizeSoFar += fieldSize + padSize;
989 // Now print the actual field value.
990 EmitGlobalConstant(field, AddrSpace);
992 // Insert padding - this may include padding to increase the size of the
993 // current field up to the ABI size (if the struct is not packed) as well
994 // as padding to ensure that the next field starts at the right offset.
995 EmitZeros(padSize, AddrSpace);
997 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
998 "Layout of constant struct may be incorrect!");
1001 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1002 unsigned AddrSpace) {
1003 // FP Constants are printed as integer constants to avoid losing
1005 LLVMContext &Context = CFP->getContext();
1006 const TargetData *TD = TM.getTargetData();
1007 if (CFP->getType() == Type::getDoubleTy(Context)) {
1008 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1009 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1010 if (MAI->getData64bitsDirective(AddrSpace)) {
1011 O << MAI->getData64bitsDirective(AddrSpace) << i;
1013 O.PadToColumn(MAI->getCommentColumn());
1014 O << MAI->getCommentString() << " double " << Val;
1017 } else if (TD->isBigEndian()) {
1018 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1020 O.PadToColumn(MAI->getCommentColumn());
1021 O << MAI->getCommentString()
1022 << " most significant word of double " << Val;
1025 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1027 O.PadToColumn(MAI->getCommentColumn());
1028 O << MAI->getCommentString()
1029 << " least significant word of double " << Val;
1033 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1035 O.PadToColumn(MAI->getCommentColumn());
1036 O << MAI->getCommentString()
1037 << " least significant word of double " << Val;
1040 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1042 O.PadToColumn(MAI->getCommentColumn());
1043 O << MAI->getCommentString()
1044 << " most significant word of double " << Val;
1049 } else if (CFP->getType() == Type::getFloatTy(Context)) {
1050 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1051 O << MAI->getData32bitsDirective(AddrSpace)
1052 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1054 O.PadToColumn(MAI->getCommentColumn());
1055 O << MAI->getCommentString() << " float " << Val;
1059 } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1060 // all long double variants are printed as hex
1061 // api needed to prevent premature destruction
1062 APInt api = CFP->getValueAPF().bitcastToAPInt();
1063 const uint64_t *p = api.getRawData();
1064 // Convert to double so we can print the approximate val as a comment.
1065 APFloat DoubleVal = CFP->getValueAPF();
1067 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1069 if (TD->isBigEndian()) {
1070 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1072 O.PadToColumn(MAI->getCommentColumn());
1073 O << MAI->getCommentString()
1074 << " most significant halfword of x86_fp80 ~"
1075 << DoubleVal.convertToDouble();
1078 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1080 O.PadToColumn(MAI->getCommentColumn());
1081 O << MAI->getCommentString() << " next halfword";
1084 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1086 O.PadToColumn(MAI->getCommentColumn());
1087 O << MAI->getCommentString() << " next halfword";
1090 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1092 O.PadToColumn(MAI->getCommentColumn());
1093 O << MAI->getCommentString() << " next halfword";
1096 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1098 O.PadToColumn(MAI->getCommentColumn());
1099 O << MAI->getCommentString()
1100 << " least significant halfword";
1104 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1106 O.PadToColumn(MAI->getCommentColumn());
1107 O << MAI->getCommentString()
1108 << " least significant halfword of x86_fp80 ~"
1109 << DoubleVal.convertToDouble();
1112 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1114 O.PadToColumn(MAI->getCommentColumn());
1115 O << MAI->getCommentString()
1116 << " next halfword";
1119 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1121 O.PadToColumn(MAI->getCommentColumn());
1122 O << MAI->getCommentString()
1123 << " next halfword";
1126 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1128 O.PadToColumn(MAI->getCommentColumn());
1129 O << MAI->getCommentString()
1130 << " next halfword";
1133 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1135 O.PadToColumn(MAI->getCommentColumn());
1136 O << MAI->getCommentString()
1137 << " most significant halfword";
1141 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1142 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1144 } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1145 // all long double variants are printed as hex
1146 // api needed to prevent premature destruction
1147 APInt api = CFP->getValueAPF().bitcastToAPInt();
1148 const uint64_t *p = api.getRawData();
1149 if (TD->isBigEndian()) {
1150 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1152 O.PadToColumn(MAI->getCommentColumn());
1153 O << MAI->getCommentString()
1154 << " most significant word of ppc_fp128";
1157 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1159 O.PadToColumn(MAI->getCommentColumn());
1160 O << MAI->getCommentString()
1164 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1166 O.PadToColumn(MAI->getCommentColumn());
1167 O << MAI->getCommentString()
1171 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1173 O.PadToColumn(MAI->getCommentColumn());
1174 O << MAI->getCommentString()
1175 << " least significant word";
1179 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1181 O.PadToColumn(MAI->getCommentColumn());
1182 O << MAI->getCommentString()
1183 << " least significant word of ppc_fp128";
1186 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1188 O.PadToColumn(MAI->getCommentColumn());
1189 O << MAI->getCommentString()
1193 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1195 O.PadToColumn(MAI->getCommentColumn());
1196 O << MAI->getCommentString()
1200 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1202 O.PadToColumn(MAI->getCommentColumn());
1203 O << MAI->getCommentString()
1204 << " most significant word";
1209 } else llvm_unreachable("Floating point constant type not handled");
1212 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1213 unsigned AddrSpace) {
1214 const TargetData *TD = TM.getTargetData();
1215 unsigned BitWidth = CI->getBitWidth();
1216 assert(isPowerOf2_32(BitWidth) &&
1217 "Non-power-of-2-sized integers not handled!");
1219 // We don't expect assemblers to support integer data directives
1220 // for more than 64 bits, so we emit the data in at most 64-bit
1221 // quantities at a time.
1222 const uint64_t *RawData = CI->getValue().getRawData();
1223 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1225 if (TD->isBigEndian())
1226 Val = RawData[e - i - 1];
1230 if (MAI->getData64bitsDirective(AddrSpace))
1231 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1232 else if (TD->isBigEndian()) {
1233 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1235 O.PadToColumn(MAI->getCommentColumn());
1236 O << MAI->getCommentString()
1237 << " most significant half of i64 " << Val;
1240 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1242 O.PadToColumn(MAI->getCommentColumn());
1243 O << MAI->getCommentString()
1244 << " least significant half of i64 " << Val;
1248 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1250 O.PadToColumn(MAI->getCommentColumn());
1251 O << MAI->getCommentString()
1252 << " least significant half of i64 " << Val;
1255 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1257 O.PadToColumn(MAI->getCommentColumn());
1258 O << MAI->getCommentString()
1259 << " most significant half of i64 " << Val;
1266 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1267 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1268 const TargetData *TD = TM.getTargetData();
1269 const Type *type = CV->getType();
1270 unsigned Size = TD->getTypeAllocSize(type);
1272 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1273 EmitZeros(Size, AddrSpace);
1275 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1276 EmitGlobalConstantArray(CVA , AddrSpace);
1278 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1279 EmitGlobalConstantStruct(CVS, AddrSpace);
1281 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1282 EmitGlobalConstantFP(CFP, AddrSpace);
1284 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1285 // Small integers are handled below; large integers are handled here.
1287 EmitGlobalConstantLargeInt(CI, AddrSpace);
1290 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1291 EmitGlobalConstantVector(CP);
1295 printDataDirective(type, AddrSpace);
1296 EmitConstantValueOnly(CV);
1298 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1300 CI->getValue().toStringUnsigned(S, 16);
1301 O.PadToColumn(MAI->getCommentColumn());
1302 O << MAI->getCommentString() << " 0x" << S.str();
1308 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1309 // Target doesn't support this yet!
1310 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1313 /// PrintSpecial - Print information related to the specified machine instr
1314 /// that is independent of the operand, and may be independent of the instr
1315 /// itself. This can be useful for portably encoding the comment character
1316 /// or other bits of target-specific knowledge into the asmstrings. The
1317 /// syntax used is ${:comment}. Targets can override this to add support
1318 /// for their own strange codes.
1319 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1320 if (!strcmp(Code, "private")) {
1321 O << MAI->getPrivateGlobalPrefix();
1322 } else if (!strcmp(Code, "comment")) {
1324 O << MAI->getCommentString();
1325 } else if (!strcmp(Code, "uid")) {
1326 // Comparing the address of MI isn't sufficient, because machineinstrs may
1327 // be allocated to the same address across functions.
1328 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1330 // If this is a new LastFn instruction, bump the counter.
1331 if (LastMI != MI || LastFn != ThisF) {
1339 raw_string_ostream Msg(msg);
1340 Msg << "Unknown special formatter '" << Code
1341 << "' for machine instr: " << *MI;
1342 llvm_report_error(Msg.str());
1346 /// processDebugLoc - Processes the debug information of each machine
1347 /// instruction's DebugLoc.
1348 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1352 if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1353 if (!DL.isUnknown()) {
1354 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1356 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1357 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1358 DICompileUnit(CurDLT.CompileUnit)));
1367 /// printInlineAsm - This method formats and prints the specified machine
1368 /// instruction that is an inline asm.
1369 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1370 unsigned NumOperands = MI->getNumOperands();
1372 // Count the number of register definitions.
1373 unsigned NumDefs = 0;
1374 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1376 assert(NumDefs != NumOperands-1 && "No asm string?");
1378 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1380 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1381 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1383 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1384 // These are useful to see where empty asm's wound up.
1385 if (AsmStr[0] == 0) {
1386 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1387 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1391 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1393 // The variant of the current asmprinter.
1394 int AsmPrinterVariant = MAI->getAssemblerDialect();
1396 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1397 const char *LastEmitted = AsmStr; // One past the last character emitted.
1399 while (*LastEmitted) {
1400 switch (*LastEmitted) {
1402 // Not a special case, emit the string section literally.
1403 const char *LiteralEnd = LastEmitted+1;
1404 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1405 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1407 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1408 O.write(LastEmitted, LiteralEnd-LastEmitted);
1409 LastEmitted = LiteralEnd;
1413 ++LastEmitted; // Consume newline character.
1414 O << '\n'; // Indent code with newline.
1417 ++LastEmitted; // Consume '$' character.
1421 switch (*LastEmitted) {
1422 default: Done = false; break;
1423 case '$': // $$ -> $
1424 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1426 ++LastEmitted; // Consume second '$' character.
1428 case '(': // $( -> same as GCC's { character.
1429 ++LastEmitted; // Consume '(' character.
1430 if (CurVariant != -1) {
1431 llvm_report_error("Nested variants found in inline asm string: '"
1432 + std::string(AsmStr) + "'");
1434 CurVariant = 0; // We're in the first variant now.
1437 ++LastEmitted; // consume '|' character.
1438 if (CurVariant == -1)
1439 O << '|'; // this is gcc's behavior for | outside a variant
1441 ++CurVariant; // We're in the next variant.
1443 case ')': // $) -> same as GCC's } char.
1444 ++LastEmitted; // consume ')' character.
1445 if (CurVariant == -1)
1446 O << '}'; // this is gcc's behavior for } outside a variant
1453 bool HasCurlyBraces = false;
1454 if (*LastEmitted == '{') { // ${variable}
1455 ++LastEmitted; // Consume '{' character.
1456 HasCurlyBraces = true;
1459 // If we have ${:foo}, then this is not a real operand reference, it is a
1460 // "magic" string reference, just like in .td files. Arrange to call
1462 if (HasCurlyBraces && *LastEmitted == ':') {
1464 const char *StrStart = LastEmitted;
1465 const char *StrEnd = strchr(StrStart, '}');
1467 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1468 + std::string(AsmStr) + "'");
1471 std::string Val(StrStart, StrEnd);
1472 PrintSpecial(MI, Val.c_str());
1473 LastEmitted = StrEnd+1;
1477 const char *IDStart = LastEmitted;
1480 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1481 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1482 llvm_report_error("Bad $ operand number in inline asm string: '"
1483 + std::string(AsmStr) + "'");
1485 LastEmitted = IDEnd;
1487 char Modifier[2] = { 0, 0 };
1489 if (HasCurlyBraces) {
1490 // If we have curly braces, check for a modifier character. This
1491 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1492 if (*LastEmitted == ':') {
1493 ++LastEmitted; // Consume ':' character.
1494 if (*LastEmitted == 0) {
1495 llvm_report_error("Bad ${:} expression in inline asm string: '"
1496 + std::string(AsmStr) + "'");
1499 Modifier[0] = *LastEmitted;
1500 ++LastEmitted; // Consume modifier character.
1503 if (*LastEmitted != '}') {
1504 llvm_report_error("Bad ${} expression in inline asm string: '"
1505 + std::string(AsmStr) + "'");
1507 ++LastEmitted; // Consume '}' character.
1510 if ((unsigned)Val >= NumOperands-1) {
1511 llvm_report_error("Invalid $ operand number in inline asm string: '"
1512 + std::string(AsmStr) + "'");
1515 // Okay, we finally have a value number. Ask the target to print this
1517 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1522 // Scan to find the machine operand number for the operand.
1523 for (; Val; --Val) {
1524 if (OpNo >= MI->getNumOperands()) break;
1525 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1526 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1529 if (OpNo >= MI->getNumOperands()) {
1532 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1533 ++OpNo; // Skip over the ID number.
1535 if (Modifier[0]=='l') // labels are target independent
1536 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1537 ->getNumber())->print(O, MAI);
1539 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1540 if ((OpFlags & 7) == 4) {
1541 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1542 Modifier[0] ? Modifier : 0);
1544 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1545 Modifier[0] ? Modifier : 0);
1551 raw_string_ostream Msg(msg);
1552 Msg << "Invalid operand found in inline asm: '"
1555 llvm_report_error(Msg.str());
1562 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1565 /// printImplicitDef - This method prints the specified machine instruction
1566 /// that is an implicit def.
1567 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1568 if (!VerboseAsm) return;
1569 O.PadToColumn(MAI->getCommentColumn());
1570 O << MAI->getCommentString() << " implicit-def: "
1571 << TRI->getName(MI->getOperand(0).getReg());
1574 /// printLabel - This method prints a local label used by debug and
1575 /// exception handling tables.
1576 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1577 printLabel(MI->getOperand(0).getImm());
1580 void AsmPrinter::printLabel(unsigned Id) const {
1581 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1584 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1585 /// instruction, using the specified assembler variant. Targets should
1586 /// overried this to format as appropriate.
1587 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1588 unsigned AsmVariant, const char *ExtraCode) {
1589 // Target doesn't support this yet!
1593 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1594 unsigned AsmVariant,
1595 const char *ExtraCode) {
1596 // Target doesn't support this yet!
1600 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1601 SmallString<60> Name;
1602 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1603 << getFunctionNumber() << '_' << MBBID;
1605 return OutContext.GetOrCreateSymbol(Name.str());
1609 /// EmitBasicBlockStart - This method prints the label for the specified
1610 /// MachineBasicBlock, an alignment (if present) and a comment describing
1611 /// it if appropriate.
1612 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1613 if (unsigned Align = MBB->getAlignment())
1614 EmitAlignment(Log2_32(Align));
1616 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1620 if (const BasicBlock *BB = MBB->getBasicBlock())
1621 if (BB->hasName()) {
1622 O.PadToColumn(MAI->getCommentColumn());
1623 O << MAI->getCommentString() << ' ';
1624 WriteAsOperand(O, BB, /*PrintType=*/false);
1631 /// printPICJumpTableSetLabel - This method prints a set label for the
1632 /// specified MachineBasicBlock for a jumptable entry.
1633 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1634 const MachineBasicBlock *MBB) const {
1635 if (!MAI->getSetDirective())
1638 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1639 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1640 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1641 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1642 << '_' << uid << '\n';
1645 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1646 const MachineBasicBlock *MBB) const {
1647 if (!MAI->getSetDirective())
1650 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1651 << getFunctionNumber() << '_' << uid << '_' << uid2
1652 << "_set_" << MBB->getNumber() << ',';
1653 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1654 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1655 << '_' << uid << '_' << uid2 << '\n';
1658 /// printDataDirective - This method prints the asm directive for the
1660 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1661 const TargetData *TD = TM.getTargetData();
1662 switch (type->getTypeID()) {
1663 case Type::FloatTyID: case Type::DoubleTyID:
1664 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1665 assert(0 && "Should have already output floating point constant.");
1667 assert(0 && "Can't handle printing this type of thing");
1668 case Type::IntegerTyID: {
1669 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1671 O << MAI->getData8bitsDirective(AddrSpace);
1672 else if (BitWidth <= 16)
1673 O << MAI->getData16bitsDirective(AddrSpace);
1674 else if (BitWidth <= 32)
1675 O << MAI->getData32bitsDirective(AddrSpace);
1676 else if (BitWidth <= 64) {
1677 assert(MAI->getData64bitsDirective(AddrSpace) &&
1678 "Target cannot handle 64-bit constant exprs!");
1679 O << MAI->getData64bitsDirective(AddrSpace);
1681 llvm_unreachable("Target cannot handle given data directive width!");
1685 case Type::PointerTyID:
1686 if (TD->getPointerSize() == 8) {
1687 assert(MAI->getData64bitsDirective(AddrSpace) &&
1688 "Target cannot handle 64-bit pointer exprs!");
1689 O << MAI->getData64bitsDirective(AddrSpace);
1690 } else if (TD->getPointerSize() == 2) {
1691 O << MAI->getData16bitsDirective(AddrSpace);
1692 } else if (TD->getPointerSize() == 1) {
1693 O << MAI->getData8bitsDirective(AddrSpace);
1695 O << MAI->getData32bitsDirective(AddrSpace);
1701 void AsmPrinter::printVisibility(const std::string& Name,
1702 unsigned Visibility) const {
1703 if (Visibility == GlobalValue::HiddenVisibility) {
1704 if (const char *Directive = MAI->getHiddenDirective())
1705 O << Directive << Name << '\n';
1706 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1707 if (const char *Directive = MAI->getProtectedDirective())
1708 O << Directive << Name << '\n';
1712 void AsmPrinter::printOffset(int64_t Offset) const {
1715 else if (Offset < 0)
1719 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1720 if (!S->usesMetadata())
1723 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1724 if (GCPI != GCMetadataPrinters.end())
1725 return GCPI->second;
1727 const char *Name = S->getName().c_str();
1729 for (GCMetadataPrinterRegistry::iterator
1730 I = GCMetadataPrinterRegistry::begin(),
1731 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1732 if (strcmp(Name, I->getName()) == 0) {
1733 GCMetadataPrinter *GMP = I->instantiate();
1735 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1739 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1740 llvm_unreachable(0);
1743 /// EmitComments - Pretty-print comments for instructions
1744 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1745 assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1747 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1749 // Print source line info.
1750 O.PadToColumn(MAI->getCommentColumn());
1751 O << MAI->getCommentString() << " SrcLine ";
1752 if (DLT.CompileUnit) {
1754 DICompileUnit CU(DLT.CompileUnit);
1755 O << CU.getFilename(Str) << " ";
1759 O << ":" << DLT.Col;
1762 /// PrintChildLoopComment - Print comments about child loops within
1763 /// the loop for this basic block, with nesting.
1765 static void PrintChildLoopComment(formatted_raw_ostream &O,
1766 const MachineLoop *loop,
1767 const MCAsmInfo *MAI,
1768 int FunctionNumber) {
1769 // Add child loop information
1770 for(MachineLoop::iterator cl = loop->begin(),
1771 clend = loop->end();
1774 MachineBasicBlock *Header = (*cl)->getHeader();
1775 assert(Header && "No header for loop");
1778 O.PadToColumn(MAI->getCommentColumn());
1780 O << MAI->getCommentString();
1781 O.indent(((*cl)->getLoopDepth()-1)*2)
1782 << " Child Loop BB" << FunctionNumber << "_"
1783 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1785 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1789 /// EmitComments - Pretty-print comments for basic blocks
1790 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1793 // Add loop depth information
1794 const MachineLoop *loop = LI->getLoopFor(&MBB);
1797 // Print a newline after bb# annotation.
1799 O.PadToColumn(MAI->getCommentColumn());
1800 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1803 O.PadToColumn(MAI->getCommentColumn());
1805 MachineBasicBlock *Header = loop->getHeader();
1806 assert(Header && "No header for loop");
1808 if (Header == &MBB) {
1809 O << MAI->getCommentString() << " Loop Header";
1810 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1813 O << MAI->getCommentString() << " Loop Header is BB"
1814 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1817 if (loop->empty()) {
1819 O.PadToColumn(MAI->getCommentColumn());
1820 O << MAI->getCommentString() << " Inner Loop";
1823 // Add parent loop information
1824 for (const MachineLoop *CurLoop = loop->getParentLoop();
1826 CurLoop = CurLoop->getParentLoop()) {
1827 MachineBasicBlock *Header = CurLoop->getHeader();
1828 assert(Header && "No header for loop");
1831 O.PadToColumn(MAI->getCommentColumn());
1832 O << MAI->getCommentString();
1833 O.indent((CurLoop->getLoopDepth()-1)*2)
1834 << " Inside Loop BB" << getFunctionNumber() << "_"
1835 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();