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/MachineModuleInfo.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/Analysis/DebugInfo.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
42 static cl::opt<cl::boolOrDefault>
43 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
44 cl::init(cl::BOU_UNSET));
46 char AsmPrinter::ID = 0;
47 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
48 const TargetAsmInfo *T, bool VDef)
49 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
50 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
51 IsInTextSection(false), LastMI(0), LastFn(0), Counter(~0U),
52 PrevDLT(0, ~0U, ~0U) {
55 case cl::BOU_UNSET: VerboseAsm = VDef; break;
56 case cl::BOU_TRUE: VerboseAsm = true; break;
57 case cl::BOU_FALSE: VerboseAsm = false; break;
61 AsmPrinter::~AsmPrinter() {
62 for (gcp_iterator I = GCMetadataPrinters.begin(),
63 E = GCMetadataPrinters.end(); I != E; ++I)
67 /// SwitchToTextSection - Switch to the specified text section of the executable
68 /// if we are not already in it!
70 void AsmPrinter::SwitchToTextSection(const char *NewSection,
71 const GlobalValue *GV) {
73 if (GV && GV->hasSection())
74 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
78 // If we're already in this section, we're done.
79 if (CurrentSection == NS) return;
81 // Close the current section, if applicable.
82 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
83 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
87 if (!CurrentSection.empty())
88 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
90 IsInTextSection = true;
93 /// SwitchToDataSection - Switch to the specified data section of the executable
94 /// if we are not already in it!
96 void AsmPrinter::SwitchToDataSection(const char *NewSection,
97 const GlobalValue *GV) {
99 if (GV && GV->hasSection())
100 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
104 // If we're already in this section, we're done.
105 if (CurrentSection == NS) return;
107 // Close the current section, if applicable.
108 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
109 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
113 if (!CurrentSection.empty())
114 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
116 IsInTextSection = false;
119 /// SwitchToSection - Switch to the specified section of the executable if we
120 /// are not already in it!
121 void AsmPrinter::SwitchToSection(const Section* NS) {
122 const std::string& NewSection = NS->getName();
124 // If we're already in this section, we're done.
125 if (CurrentSection == NewSection) return;
127 // Close the current section, if applicable.
128 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
129 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
131 // FIXME: Make CurrentSection a Section* in the future
132 CurrentSection = NewSection;
133 CurrentSection_ = NS;
135 if (!CurrentSection.empty()) {
136 // If section is named we need to switch into it via special '.section'
137 // directive and also append funky flags. Otherwise - section name is just
138 // some magic assembler directive.
140 O << TAI->getSwitchToSectionDirective()
142 << TAI->getSectionFlags(NS->getFlags());
145 O << TAI->getDataSectionStartSuffix() << '\n';
148 IsInTextSection = (NS->getFlags() & SectionFlags::Code);
151 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
152 MachineFunctionPass::getAnalysisUsage(AU);
153 AU.addRequired<GCModuleInfo>();
156 bool AsmPrinter::doInitialization(Module &M) {
157 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(),
158 TAI->getLessPrivateGlobalPrefix());
160 if (TAI->doesAllowQuotesInName())
161 Mang->setUseQuotes(true);
163 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
164 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
166 if (TAI->hasSingleParameterDotFile()) {
167 /* Very minimal debug info. It is ignored if we emit actual
168 debug info. If we don't, this at helps the user find where
169 a function came from. */
170 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
173 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
174 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
175 MP->beginAssembly(O, *this, *TAI);
177 if (!M.getModuleInlineAsm().empty())
178 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
179 << M.getModuleInlineAsm()
180 << '\n' << TAI->getCommentString()
181 << " End of file scope inline assembly\n";
183 SwitchToDataSection(""); // Reset back to no section.
185 if (TAI->doesSupportDebugInformation() ||
186 TAI->doesSupportExceptionHandling()) {
187 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
189 MMI->AnalyzeModule(M);
190 DW = getAnalysisIfAvailable<DwarfWriter>();
192 DW->BeginModule(&M, MMI, O, this, TAI);
198 bool AsmPrinter::doFinalization(Module &M) {
199 // Emit final debug information.
200 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
203 // If the target wants to know about weak references, print them all.
204 if (TAI->getWeakRefDirective()) {
205 // FIXME: This is not lazy, it would be nice to only print weak references
206 // to stuff that is actually used. Note that doing so would require targets
207 // to notice uses in operands (due to constant exprs etc). This should
208 // happen with the MC stuff eventually.
209 SwitchToDataSection("");
211 // Print out module-level global variables here.
212 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
214 if (I->hasExternalWeakLinkage())
215 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
218 for (Module::const_iterator I = M.begin(), E = M.end();
220 if (I->hasExternalWeakLinkage())
221 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
225 if (TAI->getSetDirective()) {
226 if (!M.alias_empty())
227 SwitchToSection(TAI->getTextSection());
230 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
232 std::string Name = Mang->getMangledName(I);
234 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
235 std::string Target = Mang->getMangledName(GV);
237 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
238 O << "\t.globl\t" << Name << '\n';
239 else if (I->hasWeakLinkage())
240 O << TAI->getWeakRefDirective() << Name << '\n';
241 else if (!I->hasLocalLinkage())
242 llvm_unreachable("Invalid alias linkage");
244 printVisibility(Name, I->getVisibility());
246 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
250 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
251 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
252 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
253 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
254 MP->finishAssembly(O, *this, *TAI);
256 // If we don't have any trampolines, then we don't require stack memory
257 // to be executable. Some targets have a directive to declare this.
258 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
259 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
260 if (TAI->getNonexecutableStackDirective())
261 O << TAI->getNonexecutableStackDirective() << '\n';
263 delete Mang; Mang = 0;
269 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
270 assert(MF && "No machine function?");
271 return Mang->getMangledName(MF->getFunction(), ".eh",
272 TAI->is_EHSymbolPrivate());
275 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
276 // What's my mangled name?
277 CurrentFnName = Mang->getMangledName(MF.getFunction());
278 IncrementFunctionNumber();
282 // SectionCPs - Keep track the alignment, constpool entries per Section.
286 SmallVector<unsigned, 4> CPEs;
287 SectionCPs(const Section *s, unsigned a) : S(s), Alignment(a) {};
291 /// EmitConstantPool - Print to the current output stream assembly
292 /// representations of the constants in the constant pool MCP. This is
293 /// used to print out constants which have been "spilled to memory" by
294 /// the code generator.
296 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
297 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
298 if (CP.empty()) return;
300 // Calculate sections for constant pool entries. We collect entries to go into
301 // the same section together to reduce amount of section switch statements.
302 SmallVector<SectionCPs, 4> CPSections;
303 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
304 MachineConstantPoolEntry CPE = CP[i];
305 unsigned Align = CPE.getAlignment();
306 const Section* S = TAI->SelectSectionForMachineConst(CPE.getType());
307 // The number of sections are small, just do a linear search from the
308 // last section to the first.
310 unsigned SecIdx = CPSections.size();
311 while (SecIdx != 0) {
312 if (CPSections[--SecIdx].S == S) {
318 SecIdx = CPSections.size();
319 CPSections.push_back(SectionCPs(S, Align));
322 if (Align > CPSections[SecIdx].Alignment)
323 CPSections[SecIdx].Alignment = Align;
324 CPSections[SecIdx].CPEs.push_back(i);
327 // Now print stuff into the calculated sections.
328 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
329 SwitchToSection(CPSections[i].S);
330 EmitAlignment(Log2_32(CPSections[i].Alignment));
333 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
334 unsigned CPI = CPSections[i].CPEs[j];
335 MachineConstantPoolEntry CPE = CP[CPI];
337 // Emit inter-object padding for alignment.
338 unsigned AlignMask = CPE.getAlignment() - 1;
339 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
340 EmitZeros(NewOffset - Offset);
342 const Type *Ty = CPE.getType();
343 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
345 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
346 << CPI << ":\t\t\t\t\t";
348 O << TAI->getCommentString() << ' ';
349 WriteTypeSymbolic(O, CPE.getType(), 0);
352 if (CPE.isMachineConstantPoolEntry())
353 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
355 EmitGlobalConstant(CPE.Val.ConstVal);
360 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
361 /// by the current function to the current output stream.
363 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
364 MachineFunction &MF) {
365 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
366 if (JT.empty()) return;
368 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
370 // Pick the directive to use to print the jump table entries, and switch to
371 // the appropriate section.
372 TargetLowering *LoweringInfo = TM.getTargetLowering();
374 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
375 const Function *F = MF.getFunction();
376 unsigned SectionFlags = TAI->SectionFlagsForGlobal(F);
377 bool JTInDiffSection = false;
378 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
379 !JumpTableDataSection ||
380 SectionFlags & SectionFlags::Linkonce) {
381 // In PIC mode, we need to emit the jump table to the same section as the
382 // function body itself, otherwise the label differences won't make sense.
383 // We should also do if the section name is NULL or function is declared in
384 // discardable section.
385 SwitchToSection(TAI->SectionForGlobal(F));
387 SwitchToDataSection(JumpTableDataSection);
388 JTInDiffSection = true;
391 EmitAlignment(Log2_32(MJTI->getAlignment()));
393 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
394 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
396 // If this jump table was deleted, ignore it.
397 if (JTBBs.empty()) continue;
399 // For PIC codegen, if possible we want to use the SetDirective to reduce
400 // the number of relocations the assembler will generate for the jump table.
401 // Set directives are all printed before the jump table itself.
402 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
403 if (TAI->getSetDirective() && IsPic)
404 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
405 if (EmittedSets.insert(JTBBs[ii]))
406 printPICJumpTableSetLabel(i, JTBBs[ii]);
408 // On some targets (e.g. darwin) we want to emit two consequtive labels
409 // before each jump table. The first label is never referenced, but tells
410 // the assembler and linker the extents of the jump table object. The
411 // second label is actually referenced by the code.
412 if (JTInDiffSection) {
413 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
414 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
417 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
418 << '_' << i << ":\n";
420 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
421 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
427 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
428 const MachineBasicBlock *MBB,
429 unsigned uid) const {
430 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
432 // Use JumpTableDirective otherwise honor the entry size from the jump table
434 const char *JTEntryDirective = TAI->getJumpTableDirective();
435 bool HadJTEntryDirective = JTEntryDirective != NULL;
436 if (!HadJTEntryDirective) {
437 JTEntryDirective = MJTI->getEntrySize() == 4 ?
438 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
441 O << JTEntryDirective << ' ';
443 // If we have emitted set directives for the jump table entries, print
444 // them rather than the entries themselves. If we're emitting PIC, then
445 // emit the table entries as differences between two text section labels.
446 // If we're emitting non-PIC code, then emit the entries as direct
447 // references to the target basic blocks.
449 if (TAI->getSetDirective()) {
450 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
451 << '_' << uid << "_set_" << MBB->getNumber();
453 printBasicBlockLabel(MBB, false, false, false);
454 // If the arch uses custom Jump Table directives, don't calc relative to
456 if (!HadJTEntryDirective)
457 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
458 << getFunctionNumber() << '_' << uid;
461 printBasicBlockLabel(MBB, false, false, false);
466 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
467 /// special global used by LLVM. If so, emit it and return true, otherwise
468 /// do nothing and return false.
469 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
470 if (GV->isName("llvm.used")) {
471 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
472 EmitLLVMUsedList(GV->getInitializer());
476 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
477 if (GV->getSection() == "llvm.metadata" ||
478 GV->hasAvailableExternallyLinkage())
481 if (!GV->hasAppendingLinkage()) return false;
483 assert(GV->hasInitializer() && "Not a special LLVM global!");
485 const TargetData *TD = TM.getTargetData();
486 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
487 if (GV->getName() == "llvm.global_ctors") {
488 SwitchToDataSection(TAI->getStaticCtorsSection());
489 EmitAlignment(Align, 0);
490 EmitXXStructorList(GV->getInitializer());
494 if (GV->getName() == "llvm.global_dtors") {
495 SwitchToDataSection(TAI->getStaticDtorsSection());
496 EmitAlignment(Align, 0);
497 EmitXXStructorList(GV->getInitializer());
504 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
505 /// global in the specified llvm.used list for which emitUsedDirectiveFor
506 /// is true, as being used with this directive.
507 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
508 const char *Directive = TAI->getUsedDirective();
510 // Should be an array of 'i8*'.
511 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
512 if (InitList == 0) return;
514 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
515 const GlobalValue *GV =
516 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
517 if (GV && TAI->emitUsedDirectiveFor(GV, Mang)) {
519 EmitConstantValueOnly(InitList->getOperand(i));
525 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
526 /// function pointers, ignoring the init priority.
527 void AsmPrinter::EmitXXStructorList(Constant *List) {
528 // Should be an array of '{ int, void ()* }' structs. The first value is the
529 // init priority, which we ignore.
530 if (!isa<ConstantArray>(List)) return;
531 ConstantArray *InitList = cast<ConstantArray>(List);
532 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
533 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
534 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
536 if (CS->getOperand(1)->isNullValue())
537 return; // Found a null terminator, exit printing.
538 // Emit the function pointer.
539 EmitGlobalConstant(CS->getOperand(1));
543 /// getGlobalLinkName - Returns the asm/link name of of the specified
544 /// global variable. Should be overridden by each target asm printer to
545 /// generate the appropriate value.
546 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
547 std::string &LinkName) const {
548 if (isa<Function>(GV)) {
549 LinkName += TAI->getFunctionAddrPrefix();
550 LinkName += Mang->getMangledName(GV);
551 LinkName += TAI->getFunctionAddrSuffix();
553 LinkName += TAI->getGlobalVarAddrPrefix();
554 LinkName += Mang->getMangledName(GV);
555 LinkName += TAI->getGlobalVarAddrSuffix();
561 /// EmitExternalGlobal - Emit the external reference to a global variable.
562 /// Should be overridden if an indirect reference should be used.
563 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
565 O << getGlobalLinkName(GV, GLN);
570 //===----------------------------------------------------------------------===//
571 /// LEB 128 number encoding.
573 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
574 /// representing an unsigned leb128 value.
575 void AsmPrinter::PrintULEB128(unsigned Value) const {
578 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
580 if (Value) Byte |= 0x80;
581 O << "0x" << utohex_buffer(Byte, Buffer+20);
582 if (Value) O << ", ";
586 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
587 /// representing a signed leb128 value.
588 void AsmPrinter::PrintSLEB128(int Value) const {
589 int Sign = Value >> (8 * sizeof(Value) - 1);
594 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
596 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
597 if (IsMore) Byte |= 0x80;
598 O << "0x" << utohex_buffer(Byte, Buffer+20);
599 if (IsMore) O << ", ";
603 //===--------------------------------------------------------------------===//
604 // Emission and print routines
607 /// PrintHex - Print a value as a hexidecimal value.
609 void AsmPrinter::PrintHex(int Value) const {
611 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
614 /// EOL - Print a newline character to asm stream. If a comment is present
615 /// then it will be printed first. Comments should not contain '\n'.
616 void AsmPrinter::EOL() const {
620 void AsmPrinter::EOL(const std::string &Comment) const {
621 if (VerboseAsm && !Comment.empty()) {
623 << TAI->getCommentString()
630 void AsmPrinter::EOL(const char* Comment) const {
631 if (VerboseAsm && *Comment) {
633 << TAI->getCommentString()
640 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
641 /// unsigned leb128 value.
642 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
643 if (TAI->hasLEB128()) {
647 O << TAI->getData8bitsDirective();
652 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
653 /// signed leb128 value.
654 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
655 if (TAI->hasLEB128()) {
659 O << TAI->getData8bitsDirective();
664 /// EmitInt8 - Emit a byte directive and value.
666 void AsmPrinter::EmitInt8(int Value) const {
667 O << TAI->getData8bitsDirective();
668 PrintHex(Value & 0xFF);
671 /// EmitInt16 - Emit a short directive and value.
673 void AsmPrinter::EmitInt16(int Value) const {
674 O << TAI->getData16bitsDirective();
675 PrintHex(Value & 0xFFFF);
678 /// EmitInt32 - Emit a long directive and value.
680 void AsmPrinter::EmitInt32(int Value) const {
681 O << TAI->getData32bitsDirective();
685 /// EmitInt64 - Emit a long long directive and value.
687 void AsmPrinter::EmitInt64(uint64_t Value) const {
688 if (TAI->getData64bitsDirective()) {
689 O << TAI->getData64bitsDirective();
692 if (TM.getTargetData()->isBigEndian()) {
693 EmitInt32(unsigned(Value >> 32)); O << '\n';
694 EmitInt32(unsigned(Value));
696 EmitInt32(unsigned(Value)); O << '\n';
697 EmitInt32(unsigned(Value >> 32));
702 /// toOctal - Convert the low order bits of X into an octal digit.
704 static inline char toOctal(int X) {
708 /// printStringChar - Print a char, escaped if necessary.
710 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
713 } else if (C == '\\') {
715 } else if (isprint((unsigned char)C)) {
719 case '\b': O << "\\b"; break;
720 case '\f': O << "\\f"; break;
721 case '\n': O << "\\n"; break;
722 case '\r': O << "\\r"; break;
723 case '\t': O << "\\t"; break;
726 O << toOctal(C >> 6);
727 O << toOctal(C >> 3);
728 O << toOctal(C >> 0);
734 /// EmitString - Emit a string with quotes and a null terminator.
735 /// Special characters are emitted properly.
736 /// \literal (Eg. '\t') \endliteral
737 void AsmPrinter::EmitString(const std::string &String) const {
738 EmitString(String.c_str(), String.size());
741 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
742 const char* AscizDirective = TAI->getAscizDirective();
746 O << TAI->getAsciiDirective();
748 for (unsigned i = 0; i < Size; ++i)
749 printStringChar(O, String[i]);
757 /// EmitFile - Emit a .file directive.
758 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
759 O << "\t.file\t" << Number << " \"";
760 for (unsigned i = 0, N = Name.size(); i < N; ++i)
761 printStringChar(O, Name[i]);
766 //===----------------------------------------------------------------------===//
768 // EmitAlignment - Emit an alignment directive to the specified power of
769 // two boundary. For example, if you pass in 3 here, you will get an 8
770 // byte alignment. If a global value is specified, and if that global has
771 // an explicit alignment requested, it will unconditionally override the
772 // alignment request. However, if ForcedAlignBits is specified, this value
773 // has final say: the ultimate alignment will be the max of ForcedAlignBits
774 // and the alignment computed with NumBits and the global.
778 // if (GV && GV->hasalignment) Align = GV->getalignment();
779 // Align = std::max(Align, ForcedAlignBits);
781 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
782 unsigned ForcedAlignBits,
783 bool UseFillExpr) const {
784 if (GV && GV->getAlignment())
785 NumBits = Log2_32(GV->getAlignment());
786 NumBits = std::max(NumBits, ForcedAlignBits);
788 if (NumBits == 0) return; // No need to emit alignment.
789 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
790 O << TAI->getAlignDirective() << NumBits;
792 unsigned FillValue = TAI->getTextAlignFillValue();
793 UseFillExpr &= IsInTextSection && FillValue;
802 /// EmitZeros - Emit a block of zeros.
804 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
806 if (TAI->getZeroDirective()) {
807 O << TAI->getZeroDirective() << NumZeros;
808 if (TAI->getZeroDirectiveSuffix())
809 O << TAI->getZeroDirectiveSuffix();
812 for (; NumZeros; --NumZeros)
813 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
818 // Print out the specified constant, without a storage class. Only the
819 // constants valid in constant expressions can occur here.
820 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
821 if (CV->isNullValue() || isa<UndefValue>(CV))
823 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
824 O << CI->getZExtValue();
825 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
826 // This is a constant address for a global variable or function. Use the
827 // name of the variable or function as the address value, possibly
828 // decorating it with GlobalVarAddrPrefix/Suffix or
829 // FunctionAddrPrefix/Suffix (these all default to "" )
830 if (isa<Function>(GV)) {
831 O << TAI->getFunctionAddrPrefix()
832 << Mang->getMangledName(GV)
833 << TAI->getFunctionAddrSuffix();
835 O << TAI->getGlobalVarAddrPrefix()
836 << Mang->getMangledName(GV)
837 << TAI->getGlobalVarAddrSuffix();
839 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
840 const TargetData *TD = TM.getTargetData();
841 unsigned Opcode = CE->getOpcode();
843 case Instruction::GetElementPtr: {
844 // generate a symbolic expression for the byte address
845 const Constant *ptrVal = CE->getOperand(0);
846 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
847 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
849 // Truncate/sext the offset to the pointer size.
850 if (TD->getPointerSizeInBits() != 64) {
851 int SExtAmount = 64-TD->getPointerSizeInBits();
852 Offset = (Offset << SExtAmount) >> SExtAmount;
857 EmitConstantValueOnly(ptrVal);
859 O << ") + " << Offset;
861 O << ") - " << -Offset;
863 EmitConstantValueOnly(ptrVal);
867 case Instruction::Trunc:
868 case Instruction::ZExt:
869 case Instruction::SExt:
870 case Instruction::FPTrunc:
871 case Instruction::FPExt:
872 case Instruction::UIToFP:
873 case Instruction::SIToFP:
874 case Instruction::FPToUI:
875 case Instruction::FPToSI:
876 llvm_unreachable("FIXME: Don't yet support this kind of constant cast expr");
878 case Instruction::BitCast:
879 return EmitConstantValueOnly(CE->getOperand(0));
881 case Instruction::IntToPtr: {
882 // Handle casts to pointers by changing them into casts to the appropriate
883 // integer type. This promotes constant folding and simplifies this code.
884 Constant *Op = CE->getOperand(0);
885 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
886 return EmitConstantValueOnly(Op);
890 case Instruction::PtrToInt: {
891 // Support only foldable casts to/from pointers that can be eliminated by
892 // changing the pointer to the appropriately sized integer type.
893 Constant *Op = CE->getOperand(0);
894 const Type *Ty = CE->getType();
896 // We can emit the pointer value into this slot if the slot is an
897 // integer slot greater or equal to the size of the pointer.
898 if (TD->getTypeAllocSize(Ty) >= TD->getTypeAllocSize(Op->getType()))
899 return EmitConstantValueOnly(Op);
902 EmitConstantValueOnly(Op);
903 APInt ptrMask = APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Ty));
906 ptrMask.toStringUnsigned(S);
907 O << ") & " << S.c_str() << ')';
910 case Instruction::Add:
911 case Instruction::Sub:
912 case Instruction::And:
913 case Instruction::Or:
914 case Instruction::Xor:
916 EmitConstantValueOnly(CE->getOperand(0));
919 case Instruction::Add:
922 case Instruction::Sub:
925 case Instruction::And:
928 case Instruction::Or:
931 case Instruction::Xor:
938 EmitConstantValueOnly(CE->getOperand(1));
942 llvm_unreachable("Unsupported operator!");
945 llvm_unreachable("Unknown constant value!");
949 /// printAsCString - Print the specified array as a C compatible string, only if
950 /// the predicate isString is true.
952 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
954 assert(CVA->isString() && "Array is not string compatible!");
957 for (unsigned i = 0; i != LastElt; ++i) {
959 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
960 printStringChar(O, C);
965 /// EmitString - Emit a zero-byte-terminated string constant.
967 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
968 unsigned NumElts = CVA->getNumOperands();
969 if (TAI->getAscizDirective() && NumElts &&
970 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
971 O << TAI->getAscizDirective();
972 printAsCString(O, CVA, NumElts-1);
974 O << TAI->getAsciiDirective();
975 printAsCString(O, CVA, NumElts);
980 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
981 unsigned AddrSpace) {
982 if (CVA->isString()) {
984 } else { // Not a string. Print the values in successive locations
985 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
986 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
990 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
991 const VectorType *PTy = CP->getType();
993 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
994 EmitGlobalConstant(CP->getOperand(I));
997 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
998 unsigned AddrSpace) {
999 // Print the fields in successive locations. Pad to align if needed!
1000 const TargetData *TD = TM.getTargetData();
1001 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1002 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1003 uint64_t sizeSoFar = 0;
1004 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1005 const Constant* field = CVS->getOperand(i);
1007 // Check if padding is needed and insert one or more 0s.
1008 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1009 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1010 - cvsLayout->getElementOffset(i)) - fieldSize;
1011 sizeSoFar += fieldSize + padSize;
1013 // Now print the actual field value.
1014 EmitGlobalConstant(field, AddrSpace);
1016 // Insert padding - this may include padding to increase the size of the
1017 // current field up to the ABI size (if the struct is not packed) as well
1018 // as padding to ensure that the next field starts at the right offset.
1019 EmitZeros(padSize, AddrSpace);
1021 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1022 "Layout of constant struct may be incorrect!");
1025 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1026 unsigned AddrSpace) {
1027 // FP Constants are printed as integer constants to avoid losing
1029 const TargetData *TD = TM.getTargetData();
1030 if (CFP->getType() == Type::DoubleTy) {
1031 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1032 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1033 if (TAI->getData64bitsDirective(AddrSpace)) {
1034 O << TAI->getData64bitsDirective(AddrSpace) << i;
1036 O << '\t' << TAI->getCommentString() << " double value: " << Val;
1038 } else if (TD->isBigEndian()) {
1039 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1041 O << '\t' << TAI->getCommentString()
1042 << " double most significant word " << Val;
1044 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1046 O << '\t' << TAI->getCommentString()
1047 << " double least significant word " << Val;
1050 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1052 O << '\t' << TAI->getCommentString()
1053 << " double least significant word " << Val;
1055 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1057 O << '\t' << TAI->getCommentString()
1058 << " double most significant word " << Val;
1062 } else if (CFP->getType() == Type::FloatTy) {
1063 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1064 O << TAI->getData32bitsDirective(AddrSpace)
1065 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1067 O << '\t' << TAI->getCommentString() << " float " << Val;
1070 } else if (CFP->getType() == Type::X86_FP80Ty) {
1071 // all long double variants are printed as hex
1072 // api needed to prevent premature destruction
1073 APInt api = CFP->getValueAPF().bitcastToAPInt();
1074 const uint64_t *p = api.getRawData();
1075 // Convert to double so we can print the approximate val as a comment.
1076 APFloat DoubleVal = CFP->getValueAPF();
1078 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1080 if (TD->isBigEndian()) {
1081 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1083 O << '\t' << TAI->getCommentString()
1084 << " long double most significant halfword of ~"
1085 << DoubleVal.convertToDouble();
1087 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1089 O << '\t' << TAI->getCommentString() << " long double next halfword";
1091 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1093 O << '\t' << TAI->getCommentString() << " long double next halfword";
1095 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1097 O << '\t' << TAI->getCommentString() << " long double next halfword";
1099 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1101 O << '\t' << TAI->getCommentString()
1102 << " long double least significant halfword";
1105 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1107 O << '\t' << TAI->getCommentString()
1108 << " long double least significant halfword of ~"
1109 << DoubleVal.convertToDouble();
1111 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1113 O << '\t' << TAI->getCommentString()
1114 << " long double next halfword";
1116 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1118 O << '\t' << TAI->getCommentString()
1119 << " long double next halfword";
1121 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1123 O << '\t' << TAI->getCommentString()
1124 << " long double next halfword";
1126 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1128 O << '\t' << TAI->getCommentString()
1129 << " long double most significant halfword";
1132 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) -
1133 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1135 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1136 // all long double variants are printed as hex
1137 // api needed to prevent premature destruction
1138 APInt api = CFP->getValueAPF().bitcastToAPInt();
1139 const uint64_t *p = api.getRawData();
1140 if (TD->isBigEndian()) {
1141 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1143 O << '\t' << TAI->getCommentString()
1144 << " long double most significant word";
1146 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1148 O << '\t' << TAI->getCommentString()
1149 << " long double next word";
1151 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1153 O << '\t' << TAI->getCommentString()
1154 << " long double next word";
1156 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1158 O << '\t' << TAI->getCommentString()
1159 << " long double least significant word";
1162 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1164 O << '\t' << TAI->getCommentString()
1165 << " long double least significant word";
1167 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1169 O << '\t' << TAI->getCommentString()
1170 << " long double next word";
1172 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1174 O << '\t' << TAI->getCommentString()
1175 << " long double next word";
1177 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1179 O << '\t' << TAI->getCommentString()
1180 << " long double most significant word";
1184 } else llvm_unreachable("Floating point constant type not handled");
1187 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1188 unsigned AddrSpace) {
1189 const TargetData *TD = TM.getTargetData();
1190 unsigned BitWidth = CI->getBitWidth();
1191 assert(isPowerOf2_32(BitWidth) &&
1192 "Non-power-of-2-sized integers not handled!");
1194 // We don't expect assemblers to support integer data directives
1195 // for more than 64 bits, so we emit the data in at most 64-bit
1196 // quantities at a time.
1197 const uint64_t *RawData = CI->getValue().getRawData();
1198 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1200 if (TD->isBigEndian())
1201 Val = RawData[e - i - 1];
1205 if (TAI->getData64bitsDirective(AddrSpace))
1206 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1207 else if (TD->isBigEndian()) {
1208 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1210 O << '\t' << TAI->getCommentString()
1211 << " Double-word most significant word " << Val;
1213 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1215 O << '\t' << TAI->getCommentString()
1216 << " Double-word least significant word " << Val;
1219 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1221 O << '\t' << TAI->getCommentString()
1222 << " Double-word least significant word " << Val;
1224 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1226 O << '\t' << TAI->getCommentString()
1227 << " Double-word most significant word " << Val;
1233 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1234 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1235 const TargetData *TD = TM.getTargetData();
1236 const Type *type = CV->getType();
1237 unsigned Size = TD->getTypeAllocSize(type);
1239 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1240 EmitZeros(Size, AddrSpace);
1242 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1243 EmitGlobalConstantArray(CVA , AddrSpace);
1245 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1246 EmitGlobalConstantStruct(CVS, AddrSpace);
1248 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1249 EmitGlobalConstantFP(CFP, AddrSpace);
1251 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1252 // Small integers are handled below; large integers are handled here.
1254 EmitGlobalConstantLargeInt(CI, AddrSpace);
1257 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1258 EmitGlobalConstantVector(CP);
1262 printDataDirective(type, AddrSpace);
1263 EmitConstantValueOnly(CV);
1265 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1267 CI->getValue().toStringUnsigned(S, 16);
1268 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1274 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1275 // Target doesn't support this yet!
1276 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1279 /// PrintSpecial - Print information related to the specified machine instr
1280 /// that is independent of the operand, and may be independent of the instr
1281 /// itself. This can be useful for portably encoding the comment character
1282 /// or other bits of target-specific knowledge into the asmstrings. The
1283 /// syntax used is ${:comment}. Targets can override this to add support
1284 /// for their own strange codes.
1285 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1286 if (!strcmp(Code, "private")) {
1287 O << TAI->getPrivateGlobalPrefix();
1288 } else if (!strcmp(Code, "comment")) {
1290 O << TAI->getCommentString();
1291 } else if (!strcmp(Code, "uid")) {
1292 // Comparing the address of MI isn't sufficient, because machineinstrs may
1293 // be allocated to the same address across functions.
1294 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1296 // If this is a new LastFn instruction, bump the counter.
1297 if (LastMI != MI || LastFn != ThisF) {
1305 raw_string_ostream Msg(msg);
1306 Msg << "Unknown special formatter '" << Code
1307 << "' for machine instr: " << *MI;
1308 llvm_report_error(Msg.str());
1312 /// processDebugLoc - Processes the debug information of each machine
1313 /// instruction's DebugLoc.
1314 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1315 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1316 if (!DL.isUnknown()) {
1317 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1319 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1320 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1321 DICompileUnit(CurDLT.CompileUnit)));
1328 /// printInlineAsm - This method formats and prints the specified machine
1329 /// instruction that is an inline asm.
1330 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1331 unsigned NumOperands = MI->getNumOperands();
1333 // Count the number of register definitions.
1334 unsigned NumDefs = 0;
1335 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1337 assert(NumDefs != NumOperands-1 && "No asm string?");
1339 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1341 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1342 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1344 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1345 // These are useful to see where empty asm's wound up.
1346 if (AsmStr[0] == 0) {
1347 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1351 O << TAI->getInlineAsmStart() << "\n\t";
1353 // The variant of the current asmprinter.
1354 int AsmPrinterVariant = TAI->getAssemblerDialect();
1356 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1357 const char *LastEmitted = AsmStr; // One past the last character emitted.
1359 while (*LastEmitted) {
1360 switch (*LastEmitted) {
1362 // Not a special case, emit the string section literally.
1363 const char *LiteralEnd = LastEmitted+1;
1364 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1365 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1367 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1368 O.write(LastEmitted, LiteralEnd-LastEmitted);
1369 LastEmitted = LiteralEnd;
1373 ++LastEmitted; // Consume newline character.
1374 O << '\n'; // Indent code with newline.
1377 ++LastEmitted; // Consume '$' character.
1381 switch (*LastEmitted) {
1382 default: Done = false; break;
1383 case '$': // $$ -> $
1384 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1386 ++LastEmitted; // Consume second '$' character.
1388 case '(': // $( -> same as GCC's { character.
1389 ++LastEmitted; // Consume '(' character.
1390 if (CurVariant != -1) {
1391 llvm_report_error("Nested variants found in inline asm string: '"
1392 + std::string(AsmStr) + "'");
1394 CurVariant = 0; // We're in the first variant now.
1397 ++LastEmitted; // consume '|' character.
1398 if (CurVariant == -1)
1399 O << '|'; // this is gcc's behavior for | outside a variant
1401 ++CurVariant; // We're in the next variant.
1403 case ')': // $) -> same as GCC's } char.
1404 ++LastEmitted; // consume ')' character.
1405 if (CurVariant == -1)
1406 O << '}'; // this is gcc's behavior for } outside a variant
1413 bool HasCurlyBraces = false;
1414 if (*LastEmitted == '{') { // ${variable}
1415 ++LastEmitted; // Consume '{' character.
1416 HasCurlyBraces = true;
1419 // If we have ${:foo}, then this is not a real operand reference, it is a
1420 // "magic" string reference, just like in .td files. Arrange to call
1422 if (HasCurlyBraces && *LastEmitted == ':') {
1424 const char *StrStart = LastEmitted;
1425 const char *StrEnd = strchr(StrStart, '}');
1427 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1428 + std::string(AsmStr) + "'");
1431 std::string Val(StrStart, StrEnd);
1432 PrintSpecial(MI, Val.c_str());
1433 LastEmitted = StrEnd+1;
1437 const char *IDStart = LastEmitted;
1440 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1441 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1442 llvm_report_error("Bad $ operand number in inline asm string: '"
1443 + std::string(AsmStr) + "'");
1445 LastEmitted = IDEnd;
1447 char Modifier[2] = { 0, 0 };
1449 if (HasCurlyBraces) {
1450 // If we have curly braces, check for a modifier character. This
1451 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1452 if (*LastEmitted == ':') {
1453 ++LastEmitted; // Consume ':' character.
1454 if (*LastEmitted == 0) {
1455 llvm_report_error("Bad ${:} expression in inline asm string: '"
1456 + std::string(AsmStr) + "'");
1459 Modifier[0] = *LastEmitted;
1460 ++LastEmitted; // Consume modifier character.
1463 if (*LastEmitted != '}') {
1464 llvm_report_error("Bad ${} expression in inline asm string: '"
1465 + std::string(AsmStr) + "'");
1467 ++LastEmitted; // Consume '}' character.
1470 if ((unsigned)Val >= NumOperands-1) {
1471 llvm_report_error("Invalid $ operand number in inline asm string: '"
1472 + std::string(AsmStr) + "'");
1475 // Okay, we finally have a value number. Ask the target to print this
1477 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1482 // Scan to find the machine operand number for the operand.
1483 for (; Val; --Val) {
1484 if (OpNo >= MI->getNumOperands()) break;
1485 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1486 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1489 if (OpNo >= MI->getNumOperands()) {
1492 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1493 ++OpNo; // Skip over the ID number.
1495 if (Modifier[0]=='l') // labels are target independent
1496 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1497 false, false, false);
1499 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1500 if ((OpFlags & 7) == 4) {
1501 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1502 Modifier[0] ? Modifier : 0);
1504 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1505 Modifier[0] ? Modifier : 0);
1511 raw_string_ostream Msg(msg);
1512 Msg << "Invalid operand found in inline asm: '"
1515 llvm_report_error(Msg.str());
1522 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1525 /// printImplicitDef - This method prints the specified machine instruction
1526 /// that is an implicit def.
1527 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1529 O << '\t' << TAI->getCommentString() << " implicit-def: "
1530 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1533 /// printLabel - This method prints a local label used by debug and
1534 /// exception handling tables.
1535 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1536 printLabel(MI->getOperand(0).getImm());
1539 void AsmPrinter::printLabel(unsigned Id) const {
1540 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1543 /// printDeclare - This method prints a local variable declaration used by
1545 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1546 /// entry into dwarf table.
1547 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1548 unsigned FI = MI->getOperand(0).getIndex();
1549 GlobalValue *GV = MI->getOperand(1).getGlobal();
1550 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1553 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1554 /// instruction, using the specified assembler variant. Targets should
1555 /// overried this to format as appropriate.
1556 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1557 unsigned AsmVariant, const char *ExtraCode) {
1558 // Target doesn't support this yet!
1562 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1563 unsigned AsmVariant,
1564 const char *ExtraCode) {
1565 // Target doesn't support this yet!
1569 /// printBasicBlockLabel - This method prints the label for the specified
1570 /// MachineBasicBlock
1571 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1574 bool printComment) const {
1576 unsigned Align = MBB->getAlignment();
1578 EmitAlignment(Log2_32(Align));
1581 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1582 << MBB->getNumber();
1585 if (printComment && MBB->getBasicBlock())
1586 O << '\t' << TAI->getCommentString() << ' '
1587 << MBB->getBasicBlock()->getNameStart();
1590 /// printPICJumpTableSetLabel - This method prints a set label for the
1591 /// specified MachineBasicBlock for a jumptable entry.
1592 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1593 const MachineBasicBlock *MBB) const {
1594 if (!TAI->getSetDirective())
1597 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1598 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1599 printBasicBlockLabel(MBB, false, false, false);
1600 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1601 << '_' << uid << '\n';
1604 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1605 const MachineBasicBlock *MBB) const {
1606 if (!TAI->getSetDirective())
1609 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1610 << getFunctionNumber() << '_' << uid << '_' << uid2
1611 << "_set_" << MBB->getNumber() << ',';
1612 printBasicBlockLabel(MBB, false, false, false);
1613 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1614 << '_' << uid << '_' << uid2 << '\n';
1617 /// printDataDirective - This method prints the asm directive for the
1619 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1620 const TargetData *TD = TM.getTargetData();
1621 switch (type->getTypeID()) {
1622 case Type::FloatTyID: case Type::DoubleTyID:
1623 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1624 assert(0 && "Should have already output floating point constant.");
1626 assert(0 && "Can't handle printing this type of thing");
1627 case Type::IntegerTyID: {
1628 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1630 O << TAI->getData8bitsDirective(AddrSpace);
1631 else if (BitWidth <= 16)
1632 O << TAI->getData16bitsDirective(AddrSpace);
1633 else if (BitWidth <= 32)
1634 O << TAI->getData32bitsDirective(AddrSpace);
1635 else if (BitWidth <= 64) {
1636 assert(TAI->getData64bitsDirective(AddrSpace) &&
1637 "Target cannot handle 64-bit constant exprs!");
1638 O << TAI->getData64bitsDirective(AddrSpace);
1640 llvm_unreachable("Target cannot handle given data directive width!");
1644 case Type::PointerTyID:
1645 if (TD->getPointerSize() == 8) {
1646 assert(TAI->getData64bitsDirective(AddrSpace) &&
1647 "Target cannot handle 64-bit pointer exprs!");
1648 O << TAI->getData64bitsDirective(AddrSpace);
1649 } else if (TD->getPointerSize() == 2) {
1650 O << TAI->getData16bitsDirective(AddrSpace);
1651 } else if (TD->getPointerSize() == 1) {
1652 O << TAI->getData8bitsDirective(AddrSpace);
1654 O << TAI->getData32bitsDirective(AddrSpace);
1660 void AsmPrinter::printVisibility(const std::string& Name,
1661 unsigned Visibility) const {
1662 if (Visibility == GlobalValue::HiddenVisibility) {
1663 if (const char *Directive = TAI->getHiddenDirective())
1664 O << Directive << Name << '\n';
1665 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1666 if (const char *Directive = TAI->getProtectedDirective())
1667 O << Directive << Name << '\n';
1671 void AsmPrinter::printOffset(int64_t Offset) const {
1674 else if (Offset < 0)
1678 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1679 if (!S->usesMetadata())
1682 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1683 if (GCPI != GCMetadataPrinters.end())
1684 return GCPI->second;
1686 const char *Name = S->getName().c_str();
1688 for (GCMetadataPrinterRegistry::iterator
1689 I = GCMetadataPrinterRegistry::begin(),
1690 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1691 if (strcmp(Name, I->getName()) == 0) {
1692 GCMetadataPrinter *GMP = I->instantiate();
1694 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1698 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1699 llvm_unreachable(0);
1702 /// EmitComments - Pretty-print comments for instructions
1703 void AsmPrinter::EmitComments(const MachineInstr &MI) const
1705 if (!MI.getDebugLoc().isUnknown()) {
1706 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1708 // Print source line info
1709 O.PadToColumn(TAI->getCommentColumn(), 1);
1710 O << TAI->getCommentString() << " SrcLine " << DLT.Line << ":" << DLT.Col;
1714 /// EmitComments - Pretty-print comments for instructions
1715 void AsmPrinter::EmitComments(const MCInst &MI) const
1717 if (!MI.getDebugLoc().isUnknown()) {
1718 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1720 // Print source line info
1721 O.PadToColumn(TAI->getCommentColumn(), 1);
1722 O << TAI->getCommentString() << " SrcLine " << DLT.Line << ":" << DLT.Col;