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)),
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) {
101 // If we're already in this section, we're done.
102 if (CurrentSection == NS) return;
108 NS->PrintSwitchToSection(*TAI, O);
111 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
112 AU.setPreservesAll();
113 MachineFunctionPass::getAnalysisUsage(AU);
114 AU.addRequired<GCModuleInfo>();
116 AU.addRequired<MachineLoopInfo>();
120 bool AsmPrinter::doInitialization(Module &M) {
121 // Initialize TargetLoweringObjectFile.
122 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
123 .Initialize(OutContext, TM);
125 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(),
126 TAI->getLinkerPrivateGlobalPrefix());
128 if (TAI->doesAllowQuotesInName())
129 Mang->setUseQuotes(true);
131 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
132 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
134 if (TAI->hasSingleParameterDotFile()) {
135 /* Very minimal debug info. It is ignored if we emit actual
136 debug info. If we don't, this at helps the user find where
137 a function came from. */
138 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
141 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
142 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
143 MP->beginAssembly(O, *this, *TAI);
145 if (!M.getModuleInlineAsm().empty())
146 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
147 << M.getModuleInlineAsm()
148 << '\n' << TAI->getCommentString()
149 << " End of file scope inline assembly\n";
151 SwitchToSection(0); // Reset back to no section to close off sections.
153 if (TAI->doesSupportDebugInformation() ||
154 TAI->doesSupportExceptionHandling()) {
155 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
157 MMI->AnalyzeModule(M);
158 DW = getAnalysisIfAvailable<DwarfWriter>();
160 DW->BeginModule(&M, MMI, O, this, TAI);
166 bool AsmPrinter::doFinalization(Module &M) {
167 // Emit global variables.
168 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
170 PrintGlobalVariable(I);
172 // Emit final debug information.
173 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
176 // If the target wants to know about weak references, print them all.
177 if (TAI->getWeakRefDirective()) {
178 // FIXME: This is not lazy, it would be nice to only print weak references
179 // to stuff that is actually used. Note that doing so would require targets
180 // to notice uses in operands (due to constant exprs etc). This should
181 // happen with the MC stuff eventually.
184 // Print out module-level global variables here.
185 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
187 if (I->hasExternalWeakLinkage())
188 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
191 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
192 if (I->hasExternalWeakLinkage())
193 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
197 if (TAI->getSetDirective()) {
199 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
201 std::string Name = Mang->getMangledName(I);
203 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
204 std::string Target = Mang->getMangledName(GV);
206 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
207 O << "\t.globl\t" << Name << '\n';
208 else if (I->hasWeakLinkage())
209 O << TAI->getWeakRefDirective() << Name << '\n';
210 else if (!I->hasLocalLinkage())
211 llvm_unreachable("Invalid alias linkage");
213 printVisibility(Name, I->getVisibility());
215 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
219 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
220 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
221 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
222 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
223 MP->finishAssembly(O, *this, *TAI);
225 // If we don't have any trampolines, then we don't require stack memory
226 // to be executable. Some targets have a directive to declare this.
227 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
228 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
229 if (TAI->getNonexecutableStackDirective())
230 O << TAI->getNonexecutableStackDirective() << '\n';
232 delete Mang; Mang = 0;
235 OutStreamer.Finish();
240 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
241 assert(MF && "No machine function?");
242 return Mang->getMangledName(MF->getFunction(), ".eh",
243 TAI->is_EHSymbolPrivate());
246 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
247 // What's my mangled name?
248 CurrentFnName = Mang->getMangledName(MF.getFunction());
249 IncrementFunctionNumber();
252 LI = &getAnalysis<MachineLoopInfo>();
257 // SectionCPs - Keep track the alignment, constpool entries per Section.
261 SmallVector<unsigned, 4> CPEs;
262 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
266 /// EmitConstantPool - Print to the current output stream assembly
267 /// representations of the constants in the constant pool MCP. This is
268 /// used to print out constants which have been "spilled to memory" by
269 /// the code generator.
271 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
272 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
273 if (CP.empty()) return;
275 // Calculate sections for constant pool entries. We collect entries to go into
276 // the same section together to reduce amount of section switch statements.
277 SmallVector<SectionCPs, 4> CPSections;
278 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
279 const MachineConstantPoolEntry &CPE = CP[i];
280 unsigned Align = CPE.getAlignment();
283 switch (CPE.getRelocationInfo()) {
284 default: llvm_unreachable("Unknown section kind");
285 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
287 Kind = SectionKind::getReadOnlyWithRelLocal();
290 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
291 case 4: Kind = SectionKind::getMergeableConst4(); break;
292 case 8: Kind = SectionKind::getMergeableConst8(); break;
293 case 16: Kind = SectionKind::getMergeableConst16();break;
294 default: Kind = SectionKind::getMergeableConst(); break;
298 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
300 // The number of sections are small, just do a linear search from the
301 // last section to the first.
303 unsigned SecIdx = CPSections.size();
304 while (SecIdx != 0) {
305 if (CPSections[--SecIdx].S == S) {
311 SecIdx = CPSections.size();
312 CPSections.push_back(SectionCPs(S, Align));
315 if (Align > CPSections[SecIdx].Alignment)
316 CPSections[SecIdx].Alignment = Align;
317 CPSections[SecIdx].CPEs.push_back(i);
320 // Now print stuff into the calculated sections.
321 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
322 SwitchToSection(CPSections[i].S);
323 EmitAlignment(Log2_32(CPSections[i].Alignment));
326 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
327 unsigned CPI = CPSections[i].CPEs[j];
328 MachineConstantPoolEntry CPE = CP[CPI];
330 // Emit inter-object padding for alignment.
331 unsigned AlignMask = CPE.getAlignment() - 1;
332 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
333 EmitZeros(NewOffset - Offset);
335 const Type *Ty = CPE.getType();
336 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
338 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
339 << CPI << ":\t\t\t\t\t";
341 O << TAI->getCommentString() << ' ';
342 WriteTypeSymbolic(O, CPE.getType(), 0);
345 if (CPE.isMachineConstantPoolEntry())
346 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
348 EmitGlobalConstant(CPE.Val.ConstVal);
353 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
354 /// by the current function to the current output stream.
356 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
357 MachineFunction &MF) {
358 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
359 if (JT.empty()) return;
361 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
363 // Pick the directive to use to print the jump table entries, and switch to
364 // the appropriate section.
365 TargetLowering *LoweringInfo = TM.getTargetLowering();
367 const Function *F = MF.getFunction();
368 bool JTInDiffSection = false;
369 if (F->isWeakForLinker() ||
370 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
371 // In PIC mode, we need to emit the jump table to the same section as the
372 // function body itself, otherwise the label differences won't make sense.
373 // We should also do if the section name is NULL or function is declared in
374 // discardable section.
375 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
377 // Otherwise, drop it in the readonly section.
378 const MCSection *ReadOnlySection =
379 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
380 SwitchToSection(ReadOnlySection);
381 JTInDiffSection = true;
384 EmitAlignment(Log2_32(MJTI->getAlignment()));
386 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
387 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
389 // If this jump table was deleted, ignore it.
390 if (JTBBs.empty()) continue;
392 // For PIC codegen, if possible we want to use the SetDirective to reduce
393 // the number of relocations the assembler will generate for the jump table.
394 // Set directives are all printed before the jump table itself.
395 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
396 if (TAI->getSetDirective() && IsPic)
397 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
398 if (EmittedSets.insert(JTBBs[ii]))
399 printPICJumpTableSetLabel(i, JTBBs[ii]);
401 // On some targets (e.g. darwin) we want to emit two consequtive labels
402 // before each jump table. The first label is never referenced, but tells
403 // the assembler and linker the extents of the jump table object. The
404 // second label is actually referenced by the code.
405 if (JTInDiffSection) {
406 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
407 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
410 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
411 << '_' << i << ":\n";
413 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
414 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
420 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
421 const MachineBasicBlock *MBB,
422 unsigned uid) const {
423 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
425 // Use JumpTableDirective otherwise honor the entry size from the jump table
427 const char *JTEntryDirective = TAI->getJumpTableDirective();
428 bool HadJTEntryDirective = JTEntryDirective != NULL;
429 if (!HadJTEntryDirective) {
430 JTEntryDirective = MJTI->getEntrySize() == 4 ?
431 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
434 O << JTEntryDirective << ' ';
436 // If we have emitted set directives for the jump table entries, print
437 // them rather than the entries themselves. If we're emitting PIC, then
438 // emit the table entries as differences between two text section labels.
439 // If we're emitting non-PIC code, then emit the entries as direct
440 // references to the target basic blocks.
442 if (TAI->getSetDirective()) {
443 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
444 << '_' << uid << "_set_" << MBB->getNumber();
446 printBasicBlockLabel(MBB, false, false, false);
447 // If the arch uses custom Jump Table directives, don't calc relative to
449 if (!HadJTEntryDirective)
450 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
451 << getFunctionNumber() << '_' << uid;
454 printBasicBlockLabel(MBB, false, false, false);
459 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
460 /// special global used by LLVM. If so, emit it and return true, otherwise
461 /// do nothing and return false.
462 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
463 if (GV->getName() == "llvm.used") {
464 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
465 EmitLLVMUsedList(GV->getInitializer());
469 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
470 if (GV->getSection() == "llvm.metadata" ||
471 GV->hasAvailableExternallyLinkage())
474 if (!GV->hasAppendingLinkage()) return false;
476 assert(GV->hasInitializer() && "Not a special LLVM global!");
478 const TargetData *TD = TM.getTargetData();
479 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
480 if (GV->getName() == "llvm.global_ctors") {
481 SwitchToSection(getObjFileLowering().getStaticCtorSection());
482 EmitAlignment(Align, 0);
483 EmitXXStructorList(GV->getInitializer());
487 if (GV->getName() == "llvm.global_dtors") {
488 SwitchToSection(getObjFileLowering().getStaticDtorSection());
489 EmitAlignment(Align, 0);
490 EmitXXStructorList(GV->getInitializer());
497 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
498 /// global in the specified llvm.used list for which emitUsedDirectiveFor
499 /// is true, as being used with this directive.
500 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
501 const char *Directive = TAI->getUsedDirective();
503 // Should be an array of 'i8*'.
504 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
505 if (InitList == 0) return;
507 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
508 const GlobalValue *GV =
509 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
510 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
512 EmitConstantValueOnly(InitList->getOperand(i));
518 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
519 /// function pointers, ignoring the init priority.
520 void AsmPrinter::EmitXXStructorList(Constant *List) {
521 // Should be an array of '{ int, void ()* }' structs. The first value is the
522 // init priority, which we ignore.
523 if (!isa<ConstantArray>(List)) return;
524 ConstantArray *InitList = cast<ConstantArray>(List);
525 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
526 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
527 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
529 if (CS->getOperand(1)->isNullValue())
530 return; // Found a null terminator, exit printing.
531 // Emit the function pointer.
532 EmitGlobalConstant(CS->getOperand(1));
536 /// getGlobalLinkName - Returns the asm/link name of of the specified
537 /// global variable. Should be overridden by each target asm printer to
538 /// generate the appropriate value.
539 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
540 std::string &LinkName) const {
541 if (isa<Function>(GV)) {
542 LinkName += TAI->getFunctionAddrPrefix();
543 LinkName += Mang->getMangledName(GV);
544 LinkName += TAI->getFunctionAddrSuffix();
546 LinkName += TAI->getGlobalVarAddrPrefix();
547 LinkName += Mang->getMangledName(GV);
548 LinkName += TAI->getGlobalVarAddrSuffix();
554 /// EmitExternalGlobal - Emit the external reference to a global variable.
555 /// Should be overridden if an indirect reference should be used.
556 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
558 O << getGlobalLinkName(GV, GLN);
563 //===----------------------------------------------------------------------===//
564 /// LEB 128 number encoding.
566 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
567 /// representing an unsigned leb128 value.
568 void AsmPrinter::PrintULEB128(unsigned Value) const {
571 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
573 if (Value) Byte |= 0x80;
574 O << "0x" << utohex_buffer(Byte, Buffer+20);
575 if (Value) O << ", ";
579 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
580 /// representing a signed leb128 value.
581 void AsmPrinter::PrintSLEB128(int Value) const {
582 int Sign = Value >> (8 * sizeof(Value) - 1);
587 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
589 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
590 if (IsMore) Byte |= 0x80;
591 O << "0x" << utohex_buffer(Byte, Buffer+20);
592 if (IsMore) O << ", ";
596 //===--------------------------------------------------------------------===//
597 // Emission and print routines
600 /// PrintHex - Print a value as a hexidecimal value.
602 void AsmPrinter::PrintHex(int Value) const {
604 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
607 /// EOL - Print a newline character to asm stream. If a comment is present
608 /// then it will be printed first. Comments should not contain '\n'.
609 void AsmPrinter::EOL() const {
613 void AsmPrinter::EOL(const std::string &Comment) const {
614 if (VerboseAsm && !Comment.empty()) {
616 << TAI->getCommentString()
623 void AsmPrinter::EOL(const char* Comment) const {
624 if (VerboseAsm && *Comment) {
626 << TAI->getCommentString()
633 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
634 /// unsigned leb128 value.
635 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
636 if (TAI->hasLEB128()) {
640 O << TAI->getData8bitsDirective();
645 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
646 /// signed leb128 value.
647 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
648 if (TAI->hasLEB128()) {
652 O << TAI->getData8bitsDirective();
657 /// EmitInt8 - Emit a byte directive and value.
659 void AsmPrinter::EmitInt8(int Value) const {
660 O << TAI->getData8bitsDirective();
661 PrintHex(Value & 0xFF);
664 /// EmitInt16 - Emit a short directive and value.
666 void AsmPrinter::EmitInt16(int Value) const {
667 O << TAI->getData16bitsDirective();
668 PrintHex(Value & 0xFFFF);
671 /// EmitInt32 - Emit a long directive and value.
673 void AsmPrinter::EmitInt32(int Value) const {
674 O << TAI->getData32bitsDirective();
678 /// EmitInt64 - Emit a long long directive and value.
680 void AsmPrinter::EmitInt64(uint64_t Value) const {
681 if (TAI->getData64bitsDirective()) {
682 O << TAI->getData64bitsDirective();
685 if (TM.getTargetData()->isBigEndian()) {
686 EmitInt32(unsigned(Value >> 32)); O << '\n';
687 EmitInt32(unsigned(Value));
689 EmitInt32(unsigned(Value)); O << '\n';
690 EmitInt32(unsigned(Value >> 32));
695 /// toOctal - Convert the low order bits of X into an octal digit.
697 static inline char toOctal(int X) {
701 /// printStringChar - Print a char, escaped if necessary.
703 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
706 } else if (C == '\\') {
708 } else if (isprint((unsigned char)C)) {
712 case '\b': O << "\\b"; break;
713 case '\f': O << "\\f"; break;
714 case '\n': O << "\\n"; break;
715 case '\r': O << "\\r"; break;
716 case '\t': O << "\\t"; break;
719 O << toOctal(C >> 6);
720 O << toOctal(C >> 3);
721 O << toOctal(C >> 0);
727 /// EmitString - Emit a string with quotes and a null terminator.
728 /// Special characters are emitted properly.
729 /// \literal (Eg. '\t') \endliteral
730 void AsmPrinter::EmitString(const std::string &String) const {
731 EmitString(String.c_str(), String.size());
734 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
735 const char* AscizDirective = TAI->getAscizDirective();
739 O << TAI->getAsciiDirective();
741 for (unsigned i = 0; i < Size; ++i)
742 printStringChar(O, String[i]);
750 /// EmitFile - Emit a .file directive.
751 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
752 O << "\t.file\t" << Number << " \"";
753 for (unsigned i = 0, N = Name.size(); i < N; ++i)
754 printStringChar(O, Name[i]);
759 //===----------------------------------------------------------------------===//
761 // EmitAlignment - Emit an alignment directive to the specified power of
762 // two boundary. For example, if you pass in 3 here, you will get an 8
763 // byte alignment. If a global value is specified, and if that global has
764 // an explicit alignment requested, it will unconditionally override the
765 // alignment request. However, if ForcedAlignBits is specified, this value
766 // has final say: the ultimate alignment will be the max of ForcedAlignBits
767 // and the alignment computed with NumBits and the global.
771 // if (GV && GV->hasalignment) Align = GV->getalignment();
772 // Align = std::max(Align, ForcedAlignBits);
774 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
775 unsigned ForcedAlignBits,
776 bool UseFillExpr) const {
777 if (GV && GV->getAlignment())
778 NumBits = Log2_32(GV->getAlignment());
779 NumBits = std::max(NumBits, ForcedAlignBits);
781 if (NumBits == 0) return; // No need to emit alignment.
782 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
783 O << TAI->getAlignDirective() << NumBits;
785 if (CurrentSection && CurrentSection->getKind().isText())
786 if (unsigned FillValue = TAI->getTextAlignFillValue()) {
793 /// EmitZeros - Emit a block of zeros.
795 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
797 if (TAI->getZeroDirective()) {
798 O << TAI->getZeroDirective() << NumZeros;
799 if (TAI->getZeroDirectiveSuffix())
800 O << TAI->getZeroDirectiveSuffix();
803 for (; NumZeros; --NumZeros)
804 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
809 // Print out the specified constant, without a storage class. Only the
810 // constants valid in constant expressions can occur here.
811 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
812 if (CV->isNullValue() || isa<UndefValue>(CV))
814 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
815 O << CI->getZExtValue();
816 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
817 // This is a constant address for a global variable or function. Use the
818 // name of the variable or function as the address value, possibly
819 // decorating it with GlobalVarAddrPrefix/Suffix or
820 // FunctionAddrPrefix/Suffix (these all default to "" )
821 if (isa<Function>(GV)) {
822 O << TAI->getFunctionAddrPrefix()
823 << Mang->getMangledName(GV)
824 << TAI->getFunctionAddrSuffix();
826 O << TAI->getGlobalVarAddrPrefix()
827 << Mang->getMangledName(GV)
828 << TAI->getGlobalVarAddrSuffix();
830 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
831 const TargetData *TD = TM.getTargetData();
832 unsigned Opcode = CE->getOpcode();
834 case Instruction::Trunc:
835 case Instruction::ZExt:
836 case Instruction::SExt:
837 case Instruction::FPTrunc:
838 case Instruction::FPExt:
839 case Instruction::UIToFP:
840 case Instruction::SIToFP:
841 case Instruction::FPToUI:
842 case Instruction::FPToSI:
843 llvm_unreachable("FIXME: Don't support this constant cast expr");
844 case Instruction::GetElementPtr: {
845 // generate a symbolic expression for the byte address
846 const Constant *ptrVal = CE->getOperand(0);
847 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
848 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
850 // Truncate/sext the offset to the pointer size.
851 if (TD->getPointerSizeInBits() != 64) {
852 int SExtAmount = 64-TD->getPointerSizeInBits();
853 Offset = (Offset << SExtAmount) >> SExtAmount;
858 EmitConstantValueOnly(ptrVal);
860 O << ") + " << Offset;
862 O << ") - " << -Offset;
864 EmitConstantValueOnly(ptrVal);
868 case Instruction::BitCast:
869 return EmitConstantValueOnly(CE->getOperand(0));
871 case Instruction::IntToPtr: {
872 // Handle casts to pointers by changing them into casts to the appropriate
873 // integer type. This promotes constant folding and simplifies this code.
874 Constant *Op = CE->getOperand(0);
875 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
876 return EmitConstantValueOnly(Op);
880 case Instruction::PtrToInt: {
881 // Support only foldable casts to/from pointers that can be eliminated by
882 // changing the pointer to the appropriately sized integer type.
883 Constant *Op = CE->getOperand(0);
884 const Type *Ty = CE->getType();
886 // We can emit the pointer value into this slot if the slot is an
887 // integer slot greater or equal to the size of the pointer.
888 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
889 return EmitConstantValueOnly(Op);
892 EmitConstantValueOnly(Op);
894 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
897 ptrMask.toStringUnsigned(S);
898 O << ") & " << S.c_str() << ')';
901 case Instruction::Add:
902 case Instruction::Sub:
903 case Instruction::And:
904 case Instruction::Or:
905 case Instruction::Xor:
907 EmitConstantValueOnly(CE->getOperand(0));
910 case Instruction::Add:
913 case Instruction::Sub:
916 case Instruction::And:
919 case Instruction::Or:
922 case Instruction::Xor:
929 EmitConstantValueOnly(CE->getOperand(1));
933 llvm_unreachable("Unsupported operator!");
936 llvm_unreachable("Unknown constant value!");
940 /// printAsCString - Print the specified array as a C compatible string, only if
941 /// the predicate isString is true.
943 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
945 assert(CVA->isString() && "Array is not string compatible!");
948 for (unsigned i = 0; i != LastElt; ++i) {
950 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
951 printStringChar(O, C);
956 /// EmitString - Emit a zero-byte-terminated string constant.
958 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
959 unsigned NumElts = CVA->getNumOperands();
960 if (TAI->getAscizDirective() && NumElts &&
961 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
962 O << TAI->getAscizDirective();
963 printAsCString(O, CVA, NumElts-1);
965 O << TAI->getAsciiDirective();
966 printAsCString(O, CVA, NumElts);
971 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
972 unsigned AddrSpace) {
973 if (CVA->isString()) {
975 } else { // Not a string. Print the values in successive locations
976 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
977 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
981 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
982 const VectorType *PTy = CP->getType();
984 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
985 EmitGlobalConstant(CP->getOperand(I));
988 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
989 unsigned AddrSpace) {
990 // Print the fields in successive locations. Pad to align if needed!
991 const TargetData *TD = TM.getTargetData();
992 unsigned Size = TD->getTypeAllocSize(CVS->getType());
993 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
994 uint64_t sizeSoFar = 0;
995 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
996 const Constant* field = CVS->getOperand(i);
998 // Check if padding is needed and insert one or more 0s.
999 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1000 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1001 - cvsLayout->getElementOffset(i)) - fieldSize;
1002 sizeSoFar += fieldSize + padSize;
1004 // Now print the actual field value.
1005 EmitGlobalConstant(field, AddrSpace);
1007 // Insert padding - this may include padding to increase the size of the
1008 // current field up to the ABI size (if the struct is not packed) as well
1009 // as padding to ensure that the next field starts at the right offset.
1010 EmitZeros(padSize, AddrSpace);
1012 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1013 "Layout of constant struct may be incorrect!");
1016 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1017 unsigned AddrSpace) {
1018 // FP Constants are printed as integer constants to avoid losing
1020 const TargetData *TD = TM.getTargetData();
1021 if (CFP->getType() == Type::DoubleTy) {
1022 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1023 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1024 if (TAI->getData64bitsDirective(AddrSpace)) {
1025 O << TAI->getData64bitsDirective(AddrSpace) << i;
1027 O << '\t' << TAI->getCommentString() << " double value: " << Val;
1029 } else if (TD->isBigEndian()) {
1030 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1032 O << '\t' << TAI->getCommentString()
1033 << " double most significant word " << Val;
1035 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1037 O << '\t' << TAI->getCommentString()
1038 << " double least significant word " << Val;
1041 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1043 O << '\t' << TAI->getCommentString()
1044 << " double least significant word " << Val;
1046 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1048 O << '\t' << TAI->getCommentString()
1049 << " double most significant word " << Val;
1053 } else if (CFP->getType() == Type::FloatTy) {
1054 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1055 O << TAI->getData32bitsDirective(AddrSpace)
1056 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1058 O << '\t' << TAI->getCommentString() << " float " << Val;
1061 } else if (CFP->getType() == Type::X86_FP80Ty) {
1062 // all long double variants are printed as hex
1063 // api needed to prevent premature destruction
1064 APInt api = CFP->getValueAPF().bitcastToAPInt();
1065 const uint64_t *p = api.getRawData();
1066 // Convert to double so we can print the approximate val as a comment.
1067 APFloat DoubleVal = CFP->getValueAPF();
1069 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1071 if (TD->isBigEndian()) {
1072 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1074 O << '\t' << TAI->getCommentString()
1075 << " long double most significant halfword of ~"
1076 << DoubleVal.convertToDouble();
1078 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1080 O << '\t' << TAI->getCommentString() << " long double next halfword";
1082 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1084 O << '\t' << TAI->getCommentString() << " long double next halfword";
1086 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1088 O << '\t' << TAI->getCommentString() << " long double next halfword";
1090 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1092 O << '\t' << TAI->getCommentString()
1093 << " long double least significant halfword";
1096 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1098 O << '\t' << TAI->getCommentString()
1099 << " long double least significant halfword of ~"
1100 << DoubleVal.convertToDouble();
1102 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1104 O << '\t' << TAI->getCommentString()
1105 << " long double next halfword";
1107 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1109 O << '\t' << TAI->getCommentString()
1110 << " long double next halfword";
1112 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1114 O << '\t' << TAI->getCommentString()
1115 << " long double next halfword";
1117 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1119 O << '\t' << TAI->getCommentString()
1120 << " long double most significant halfword";
1123 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) -
1124 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1126 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1127 // all long double variants are printed as hex
1128 // api needed to prevent premature destruction
1129 APInt api = CFP->getValueAPF().bitcastToAPInt();
1130 const uint64_t *p = api.getRawData();
1131 if (TD->isBigEndian()) {
1132 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1134 O << '\t' << TAI->getCommentString()
1135 << " long double most significant word";
1137 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1139 O << '\t' << TAI->getCommentString()
1140 << " long double next word";
1142 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1144 O << '\t' << TAI->getCommentString()
1145 << " long double next word";
1147 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1149 O << '\t' << TAI->getCommentString()
1150 << " long double least significant word";
1153 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1155 O << '\t' << TAI->getCommentString()
1156 << " long double least significant word";
1158 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1160 O << '\t' << TAI->getCommentString()
1161 << " long double next word";
1163 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1165 O << '\t' << TAI->getCommentString()
1166 << " long double next word";
1168 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1170 O << '\t' << TAI->getCommentString()
1171 << " long double most significant word";
1175 } else llvm_unreachable("Floating point constant type not handled");
1178 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1179 unsigned AddrSpace) {
1180 const TargetData *TD = TM.getTargetData();
1181 unsigned BitWidth = CI->getBitWidth();
1182 assert(isPowerOf2_32(BitWidth) &&
1183 "Non-power-of-2-sized integers not handled!");
1185 // We don't expect assemblers to support integer data directives
1186 // for more than 64 bits, so we emit the data in at most 64-bit
1187 // quantities at a time.
1188 const uint64_t *RawData = CI->getValue().getRawData();
1189 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1191 if (TD->isBigEndian())
1192 Val = RawData[e - i - 1];
1196 if (TAI->getData64bitsDirective(AddrSpace))
1197 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1198 else if (TD->isBigEndian()) {
1199 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1201 O << '\t' << TAI->getCommentString()
1202 << " Double-word most significant word " << Val;
1204 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1206 O << '\t' << TAI->getCommentString()
1207 << " Double-word least significant word " << Val;
1210 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1212 O << '\t' << TAI->getCommentString()
1213 << " Double-word least significant word " << Val;
1215 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1217 O << '\t' << TAI->getCommentString()
1218 << " Double-word most significant word " << Val;
1224 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1225 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1226 const TargetData *TD = TM.getTargetData();
1227 const Type *type = CV->getType();
1228 unsigned Size = TD->getTypeAllocSize(type);
1230 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1231 EmitZeros(Size, AddrSpace);
1233 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1234 EmitGlobalConstantArray(CVA , AddrSpace);
1236 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1237 EmitGlobalConstantStruct(CVS, AddrSpace);
1239 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1240 EmitGlobalConstantFP(CFP, AddrSpace);
1242 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1243 // Small integers are handled below; large integers are handled here.
1245 EmitGlobalConstantLargeInt(CI, AddrSpace);
1248 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1249 EmitGlobalConstantVector(CP);
1253 printDataDirective(type, AddrSpace);
1254 EmitConstantValueOnly(CV);
1256 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1258 CI->getValue().toStringUnsigned(S, 16);
1259 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1265 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1266 // Target doesn't support this yet!
1267 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1270 /// PrintSpecial - Print information related to the specified machine instr
1271 /// that is independent of the operand, and may be independent of the instr
1272 /// itself. This can be useful for portably encoding the comment character
1273 /// or other bits of target-specific knowledge into the asmstrings. The
1274 /// syntax used is ${:comment}. Targets can override this to add support
1275 /// for their own strange codes.
1276 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1277 if (!strcmp(Code, "private")) {
1278 O << TAI->getPrivateGlobalPrefix();
1279 } else if (!strcmp(Code, "comment")) {
1281 O << TAI->getCommentString();
1282 } else if (!strcmp(Code, "uid")) {
1283 // Comparing the address of MI isn't sufficient, because machineinstrs may
1284 // be allocated to the same address across functions.
1285 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1287 // If this is a new LastFn instruction, bump the counter.
1288 if (LastMI != MI || LastFn != ThisF) {
1296 raw_string_ostream Msg(msg);
1297 Msg << "Unknown special formatter '" << Code
1298 << "' for machine instr: " << *MI;
1299 llvm_report_error(Msg.str());
1303 /// processDebugLoc - Processes the debug information of each machine
1304 /// instruction's DebugLoc.
1305 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1309 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1310 if (!DL.isUnknown()) {
1311 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1313 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1314 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1315 DICompileUnit(CurDLT.CompileUnit)));
1322 /// printInlineAsm - This method formats and prints the specified machine
1323 /// instruction that is an inline asm.
1324 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1325 unsigned NumOperands = MI->getNumOperands();
1327 // Count the number of register definitions.
1328 unsigned NumDefs = 0;
1329 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1331 assert(NumDefs != NumOperands-1 && "No asm string?");
1333 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1335 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1336 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1338 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1339 // These are useful to see where empty asm's wound up.
1340 if (AsmStr[0] == 0) {
1341 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1345 O << TAI->getInlineAsmStart() << "\n\t";
1347 // The variant of the current asmprinter.
1348 int AsmPrinterVariant = TAI->getAssemblerDialect();
1350 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1351 const char *LastEmitted = AsmStr; // One past the last character emitted.
1353 while (*LastEmitted) {
1354 switch (*LastEmitted) {
1356 // Not a special case, emit the string section literally.
1357 const char *LiteralEnd = LastEmitted+1;
1358 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1359 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1361 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1362 O.write(LastEmitted, LiteralEnd-LastEmitted);
1363 LastEmitted = LiteralEnd;
1367 ++LastEmitted; // Consume newline character.
1368 O << '\n'; // Indent code with newline.
1371 ++LastEmitted; // Consume '$' character.
1375 switch (*LastEmitted) {
1376 default: Done = false; break;
1377 case '$': // $$ -> $
1378 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1380 ++LastEmitted; // Consume second '$' character.
1382 case '(': // $( -> same as GCC's { character.
1383 ++LastEmitted; // Consume '(' character.
1384 if (CurVariant != -1) {
1385 llvm_report_error("Nested variants found in inline asm string: '"
1386 + std::string(AsmStr) + "'");
1388 CurVariant = 0; // We're in the first variant now.
1391 ++LastEmitted; // consume '|' character.
1392 if (CurVariant == -1)
1393 O << '|'; // this is gcc's behavior for | outside a variant
1395 ++CurVariant; // We're in the next variant.
1397 case ')': // $) -> same as GCC's } char.
1398 ++LastEmitted; // consume ')' character.
1399 if (CurVariant == -1)
1400 O << '}'; // this is gcc's behavior for } outside a variant
1407 bool HasCurlyBraces = false;
1408 if (*LastEmitted == '{') { // ${variable}
1409 ++LastEmitted; // Consume '{' character.
1410 HasCurlyBraces = true;
1413 // If we have ${:foo}, then this is not a real operand reference, it is a
1414 // "magic" string reference, just like in .td files. Arrange to call
1416 if (HasCurlyBraces && *LastEmitted == ':') {
1418 const char *StrStart = LastEmitted;
1419 const char *StrEnd = strchr(StrStart, '}');
1421 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1422 + std::string(AsmStr) + "'");
1425 std::string Val(StrStart, StrEnd);
1426 PrintSpecial(MI, Val.c_str());
1427 LastEmitted = StrEnd+1;
1431 const char *IDStart = LastEmitted;
1434 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1435 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1436 llvm_report_error("Bad $ operand number in inline asm string: '"
1437 + std::string(AsmStr) + "'");
1439 LastEmitted = IDEnd;
1441 char Modifier[2] = { 0, 0 };
1443 if (HasCurlyBraces) {
1444 // If we have curly braces, check for a modifier character. This
1445 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1446 if (*LastEmitted == ':') {
1447 ++LastEmitted; // Consume ':' character.
1448 if (*LastEmitted == 0) {
1449 llvm_report_error("Bad ${:} expression in inline asm string: '"
1450 + std::string(AsmStr) + "'");
1453 Modifier[0] = *LastEmitted;
1454 ++LastEmitted; // Consume modifier character.
1457 if (*LastEmitted != '}') {
1458 llvm_report_error("Bad ${} expression in inline asm string: '"
1459 + std::string(AsmStr) + "'");
1461 ++LastEmitted; // Consume '}' character.
1464 if ((unsigned)Val >= NumOperands-1) {
1465 llvm_report_error("Invalid $ operand number in inline asm string: '"
1466 + std::string(AsmStr) + "'");
1469 // Okay, we finally have a value number. Ask the target to print this
1471 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1476 // Scan to find the machine operand number for the operand.
1477 for (; Val; --Val) {
1478 if (OpNo >= MI->getNumOperands()) break;
1479 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1480 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1483 if (OpNo >= MI->getNumOperands()) {
1486 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1487 ++OpNo; // Skip over the ID number.
1489 if (Modifier[0]=='l') // labels are target independent
1490 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1491 false, false, false);
1493 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1494 if ((OpFlags & 7) == 4) {
1495 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1496 Modifier[0] ? Modifier : 0);
1498 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1499 Modifier[0] ? Modifier : 0);
1505 raw_string_ostream Msg(msg);
1506 Msg << "Invalid operand found in inline asm: '"
1509 llvm_report_error(Msg.str());
1516 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1519 /// printImplicitDef - This method prints the specified machine instruction
1520 /// that is an implicit def.
1521 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1523 O << '\t' << TAI->getCommentString() << " implicit-def: "
1524 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1527 /// printLabel - This method prints a local label used by debug and
1528 /// exception handling tables.
1529 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1530 printLabel(MI->getOperand(0).getImm());
1533 void AsmPrinter::printLabel(unsigned Id) const {
1534 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1537 /// printDeclare - This method prints a local variable declaration used by
1539 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1540 /// entry into dwarf table.
1541 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1542 unsigned FI = MI->getOperand(0).getIndex();
1543 GlobalValue *GV = MI->getOperand(1).getGlobal();
1544 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1547 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1548 /// instruction, using the specified assembler variant. Targets should
1549 /// overried this to format as appropriate.
1550 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1551 unsigned AsmVariant, const char *ExtraCode) {
1552 // Target doesn't support this yet!
1556 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1557 unsigned AsmVariant,
1558 const char *ExtraCode) {
1559 // Target doesn't support this yet!
1563 /// printBasicBlockLabel - This method prints the label for the specified
1564 /// MachineBasicBlock
1565 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1568 bool printComment) const {
1570 unsigned Align = MBB->getAlignment();
1572 EmitAlignment(Log2_32(Align));
1575 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1576 << MBB->getNumber();
1580 O.PadToColumn(TAI->getCommentColumn(), 1);
1582 if (MBB->getBasicBlock())
1583 O << '\t' << TAI->getCommentString() << ' '
1584 << MBB->getBasicBlock()->getNameStr();
1591 /// printPICJumpTableSetLabel - This method prints a set label for the
1592 /// specified MachineBasicBlock for a jumptable entry.
1593 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1594 const MachineBasicBlock *MBB) const {
1595 if (!TAI->getSetDirective())
1598 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1599 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1600 printBasicBlockLabel(MBB, false, false, false);
1601 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1602 << '_' << uid << '\n';
1605 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1606 const MachineBasicBlock *MBB) const {
1607 if (!TAI->getSetDirective())
1610 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1611 << getFunctionNumber() << '_' << uid << '_' << uid2
1612 << "_set_" << MBB->getNumber() << ',';
1613 printBasicBlockLabel(MBB, false, false, false);
1614 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1615 << '_' << uid << '_' << uid2 << '\n';
1618 /// printDataDirective - This method prints the asm directive for the
1620 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1621 const TargetData *TD = TM.getTargetData();
1622 switch (type->getTypeID()) {
1623 case Type::FloatTyID: case Type::DoubleTyID:
1624 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1625 assert(0 && "Should have already output floating point constant.");
1627 assert(0 && "Can't handle printing this type of thing");
1628 case Type::IntegerTyID: {
1629 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1631 O << TAI->getData8bitsDirective(AddrSpace);
1632 else if (BitWidth <= 16)
1633 O << TAI->getData16bitsDirective(AddrSpace);
1634 else if (BitWidth <= 32)
1635 O << TAI->getData32bitsDirective(AddrSpace);
1636 else if (BitWidth <= 64) {
1637 assert(TAI->getData64bitsDirective(AddrSpace) &&
1638 "Target cannot handle 64-bit constant exprs!");
1639 O << TAI->getData64bitsDirective(AddrSpace);
1641 llvm_unreachable("Target cannot handle given data directive width!");
1645 case Type::PointerTyID:
1646 if (TD->getPointerSize() == 8) {
1647 assert(TAI->getData64bitsDirective(AddrSpace) &&
1648 "Target cannot handle 64-bit pointer exprs!");
1649 O << TAI->getData64bitsDirective(AddrSpace);
1650 } else if (TD->getPointerSize() == 2) {
1651 O << TAI->getData16bitsDirective(AddrSpace);
1652 } else if (TD->getPointerSize() == 1) {
1653 O << TAI->getData8bitsDirective(AddrSpace);
1655 O << TAI->getData32bitsDirective(AddrSpace);
1661 void AsmPrinter::printVisibility(const std::string& Name,
1662 unsigned Visibility) const {
1663 if (Visibility == GlobalValue::HiddenVisibility) {
1664 if (const char *Directive = TAI->getHiddenDirective())
1665 O << Directive << Name << '\n';
1666 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1667 if (const char *Directive = TAI->getProtectedDirective())
1668 O << Directive << Name << '\n';
1672 void AsmPrinter::printOffset(int64_t Offset) const {
1675 else if (Offset < 0)
1679 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1680 if (!S->usesMetadata())
1683 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1684 if (GCPI != GCMetadataPrinters.end())
1685 return GCPI->second;
1687 const char *Name = S->getName().c_str();
1689 for (GCMetadataPrinterRegistry::iterator
1690 I = GCMetadataPrinterRegistry::begin(),
1691 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1692 if (strcmp(Name, I->getName()) == 0) {
1693 GCMetadataPrinter *GMP = I->instantiate();
1695 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1699 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1700 llvm_unreachable(0);
1703 /// EmitComments - Pretty-print comments for instructions
1704 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1706 MI.getDebugLoc().isUnknown())
1709 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1711 // Print source line info
1712 O.PadToColumn(TAI->getCommentColumn(), 1);
1713 O << TAI->getCommentString() << " SrcLine ";
1714 if (DLT.CompileUnit->hasInitializer()) {
1715 Constant *Name = DLT.CompileUnit->getInitializer();
1716 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1717 if (NameString->isString())
1718 O << NameString->getAsString() << " ";
1722 O << ":" << DLT.Col;
1725 /// EmitComments - Pretty-print comments for instructions
1726 void AsmPrinter::EmitComments(const MCInst &MI) const
1729 if (!MI.getDebugLoc().isUnknown()) {
1730 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1732 // Print source line info
1733 O.PadToColumn(TAI->getCommentColumn(), 1);
1734 O << TAI->getCommentString() << " SrcLine ";
1735 if (DLT.CompileUnit->hasInitializer()) {
1736 Constant *Name = DLT.CompileUnit->getInitializer();
1737 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1738 if (NameString->isString()) {
1739 O << NameString->getAsString() << " ";
1744 O << ":" << DLT.Col;
1749 /// EmitComments - Pretty-print comments for basic blocks
1750 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1753 // Add loop depth information
1754 const MachineLoop *loop = LI->getLoopFor(&MBB);
1757 // Print a newline after bb# annotation.
1759 O.PadToColumn(TAI->getCommentColumn(), 1);
1760 O << TAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1763 O.PadToColumn(TAI->getCommentColumn(), 1);
1765 MachineBasicBlock *Header = loop->getHeader();
1766 assert(Header && "No header for loop");
1768 if (Header == &MBB) {
1769 O << TAI->getCommentString() << " Loop Header";
1770 PrintChildLoopComment(loop);
1773 O << TAI->getCommentString() << " Loop Header is BB"
1774 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1777 if (loop->empty()) {
1779 O.PadToColumn(TAI->getCommentColumn(), 1);
1780 O << TAI->getCommentString() << " Inner Loop";
1783 // Add parent loop information
1784 for (const MachineLoop *CurLoop = loop->getParentLoop();
1786 CurLoop = CurLoop->getParentLoop()) {
1787 MachineBasicBlock *Header = CurLoop->getHeader();
1788 assert(Header && "No header for loop");
1791 O.PadToColumn(TAI->getCommentColumn(), 1);
1792 O << TAI->getCommentString() << Indent(CurLoop->getLoopDepth()-1)
1793 << " Inside Loop BB" << getFunctionNumber() << "_"
1794 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();
1800 void AsmPrinter::PrintChildLoopComment(const MachineLoop *loop) const {
1801 // Add child loop information
1802 for(MachineLoop::iterator cl = loop->begin(),
1803 clend = loop->end();
1806 MachineBasicBlock *Header = (*cl)->getHeader();
1807 assert(Header && "No header for loop");
1810 O.PadToColumn(TAI->getCommentColumn(), 1);
1812 O << TAI->getCommentString() << Indent((*cl)->getLoopDepth()-1)
1813 << " Child Loop BB" << getFunctionNumber() << "_"
1814 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1816 PrintChildLoopComment(*cl);