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/MCContext.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringExtras.h"
45 static cl::opt<cl::boolOrDefault>
46 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
47 cl::init(cl::BOU_UNSET));
49 char AsmPrinter::ID = 0;
50 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
51 const TargetAsmInfo *T, bool VDef)
52 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
53 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
55 OutContext(*new MCContext()),
56 OutStreamer(*createAsmStreamer(OutContext, O)),
58 IsInTextSection(false), LastMI(0), LastFn(0), Counter(~0U),
59 PrevDLT(0, ~0U, ~0U) {
62 case cl::BOU_UNSET: VerboseAsm = VDef; break;
63 case cl::BOU_TRUE: VerboseAsm = true; break;
64 case cl::BOU_FALSE: VerboseAsm = false; break;
68 AsmPrinter::~AsmPrinter() {
69 for (gcp_iterator I = GCMetadataPrinters.begin(),
70 E = GCMetadataPrinters.end(); I != E; ++I)
77 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
78 return TM.getTargetLowering()->getObjFileLowering();
82 /// SwitchToTextSection - Switch to the specified text section of the executable
83 /// if we are not already in it!
85 void AsmPrinter::SwitchToTextSection(const char *NewSection,
86 const GlobalValue *GV) {
88 if (GV && GV->hasSection())
89 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
93 // If we're already in this section, we're done.
94 if (CurrentSection == NS) return;
96 // Close the current section, if applicable.
97 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
98 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
102 if (!CurrentSection.empty())
103 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
105 IsInTextSection = true;
108 /// SwitchToDataSection - Switch to the specified data section of the executable
109 /// if we are not already in it!
111 void AsmPrinter::SwitchToDataSection(const char *NewSection,
112 const GlobalValue *GV) {
114 if (GV && GV->hasSection())
115 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
119 // If we're already in this section, we're done.
120 if (CurrentSection == NS) return;
122 // Close the current section, if applicable.
123 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
124 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
128 if (!CurrentSection.empty())
129 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
131 IsInTextSection = false;
134 /// SwitchToSection - Switch to the specified section of the executable if we
135 /// are not already in it!
136 void AsmPrinter::SwitchToSection(const MCSection *NS) {
137 const std::string &NewSection = NS->getName();
139 // If we're already in this section, we're done.
140 if (CurrentSection == NewSection) return;
142 // Close the current section, if applicable.
143 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
144 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
146 // FIXME: Make CurrentSection a Section* in the future
147 CurrentSection = NewSection;
148 CurrentSection_ = NS;
150 if (!CurrentSection.empty()) {
151 // If section is named we need to switch into it via special '.section'
152 // directive and also append funky flags. Otherwise - section name is just
153 // some magic assembler directive.
154 if (!NS->isDirective()) {
155 SmallString<32> FlagsStr;
157 getObjFileLowering().getSectionFlagsAsString(NS->getKind(), FlagsStr);
159 O << TAI->getSwitchToSectionDirective()
165 O << TAI->getDataSectionStartSuffix() << '\n';
168 IsInTextSection = NS->getKind().isText();
171 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
172 AU.setPreservesAll();
173 MachineFunctionPass::getAnalysisUsage(AU);
174 AU.addRequired<GCModuleInfo>();
177 bool AsmPrinter::doInitialization(Module &M) {
178 // Initialize TargetLoweringObjectFile.
179 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
180 .Initialize(OutContext, TM);
182 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(),
183 TAI->getLinkerPrivateGlobalPrefix());
185 if (TAI->doesAllowQuotesInName())
186 Mang->setUseQuotes(true);
188 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
189 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
191 if (TAI->hasSingleParameterDotFile()) {
192 /* Very minimal debug info. It is ignored if we emit actual
193 debug info. If we don't, this at helps the user find where
194 a function came from. */
195 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
198 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
199 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
200 MP->beginAssembly(O, *this, *TAI);
202 if (!M.getModuleInlineAsm().empty())
203 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
204 << M.getModuleInlineAsm()
205 << '\n' << TAI->getCommentString()
206 << " End of file scope inline assembly\n";
208 SwitchToDataSection(""); // Reset back to no section.
210 if (TAI->doesSupportDebugInformation() ||
211 TAI->doesSupportExceptionHandling()) {
212 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
214 MMI->AnalyzeModule(M);
215 DW = getAnalysisIfAvailable<DwarfWriter>();
217 DW->BeginModule(&M, MMI, O, this, TAI);
223 bool AsmPrinter::doFinalization(Module &M) {
224 // Emit global variables.
225 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
227 PrintGlobalVariable(I);
229 // Emit final debug information.
230 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
233 // If the target wants to know about weak references, print them all.
234 if (TAI->getWeakRefDirective()) {
235 // FIXME: This is not lazy, it would be nice to only print weak references
236 // to stuff that is actually used. Note that doing so would require targets
237 // to notice uses in operands (due to constant exprs etc). This should
238 // happen with the MC stuff eventually.
239 SwitchToDataSection("");
241 // Print out module-level global variables here.
242 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
244 if (I->hasExternalWeakLinkage())
245 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
248 for (Module::const_iterator I = M.begin(), E = M.end();
250 if (I->hasExternalWeakLinkage())
251 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
255 if (TAI->getSetDirective()) {
257 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
259 std::string Name = Mang->getMangledName(I);
261 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
262 std::string Target = Mang->getMangledName(GV);
264 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
265 O << "\t.globl\t" << Name << '\n';
266 else if (I->hasWeakLinkage())
267 O << TAI->getWeakRefDirective() << Name << '\n';
268 else if (!I->hasLocalLinkage())
269 llvm_unreachable("Invalid alias linkage");
271 printVisibility(Name, I->getVisibility());
273 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
277 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
278 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
279 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
280 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
281 MP->finishAssembly(O, *this, *TAI);
283 // If we don't have any trampolines, then we don't require stack memory
284 // to be executable. Some targets have a directive to declare this.
285 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
286 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
287 if (TAI->getNonexecutableStackDirective())
288 O << TAI->getNonexecutableStackDirective() << '\n';
290 delete Mang; Mang = 0;
293 OutStreamer.Finish();
298 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
299 assert(MF && "No machine function?");
300 return Mang->getMangledName(MF->getFunction(), ".eh",
301 TAI->is_EHSymbolPrivate());
304 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
305 // What's my mangled name?
306 CurrentFnName = Mang->getMangledName(MF.getFunction());
307 IncrementFunctionNumber();
311 // SectionCPs - Keep track the alignment, constpool entries per Section.
315 SmallVector<unsigned, 4> CPEs;
316 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
320 /// EmitConstantPool - Print to the current output stream assembly
321 /// representations of the constants in the constant pool MCP. This is
322 /// used to print out constants which have been "spilled to memory" by
323 /// the code generator.
325 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
326 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
327 if (CP.empty()) return;
329 // Calculate sections for constant pool entries. We collect entries to go into
330 // the same section together to reduce amount of section switch statements.
331 SmallVector<SectionCPs, 4> CPSections;
332 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
333 const MachineConstantPoolEntry &CPE = CP[i];
334 unsigned Align = CPE.getAlignment();
337 switch (CPE.getRelocationInfo()) {
338 default: llvm_unreachable("Unknown section kind");
339 case 2: Kind = SectionKind::get(SectionKind::ReadOnlyWithRel); break;
341 Kind = SectionKind::get(SectionKind::ReadOnlyWithRelLocal);
344 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
345 case 4: Kind = SectionKind::get(SectionKind::MergeableConst4); break;
346 case 8: Kind = SectionKind::get(SectionKind::MergeableConst8); break;
347 case 16: Kind = SectionKind::get(SectionKind::MergeableConst16);break;
348 default: Kind = SectionKind::get(SectionKind::MergeableConst); break;
353 getObjFileLowering().getSectionForMergeableConstant(Kind);
355 // The number of sections are small, just do a linear search from the
356 // last section to the first.
358 unsigned SecIdx = CPSections.size();
359 while (SecIdx != 0) {
360 if (CPSections[--SecIdx].S == S) {
366 SecIdx = CPSections.size();
367 CPSections.push_back(SectionCPs(S, Align));
370 if (Align > CPSections[SecIdx].Alignment)
371 CPSections[SecIdx].Alignment = Align;
372 CPSections[SecIdx].CPEs.push_back(i);
375 // Now print stuff into the calculated sections.
376 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
377 SwitchToSection(CPSections[i].S);
378 EmitAlignment(Log2_32(CPSections[i].Alignment));
381 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
382 unsigned CPI = CPSections[i].CPEs[j];
383 MachineConstantPoolEntry CPE = CP[CPI];
385 // Emit inter-object padding for alignment.
386 unsigned AlignMask = CPE.getAlignment() - 1;
387 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
388 EmitZeros(NewOffset - Offset);
390 const Type *Ty = CPE.getType();
391 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
393 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
394 << CPI << ":\t\t\t\t\t";
396 O << TAI->getCommentString() << ' ';
397 WriteTypeSymbolic(O, CPE.getType(), 0);
400 if (CPE.isMachineConstantPoolEntry())
401 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
403 EmitGlobalConstant(CPE.Val.ConstVal);
408 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
409 /// by the current function to the current output stream.
411 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
412 MachineFunction &MF) {
413 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
414 if (JT.empty()) return;
416 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
418 // Pick the directive to use to print the jump table entries, and switch to
419 // the appropriate section.
420 TargetLowering *LoweringInfo = TM.getTargetLowering();
422 const char *JumpTableDataSection = TAI->getJumpTableDataSection();
423 const Function *F = MF.getFunction();
425 const MCSection *FuncSection =
426 getObjFileLowering().SectionForGlobal(F, Mang, TM);
428 bool JTInDiffSection = false;
429 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
430 !JumpTableDataSection || F->isWeakForLinker()) {
431 // In PIC mode, we need to emit the jump table to the same section as the
432 // function body itself, otherwise the label differences won't make sense.
433 // We should also do if the section name is NULL or function is declared in
434 // discardable section.
435 SwitchToSection(FuncSection);
437 SwitchToDataSection(JumpTableDataSection);
438 JTInDiffSection = true;
441 EmitAlignment(Log2_32(MJTI->getAlignment()));
443 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
444 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
446 // If this jump table was deleted, ignore it.
447 if (JTBBs.empty()) continue;
449 // For PIC codegen, if possible we want to use the SetDirective to reduce
450 // the number of relocations the assembler will generate for the jump table.
451 // Set directives are all printed before the jump table itself.
452 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
453 if (TAI->getSetDirective() && IsPic)
454 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
455 if (EmittedSets.insert(JTBBs[ii]))
456 printPICJumpTableSetLabel(i, JTBBs[ii]);
458 // On some targets (e.g. darwin) we want to emit two consequtive labels
459 // before each jump table. The first label is never referenced, but tells
460 // the assembler and linker the extents of the jump table object. The
461 // second label is actually referenced by the code.
462 if (JTInDiffSection) {
463 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
464 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
467 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
468 << '_' << i << ":\n";
470 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
471 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
477 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
478 const MachineBasicBlock *MBB,
479 unsigned uid) const {
480 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
482 // Use JumpTableDirective otherwise honor the entry size from the jump table
484 const char *JTEntryDirective = TAI->getJumpTableDirective();
485 bool HadJTEntryDirective = JTEntryDirective != NULL;
486 if (!HadJTEntryDirective) {
487 JTEntryDirective = MJTI->getEntrySize() == 4 ?
488 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
491 O << JTEntryDirective << ' ';
493 // If we have emitted set directives for the jump table entries, print
494 // them rather than the entries themselves. If we're emitting PIC, then
495 // emit the table entries as differences between two text section labels.
496 // If we're emitting non-PIC code, then emit the entries as direct
497 // references to the target basic blocks.
499 if (TAI->getSetDirective()) {
500 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
501 << '_' << uid << "_set_" << MBB->getNumber();
503 printBasicBlockLabel(MBB, false, false, false);
504 // If the arch uses custom Jump Table directives, don't calc relative to
506 if (!HadJTEntryDirective)
507 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
508 << getFunctionNumber() << '_' << uid;
511 printBasicBlockLabel(MBB, false, false, false);
516 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
517 /// special global used by LLVM. If so, emit it and return true, otherwise
518 /// do nothing and return false.
519 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
520 if (GV->getName() == "llvm.used") {
521 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
522 EmitLLVMUsedList(GV->getInitializer());
526 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
527 if (GV->getSection() == "llvm.metadata" ||
528 GV->hasAvailableExternallyLinkage())
531 if (!GV->hasAppendingLinkage()) return false;
533 assert(GV->hasInitializer() && "Not a special LLVM global!");
535 const TargetData *TD = TM.getTargetData();
536 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
537 if (GV->getName() == "llvm.global_ctors") {
538 SwitchToDataSection(TAI->getStaticCtorsSection());
539 EmitAlignment(Align, 0);
540 EmitXXStructorList(GV->getInitializer());
544 if (GV->getName() == "llvm.global_dtors") {
545 SwitchToDataSection(TAI->getStaticDtorsSection());
546 EmitAlignment(Align, 0);
547 EmitXXStructorList(GV->getInitializer());
554 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
555 /// global in the specified llvm.used list for which emitUsedDirectiveFor
556 /// is true, as being used with this directive.
557 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
558 const char *Directive = TAI->getUsedDirective();
560 // Should be an array of 'i8*'.
561 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
562 if (InitList == 0) return;
564 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
565 const GlobalValue *GV =
566 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
567 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
569 EmitConstantValueOnly(InitList->getOperand(i));
575 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
576 /// function pointers, ignoring the init priority.
577 void AsmPrinter::EmitXXStructorList(Constant *List) {
578 // Should be an array of '{ int, void ()* }' structs. The first value is the
579 // init priority, which we ignore.
580 if (!isa<ConstantArray>(List)) return;
581 ConstantArray *InitList = cast<ConstantArray>(List);
582 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
583 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
584 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
586 if (CS->getOperand(1)->isNullValue())
587 return; // Found a null terminator, exit printing.
588 // Emit the function pointer.
589 EmitGlobalConstant(CS->getOperand(1));
593 /// getGlobalLinkName - Returns the asm/link name of of the specified
594 /// global variable. Should be overridden by each target asm printer to
595 /// generate the appropriate value.
596 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
597 std::string &LinkName) const {
598 if (isa<Function>(GV)) {
599 LinkName += TAI->getFunctionAddrPrefix();
600 LinkName += Mang->getMangledName(GV);
601 LinkName += TAI->getFunctionAddrSuffix();
603 LinkName += TAI->getGlobalVarAddrPrefix();
604 LinkName += Mang->getMangledName(GV);
605 LinkName += TAI->getGlobalVarAddrSuffix();
611 /// EmitExternalGlobal - Emit the external reference to a global variable.
612 /// Should be overridden if an indirect reference should be used.
613 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
615 O << getGlobalLinkName(GV, GLN);
620 //===----------------------------------------------------------------------===//
621 /// LEB 128 number encoding.
623 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
624 /// representing an unsigned leb128 value.
625 void AsmPrinter::PrintULEB128(unsigned Value) const {
628 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
630 if (Value) Byte |= 0x80;
631 O << "0x" << utohex_buffer(Byte, Buffer+20);
632 if (Value) O << ", ";
636 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
637 /// representing a signed leb128 value.
638 void AsmPrinter::PrintSLEB128(int Value) const {
639 int Sign = Value >> (8 * sizeof(Value) - 1);
644 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
646 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
647 if (IsMore) Byte |= 0x80;
648 O << "0x" << utohex_buffer(Byte, Buffer+20);
649 if (IsMore) O << ", ";
653 //===--------------------------------------------------------------------===//
654 // Emission and print routines
657 /// PrintHex - Print a value as a hexidecimal value.
659 void AsmPrinter::PrintHex(int Value) const {
661 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
664 /// EOL - Print a newline character to asm stream. If a comment is present
665 /// then it will be printed first. Comments should not contain '\n'.
666 void AsmPrinter::EOL() const {
670 void AsmPrinter::EOL(const std::string &Comment) const {
671 if (VerboseAsm && !Comment.empty()) {
673 << TAI->getCommentString()
680 void AsmPrinter::EOL(const char* Comment) const {
681 if (VerboseAsm && *Comment) {
683 << TAI->getCommentString()
690 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
691 /// unsigned leb128 value.
692 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
693 if (TAI->hasLEB128()) {
697 O << TAI->getData8bitsDirective();
702 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
703 /// signed leb128 value.
704 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
705 if (TAI->hasLEB128()) {
709 O << TAI->getData8bitsDirective();
714 /// EmitInt8 - Emit a byte directive and value.
716 void AsmPrinter::EmitInt8(int Value) const {
717 O << TAI->getData8bitsDirective();
718 PrintHex(Value & 0xFF);
721 /// EmitInt16 - Emit a short directive and value.
723 void AsmPrinter::EmitInt16(int Value) const {
724 O << TAI->getData16bitsDirective();
725 PrintHex(Value & 0xFFFF);
728 /// EmitInt32 - Emit a long directive and value.
730 void AsmPrinter::EmitInt32(int Value) const {
731 O << TAI->getData32bitsDirective();
735 /// EmitInt64 - Emit a long long directive and value.
737 void AsmPrinter::EmitInt64(uint64_t Value) const {
738 if (TAI->getData64bitsDirective()) {
739 O << TAI->getData64bitsDirective();
742 if (TM.getTargetData()->isBigEndian()) {
743 EmitInt32(unsigned(Value >> 32)); O << '\n';
744 EmitInt32(unsigned(Value));
746 EmitInt32(unsigned(Value)); O << '\n';
747 EmitInt32(unsigned(Value >> 32));
752 /// toOctal - Convert the low order bits of X into an octal digit.
754 static inline char toOctal(int X) {
758 /// printStringChar - Print a char, escaped if necessary.
760 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
763 } else if (C == '\\') {
765 } else if (isprint((unsigned char)C)) {
769 case '\b': O << "\\b"; break;
770 case '\f': O << "\\f"; break;
771 case '\n': O << "\\n"; break;
772 case '\r': O << "\\r"; break;
773 case '\t': O << "\\t"; break;
776 O << toOctal(C >> 6);
777 O << toOctal(C >> 3);
778 O << toOctal(C >> 0);
784 /// EmitString - Emit a string with quotes and a null terminator.
785 /// Special characters are emitted properly.
786 /// \literal (Eg. '\t') \endliteral
787 void AsmPrinter::EmitString(const std::string &String) const {
788 EmitString(String.c_str(), String.size());
791 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
792 const char* AscizDirective = TAI->getAscizDirective();
796 O << TAI->getAsciiDirective();
798 for (unsigned i = 0; i < Size; ++i)
799 printStringChar(O, String[i]);
807 /// EmitFile - Emit a .file directive.
808 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
809 O << "\t.file\t" << Number << " \"";
810 for (unsigned i = 0, N = Name.size(); i < N; ++i)
811 printStringChar(O, Name[i]);
816 //===----------------------------------------------------------------------===//
818 // EmitAlignment - Emit an alignment directive to the specified power of
819 // two boundary. For example, if you pass in 3 here, you will get an 8
820 // byte alignment. If a global value is specified, and if that global has
821 // an explicit alignment requested, it will unconditionally override the
822 // alignment request. However, if ForcedAlignBits is specified, this value
823 // has final say: the ultimate alignment will be the max of ForcedAlignBits
824 // and the alignment computed with NumBits and the global.
828 // if (GV && GV->hasalignment) Align = GV->getalignment();
829 // Align = std::max(Align, ForcedAlignBits);
831 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
832 unsigned ForcedAlignBits,
833 bool UseFillExpr) const {
834 if (GV && GV->getAlignment())
835 NumBits = Log2_32(GV->getAlignment());
836 NumBits = std::max(NumBits, ForcedAlignBits);
838 if (NumBits == 0) return; // No need to emit alignment.
839 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
840 O << TAI->getAlignDirective() << NumBits;
842 unsigned FillValue = TAI->getTextAlignFillValue();
843 UseFillExpr &= IsInTextSection && FillValue;
851 /// PadToColumn - This gets called every time a tab is emitted. If
852 /// column padding is turned on, we replace the tab with the
853 /// appropriate amount of padding. If not, we replace the tab with a
854 /// space, except for the first operand so that initial operands are
855 /// always lined up by tabs.
856 void AsmPrinter::PadToColumn(unsigned Operand) const {
857 if (TAI->getOperandColumn(Operand) > 0) {
858 O.PadToColumn(TAI->getOperandColumn(Operand), 1);
862 // Emit the tab after the mnemonic.
866 // Replace the tab with a space.
872 /// EmitZeros - Emit a block of zeros.
874 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
876 if (TAI->getZeroDirective()) {
877 O << TAI->getZeroDirective() << NumZeros;
878 if (TAI->getZeroDirectiveSuffix())
879 O << TAI->getZeroDirectiveSuffix();
882 for (; NumZeros; --NumZeros)
883 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
888 // Print out the specified constant, without a storage class. Only the
889 // constants valid in constant expressions can occur here.
890 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
891 if (CV->isNullValue() || isa<UndefValue>(CV))
893 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
894 O << CI->getZExtValue();
895 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
896 // This is a constant address for a global variable or function. Use the
897 // name of the variable or function as the address value, possibly
898 // decorating it with GlobalVarAddrPrefix/Suffix or
899 // FunctionAddrPrefix/Suffix (these all default to "" )
900 if (isa<Function>(GV)) {
901 O << TAI->getFunctionAddrPrefix()
902 << Mang->getMangledName(GV)
903 << TAI->getFunctionAddrSuffix();
905 O << TAI->getGlobalVarAddrPrefix()
906 << Mang->getMangledName(GV)
907 << TAI->getGlobalVarAddrSuffix();
909 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
910 const TargetData *TD = TM.getTargetData();
911 unsigned Opcode = CE->getOpcode();
913 case Instruction::GetElementPtr: {
914 // generate a symbolic expression for the byte address
915 const Constant *ptrVal = CE->getOperand(0);
916 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
917 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
919 // Truncate/sext the offset to the pointer size.
920 if (TD->getPointerSizeInBits() != 64) {
921 int SExtAmount = 64-TD->getPointerSizeInBits();
922 Offset = (Offset << SExtAmount) >> SExtAmount;
927 EmitConstantValueOnly(ptrVal);
929 O << ") + " << Offset;
931 O << ") - " << -Offset;
933 EmitConstantValueOnly(ptrVal);
937 case Instruction::Trunc:
938 case Instruction::ZExt:
939 case Instruction::SExt:
940 case Instruction::FPTrunc:
941 case Instruction::FPExt:
942 case Instruction::UIToFP:
943 case Instruction::SIToFP:
944 case Instruction::FPToUI:
945 case Instruction::FPToSI:
946 llvm_unreachable("FIXME: Don't yet support this kind of constant cast expr");
948 case Instruction::BitCast:
949 return EmitConstantValueOnly(CE->getOperand(0));
951 case Instruction::IntToPtr: {
952 // Handle casts to pointers by changing them into casts to the appropriate
953 // integer type. This promotes constant folding and simplifies this code.
954 Constant *Op = CE->getOperand(0);
955 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
956 return EmitConstantValueOnly(Op);
960 case Instruction::PtrToInt: {
961 // Support only foldable casts to/from pointers that can be eliminated by
962 // changing the pointer to the appropriately sized integer type.
963 Constant *Op = CE->getOperand(0);
964 const Type *Ty = CE->getType();
966 // We can emit the pointer value into this slot if the slot is an
967 // integer slot greater or equal to the size of the pointer.
968 if (TD->getTypeAllocSize(Ty) >= TD->getTypeAllocSize(Op->getType()))
969 return EmitConstantValueOnly(Op);
972 EmitConstantValueOnly(Op);
973 APInt ptrMask = APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Ty));
976 ptrMask.toStringUnsigned(S);
977 O << ") & " << S.c_str() << ')';
980 case Instruction::Add:
981 case Instruction::Sub:
982 case Instruction::And:
983 case Instruction::Or:
984 case Instruction::Xor:
986 EmitConstantValueOnly(CE->getOperand(0));
989 case Instruction::Add:
992 case Instruction::Sub:
995 case Instruction::And:
998 case Instruction::Or:
1001 case Instruction::Xor:
1008 EmitConstantValueOnly(CE->getOperand(1));
1012 llvm_unreachable("Unsupported operator!");
1015 llvm_unreachable("Unknown constant value!");
1019 /// printAsCString - Print the specified array as a C compatible string, only if
1020 /// the predicate isString is true.
1022 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
1024 assert(CVA->isString() && "Array is not string compatible!");
1027 for (unsigned i = 0; i != LastElt; ++i) {
1029 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
1030 printStringChar(O, C);
1035 /// EmitString - Emit a zero-byte-terminated string constant.
1037 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
1038 unsigned NumElts = CVA->getNumOperands();
1039 if (TAI->getAscizDirective() && NumElts &&
1040 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
1041 O << TAI->getAscizDirective();
1042 printAsCString(O, CVA, NumElts-1);
1044 O << TAI->getAsciiDirective();
1045 printAsCString(O, CVA, NumElts);
1050 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
1051 unsigned AddrSpace) {
1052 if (CVA->isString()) {
1054 } else { // Not a string. Print the values in successive locations
1055 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
1056 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1060 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1061 const VectorType *PTy = CP->getType();
1063 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1064 EmitGlobalConstant(CP->getOperand(I));
1067 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1068 unsigned AddrSpace) {
1069 // Print the fields in successive locations. Pad to align if needed!
1070 const TargetData *TD = TM.getTargetData();
1071 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1072 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1073 uint64_t sizeSoFar = 0;
1074 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1075 const Constant* field = CVS->getOperand(i);
1077 // Check if padding is needed and insert one or more 0s.
1078 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1079 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1080 - cvsLayout->getElementOffset(i)) - fieldSize;
1081 sizeSoFar += fieldSize + padSize;
1083 // Now print the actual field value.
1084 EmitGlobalConstant(field, AddrSpace);
1086 // Insert padding - this may include padding to increase the size of the
1087 // current field up to the ABI size (if the struct is not packed) as well
1088 // as padding to ensure that the next field starts at the right offset.
1089 EmitZeros(padSize, AddrSpace);
1091 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1092 "Layout of constant struct may be incorrect!");
1095 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1096 unsigned AddrSpace) {
1097 // FP Constants are printed as integer constants to avoid losing
1099 const TargetData *TD = TM.getTargetData();
1100 if (CFP->getType() == Type::DoubleTy) {
1101 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1102 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1103 if (TAI->getData64bitsDirective(AddrSpace)) {
1104 O << TAI->getData64bitsDirective(AddrSpace) << i;
1106 O << '\t' << TAI->getCommentString() << " double value: " << Val;
1108 } else if (TD->isBigEndian()) {
1109 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1111 O << '\t' << TAI->getCommentString()
1112 << " double most significant word " << Val;
1114 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1116 O << '\t' << TAI->getCommentString()
1117 << " double least significant word " << Val;
1120 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1122 O << '\t' << TAI->getCommentString()
1123 << " double least significant word " << Val;
1125 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1127 O << '\t' << TAI->getCommentString()
1128 << " double most significant word " << Val;
1132 } else if (CFP->getType() == Type::FloatTy) {
1133 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1134 O << TAI->getData32bitsDirective(AddrSpace)
1135 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1137 O << '\t' << TAI->getCommentString() << " float " << Val;
1140 } else if (CFP->getType() == Type::X86_FP80Ty) {
1141 // all long double variants are printed as hex
1142 // api needed to prevent premature destruction
1143 APInt api = CFP->getValueAPF().bitcastToAPInt();
1144 const uint64_t *p = api.getRawData();
1145 // Convert to double so we can print the approximate val as a comment.
1146 APFloat DoubleVal = CFP->getValueAPF();
1148 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1150 if (TD->isBigEndian()) {
1151 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1153 O << '\t' << TAI->getCommentString()
1154 << " long double most significant halfword of ~"
1155 << DoubleVal.convertToDouble();
1157 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1159 O << '\t' << TAI->getCommentString() << " long double next halfword";
1161 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1163 O << '\t' << TAI->getCommentString() << " long double next halfword";
1165 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1167 O << '\t' << TAI->getCommentString() << " long double next halfword";
1169 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1171 O << '\t' << TAI->getCommentString()
1172 << " long double least significant halfword";
1175 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1177 O << '\t' << TAI->getCommentString()
1178 << " long double least significant halfword of ~"
1179 << DoubleVal.convertToDouble();
1181 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1183 O << '\t' << TAI->getCommentString()
1184 << " long double next halfword";
1186 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1188 O << '\t' << TAI->getCommentString()
1189 << " long double next halfword";
1191 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1193 O << '\t' << TAI->getCommentString()
1194 << " long double next halfword";
1196 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1198 O << '\t' << TAI->getCommentString()
1199 << " long double most significant halfword";
1202 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) -
1203 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1205 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1206 // all long double variants are printed as hex
1207 // api needed to prevent premature destruction
1208 APInt api = CFP->getValueAPF().bitcastToAPInt();
1209 const uint64_t *p = api.getRawData();
1210 if (TD->isBigEndian()) {
1211 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1213 O << '\t' << TAI->getCommentString()
1214 << " long double most significant word";
1216 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1218 O << '\t' << TAI->getCommentString()
1219 << " long double next word";
1221 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1223 O << '\t' << TAI->getCommentString()
1224 << " long double next word";
1226 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1228 O << '\t' << TAI->getCommentString()
1229 << " long double least significant word";
1232 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1234 O << '\t' << TAI->getCommentString()
1235 << " long double least significant word";
1237 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1239 O << '\t' << TAI->getCommentString()
1240 << " long double next word";
1242 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1244 O << '\t' << TAI->getCommentString()
1245 << " long double next word";
1247 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1249 O << '\t' << TAI->getCommentString()
1250 << " long double most significant word";
1254 } else llvm_unreachable("Floating point constant type not handled");
1257 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1258 unsigned AddrSpace) {
1259 const TargetData *TD = TM.getTargetData();
1260 unsigned BitWidth = CI->getBitWidth();
1261 assert(isPowerOf2_32(BitWidth) &&
1262 "Non-power-of-2-sized integers not handled!");
1264 // We don't expect assemblers to support integer data directives
1265 // for more than 64 bits, so we emit the data in at most 64-bit
1266 // quantities at a time.
1267 const uint64_t *RawData = CI->getValue().getRawData();
1268 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1270 if (TD->isBigEndian())
1271 Val = RawData[e - i - 1];
1275 if (TAI->getData64bitsDirective(AddrSpace))
1276 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1277 else if (TD->isBigEndian()) {
1278 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1280 O << '\t' << TAI->getCommentString()
1281 << " Double-word most significant word " << Val;
1283 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1285 O << '\t' << TAI->getCommentString()
1286 << " Double-word least significant word " << Val;
1289 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1291 O << '\t' << TAI->getCommentString()
1292 << " Double-word least significant word " << Val;
1294 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1296 O << '\t' << TAI->getCommentString()
1297 << " Double-word most significant word " << Val;
1303 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1304 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1305 const TargetData *TD = TM.getTargetData();
1306 const Type *type = CV->getType();
1307 unsigned Size = TD->getTypeAllocSize(type);
1309 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1310 EmitZeros(Size, AddrSpace);
1312 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1313 EmitGlobalConstantArray(CVA , AddrSpace);
1315 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1316 EmitGlobalConstantStruct(CVS, AddrSpace);
1318 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1319 EmitGlobalConstantFP(CFP, AddrSpace);
1321 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1322 // Small integers are handled below; large integers are handled here.
1324 EmitGlobalConstantLargeInt(CI, AddrSpace);
1327 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1328 EmitGlobalConstantVector(CP);
1332 printDataDirective(type, AddrSpace);
1333 EmitConstantValueOnly(CV);
1335 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1337 CI->getValue().toStringUnsigned(S, 16);
1338 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1344 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1345 // Target doesn't support this yet!
1346 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1349 /// PrintSpecial - Print information related to the specified machine instr
1350 /// that is independent of the operand, and may be independent of the instr
1351 /// itself. This can be useful for portably encoding the comment character
1352 /// or other bits of target-specific knowledge into the asmstrings. The
1353 /// syntax used is ${:comment}. Targets can override this to add support
1354 /// for their own strange codes.
1355 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1356 if (!strcmp(Code, "private")) {
1357 O << TAI->getPrivateGlobalPrefix();
1358 } else if (!strcmp(Code, "comment")) {
1360 O << TAI->getCommentString();
1361 } else if (!strcmp(Code, "uid")) {
1362 // Comparing the address of MI isn't sufficient, because machineinstrs may
1363 // be allocated to the same address across functions.
1364 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1366 // If this is a new LastFn instruction, bump the counter.
1367 if (LastMI != MI || LastFn != ThisF) {
1375 raw_string_ostream Msg(msg);
1376 Msg << "Unknown special formatter '" << Code
1377 << "' for machine instr: " << *MI;
1378 llvm_report_error(Msg.str());
1382 /// processDebugLoc - Processes the debug information of each machine
1383 /// instruction's DebugLoc.
1384 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1385 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1386 if (!DL.isUnknown()) {
1387 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1389 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1390 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1391 DICompileUnit(CurDLT.CompileUnit)));
1398 /// printInlineAsm - This method formats and prints the specified machine
1399 /// instruction that is an inline asm.
1400 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1401 unsigned NumOperands = MI->getNumOperands();
1403 // Count the number of register definitions.
1404 unsigned NumDefs = 0;
1405 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1407 assert(NumDefs != NumOperands-1 && "No asm string?");
1409 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1411 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1412 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1414 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1415 // These are useful to see where empty asm's wound up.
1416 if (AsmStr[0] == 0) {
1417 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1421 O << TAI->getInlineAsmStart() << "\n\t";
1423 // The variant of the current asmprinter.
1424 int AsmPrinterVariant = TAI->getAssemblerDialect();
1426 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1427 const char *LastEmitted = AsmStr; // One past the last character emitted.
1429 while (*LastEmitted) {
1430 switch (*LastEmitted) {
1432 // Not a special case, emit the string section literally.
1433 const char *LiteralEnd = LastEmitted+1;
1434 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1435 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1437 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1438 O.write(LastEmitted, LiteralEnd-LastEmitted);
1439 LastEmitted = LiteralEnd;
1443 ++LastEmitted; // Consume newline character.
1444 O << '\n'; // Indent code with newline.
1447 ++LastEmitted; // Consume '$' character.
1451 switch (*LastEmitted) {
1452 default: Done = false; break;
1453 case '$': // $$ -> $
1454 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1456 ++LastEmitted; // Consume second '$' character.
1458 case '(': // $( -> same as GCC's { character.
1459 ++LastEmitted; // Consume '(' character.
1460 if (CurVariant != -1) {
1461 llvm_report_error("Nested variants found in inline asm string: '"
1462 + std::string(AsmStr) + "'");
1464 CurVariant = 0; // We're in the first variant now.
1467 ++LastEmitted; // consume '|' character.
1468 if (CurVariant == -1)
1469 O << '|'; // this is gcc's behavior for | outside a variant
1471 ++CurVariant; // We're in the next variant.
1473 case ')': // $) -> same as GCC's } char.
1474 ++LastEmitted; // consume ')' character.
1475 if (CurVariant == -1)
1476 O << '}'; // this is gcc's behavior for } outside a variant
1483 bool HasCurlyBraces = false;
1484 if (*LastEmitted == '{') { // ${variable}
1485 ++LastEmitted; // Consume '{' character.
1486 HasCurlyBraces = true;
1489 // If we have ${:foo}, then this is not a real operand reference, it is a
1490 // "magic" string reference, just like in .td files. Arrange to call
1492 if (HasCurlyBraces && *LastEmitted == ':') {
1494 const char *StrStart = LastEmitted;
1495 const char *StrEnd = strchr(StrStart, '}');
1497 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1498 + std::string(AsmStr) + "'");
1501 std::string Val(StrStart, StrEnd);
1502 PrintSpecial(MI, Val.c_str());
1503 LastEmitted = StrEnd+1;
1507 const char *IDStart = LastEmitted;
1510 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1511 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1512 llvm_report_error("Bad $ operand number in inline asm string: '"
1513 + std::string(AsmStr) + "'");
1515 LastEmitted = IDEnd;
1517 char Modifier[2] = { 0, 0 };
1519 if (HasCurlyBraces) {
1520 // If we have curly braces, check for a modifier character. This
1521 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1522 if (*LastEmitted == ':') {
1523 ++LastEmitted; // Consume ':' character.
1524 if (*LastEmitted == 0) {
1525 llvm_report_error("Bad ${:} expression in inline asm string: '"
1526 + std::string(AsmStr) + "'");
1529 Modifier[0] = *LastEmitted;
1530 ++LastEmitted; // Consume modifier character.
1533 if (*LastEmitted != '}') {
1534 llvm_report_error("Bad ${} expression in inline asm string: '"
1535 + std::string(AsmStr) + "'");
1537 ++LastEmitted; // Consume '}' character.
1540 if ((unsigned)Val >= NumOperands-1) {
1541 llvm_report_error("Invalid $ operand number in inline asm string: '"
1542 + std::string(AsmStr) + "'");
1545 // Okay, we finally have a value number. Ask the target to print this
1547 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1552 // Scan to find the machine operand number for the operand.
1553 for (; Val; --Val) {
1554 if (OpNo >= MI->getNumOperands()) break;
1555 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1556 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1559 if (OpNo >= MI->getNumOperands()) {
1562 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1563 ++OpNo; // Skip over the ID number.
1565 if (Modifier[0]=='l') // labels are target independent
1566 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1567 false, false, false);
1569 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1570 if ((OpFlags & 7) == 4) {
1571 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1572 Modifier[0] ? Modifier : 0);
1574 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1575 Modifier[0] ? Modifier : 0);
1581 raw_string_ostream Msg(msg);
1582 Msg << "Invalid operand found in inline asm: '"
1585 llvm_report_error(Msg.str());
1592 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1595 /// printImplicitDef - This method prints the specified machine instruction
1596 /// that is an implicit def.
1597 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1599 O << '\t' << TAI->getCommentString() << " implicit-def: "
1600 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1603 /// printLabel - This method prints a local label used by debug and
1604 /// exception handling tables.
1605 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1606 printLabel(MI->getOperand(0).getImm());
1609 void AsmPrinter::printLabel(unsigned Id) const {
1610 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1613 /// printDeclare - This method prints a local variable declaration used by
1615 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1616 /// entry into dwarf table.
1617 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1618 unsigned FI = MI->getOperand(0).getIndex();
1619 GlobalValue *GV = MI->getOperand(1).getGlobal();
1620 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1623 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1624 /// instruction, using the specified assembler variant. Targets should
1625 /// overried this to format as appropriate.
1626 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1627 unsigned AsmVariant, const char *ExtraCode) {
1628 // Target doesn't support this yet!
1632 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1633 unsigned AsmVariant,
1634 const char *ExtraCode) {
1635 // Target doesn't support this yet!
1639 /// printBasicBlockLabel - This method prints the label for the specified
1640 /// MachineBasicBlock
1641 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1644 bool printComment) const {
1646 unsigned Align = MBB->getAlignment();
1648 EmitAlignment(Log2_32(Align));
1651 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1652 << MBB->getNumber();
1655 if (printComment && MBB->getBasicBlock())
1656 O << '\t' << TAI->getCommentString() << ' '
1657 << MBB->getBasicBlock()->getNameStr();
1660 /// printPICJumpTableSetLabel - This method prints a set label for the
1661 /// specified MachineBasicBlock for a jumptable entry.
1662 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1663 const MachineBasicBlock *MBB) const {
1664 if (!TAI->getSetDirective())
1667 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1668 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1669 printBasicBlockLabel(MBB, false, false, false);
1670 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1671 << '_' << uid << '\n';
1674 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1675 const MachineBasicBlock *MBB) const {
1676 if (!TAI->getSetDirective())
1679 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1680 << getFunctionNumber() << '_' << uid << '_' << uid2
1681 << "_set_" << MBB->getNumber() << ',';
1682 printBasicBlockLabel(MBB, false, false, false);
1683 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1684 << '_' << uid << '_' << uid2 << '\n';
1687 /// printDataDirective - This method prints the asm directive for the
1689 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1690 const TargetData *TD = TM.getTargetData();
1691 switch (type->getTypeID()) {
1692 case Type::FloatTyID: case Type::DoubleTyID:
1693 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1694 assert(0 && "Should have already output floating point constant.");
1696 assert(0 && "Can't handle printing this type of thing");
1697 case Type::IntegerTyID: {
1698 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1700 O << TAI->getData8bitsDirective(AddrSpace);
1701 else if (BitWidth <= 16)
1702 O << TAI->getData16bitsDirective(AddrSpace);
1703 else if (BitWidth <= 32)
1704 O << TAI->getData32bitsDirective(AddrSpace);
1705 else if (BitWidth <= 64) {
1706 assert(TAI->getData64bitsDirective(AddrSpace) &&
1707 "Target cannot handle 64-bit constant exprs!");
1708 O << TAI->getData64bitsDirective(AddrSpace);
1710 llvm_unreachable("Target cannot handle given data directive width!");
1714 case Type::PointerTyID:
1715 if (TD->getPointerSize() == 8) {
1716 assert(TAI->getData64bitsDirective(AddrSpace) &&
1717 "Target cannot handle 64-bit pointer exprs!");
1718 O << TAI->getData64bitsDirective(AddrSpace);
1719 } else if (TD->getPointerSize() == 2) {
1720 O << TAI->getData16bitsDirective(AddrSpace);
1721 } else if (TD->getPointerSize() == 1) {
1722 O << TAI->getData8bitsDirective(AddrSpace);
1724 O << TAI->getData32bitsDirective(AddrSpace);
1730 void AsmPrinter::printVisibility(const std::string& Name,
1731 unsigned Visibility) const {
1732 if (Visibility == GlobalValue::HiddenVisibility) {
1733 if (const char *Directive = TAI->getHiddenDirective())
1734 O << Directive << Name << '\n';
1735 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1736 if (const char *Directive = TAI->getProtectedDirective())
1737 O << Directive << Name << '\n';
1741 void AsmPrinter::printOffset(int64_t Offset) const {
1744 else if (Offset < 0)
1748 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1749 if (!S->usesMetadata())
1752 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1753 if (GCPI != GCMetadataPrinters.end())
1754 return GCPI->second;
1756 const char *Name = S->getName().c_str();
1758 for (GCMetadataPrinterRegistry::iterator
1759 I = GCMetadataPrinterRegistry::begin(),
1760 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1761 if (strcmp(Name, I->getName()) == 0) {
1762 GCMetadataPrinter *GMP = I->instantiate();
1764 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1768 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1769 llvm_unreachable(0);
1772 /// EmitComments - Pretty-print comments for instructions
1773 void AsmPrinter::EmitComments(const MachineInstr &MI) const
1776 if (!MI.getDebugLoc().isUnknown()) {
1777 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1779 // Print source line info
1780 O.PadToColumn(TAI->getCommentColumn(), 1);
1781 O << TAI->getCommentString() << " SrcLine ";
1782 if (DLT.CompileUnit->hasInitializer()) {
1783 Constant *Name = DLT.CompileUnit->getInitializer();
1784 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1785 if (NameString->isString()) {
1786 O << NameString->getAsString() << " ";
1791 O << ":" << DLT.Col;
1796 /// EmitComments - Pretty-print comments for instructions
1797 void AsmPrinter::EmitComments(const MCInst &MI) const
1800 if (!MI.getDebugLoc().isUnknown()) {
1801 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1803 // Print source line info
1804 O.PadToColumn(TAI->getCommentColumn(), 1);
1805 O << TAI->getCommentString() << " SrcLine ";
1806 if (DLT.CompileUnit->hasInitializer()) {
1807 Constant *Name = DLT.CompileUnit->getInitializer();
1808 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1809 if (NameString->isString()) {
1810 O << NameString->getAsString() << " ";
1815 O << ":" << DLT.Col;