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/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/Analysis/DebugInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/IOManip.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
47 static cl::opt<cl::boolOrDefault>
48 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
49 cl::init(cl::BOU_UNSET));
51 static cl::opt<cl::boolOrDefault>
52 AsmExuberant("asm-exuberant", cl::desc("Add many comments."),
53 cl::init(cl::BOU_FALSE));
55 char AsmPrinter::ID = 0;
56 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
57 const TargetAsmInfo *T, bool VDef)
58 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
59 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
61 OutContext(*new MCContext()),
62 OutStreamer(*createAsmStreamer(OutContext, O, *T, this)),
64 LastMI(0), LastFn(0), Counter(~0U),
65 PrevDLT(0, ~0U, ~0U) {
69 case cl::BOU_UNSET: VerboseAsm = VDef; break;
70 case cl::BOU_TRUE: VerboseAsm = true; break;
71 case cl::BOU_FALSE: VerboseAsm = false; break;
73 switch (AsmExuberant) {
74 case cl::BOU_UNSET: ExuberantAsm = false; break;
75 case cl::BOU_TRUE: ExuberantAsm = true; break;
76 case cl::BOU_FALSE: ExuberantAsm = false; break;
80 AsmPrinter::~AsmPrinter() {
81 for (gcp_iterator I = GCMetadataPrinters.begin(),
82 E = GCMetadataPrinters.end(); I != E; ++I)
89 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
90 return TM.getTargetLowering()->getObjFileLowering();
93 /// SwitchToSection - Switch to the specified section of the executable if we
94 /// are not already in it! If "NS" is null, then this causes us to exit the
95 /// current section and not reenter another one. This is generally used for
98 /// FIXME: Remove support for null sections.
100 void AsmPrinter::SwitchToSection(const MCSection *NS) {
102 // FIXME: Remove support for null sections!
104 OutStreamer.SwitchSection(NS);
107 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
108 AU.setPreservesAll();
109 MachineFunctionPass::getAnalysisUsage(AU);
110 AU.addRequired<GCModuleInfo>();
112 AU.addRequired<MachineLoopInfo>();
115 bool AsmPrinter::doInitialization(Module &M) {
116 // Initialize TargetLoweringObjectFile.
117 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
118 .Initialize(OutContext, TM);
120 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(),
121 TAI->getLinkerPrivateGlobalPrefix());
123 if (TAI->doesAllowQuotesInName())
124 Mang->setUseQuotes(true);
126 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
127 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
129 if (TAI->hasSingleParameterDotFile()) {
130 /* Very minimal debug info. It is ignored if we emit actual
131 debug info. If we don't, this at helps the user find where
132 a function came from. */
133 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
136 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
137 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
138 MP->beginAssembly(O, *this, *TAI);
140 if (!M.getModuleInlineAsm().empty())
141 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
142 << M.getModuleInlineAsm()
143 << '\n' << TAI->getCommentString()
144 << " End of file scope inline assembly\n";
146 SwitchToSection(0); // Reset back to no section to close off sections.
148 if (TAI->doesSupportDebugInformation() ||
149 TAI->doesSupportExceptionHandling()) {
150 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
152 MMI->AnalyzeModule(M);
153 DW = getAnalysisIfAvailable<DwarfWriter>();
155 DW->BeginModule(&M, MMI, O, this, TAI);
161 bool AsmPrinter::doFinalization(Module &M) {
162 // Emit global variables.
163 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
165 PrintGlobalVariable(I);
167 // Emit final debug information.
168 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
171 // If the target wants to know about weak references, print them all.
172 if (TAI->getWeakRefDirective()) {
173 // FIXME: This is not lazy, it would be nice to only print weak references
174 // to stuff that is actually used. Note that doing so would require targets
175 // to notice uses in operands (due to constant exprs etc). This should
176 // happen with the MC stuff eventually.
179 // Print out module-level global variables here.
180 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
182 if (I->hasExternalWeakLinkage())
183 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
186 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
187 if (I->hasExternalWeakLinkage())
188 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
192 if (TAI->getSetDirective()) {
194 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
196 std::string Name = Mang->getMangledName(I);
198 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
199 std::string Target = Mang->getMangledName(GV);
201 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
202 O << "\t.globl\t" << Name << '\n';
203 else if (I->hasWeakLinkage())
204 O << TAI->getWeakRefDirective() << Name << '\n';
205 else if (!I->hasLocalLinkage())
206 llvm_unreachable("Invalid alias linkage");
208 printVisibility(Name, I->getVisibility());
210 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
214 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
215 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
216 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
217 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
218 MP->finishAssembly(O, *this, *TAI);
220 // If we don't have any trampolines, then we don't require stack memory
221 // to be executable. Some targets have a directive to declare this.
222 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
223 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
224 if (TAI->getNonexecutableStackDirective())
225 O << TAI->getNonexecutableStackDirective() << '\n';
227 delete Mang; Mang = 0;
230 OutStreamer.Finish();
235 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
236 assert(MF && "No machine function?");
237 return Mang->getMangledName(MF->getFunction(), ".eh",
238 TAI->is_EHSymbolPrivate());
241 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
242 // What's my mangled name?
243 CurrentFnName = Mang->getMangledName(MF.getFunction());
244 IncrementFunctionNumber();
247 LI = &getAnalysis<MachineLoopInfo>();
252 // SectionCPs - Keep track the alignment, constpool entries per Section.
256 SmallVector<unsigned, 4> CPEs;
257 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
261 /// EmitConstantPool - Print to the current output stream assembly
262 /// representations of the constants in the constant pool MCP. This is
263 /// used to print out constants which have been "spilled to memory" by
264 /// the code generator.
266 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
267 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
268 if (CP.empty()) return;
270 // Calculate sections for constant pool entries. We collect entries to go into
271 // the same section together to reduce amount of section switch statements.
272 SmallVector<SectionCPs, 4> CPSections;
273 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
274 const MachineConstantPoolEntry &CPE = CP[i];
275 unsigned Align = CPE.getAlignment();
278 switch (CPE.getRelocationInfo()) {
279 default: llvm_unreachable("Unknown section kind");
280 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
282 Kind = SectionKind::getReadOnlyWithRelLocal();
285 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
286 case 4: Kind = SectionKind::getMergeableConst4(); break;
287 case 8: Kind = SectionKind::getMergeableConst8(); break;
288 case 16: Kind = SectionKind::getMergeableConst16();break;
289 default: Kind = SectionKind::getMergeableConst(); break;
293 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
295 // The number of sections are small, just do a linear search from the
296 // last section to the first.
298 unsigned SecIdx = CPSections.size();
299 while (SecIdx != 0) {
300 if (CPSections[--SecIdx].S == S) {
306 SecIdx = CPSections.size();
307 CPSections.push_back(SectionCPs(S, Align));
310 if (Align > CPSections[SecIdx].Alignment)
311 CPSections[SecIdx].Alignment = Align;
312 CPSections[SecIdx].CPEs.push_back(i);
315 // Now print stuff into the calculated sections.
316 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
317 SwitchToSection(CPSections[i].S);
318 EmitAlignment(Log2_32(CPSections[i].Alignment));
321 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
322 unsigned CPI = CPSections[i].CPEs[j];
323 MachineConstantPoolEntry CPE = CP[CPI];
325 // Emit inter-object padding for alignment.
326 unsigned AlignMask = CPE.getAlignment() - 1;
327 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
328 EmitZeros(NewOffset - Offset);
330 const Type *Ty = CPE.getType();
331 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
333 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
336 O.PadToColumn(TAI->getCommentColumn(), 1);
337 O << TAI->getCommentString() << " constant ";
338 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
341 if (CPE.isMachineConstantPoolEntry())
342 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
344 EmitGlobalConstant(CPE.Val.ConstVal);
349 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
350 /// by the current function to the current output stream.
352 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
353 MachineFunction &MF) {
354 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
355 if (JT.empty()) return;
357 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
359 // Pick the directive to use to print the jump table entries, and switch to
360 // the appropriate section.
361 TargetLowering *LoweringInfo = TM.getTargetLowering();
363 const Function *F = MF.getFunction();
364 bool JTInDiffSection = false;
365 if (F->isWeakForLinker() ||
366 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
367 // In PIC mode, we need to emit the jump table to the same section as the
368 // function body itself, otherwise the label differences won't make sense.
369 // We should also do if the section name is NULL or function is declared in
370 // discardable section.
371 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
373 // Otherwise, drop it in the readonly section.
374 const MCSection *ReadOnlySection =
375 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
376 SwitchToSection(ReadOnlySection);
377 JTInDiffSection = true;
380 EmitAlignment(Log2_32(MJTI->getAlignment()));
382 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
383 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
385 // If this jump table was deleted, ignore it.
386 if (JTBBs.empty()) continue;
388 // For PIC codegen, if possible we want to use the SetDirective to reduce
389 // the number of relocations the assembler will generate for the jump table.
390 // Set directives are all printed before the jump table itself.
391 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
392 if (TAI->getSetDirective() && IsPic)
393 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
394 if (EmittedSets.insert(JTBBs[ii]))
395 printPICJumpTableSetLabel(i, JTBBs[ii]);
397 // On some targets (e.g. darwin) we want to emit two consequtive labels
398 // before each jump table. The first label is never referenced, but tells
399 // the assembler and linker the extents of the jump table object. The
400 // second label is actually referenced by the code.
401 if (JTInDiffSection) {
402 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
403 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
406 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
407 << '_' << i << ":\n";
409 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
410 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
416 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
417 const MachineBasicBlock *MBB,
418 unsigned uid) const {
419 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
421 // Use JumpTableDirective otherwise honor the entry size from the jump table
423 const char *JTEntryDirective = TAI->getJumpTableDirective(isPIC);
424 bool HadJTEntryDirective = JTEntryDirective != NULL;
425 if (!HadJTEntryDirective) {
426 JTEntryDirective = MJTI->getEntrySize() == 4 ?
427 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
430 O << JTEntryDirective << ' ';
432 // If we have emitted set directives for the jump table entries, print
433 // them rather than the entries themselves. If we're emitting PIC, then
434 // emit the table entries as differences between two text section labels.
435 // If we're emitting non-PIC code, then emit the entries as direct
436 // references to the target basic blocks.
438 printBasicBlockLabel(MBB, false, false, false);
439 } else if (TAI->getSetDirective()) {
440 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
441 << '_' << uid << "_set_" << MBB->getNumber();
443 printBasicBlockLabel(MBB, false, false, false);
444 // If the arch uses custom Jump Table directives, don't calc relative to
446 if (!HadJTEntryDirective)
447 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
448 << getFunctionNumber() << '_' << uid;
453 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
454 /// special global used by LLVM. If so, emit it and return true, otherwise
455 /// do nothing and return false.
456 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
457 if (GV->getName() == "llvm.used") {
458 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
459 EmitLLVMUsedList(GV->getInitializer());
463 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
464 if (GV->getSection() == "llvm.metadata" ||
465 GV->hasAvailableExternallyLinkage())
468 if (!GV->hasAppendingLinkage()) return false;
470 assert(GV->hasInitializer() && "Not a special LLVM global!");
472 const TargetData *TD = TM.getTargetData();
473 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
474 if (GV->getName() == "llvm.global_ctors") {
475 SwitchToSection(getObjFileLowering().getStaticCtorSection());
476 EmitAlignment(Align, 0);
477 EmitXXStructorList(GV->getInitializer());
481 if (GV->getName() == "llvm.global_dtors") {
482 SwitchToSection(getObjFileLowering().getStaticDtorSection());
483 EmitAlignment(Align, 0);
484 EmitXXStructorList(GV->getInitializer());
491 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
492 /// global in the specified llvm.used list for which emitUsedDirectiveFor
493 /// is true, as being used with this directive.
494 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
495 const char *Directive = TAI->getUsedDirective();
497 // Should be an array of 'i8*'.
498 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
499 if (InitList == 0) return;
501 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
502 const GlobalValue *GV =
503 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
504 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
506 EmitConstantValueOnly(InitList->getOperand(i));
512 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
513 /// function pointers, ignoring the init priority.
514 void AsmPrinter::EmitXXStructorList(Constant *List) {
515 // Should be an array of '{ int, void ()* }' structs. The first value is the
516 // init priority, which we ignore.
517 if (!isa<ConstantArray>(List)) return;
518 ConstantArray *InitList = cast<ConstantArray>(List);
519 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
520 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
521 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
523 if (CS->getOperand(1)->isNullValue())
524 return; // Found a null terminator, exit printing.
525 // Emit the function pointer.
526 EmitGlobalConstant(CS->getOperand(1));
530 /// getGlobalLinkName - Returns the asm/link name of of the specified
531 /// global variable. Should be overridden by each target asm printer to
532 /// generate the appropriate value.
533 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
534 std::string &LinkName) const {
535 if (isa<Function>(GV)) {
536 LinkName += TAI->getFunctionAddrPrefix();
537 LinkName += Mang->getMangledName(GV);
538 LinkName += TAI->getFunctionAddrSuffix();
540 LinkName += TAI->getGlobalVarAddrPrefix();
541 LinkName += Mang->getMangledName(GV);
542 LinkName += TAI->getGlobalVarAddrSuffix();
548 /// EmitExternalGlobal - Emit the external reference to a global variable.
549 /// Should be overridden if an indirect reference should be used.
550 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
552 O << getGlobalLinkName(GV, GLN);
557 //===----------------------------------------------------------------------===//
558 /// LEB 128 number encoding.
560 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
561 /// representing an unsigned leb128 value.
562 void AsmPrinter::PrintULEB128(unsigned Value) const {
565 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
567 if (Value) Byte |= 0x80;
568 O << "0x" << utohex_buffer(Byte, Buffer+20);
569 if (Value) O << ", ";
573 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
574 /// representing a signed leb128 value.
575 void AsmPrinter::PrintSLEB128(int Value) const {
576 int Sign = Value >> (8 * sizeof(Value) - 1);
581 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
583 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
584 if (IsMore) Byte |= 0x80;
585 O << "0x" << utohex_buffer(Byte, Buffer+20);
586 if (IsMore) O << ", ";
590 //===--------------------------------------------------------------------===//
591 // Emission and print routines
594 /// PrintHex - Print a value as a hexidecimal value.
596 void AsmPrinter::PrintHex(int Value) const {
598 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
601 /// EOL - Print a newline character to asm stream. If a comment is present
602 /// then it will be printed first. Comments should not contain '\n'.
603 void AsmPrinter::EOL() const {
607 void AsmPrinter::EOL(const std::string &Comment) const {
608 if (VerboseAsm && !Comment.empty()) {
609 O.PadToColumn(TAI->getCommentColumn(), 1);
610 O << TAI->getCommentString()
617 void AsmPrinter::EOL(const char* Comment) const {
618 if (VerboseAsm && *Comment) {
619 O.PadToColumn(TAI->getCommentColumn(), 1);
620 O << TAI->getCommentString()
627 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
628 /// unsigned leb128 value.
629 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
630 if (TAI->hasLEB128()) {
634 O << TAI->getData8bitsDirective();
639 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
640 /// signed leb128 value.
641 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
642 if (TAI->hasLEB128()) {
646 O << TAI->getData8bitsDirective();
651 /// EmitInt8 - Emit a byte directive and value.
653 void AsmPrinter::EmitInt8(int Value) const {
654 O << TAI->getData8bitsDirective();
655 PrintHex(Value & 0xFF);
658 /// EmitInt16 - Emit a short directive and value.
660 void AsmPrinter::EmitInt16(int Value) const {
661 O << TAI->getData16bitsDirective();
662 PrintHex(Value & 0xFFFF);
665 /// EmitInt32 - Emit a long directive and value.
667 void AsmPrinter::EmitInt32(int Value) const {
668 O << TAI->getData32bitsDirective();
672 /// EmitInt64 - Emit a long long directive and value.
674 void AsmPrinter::EmitInt64(uint64_t Value) const {
675 if (TAI->getData64bitsDirective()) {
676 O << TAI->getData64bitsDirective();
679 if (TM.getTargetData()->isBigEndian()) {
680 EmitInt32(unsigned(Value >> 32)); O << '\n';
681 EmitInt32(unsigned(Value));
683 EmitInt32(unsigned(Value)); O << '\n';
684 EmitInt32(unsigned(Value >> 32));
689 /// toOctal - Convert the low order bits of X into an octal digit.
691 static inline char toOctal(int X) {
695 /// printStringChar - Print a char, escaped if necessary.
697 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
700 } else if (C == '\\') {
702 } else if (isprint((unsigned char)C)) {
706 case '\b': O << "\\b"; break;
707 case '\f': O << "\\f"; break;
708 case '\n': O << "\\n"; break;
709 case '\r': O << "\\r"; break;
710 case '\t': O << "\\t"; break;
713 O << toOctal(C >> 6);
714 O << toOctal(C >> 3);
715 O << toOctal(C >> 0);
721 /// EmitString - Emit a string with quotes and a null terminator.
722 /// Special characters are emitted properly.
723 /// \literal (Eg. '\t') \endliteral
724 void AsmPrinter::EmitString(const std::string &String) const {
725 EmitString(String.c_str(), String.size());
728 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
729 const char* AscizDirective = TAI->getAscizDirective();
733 O << TAI->getAsciiDirective();
735 for (unsigned i = 0; i < Size; ++i)
736 printStringChar(O, String[i]);
744 /// EmitFile - Emit a .file directive.
745 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
746 O << "\t.file\t" << Number << " \"";
747 for (unsigned i = 0, N = Name.size(); i < N; ++i)
748 printStringChar(O, Name[i]);
753 //===----------------------------------------------------------------------===//
755 // EmitAlignment - Emit an alignment directive to the specified power of
756 // two boundary. For example, if you pass in 3 here, you will get an 8
757 // byte alignment. If a global value is specified, and if that global has
758 // an explicit alignment requested, it will unconditionally override the
759 // alignment request. However, if ForcedAlignBits is specified, this value
760 // has final say: the ultimate alignment will be the max of ForcedAlignBits
761 // and the alignment computed with NumBits and the global.
765 // if (GV && GV->hasalignment) Align = GV->getalignment();
766 // Align = std::max(Align, ForcedAlignBits);
768 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
769 unsigned ForcedAlignBits,
770 bool UseFillExpr) const {
771 if (GV && GV->getAlignment())
772 NumBits = Log2_32(GV->getAlignment());
773 NumBits = std::max(NumBits, ForcedAlignBits);
775 if (NumBits == 0) return; // No need to emit alignment.
776 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
777 O << TAI->getAlignDirective() << NumBits;
779 if (CurrentSection && CurrentSection->getKind().isText())
780 if (unsigned FillValue = TAI->getTextAlignFillValue()) {
787 /// EmitZeros - Emit a block of zeros.
789 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
791 if (TAI->getZeroDirective()) {
792 O << TAI->getZeroDirective() << NumZeros;
793 if (TAI->getZeroDirectiveSuffix())
794 O << TAI->getZeroDirectiveSuffix();
797 for (; NumZeros; --NumZeros)
798 O << TAI->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, possibly
813 // decorating it with GlobalVarAddrPrefix/Suffix or
814 // FunctionAddrPrefix/Suffix (these all default to "" )
815 if (isa<Function>(GV)) {
816 O << TAI->getFunctionAddrPrefix()
817 << Mang->getMangledName(GV)
818 << TAI->getFunctionAddrSuffix();
820 O << TAI->getGlobalVarAddrPrefix()
821 << Mang->getMangledName(GV)
822 << TAI->getGlobalVarAddrSuffix();
824 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
825 const TargetData *TD = TM.getTargetData();
826 unsigned Opcode = CE->getOpcode();
828 case Instruction::Trunc:
829 case Instruction::ZExt:
830 case Instruction::SExt:
831 case Instruction::FPTrunc:
832 case Instruction::FPExt:
833 case Instruction::UIToFP:
834 case Instruction::SIToFP:
835 case Instruction::FPToUI:
836 case Instruction::FPToSI:
837 llvm_unreachable("FIXME: Don't support this constant cast expr");
838 case Instruction::GetElementPtr: {
839 // generate a symbolic expression for the byte address
840 const Constant *ptrVal = CE->getOperand(0);
841 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
842 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
844 // Truncate/sext the offset to the pointer size.
845 if (TD->getPointerSizeInBits() != 64) {
846 int SExtAmount = 64-TD->getPointerSizeInBits();
847 Offset = (Offset << SExtAmount) >> SExtAmount;
852 EmitConstantValueOnly(ptrVal);
854 O << ") + " << Offset;
856 O << ") - " << -Offset;
858 EmitConstantValueOnly(ptrVal);
862 case Instruction::BitCast:
863 return EmitConstantValueOnly(CE->getOperand(0));
865 case Instruction::IntToPtr: {
866 // Handle casts to pointers by changing them into casts to the appropriate
867 // integer type. This promotes constant folding and simplifies this code.
868 Constant *Op = CE->getOperand(0);
869 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
871 return EmitConstantValueOnly(Op);
875 case Instruction::PtrToInt: {
876 // Support only foldable casts to/from pointers that can be eliminated by
877 // changing the pointer to the appropriately sized integer type.
878 Constant *Op = CE->getOperand(0);
879 const Type *Ty = CE->getType();
881 // We can emit the pointer value into this slot if the slot is an
882 // integer slot greater or equal to the size of the pointer.
883 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
884 return EmitConstantValueOnly(Op);
887 EmitConstantValueOnly(Op);
889 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
892 ptrMask.toStringUnsigned(S);
893 O << ") & " << S.c_str() << ')';
896 case Instruction::Add:
897 case Instruction::Sub:
898 case Instruction::And:
899 case Instruction::Or:
900 case Instruction::Xor:
902 EmitConstantValueOnly(CE->getOperand(0));
905 case Instruction::Add:
908 case Instruction::Sub:
911 case Instruction::And:
914 case Instruction::Or:
917 case Instruction::Xor:
924 EmitConstantValueOnly(CE->getOperand(1));
928 llvm_unreachable("Unsupported operator!");
931 llvm_unreachable("Unknown constant value!");
935 /// printAsCString - Print the specified array as a C compatible string, only if
936 /// the predicate isString is true.
938 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
940 assert(CVA->isString() && "Array is not string compatible!");
943 for (unsigned i = 0; i != LastElt; ++i) {
945 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
946 printStringChar(O, C);
951 /// EmitString - Emit a zero-byte-terminated string constant.
953 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
954 unsigned NumElts = CVA->getNumOperands();
955 if (TAI->getAscizDirective() && NumElts &&
956 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
957 O << TAI->getAscizDirective();
958 printAsCString(O, CVA, NumElts-1);
960 O << TAI->getAsciiDirective();
961 printAsCString(O, CVA, NumElts);
966 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
967 unsigned AddrSpace) {
968 if (CVA->isString()) {
970 } else { // Not a string. Print the values in successive locations
971 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
972 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
976 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
977 const VectorType *PTy = CP->getType();
979 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
980 EmitGlobalConstant(CP->getOperand(I));
983 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
984 unsigned AddrSpace) {
985 // Print the fields in successive locations. Pad to align if needed!
986 const TargetData *TD = TM.getTargetData();
987 unsigned Size = TD->getTypeAllocSize(CVS->getType());
988 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
989 uint64_t sizeSoFar = 0;
990 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
991 const Constant* field = CVS->getOperand(i);
993 // Check if padding is needed and insert one or more 0s.
994 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
995 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
996 - cvsLayout->getElementOffset(i)) - fieldSize;
997 sizeSoFar += fieldSize + padSize;
999 // Now print the actual field value.
1000 EmitGlobalConstant(field, AddrSpace);
1002 // Insert padding - this may include padding to increase the size of the
1003 // current field up to the ABI size (if the struct is not packed) as well
1004 // as padding to ensure that the next field starts at the right offset.
1005 EmitZeros(padSize, AddrSpace);
1007 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1008 "Layout of constant struct may be incorrect!");
1011 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1012 unsigned AddrSpace) {
1013 // FP Constants are printed as integer constants to avoid losing
1015 LLVMContext &Context = CFP->getContext();
1016 const TargetData *TD = TM.getTargetData();
1017 if (CFP->getType() == Type::getDoubleTy(Context)) {
1018 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1019 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1020 if (TAI->getData64bitsDirective(AddrSpace)) {
1021 O << TAI->getData64bitsDirective(AddrSpace) << i;
1023 O.PadToColumn(TAI->getCommentColumn(), 1);
1024 O << TAI->getCommentString() << " double " << Val;
1027 } else if (TD->isBigEndian()) {
1028 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1030 O.PadToColumn(TAI->getCommentColumn(), 1);
1031 O << TAI->getCommentString()
1032 << " most significant word of double " << Val;
1035 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1037 O.PadToColumn(TAI->getCommentColumn(), 1);
1038 O << TAI->getCommentString()
1039 << " least significant word of double " << Val;
1043 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1045 O.PadToColumn(TAI->getCommentColumn(), 1);
1046 O << TAI->getCommentString()
1047 << " least significant word of double " << Val;
1050 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1052 O.PadToColumn(TAI->getCommentColumn(), 1);
1053 O << TAI->getCommentString()
1054 << " most significant word of double " << Val;
1059 } else if (CFP->getType() == Type::getFloatTy(Context)) {
1060 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1061 O << TAI->getData32bitsDirective(AddrSpace)
1062 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1064 O.PadToColumn(TAI->getCommentColumn(), 1);
1065 O << TAI->getCommentString() << " float " << Val;
1069 } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1070 // all long double variants are printed as hex
1071 // api needed to prevent premature destruction
1072 APInt api = CFP->getValueAPF().bitcastToAPInt();
1073 const uint64_t *p = api.getRawData();
1074 // Convert to double so we can print the approximate val as a comment.
1075 APFloat DoubleVal = CFP->getValueAPF();
1077 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1079 if (TD->isBigEndian()) {
1080 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1082 O.PadToColumn(TAI->getCommentColumn(), 1);
1083 O << TAI->getCommentString()
1084 << " most significant halfword of x86_fp80 ~"
1085 << DoubleVal.convertToDouble();
1088 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1090 O.PadToColumn(TAI->getCommentColumn(), 1);
1091 O << TAI->getCommentString() << " next halfword";
1094 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1096 O.PadToColumn(TAI->getCommentColumn(), 1);
1097 O << TAI->getCommentString() << " next halfword";
1100 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1102 O.PadToColumn(TAI->getCommentColumn(), 1);
1103 O << TAI->getCommentString() << " next halfword";
1106 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1108 O.PadToColumn(TAI->getCommentColumn(), 1);
1109 O << TAI->getCommentString()
1110 << " least significant halfword";
1114 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1116 O.PadToColumn(TAI->getCommentColumn(), 1);
1117 O << TAI->getCommentString()
1118 << " least significant halfword of x86_fp80 ~"
1119 << DoubleVal.convertToDouble();
1122 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1124 O.PadToColumn(TAI->getCommentColumn(), 1);
1125 O << TAI->getCommentString()
1126 << " next halfword";
1129 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1131 O.PadToColumn(TAI->getCommentColumn(), 1);
1132 O << TAI->getCommentString()
1133 << " next halfword";
1136 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1138 O.PadToColumn(TAI->getCommentColumn(), 1);
1139 O << TAI->getCommentString()
1140 << " next halfword";
1143 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1145 O.PadToColumn(TAI->getCommentColumn(), 1);
1146 O << TAI->getCommentString()
1147 << " most significant halfword";
1151 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1152 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1154 } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1155 // all long double variants are printed as hex
1156 // api needed to prevent premature destruction
1157 APInt api = CFP->getValueAPF().bitcastToAPInt();
1158 const uint64_t *p = api.getRawData();
1159 if (TD->isBigEndian()) {
1160 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1162 O.PadToColumn(TAI->getCommentColumn(), 1);
1163 O << TAI->getCommentString()
1164 << " most significant word of ppc_fp128";
1167 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1169 O.PadToColumn(TAI->getCommentColumn(), 1);
1170 O << TAI->getCommentString()
1174 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1176 O.PadToColumn(TAI->getCommentColumn(), 1);
1177 O << TAI->getCommentString()
1181 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1183 O.PadToColumn(TAI->getCommentColumn(), 1);
1184 O << TAI->getCommentString()
1185 << " least significant word";
1189 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1191 O.PadToColumn(TAI->getCommentColumn(), 1);
1192 O << TAI->getCommentString()
1193 << " least significant word of ppc_fp128";
1196 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1198 O.PadToColumn(TAI->getCommentColumn(), 1);
1199 O << TAI->getCommentString()
1203 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1205 O.PadToColumn(TAI->getCommentColumn(), 1);
1206 O << TAI->getCommentString()
1210 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1212 O.PadToColumn(TAI->getCommentColumn(), 1);
1213 O << TAI->getCommentString()
1214 << " most significant word";
1219 } else llvm_unreachable("Floating point constant type not handled");
1222 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1223 unsigned AddrSpace) {
1224 const TargetData *TD = TM.getTargetData();
1225 unsigned BitWidth = CI->getBitWidth();
1226 assert(isPowerOf2_32(BitWidth) &&
1227 "Non-power-of-2-sized integers not handled!");
1229 // We don't expect assemblers to support integer data directives
1230 // for more than 64 bits, so we emit the data in at most 64-bit
1231 // quantities at a time.
1232 const uint64_t *RawData = CI->getValue().getRawData();
1233 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1235 if (TD->isBigEndian())
1236 Val = RawData[e - i - 1];
1240 if (TAI->getData64bitsDirective(AddrSpace))
1241 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1242 else if (TD->isBigEndian()) {
1243 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1245 O.PadToColumn(TAI->getCommentColumn(), 1);
1246 O << TAI->getCommentString()
1247 << " most significant half of i64 " << Val;
1250 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1252 O.PadToColumn(TAI->getCommentColumn(), 1);
1253 O << TAI->getCommentString()
1254 << " least significant half of i64 " << Val;
1258 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1260 O.PadToColumn(TAI->getCommentColumn(), 1);
1261 O << TAI->getCommentString()
1262 << " least significant half of i64 " << Val;
1265 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1267 O.PadToColumn(TAI->getCommentColumn(), 1);
1268 O << TAI->getCommentString()
1269 << " most significant half of i64 " << Val;
1276 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1277 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1278 const TargetData *TD = TM.getTargetData();
1279 const Type *type = CV->getType();
1280 unsigned Size = TD->getTypeAllocSize(type);
1282 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1283 EmitZeros(Size, AddrSpace);
1285 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1286 EmitGlobalConstantArray(CVA , AddrSpace);
1288 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1289 EmitGlobalConstantStruct(CVS, AddrSpace);
1291 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1292 EmitGlobalConstantFP(CFP, AddrSpace);
1294 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1295 // Small integers are handled below; large integers are handled here.
1297 EmitGlobalConstantLargeInt(CI, AddrSpace);
1300 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1301 EmitGlobalConstantVector(CP);
1305 printDataDirective(type, AddrSpace);
1306 EmitConstantValueOnly(CV);
1308 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1310 CI->getValue().toStringUnsigned(S, 16);
1311 O.PadToColumn(TAI->getCommentColumn(), 1);
1312 O << TAI->getCommentString() << " 0x" << S.c_str();
1318 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1319 // Target doesn't support this yet!
1320 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1323 /// PrintSpecial - Print information related to the specified machine instr
1324 /// that is independent of the operand, and may be independent of the instr
1325 /// itself. This can be useful for portably encoding the comment character
1326 /// or other bits of target-specific knowledge into the asmstrings. The
1327 /// syntax used is ${:comment}. Targets can override this to add support
1328 /// for their own strange codes.
1329 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1330 if (!strcmp(Code, "private")) {
1331 O << TAI->getPrivateGlobalPrefix();
1332 } else if (!strcmp(Code, "comment")) {
1334 O << TAI->getCommentString();
1335 } else if (!strcmp(Code, "uid")) {
1336 // Comparing the address of MI isn't sufficient, because machineinstrs may
1337 // be allocated to the same address across functions.
1338 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1340 // If this is a new LastFn instruction, bump the counter.
1341 if (LastMI != MI || LastFn != ThisF) {
1349 raw_string_ostream Msg(msg);
1350 Msg << "Unknown special formatter '" << Code
1351 << "' for machine instr: " << *MI;
1352 llvm_report_error(Msg.str());
1356 /// processDebugLoc - Processes the debug information of each machine
1357 /// instruction's DebugLoc.
1358 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1362 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1363 if (!DL.isUnknown()) {
1364 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1366 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1367 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1368 DICompileUnit(CurDLT.CompileUnit)));
1375 /// printInlineAsm - This method formats and prints the specified machine
1376 /// instruction that is an inline asm.
1377 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1378 unsigned NumOperands = MI->getNumOperands();
1380 // Count the number of register definitions.
1381 unsigned NumDefs = 0;
1382 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1384 assert(NumDefs != NumOperands-1 && "No asm string?");
1386 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1388 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1389 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1391 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1392 // These are useful to see where empty asm's wound up.
1393 if (AsmStr[0] == 0) {
1394 O << TAI->getCommentString() << TAI->getInlineAsmStart() << "\n\t";
1395 O << TAI->getCommentString() << TAI->getInlineAsmEnd() << '\n';
1399 O << TAI->getCommentString() << TAI->getInlineAsmStart() << "\n\t";
1401 // The variant of the current asmprinter.
1402 int AsmPrinterVariant = TAI->getAssemblerDialect();
1404 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1405 const char *LastEmitted = AsmStr; // One past the last character emitted.
1407 while (*LastEmitted) {
1408 switch (*LastEmitted) {
1410 // Not a special case, emit the string section literally.
1411 const char *LiteralEnd = LastEmitted+1;
1412 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1413 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1415 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1416 O.write(LastEmitted, LiteralEnd-LastEmitted);
1417 LastEmitted = LiteralEnd;
1421 ++LastEmitted; // Consume newline character.
1422 O << '\n'; // Indent code with newline.
1425 ++LastEmitted; // Consume '$' character.
1429 switch (*LastEmitted) {
1430 default: Done = false; break;
1431 case '$': // $$ -> $
1432 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1434 ++LastEmitted; // Consume second '$' character.
1436 case '(': // $( -> same as GCC's { character.
1437 ++LastEmitted; // Consume '(' character.
1438 if (CurVariant != -1) {
1439 llvm_report_error("Nested variants found in inline asm string: '"
1440 + std::string(AsmStr) + "'");
1442 CurVariant = 0; // We're in the first variant now.
1445 ++LastEmitted; // consume '|' character.
1446 if (CurVariant == -1)
1447 O << '|'; // this is gcc's behavior for | outside a variant
1449 ++CurVariant; // We're in the next variant.
1451 case ')': // $) -> same as GCC's } char.
1452 ++LastEmitted; // consume ')' character.
1453 if (CurVariant == -1)
1454 O << '}'; // this is gcc's behavior for } outside a variant
1461 bool HasCurlyBraces = false;
1462 if (*LastEmitted == '{') { // ${variable}
1463 ++LastEmitted; // Consume '{' character.
1464 HasCurlyBraces = true;
1467 // If we have ${:foo}, then this is not a real operand reference, it is a
1468 // "magic" string reference, just like in .td files. Arrange to call
1470 if (HasCurlyBraces && *LastEmitted == ':') {
1472 const char *StrStart = LastEmitted;
1473 const char *StrEnd = strchr(StrStart, '}');
1475 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1476 + std::string(AsmStr) + "'");
1479 std::string Val(StrStart, StrEnd);
1480 PrintSpecial(MI, Val.c_str());
1481 LastEmitted = StrEnd+1;
1485 const char *IDStart = LastEmitted;
1488 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1489 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1490 llvm_report_error("Bad $ operand number in inline asm string: '"
1491 + std::string(AsmStr) + "'");
1493 LastEmitted = IDEnd;
1495 char Modifier[2] = { 0, 0 };
1497 if (HasCurlyBraces) {
1498 // If we have curly braces, check for a modifier character. This
1499 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1500 if (*LastEmitted == ':') {
1501 ++LastEmitted; // Consume ':' character.
1502 if (*LastEmitted == 0) {
1503 llvm_report_error("Bad ${:} expression in inline asm string: '"
1504 + std::string(AsmStr) + "'");
1507 Modifier[0] = *LastEmitted;
1508 ++LastEmitted; // Consume modifier character.
1511 if (*LastEmitted != '}') {
1512 llvm_report_error("Bad ${} expression in inline asm string: '"
1513 + std::string(AsmStr) + "'");
1515 ++LastEmitted; // Consume '}' character.
1518 if ((unsigned)Val >= NumOperands-1) {
1519 llvm_report_error("Invalid $ operand number in inline asm string: '"
1520 + std::string(AsmStr) + "'");
1523 // Okay, we finally have a value number. Ask the target to print this
1525 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1530 // Scan to find the machine operand number for the operand.
1531 for (; Val; --Val) {
1532 if (OpNo >= MI->getNumOperands()) break;
1533 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1534 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1537 if (OpNo >= MI->getNumOperands()) {
1540 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1541 ++OpNo; // Skip over the ID number.
1543 if (Modifier[0]=='l') // labels are target independent
1544 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1545 false, false, false);
1547 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1548 if ((OpFlags & 7) == 4) {
1549 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1550 Modifier[0] ? Modifier : 0);
1552 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1553 Modifier[0] ? Modifier : 0);
1559 raw_string_ostream Msg(msg);
1560 Msg << "Invalid operand found in inline asm: '"
1563 llvm_report_error(Msg.str());
1570 O << "\n\t" << TAI->getCommentString() << TAI->getInlineAsmEnd() << '\n';
1573 /// printImplicitDef - This method prints the specified machine instruction
1574 /// that is an implicit def.
1575 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1577 O.PadToColumn(TAI->getCommentColumn(), 1);
1578 O << TAI->getCommentString() << " implicit-def: "
1579 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1583 /// printLabel - This method prints a local label used by debug and
1584 /// exception handling tables.
1585 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1586 printLabel(MI->getOperand(0).getImm());
1589 void AsmPrinter::printLabel(unsigned Id) const {
1590 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1593 /// printDeclare - This method prints a local variable declaration used by
1595 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1596 /// entry into dwarf table.
1597 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1598 unsigned FI = MI->getOperand(0).getIndex();
1599 GlobalValue *GV = MI->getOperand(1).getGlobal();
1600 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1603 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1604 /// instruction, using the specified assembler variant. Targets should
1605 /// overried this to format as appropriate.
1606 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1607 unsigned AsmVariant, const char *ExtraCode) {
1608 // Target doesn't support this yet!
1612 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1613 unsigned AsmVariant,
1614 const char *ExtraCode) {
1615 // Target doesn't support this yet!
1619 /// printBasicBlockLabel - This method prints the label for the specified
1620 /// MachineBasicBlock
1621 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1624 bool printComment) const {
1626 unsigned Align = MBB->getAlignment();
1628 EmitAlignment(Log2_32(Align));
1631 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1632 << MBB->getNumber();
1636 if (const BasicBlock *BB = MBB->getBasicBlock())
1637 if (BB->hasName()) {
1638 O.PadToColumn(TAI->getCommentColumn(), 1);
1639 O << TAI->getCommentString() << ' ';
1640 WriteAsOperand(O, BB, /*PrintType=*/false);
1648 /// printPICJumpTableSetLabel - This method prints a set label for the
1649 /// specified MachineBasicBlock for a jumptable entry.
1650 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1651 const MachineBasicBlock *MBB) const {
1652 if (!TAI->getSetDirective())
1655 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1656 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1657 printBasicBlockLabel(MBB, false, false, false);
1658 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1659 << '_' << uid << '\n';
1662 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1663 const MachineBasicBlock *MBB) const {
1664 if (!TAI->getSetDirective())
1667 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1668 << getFunctionNumber() << '_' << uid << '_' << uid2
1669 << "_set_" << MBB->getNumber() << ',';
1670 printBasicBlockLabel(MBB, false, false, false);
1671 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1672 << '_' << uid << '_' << uid2 << '\n';
1675 /// printDataDirective - This method prints the asm directive for the
1677 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1678 const TargetData *TD = TM.getTargetData();
1679 switch (type->getTypeID()) {
1680 case Type::FloatTyID: case Type::DoubleTyID:
1681 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1682 assert(0 && "Should have already output floating point constant.");
1684 assert(0 && "Can't handle printing this type of thing");
1685 case Type::IntegerTyID: {
1686 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1688 O << TAI->getData8bitsDirective(AddrSpace);
1689 else if (BitWidth <= 16)
1690 O << TAI->getData16bitsDirective(AddrSpace);
1691 else if (BitWidth <= 32)
1692 O << TAI->getData32bitsDirective(AddrSpace);
1693 else if (BitWidth <= 64) {
1694 assert(TAI->getData64bitsDirective(AddrSpace) &&
1695 "Target cannot handle 64-bit constant exprs!");
1696 O << TAI->getData64bitsDirective(AddrSpace);
1698 llvm_unreachable("Target cannot handle given data directive width!");
1702 case Type::PointerTyID:
1703 if (TD->getPointerSize() == 8) {
1704 assert(TAI->getData64bitsDirective(AddrSpace) &&
1705 "Target cannot handle 64-bit pointer exprs!");
1706 O << TAI->getData64bitsDirective(AddrSpace);
1707 } else if (TD->getPointerSize() == 2) {
1708 O << TAI->getData16bitsDirective(AddrSpace);
1709 } else if (TD->getPointerSize() == 1) {
1710 O << TAI->getData8bitsDirective(AddrSpace);
1712 O << TAI->getData32bitsDirective(AddrSpace);
1718 void AsmPrinter::printVisibility(const std::string& Name,
1719 unsigned Visibility) const {
1720 if (Visibility == GlobalValue::HiddenVisibility) {
1721 if (const char *Directive = TAI->getHiddenDirective())
1722 O << Directive << Name << '\n';
1723 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1724 if (const char *Directive = TAI->getProtectedDirective())
1725 O << Directive << Name << '\n';
1729 void AsmPrinter::printOffset(int64_t Offset) const {
1732 else if (Offset < 0)
1736 void AsmPrinter::printMCInst(const MCInst *MI) {
1737 llvm_unreachable("MCInst printing unavailable on this target!");
1740 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1741 if (!S->usesMetadata())
1744 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1745 if (GCPI != GCMetadataPrinters.end())
1746 return GCPI->second;
1748 const char *Name = S->getName().c_str();
1750 for (GCMetadataPrinterRegistry::iterator
1751 I = GCMetadataPrinterRegistry::begin(),
1752 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1753 if (strcmp(Name, I->getName()) == 0) {
1754 GCMetadataPrinter *GMP = I->instantiate();
1756 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1760 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1761 llvm_unreachable(0);
1764 /// EmitComments - Pretty-print comments for instructions
1765 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1767 MI.getDebugLoc().isUnknown())
1770 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1772 // Print source line info
1773 O.PadToColumn(TAI->getCommentColumn(), 1);
1774 O << TAI->getCommentString() << " SrcLine ";
1775 if (DLT.CompileUnit->hasInitializer()) {
1776 Constant *Name = DLT.CompileUnit->getInitializer();
1777 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1778 if (NameString->isString())
1779 O << NameString->getAsString() << " ";
1783 O << ":" << DLT.Col;
1786 /// EmitComments - Pretty-print comments for instructions
1787 void AsmPrinter::EmitComments(const MCInst &MI) const
1790 if (!MI.getDebugLoc().isUnknown()) {
1791 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1793 // Print source line info
1794 O.PadToColumn(TAI->getCommentColumn(), 1);
1795 O << TAI->getCommentString() << " SrcLine ";
1796 if (DLT.CompileUnit->hasInitializer()) {
1797 Constant *Name = DLT.CompileUnit->getInitializer();
1798 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1799 if (NameString->isString()) {
1800 O << NameString->getAsString() << " ";
1805 O << ":" << DLT.Col;
1810 /// EmitComments - Pretty-print comments for basic blocks
1811 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1814 // Add loop depth information
1815 const MachineLoop *loop = LI->getLoopFor(&MBB);
1818 // Print a newline after bb# annotation.
1820 O.PadToColumn(TAI->getCommentColumn(), 1);
1821 O << TAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1824 O.PadToColumn(TAI->getCommentColumn(), 1);
1826 MachineBasicBlock *Header = loop->getHeader();
1827 assert(Header && "No header for loop");
1829 if (Header == &MBB) {
1830 O << TAI->getCommentString() << " Loop Header";
1831 PrintChildLoopComment(loop);
1834 O << TAI->getCommentString() << " Loop Header is BB"
1835 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1838 if (loop->empty()) {
1840 O.PadToColumn(TAI->getCommentColumn(), 1);
1841 O << TAI->getCommentString() << " Inner Loop";
1844 // Add parent loop information
1845 for (const MachineLoop *CurLoop = loop->getParentLoop();
1847 CurLoop = CurLoop->getParentLoop()) {
1848 MachineBasicBlock *Header = CurLoop->getHeader();
1849 assert(Header && "No header for loop");
1852 O.PadToColumn(TAI->getCommentColumn(), 1);
1853 O << TAI->getCommentString() << Indent(CurLoop->getLoopDepth()-1)
1854 << " Inside Loop BB" << getFunctionNumber() << "_"
1855 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();
1861 void AsmPrinter::PrintChildLoopComment(const MachineLoop *loop) const {
1862 // Add child loop information
1863 for(MachineLoop::iterator cl = loop->begin(),
1864 clend = loop->end();
1867 MachineBasicBlock *Header = (*cl)->getHeader();
1868 assert(Header && "No header for loop");
1871 O.PadToColumn(TAI->getCommentColumn(), 1);
1873 O << TAI->getCommentString() << Indent((*cl)->getLoopDepth()-1)
1874 << " Child Loop BB" << getFunctionNumber() << "_"
1875 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1877 PrintChildLoopComment(*cl);