Fix part 1 of pr4682. PICADD is a 16-bit instruction even in thumb2 mode.
[llvm/avr.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
blob1de31bbc795b5a02e4a339ed057d5f4af8175dd1
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
42 #include <cerrno>
43 using namespace llvm;
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 LastMI(0), LastFn(0), Counter(~0U),
59 PrevDLT(0, ~0U, ~0U) {
60 CurrentSection = 0;
61 DW = 0; MMI = 0;
62 switch (AsmVerbose) {
63 case cl::BOU_UNSET: VerboseAsm = VDef; break;
64 case cl::BOU_TRUE: VerboseAsm = true; break;
65 case cl::BOU_FALSE: VerboseAsm = false; break;
69 AsmPrinter::~AsmPrinter() {
70 for (gcp_iterator I = GCMetadataPrinters.begin(),
71 E = GCMetadataPrinters.end(); I != E; ++I)
72 delete I->second;
74 delete &OutStreamer;
75 delete &OutContext;
78 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
79 return TM.getTargetLowering()->getObjFileLowering();
82 /// SwitchToSection - Switch to the specified section of the executable if we
83 /// are not already in it! If "NS" is null, then this causes us to exit the
84 /// current section and not reenter another one. This is generally used for
85 /// asmprinter hacks.
86 ///
87 /// FIXME: Remove support for null sections.
88 ///
89 void AsmPrinter::SwitchToSection(const MCSection *NS) {
90 // If we're already in this section, we're done.
91 if (CurrentSection == NS) return;
93 CurrentSection = NS;
95 if (NS != 0) {
96 // If section is named we need to switch into it via special '.section'
97 // directive and also append funky flags. Otherwise - section name is just
98 // some magic assembler directive.
99 if (!NS->isDirective()) {
100 SmallString<32> FlagsStr;
102 getObjFileLowering().getSectionFlagsAsString(NS->getKind(), FlagsStr);
104 O << TAI->getSwitchToSectionDirective()
105 << CurrentSection->getName() << FlagsStr.c_str();
106 } else {
107 O << CurrentSection->getName();
109 O << TAI->getDataSectionStartSuffix() << '\n';
113 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.setPreservesAll();
115 MachineFunctionPass::getAnalysisUsage(AU);
116 AU.addRequired<GCModuleInfo>();
119 bool AsmPrinter::doInitialization(Module &M) {
120 // Initialize TargetLoweringObjectFile.
121 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
122 .Initialize(OutContext, TM);
124 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(),
125 TAI->getLinkerPrivateGlobalPrefix());
127 if (TAI->doesAllowQuotesInName())
128 Mang->setUseQuotes(true);
130 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
131 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
133 if (TAI->hasSingleParameterDotFile()) {
134 /* Very minimal debug info. It is ignored if we emit actual
135 debug info. If we don't, this at helps the user find where
136 a function came from. */
137 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
140 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
141 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
142 MP->beginAssembly(O, *this, *TAI);
144 if (!M.getModuleInlineAsm().empty())
145 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
146 << M.getModuleInlineAsm()
147 << '\n' << TAI->getCommentString()
148 << " End of file scope inline assembly\n";
150 SwitchToSection(0); // Reset back to no section to close off sections.
152 if (TAI->doesSupportDebugInformation() ||
153 TAI->doesSupportExceptionHandling()) {
154 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
155 if (MMI)
156 MMI->AnalyzeModule(M);
157 DW = getAnalysisIfAvailable<DwarfWriter>();
158 if (DW)
159 DW->BeginModule(&M, MMI, O, this, TAI);
162 return false;
165 bool AsmPrinter::doFinalization(Module &M) {
166 // Emit global variables.
167 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
168 I != E; ++I)
169 PrintGlobalVariable(I);
171 // Emit final debug information.
172 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
173 DW->EndModule();
175 // If the target wants to know about weak references, print them all.
176 if (TAI->getWeakRefDirective()) {
177 // FIXME: This is not lazy, it would be nice to only print weak references
178 // to stuff that is actually used. Note that doing so would require targets
179 // to notice uses in operands (due to constant exprs etc). This should
180 // happen with the MC stuff eventually.
181 SwitchToSection(0);
183 // Print out module-level global variables here.
184 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
185 I != E; ++I) {
186 if (I->hasExternalWeakLinkage())
187 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
190 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
191 if (I->hasExternalWeakLinkage())
192 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
196 if (TAI->getSetDirective()) {
197 O << '\n';
198 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
199 I != E; ++I) {
200 std::string Name = Mang->getMangledName(I);
202 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
203 std::string Target = Mang->getMangledName(GV);
205 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
206 O << "\t.globl\t" << Name << '\n';
207 else if (I->hasWeakLinkage())
208 O << TAI->getWeakRefDirective() << Name << '\n';
209 else if (!I->hasLocalLinkage())
210 llvm_unreachable("Invalid alias linkage");
212 printVisibility(Name, I->getVisibility());
214 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
218 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
219 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
220 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
221 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
222 MP->finishAssembly(O, *this, *TAI);
224 // If we don't have any trampolines, then we don't require stack memory
225 // to be executable. Some targets have a directive to declare this.
226 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
227 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
228 if (TAI->getNonexecutableStackDirective())
229 O << TAI->getNonexecutableStackDirective() << '\n';
231 delete Mang; Mang = 0;
232 DW = 0; MMI = 0;
234 OutStreamer.Finish();
235 return false;
238 std::string
239 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
240 assert(MF && "No machine function?");
241 return Mang->getMangledName(MF->getFunction(), ".eh",
242 TAI->is_EHSymbolPrivate());
245 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
246 // What's my mangled name?
247 CurrentFnName = Mang->getMangledName(MF.getFunction());
248 IncrementFunctionNumber();
251 namespace {
252 // SectionCPs - Keep track the alignment, constpool entries per Section.
253 struct SectionCPs {
254 const MCSection *S;
255 unsigned Alignment;
256 SmallVector<unsigned, 4> CPEs;
257 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
261 /// EmitConstantPool - Print to the current output stream assembly
262 /// representations of the constants in the constant pool MCP. This is
263 /// used to print out constants which have been "spilled to memory" by
264 /// the code generator.
266 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
267 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
268 if (CP.empty()) return;
270 // Calculate sections for constant pool entries. We collect entries to go into
271 // the same section together to reduce amount of section switch statements.
272 SmallVector<SectionCPs, 4> CPSections;
273 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
274 const MachineConstantPoolEntry &CPE = CP[i];
275 unsigned Align = CPE.getAlignment();
277 SectionKind Kind;
278 switch (CPE.getRelocationInfo()) {
279 default: llvm_unreachable("Unknown section kind");
280 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
281 case 1:
282 Kind = SectionKind::getReadOnlyWithRelLocal();
283 break;
284 case 0:
285 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
286 case 4: Kind = SectionKind::getMergeableConst4(); break;
287 case 8: Kind = SectionKind::getMergeableConst8(); break;
288 case 16: Kind = SectionKind::getMergeableConst16();break;
289 default: Kind = SectionKind::getMergeableConst(); break;
293 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
295 // The number of sections are small, just do a linear search from the
296 // last section to the first.
297 bool Found = false;
298 unsigned SecIdx = CPSections.size();
299 while (SecIdx != 0) {
300 if (CPSections[--SecIdx].S == S) {
301 Found = true;
302 break;
305 if (!Found) {
306 SecIdx = CPSections.size();
307 CPSections.push_back(SectionCPs(S, Align));
310 if (Align > CPSections[SecIdx].Alignment)
311 CPSections[SecIdx].Alignment = Align;
312 CPSections[SecIdx].CPEs.push_back(i);
315 // Now print stuff into the calculated sections.
316 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
317 SwitchToSection(CPSections[i].S);
318 EmitAlignment(Log2_32(CPSections[i].Alignment));
320 unsigned Offset = 0;
321 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
322 unsigned CPI = CPSections[i].CPEs[j];
323 MachineConstantPoolEntry CPE = CP[CPI];
325 // Emit inter-object padding for alignment.
326 unsigned AlignMask = CPE.getAlignment() - 1;
327 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
328 EmitZeros(NewOffset - Offset);
330 const Type *Ty = CPE.getType();
331 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
333 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
334 << CPI << ":\t\t\t\t\t";
335 if (VerboseAsm) {
336 O << TAI->getCommentString() << ' ';
337 WriteTypeSymbolic(O, CPE.getType(), 0);
339 O << '\n';
340 if (CPE.isMachineConstantPoolEntry())
341 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
342 else
343 EmitGlobalConstant(CPE.Val.ConstVal);
348 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
349 /// by the current function to the current output stream.
351 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
352 MachineFunction &MF) {
353 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
354 if (JT.empty()) return;
356 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
358 // Pick the directive to use to print the jump table entries, and switch to
359 // the appropriate section.
360 TargetLowering *LoweringInfo = TM.getTargetLowering();
362 const Function *F = MF.getFunction();
363 bool JTInDiffSection = false;
364 if (F->isWeakForLinker() ||
365 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
366 // In PIC mode, we need to emit the jump table to the same section as the
367 // function body itself, otherwise the label differences won't make sense.
368 // We should also do if the section name is NULL or function is declared in
369 // discardable section.
370 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
371 } else {
372 // Otherwise, drop it in the readonly section.
373 const MCSection *ReadOnlySection =
374 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
375 SwitchToSection(ReadOnlySection);
376 JTInDiffSection = true;
379 EmitAlignment(Log2_32(MJTI->getAlignment()));
381 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
382 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
384 // If this jump table was deleted, ignore it.
385 if (JTBBs.empty()) continue;
387 // For PIC codegen, if possible we want to use the SetDirective to reduce
388 // the number of relocations the assembler will generate for the jump table.
389 // Set directives are all printed before the jump table itself.
390 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
391 if (TAI->getSetDirective() && IsPic)
392 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
393 if (EmittedSets.insert(JTBBs[ii]))
394 printPICJumpTableSetLabel(i, JTBBs[ii]);
396 // On some targets (e.g. darwin) we want to emit two consequtive labels
397 // before each jump table. The first label is never referenced, but tells
398 // the assembler and linker the extents of the jump table object. The
399 // second label is actually referenced by the code.
400 if (JTInDiffSection) {
401 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
402 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
405 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
406 << '_' << i << ":\n";
408 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
409 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
410 O << '\n';
415 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
416 const MachineBasicBlock *MBB,
417 unsigned uid) const {
418 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
420 // Use JumpTableDirective otherwise honor the entry size from the jump table
421 // info.
422 const char *JTEntryDirective = TAI->getJumpTableDirective();
423 bool HadJTEntryDirective = JTEntryDirective != NULL;
424 if (!HadJTEntryDirective) {
425 JTEntryDirective = MJTI->getEntrySize() == 4 ?
426 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
429 O << JTEntryDirective << ' ';
431 // If we have emitted set directives for the jump table entries, print
432 // them rather than the entries themselves. If we're emitting PIC, then
433 // emit the table entries as differences between two text section labels.
434 // If we're emitting non-PIC code, then emit the entries as direct
435 // references to the target basic blocks.
436 if (IsPic) {
437 if (TAI->getSetDirective()) {
438 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
439 << '_' << uid << "_set_" << MBB->getNumber();
440 } else {
441 printBasicBlockLabel(MBB, false, false, false);
442 // If the arch uses custom Jump Table directives, don't calc relative to
443 // JT
444 if (!HadJTEntryDirective)
445 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
446 << getFunctionNumber() << '_' << uid;
448 } else {
449 printBasicBlockLabel(MBB, false, false, false);
454 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
455 /// special global used by LLVM. If so, emit it and return true, otherwise
456 /// do nothing and return false.
457 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
458 if (GV->getName() == "llvm.used") {
459 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
460 EmitLLVMUsedList(GV->getInitializer());
461 return true;
464 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
465 if (GV->getSection() == "llvm.metadata" ||
466 GV->hasAvailableExternallyLinkage())
467 return true;
469 if (!GV->hasAppendingLinkage()) return false;
471 assert(GV->hasInitializer() && "Not a special LLVM global!");
473 const TargetData *TD = TM.getTargetData();
474 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
475 if (GV->getName() == "llvm.global_ctors") {
476 SwitchToSection(getObjFileLowering().getStaticCtorSection());
477 EmitAlignment(Align, 0);
478 EmitXXStructorList(GV->getInitializer());
479 return true;
482 if (GV->getName() == "llvm.global_dtors") {
483 SwitchToSection(getObjFileLowering().getStaticDtorSection());
484 EmitAlignment(Align, 0);
485 EmitXXStructorList(GV->getInitializer());
486 return true;
489 return false;
492 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
493 /// global in the specified llvm.used list for which emitUsedDirectiveFor
494 /// is true, as being used with this directive.
495 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
496 const char *Directive = TAI->getUsedDirective();
498 // Should be an array of 'i8*'.
499 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
500 if (InitList == 0) return;
502 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
503 const GlobalValue *GV =
504 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
505 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
506 O << Directive;
507 EmitConstantValueOnly(InitList->getOperand(i));
508 O << '\n';
513 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
514 /// function pointers, ignoring the init priority.
515 void AsmPrinter::EmitXXStructorList(Constant *List) {
516 // Should be an array of '{ int, void ()* }' structs. The first value is the
517 // init priority, which we ignore.
518 if (!isa<ConstantArray>(List)) return;
519 ConstantArray *InitList = cast<ConstantArray>(List);
520 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
521 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
522 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
524 if (CS->getOperand(1)->isNullValue())
525 return; // Found a null terminator, exit printing.
526 // Emit the function pointer.
527 EmitGlobalConstant(CS->getOperand(1));
531 /// getGlobalLinkName - Returns the asm/link name of of the specified
532 /// global variable. Should be overridden by each target asm printer to
533 /// generate the appropriate value.
534 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
535 std::string &LinkName) const {
536 if (isa<Function>(GV)) {
537 LinkName += TAI->getFunctionAddrPrefix();
538 LinkName += Mang->getMangledName(GV);
539 LinkName += TAI->getFunctionAddrSuffix();
540 } else {
541 LinkName += TAI->getGlobalVarAddrPrefix();
542 LinkName += Mang->getMangledName(GV);
543 LinkName += TAI->getGlobalVarAddrSuffix();
546 return LinkName;
549 /// EmitExternalGlobal - Emit the external reference to a global variable.
550 /// Should be overridden if an indirect reference should be used.
551 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
552 std::string GLN;
553 O << getGlobalLinkName(GV, GLN);
558 //===----------------------------------------------------------------------===//
559 /// LEB 128 number encoding.
561 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
562 /// representing an unsigned leb128 value.
563 void AsmPrinter::PrintULEB128(unsigned Value) const {
564 char Buffer[20];
565 do {
566 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
567 Value >>= 7;
568 if (Value) Byte |= 0x80;
569 O << "0x" << utohex_buffer(Byte, Buffer+20);
570 if (Value) O << ", ";
571 } while (Value);
574 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
575 /// representing a signed leb128 value.
576 void AsmPrinter::PrintSLEB128(int Value) const {
577 int Sign = Value >> (8 * sizeof(Value) - 1);
578 bool IsMore;
579 char Buffer[20];
581 do {
582 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
583 Value >>= 7;
584 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
585 if (IsMore) Byte |= 0x80;
586 O << "0x" << utohex_buffer(Byte, Buffer+20);
587 if (IsMore) O << ", ";
588 } while (IsMore);
591 //===--------------------------------------------------------------------===//
592 // Emission and print routines
595 /// PrintHex - Print a value as a hexidecimal value.
597 void AsmPrinter::PrintHex(int Value) const {
598 char Buffer[20];
599 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
602 /// EOL - Print a newline character to asm stream. If a comment is present
603 /// then it will be printed first. Comments should not contain '\n'.
604 void AsmPrinter::EOL() const {
605 O << '\n';
608 void AsmPrinter::EOL(const std::string &Comment) const {
609 if (VerboseAsm && !Comment.empty()) {
610 O << '\t'
611 << TAI->getCommentString()
612 << ' '
613 << Comment;
615 O << '\n';
618 void AsmPrinter::EOL(const char* Comment) const {
619 if (VerboseAsm && *Comment) {
620 O << '\t'
621 << TAI->getCommentString()
622 << ' '
623 << Comment;
625 O << '\n';
628 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
629 /// unsigned leb128 value.
630 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
631 if (TAI->hasLEB128()) {
632 O << "\t.uleb128\t"
633 << Value;
634 } else {
635 O << TAI->getData8bitsDirective();
636 PrintULEB128(Value);
640 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
641 /// signed leb128 value.
642 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
643 if (TAI->hasLEB128()) {
644 O << "\t.sleb128\t"
645 << Value;
646 } else {
647 O << TAI->getData8bitsDirective();
648 PrintSLEB128(Value);
652 /// EmitInt8 - Emit a byte directive and value.
654 void AsmPrinter::EmitInt8(int Value) const {
655 O << TAI->getData8bitsDirective();
656 PrintHex(Value & 0xFF);
659 /// EmitInt16 - Emit a short directive and value.
661 void AsmPrinter::EmitInt16(int Value) const {
662 O << TAI->getData16bitsDirective();
663 PrintHex(Value & 0xFFFF);
666 /// EmitInt32 - Emit a long directive and value.
668 void AsmPrinter::EmitInt32(int Value) const {
669 O << TAI->getData32bitsDirective();
670 PrintHex(Value);
673 /// EmitInt64 - Emit a long long directive and value.
675 void AsmPrinter::EmitInt64(uint64_t Value) const {
676 if (TAI->getData64bitsDirective()) {
677 O << TAI->getData64bitsDirective();
678 PrintHex(Value);
679 } else {
680 if (TM.getTargetData()->isBigEndian()) {
681 EmitInt32(unsigned(Value >> 32)); O << '\n';
682 EmitInt32(unsigned(Value));
683 } else {
684 EmitInt32(unsigned(Value)); O << '\n';
685 EmitInt32(unsigned(Value >> 32));
690 /// toOctal - Convert the low order bits of X into an octal digit.
692 static inline char toOctal(int X) {
693 return (X&7)+'0';
696 /// printStringChar - Print a char, escaped if necessary.
698 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
699 if (C == '"') {
700 O << "\\\"";
701 } else if (C == '\\') {
702 O << "\\\\";
703 } else if (isprint((unsigned char)C)) {
704 O << C;
705 } else {
706 switch(C) {
707 case '\b': O << "\\b"; break;
708 case '\f': O << "\\f"; break;
709 case '\n': O << "\\n"; break;
710 case '\r': O << "\\r"; break;
711 case '\t': O << "\\t"; break;
712 default:
713 O << '\\';
714 O << toOctal(C >> 6);
715 O << toOctal(C >> 3);
716 O << toOctal(C >> 0);
717 break;
722 /// EmitString - Emit a string with quotes and a null terminator.
723 /// Special characters are emitted properly.
724 /// \literal (Eg. '\t') \endliteral
725 void AsmPrinter::EmitString(const std::string &String) const {
726 EmitString(String.c_str(), String.size());
729 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
730 const char* AscizDirective = TAI->getAscizDirective();
731 if (AscizDirective)
732 O << AscizDirective;
733 else
734 O << TAI->getAsciiDirective();
735 O << '\"';
736 for (unsigned i = 0; i < Size; ++i)
737 printStringChar(O, String[i]);
738 if (AscizDirective)
739 O << '\"';
740 else
741 O << "\\0\"";
745 /// EmitFile - Emit a .file directive.
746 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
747 O << "\t.file\t" << Number << " \"";
748 for (unsigned i = 0, N = Name.size(); i < N; ++i)
749 printStringChar(O, Name[i]);
750 O << '\"';
754 //===----------------------------------------------------------------------===//
756 // EmitAlignment - Emit an alignment directive to the specified power of
757 // two boundary. For example, if you pass in 3 here, you will get an 8
758 // byte alignment. If a global value is specified, and if that global has
759 // an explicit alignment requested, it will unconditionally override the
760 // alignment request. However, if ForcedAlignBits is specified, this value
761 // has final say: the ultimate alignment will be the max of ForcedAlignBits
762 // and the alignment computed with NumBits and the global.
764 // The algorithm is:
765 // Align = NumBits;
766 // if (GV && GV->hasalignment) Align = GV->getalignment();
767 // Align = std::max(Align, ForcedAlignBits);
769 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
770 unsigned ForcedAlignBits,
771 bool UseFillExpr) const {
772 if (GV && GV->getAlignment())
773 NumBits = Log2_32(GV->getAlignment());
774 NumBits = std::max(NumBits, ForcedAlignBits);
776 if (NumBits == 0) return; // No need to emit alignment.
777 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
778 O << TAI->getAlignDirective() << NumBits;
780 if (CurrentSection && CurrentSection->getKind().isText())
781 if (unsigned FillValue = TAI->getTextAlignFillValue()) {
782 O << ',';
783 PrintHex(FillValue);
785 O << '\n';
788 /// PadToColumn - This gets called every time a tab is emitted. If
789 /// column padding is turned on, we replace the tab with the
790 /// appropriate amount of padding. If not, we replace the tab with a
791 /// space, except for the first operand so that initial operands are
792 /// always lined up by tabs.
793 void AsmPrinter::PadToColumn(unsigned Operand) const {
794 if (TAI->getOperandColumn(Operand) > 0) {
795 O.PadToColumn(TAI->getOperandColumn(Operand), 1);
797 else {
798 if (Operand == 1) {
799 // Emit the tab after the mnemonic.
800 O << '\t';
802 else {
803 // Replace the tab with a space.
804 O << ' ';
809 /// EmitZeros - Emit a block of zeros.
811 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
812 if (NumZeros) {
813 if (TAI->getZeroDirective()) {
814 O << TAI->getZeroDirective() << NumZeros;
815 if (TAI->getZeroDirectiveSuffix())
816 O << TAI->getZeroDirectiveSuffix();
817 O << '\n';
818 } else {
819 for (; NumZeros; --NumZeros)
820 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
825 // Print out the specified constant, without a storage class. Only the
826 // constants valid in constant expressions can occur here.
827 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
828 if (CV->isNullValue() || isa<UndefValue>(CV))
829 O << '0';
830 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
831 O << CI->getZExtValue();
832 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
833 // This is a constant address for a global variable or function. Use the
834 // name of the variable or function as the address value, possibly
835 // decorating it with GlobalVarAddrPrefix/Suffix or
836 // FunctionAddrPrefix/Suffix (these all default to "" )
837 if (isa<Function>(GV)) {
838 O << TAI->getFunctionAddrPrefix()
839 << Mang->getMangledName(GV)
840 << TAI->getFunctionAddrSuffix();
841 } else {
842 O << TAI->getGlobalVarAddrPrefix()
843 << Mang->getMangledName(GV)
844 << TAI->getGlobalVarAddrSuffix();
846 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
847 const TargetData *TD = TM.getTargetData();
848 unsigned Opcode = CE->getOpcode();
849 switch (Opcode) {
850 case Instruction::Trunc:
851 case Instruction::ZExt:
852 case Instruction::SExt:
853 case Instruction::FPTrunc:
854 case Instruction::FPExt:
855 case Instruction::UIToFP:
856 case Instruction::SIToFP:
857 case Instruction::FPToUI:
858 case Instruction::FPToSI:
859 llvm_unreachable("FIXME: Don't support this constant cast expr");
860 case Instruction::GetElementPtr: {
861 // generate a symbolic expression for the byte address
862 const Constant *ptrVal = CE->getOperand(0);
863 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
864 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
865 idxVec.size())) {
866 // Truncate/sext the offset to the pointer size.
867 if (TD->getPointerSizeInBits() != 64) {
868 int SExtAmount = 64-TD->getPointerSizeInBits();
869 Offset = (Offset << SExtAmount) >> SExtAmount;
872 if (Offset)
873 O << '(';
874 EmitConstantValueOnly(ptrVal);
875 if (Offset > 0)
876 O << ") + " << Offset;
877 else if (Offset < 0)
878 O << ") - " << -Offset;
879 } else {
880 EmitConstantValueOnly(ptrVal);
882 break;
884 case Instruction::BitCast:
885 return EmitConstantValueOnly(CE->getOperand(0));
887 case Instruction::IntToPtr: {
888 // Handle casts to pointers by changing them into casts to the appropriate
889 // integer type. This promotes constant folding and simplifies this code.
890 Constant *Op = CE->getOperand(0);
891 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
892 return EmitConstantValueOnly(Op);
896 case Instruction::PtrToInt: {
897 // Support only foldable casts to/from pointers that can be eliminated by
898 // changing the pointer to the appropriately sized integer type.
899 Constant *Op = CE->getOperand(0);
900 const Type *Ty = CE->getType();
902 // We can emit the pointer value into this slot if the slot is an
903 // integer slot greater or equal to the size of the pointer.
904 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
905 return EmitConstantValueOnly(Op);
907 O << "((";
908 EmitConstantValueOnly(Op);
909 APInt ptrMask =
910 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
912 SmallString<40> S;
913 ptrMask.toStringUnsigned(S);
914 O << ") & " << S.c_str() << ')';
915 break;
917 case Instruction::Add:
918 case Instruction::Sub:
919 case Instruction::And:
920 case Instruction::Or:
921 case Instruction::Xor:
922 O << '(';
923 EmitConstantValueOnly(CE->getOperand(0));
924 O << ')';
925 switch (Opcode) {
926 case Instruction::Add:
927 O << " + ";
928 break;
929 case Instruction::Sub:
930 O << " - ";
931 break;
932 case Instruction::And:
933 O << " & ";
934 break;
935 case Instruction::Or:
936 O << " | ";
937 break;
938 case Instruction::Xor:
939 O << " ^ ";
940 break;
941 default:
942 break;
944 O << '(';
945 EmitConstantValueOnly(CE->getOperand(1));
946 O << ')';
947 break;
948 default:
949 llvm_unreachable("Unsupported operator!");
951 } else {
952 llvm_unreachable("Unknown constant value!");
956 /// printAsCString - Print the specified array as a C compatible string, only if
957 /// the predicate isString is true.
959 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
960 unsigned LastElt) {
961 assert(CVA->isString() && "Array is not string compatible!");
963 O << '\"';
964 for (unsigned i = 0; i != LastElt; ++i) {
965 unsigned char C =
966 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
967 printStringChar(O, C);
969 O << '\"';
972 /// EmitString - Emit a zero-byte-terminated string constant.
974 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
975 unsigned NumElts = CVA->getNumOperands();
976 if (TAI->getAscizDirective() && NumElts &&
977 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
978 O << TAI->getAscizDirective();
979 printAsCString(O, CVA, NumElts-1);
980 } else {
981 O << TAI->getAsciiDirective();
982 printAsCString(O, CVA, NumElts);
984 O << '\n';
987 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
988 unsigned AddrSpace) {
989 if (CVA->isString()) {
990 EmitString(CVA);
991 } else { // Not a string. Print the values in successive locations
992 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
993 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
997 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
998 const VectorType *PTy = CP->getType();
1000 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1001 EmitGlobalConstant(CP->getOperand(I));
1004 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1005 unsigned AddrSpace) {
1006 // Print the fields in successive locations. Pad to align if needed!
1007 const TargetData *TD = TM.getTargetData();
1008 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1009 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1010 uint64_t sizeSoFar = 0;
1011 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1012 const Constant* field = CVS->getOperand(i);
1014 // Check if padding is needed and insert one or more 0s.
1015 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1016 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1017 - cvsLayout->getElementOffset(i)) - fieldSize;
1018 sizeSoFar += fieldSize + padSize;
1020 // Now print the actual field value.
1021 EmitGlobalConstant(field, AddrSpace);
1023 // Insert padding - this may include padding to increase the size of the
1024 // current field up to the ABI size (if the struct is not packed) as well
1025 // as padding to ensure that the next field starts at the right offset.
1026 EmitZeros(padSize, AddrSpace);
1028 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1029 "Layout of constant struct may be incorrect!");
1032 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1033 unsigned AddrSpace) {
1034 // FP Constants are printed as integer constants to avoid losing
1035 // precision...
1036 const TargetData *TD = TM.getTargetData();
1037 if (CFP->getType() == Type::DoubleTy) {
1038 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1039 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1040 if (TAI->getData64bitsDirective(AddrSpace)) {
1041 O << TAI->getData64bitsDirective(AddrSpace) << i;
1042 if (VerboseAsm)
1043 O << '\t' << TAI->getCommentString() << " double value: " << Val;
1044 O << '\n';
1045 } else if (TD->isBigEndian()) {
1046 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1047 if (VerboseAsm)
1048 O << '\t' << TAI->getCommentString()
1049 << " double most significant word " << Val;
1050 O << '\n';
1051 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1052 if (VerboseAsm)
1053 O << '\t' << TAI->getCommentString()
1054 << " double least significant word " << Val;
1055 O << '\n';
1056 } else {
1057 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1058 if (VerboseAsm)
1059 O << '\t' << TAI->getCommentString()
1060 << " double least significant word " << Val;
1061 O << '\n';
1062 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1063 if (VerboseAsm)
1064 O << '\t' << TAI->getCommentString()
1065 << " double most significant word " << Val;
1066 O << '\n';
1068 return;
1069 } else if (CFP->getType() == Type::FloatTy) {
1070 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1071 O << TAI->getData32bitsDirective(AddrSpace)
1072 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1073 if (VerboseAsm)
1074 O << '\t' << TAI->getCommentString() << " float " << Val;
1075 O << '\n';
1076 return;
1077 } else if (CFP->getType() == Type::X86_FP80Ty) {
1078 // all long double variants are printed as hex
1079 // api needed to prevent premature destruction
1080 APInt api = CFP->getValueAPF().bitcastToAPInt();
1081 const uint64_t *p = api.getRawData();
1082 // Convert to double so we can print the approximate val as a comment.
1083 APFloat DoubleVal = CFP->getValueAPF();
1084 bool ignored;
1085 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1086 &ignored);
1087 if (TD->isBigEndian()) {
1088 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1089 if (VerboseAsm)
1090 O << '\t' << TAI->getCommentString()
1091 << " long double most significant halfword of ~"
1092 << DoubleVal.convertToDouble();
1093 O << '\n';
1094 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1095 if (VerboseAsm)
1096 O << '\t' << TAI->getCommentString() << " long double next halfword";
1097 O << '\n';
1098 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1099 if (VerboseAsm)
1100 O << '\t' << TAI->getCommentString() << " long double next halfword";
1101 O << '\n';
1102 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1103 if (VerboseAsm)
1104 O << '\t' << TAI->getCommentString() << " long double next halfword";
1105 O << '\n';
1106 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1107 if (VerboseAsm)
1108 O << '\t' << TAI->getCommentString()
1109 << " long double least significant halfword";
1110 O << '\n';
1111 } else {
1112 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1113 if (VerboseAsm)
1114 O << '\t' << TAI->getCommentString()
1115 << " long double least significant halfword of ~"
1116 << DoubleVal.convertToDouble();
1117 O << '\n';
1118 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1119 if (VerboseAsm)
1120 O << '\t' << TAI->getCommentString()
1121 << " long double next halfword";
1122 O << '\n';
1123 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1124 if (VerboseAsm)
1125 O << '\t' << TAI->getCommentString()
1126 << " long double next halfword";
1127 O << '\n';
1128 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1129 if (VerboseAsm)
1130 O << '\t' << TAI->getCommentString()
1131 << " long double next halfword";
1132 O << '\n';
1133 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1134 if (VerboseAsm)
1135 O << '\t' << TAI->getCommentString()
1136 << " long double most significant halfword";
1137 O << '\n';
1139 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) -
1140 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1141 return;
1142 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1143 // all long double variants are printed as hex
1144 // api needed to prevent premature destruction
1145 APInt api = CFP->getValueAPF().bitcastToAPInt();
1146 const uint64_t *p = api.getRawData();
1147 if (TD->isBigEndian()) {
1148 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1149 if (VerboseAsm)
1150 O << '\t' << TAI->getCommentString()
1151 << " long double most significant word";
1152 O << '\n';
1153 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1154 if (VerboseAsm)
1155 O << '\t' << TAI->getCommentString()
1156 << " long double next word";
1157 O << '\n';
1158 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1159 if (VerboseAsm)
1160 O << '\t' << TAI->getCommentString()
1161 << " long double next word";
1162 O << '\n';
1163 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1164 if (VerboseAsm)
1165 O << '\t' << TAI->getCommentString()
1166 << " long double least significant word";
1167 O << '\n';
1168 } else {
1169 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1170 if (VerboseAsm)
1171 O << '\t' << TAI->getCommentString()
1172 << " long double least significant word";
1173 O << '\n';
1174 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1175 if (VerboseAsm)
1176 O << '\t' << TAI->getCommentString()
1177 << " long double next word";
1178 O << '\n';
1179 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1180 if (VerboseAsm)
1181 O << '\t' << TAI->getCommentString()
1182 << " long double next word";
1183 O << '\n';
1184 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1185 if (VerboseAsm)
1186 O << '\t' << TAI->getCommentString()
1187 << " long double most significant word";
1188 O << '\n';
1190 return;
1191 } else llvm_unreachable("Floating point constant type not handled");
1194 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1195 unsigned AddrSpace) {
1196 const TargetData *TD = TM.getTargetData();
1197 unsigned BitWidth = CI->getBitWidth();
1198 assert(isPowerOf2_32(BitWidth) &&
1199 "Non-power-of-2-sized integers not handled!");
1201 // We don't expect assemblers to support integer data directives
1202 // for more than 64 bits, so we emit the data in at most 64-bit
1203 // quantities at a time.
1204 const uint64_t *RawData = CI->getValue().getRawData();
1205 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1206 uint64_t Val;
1207 if (TD->isBigEndian())
1208 Val = RawData[e - i - 1];
1209 else
1210 Val = RawData[i];
1212 if (TAI->getData64bitsDirective(AddrSpace))
1213 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1214 else if (TD->isBigEndian()) {
1215 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1216 if (VerboseAsm)
1217 O << '\t' << TAI->getCommentString()
1218 << " Double-word most significant word " << Val;
1219 O << '\n';
1220 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1221 if (VerboseAsm)
1222 O << '\t' << TAI->getCommentString()
1223 << " Double-word least significant word " << Val;
1224 O << '\n';
1225 } else {
1226 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1227 if (VerboseAsm)
1228 O << '\t' << TAI->getCommentString()
1229 << " Double-word least significant word " << Val;
1230 O << '\n';
1231 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1232 if (VerboseAsm)
1233 O << '\t' << TAI->getCommentString()
1234 << " Double-word most significant word " << Val;
1235 O << '\n';
1240 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1241 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1242 const TargetData *TD = TM.getTargetData();
1243 const Type *type = CV->getType();
1244 unsigned Size = TD->getTypeAllocSize(type);
1246 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1247 EmitZeros(Size, AddrSpace);
1248 return;
1249 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1250 EmitGlobalConstantArray(CVA , AddrSpace);
1251 return;
1252 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1253 EmitGlobalConstantStruct(CVS, AddrSpace);
1254 return;
1255 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1256 EmitGlobalConstantFP(CFP, AddrSpace);
1257 return;
1258 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1259 // Small integers are handled below; large integers are handled here.
1260 if (Size > 4) {
1261 EmitGlobalConstantLargeInt(CI, AddrSpace);
1262 return;
1264 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1265 EmitGlobalConstantVector(CP);
1266 return;
1269 printDataDirective(type, AddrSpace);
1270 EmitConstantValueOnly(CV);
1271 if (VerboseAsm) {
1272 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1273 SmallString<40> S;
1274 CI->getValue().toStringUnsigned(S, 16);
1275 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1278 O << '\n';
1281 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1282 // Target doesn't support this yet!
1283 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1286 /// PrintSpecial - Print information related to the specified machine instr
1287 /// that is independent of the operand, and may be independent of the instr
1288 /// itself. This can be useful for portably encoding the comment character
1289 /// or other bits of target-specific knowledge into the asmstrings. The
1290 /// syntax used is ${:comment}. Targets can override this to add support
1291 /// for their own strange codes.
1292 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1293 if (!strcmp(Code, "private")) {
1294 O << TAI->getPrivateGlobalPrefix();
1295 } else if (!strcmp(Code, "comment")) {
1296 if (VerboseAsm)
1297 O << TAI->getCommentString();
1298 } else if (!strcmp(Code, "uid")) {
1299 // Comparing the address of MI isn't sufficient, because machineinstrs may
1300 // be allocated to the same address across functions.
1301 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1303 // If this is a new LastFn instruction, bump the counter.
1304 if (LastMI != MI || LastFn != ThisF) {
1305 ++Counter;
1306 LastMI = MI;
1307 LastFn = ThisF;
1309 O << Counter;
1310 } else {
1311 std::string msg;
1312 raw_string_ostream Msg(msg);
1313 Msg << "Unknown special formatter '" << Code
1314 << "' for machine instr: " << *MI;
1315 llvm_report_error(Msg.str());
1319 /// processDebugLoc - Processes the debug information of each machine
1320 /// instruction's DebugLoc.
1321 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1322 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1323 if (!DL.isUnknown()) {
1324 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1326 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1327 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1328 DICompileUnit(CurDLT.CompileUnit)));
1330 PrevDLT = CurDLT;
1335 /// printInlineAsm - This method formats and prints the specified machine
1336 /// instruction that is an inline asm.
1337 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1338 unsigned NumOperands = MI->getNumOperands();
1340 // Count the number of register definitions.
1341 unsigned NumDefs = 0;
1342 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1343 ++NumDefs)
1344 assert(NumDefs != NumOperands-1 && "No asm string?");
1346 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1348 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1349 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1351 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1352 // These are useful to see where empty asm's wound up.
1353 if (AsmStr[0] == 0) {
1354 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1355 return;
1358 O << TAI->getInlineAsmStart() << "\n\t";
1360 // The variant of the current asmprinter.
1361 int AsmPrinterVariant = TAI->getAssemblerDialect();
1363 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1364 const char *LastEmitted = AsmStr; // One past the last character emitted.
1366 while (*LastEmitted) {
1367 switch (*LastEmitted) {
1368 default: {
1369 // Not a special case, emit the string section literally.
1370 const char *LiteralEnd = LastEmitted+1;
1371 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1372 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1373 ++LiteralEnd;
1374 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1375 O.write(LastEmitted, LiteralEnd-LastEmitted);
1376 LastEmitted = LiteralEnd;
1377 break;
1379 case '\n':
1380 ++LastEmitted; // Consume newline character.
1381 O << '\n'; // Indent code with newline.
1382 break;
1383 case '$': {
1384 ++LastEmitted; // Consume '$' character.
1385 bool Done = true;
1387 // Handle escapes.
1388 switch (*LastEmitted) {
1389 default: Done = false; break;
1390 case '$': // $$ -> $
1391 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1392 O << '$';
1393 ++LastEmitted; // Consume second '$' character.
1394 break;
1395 case '(': // $( -> same as GCC's { character.
1396 ++LastEmitted; // Consume '(' character.
1397 if (CurVariant != -1) {
1398 llvm_report_error("Nested variants found in inline asm string: '"
1399 + std::string(AsmStr) + "'");
1401 CurVariant = 0; // We're in the first variant now.
1402 break;
1403 case '|':
1404 ++LastEmitted; // consume '|' character.
1405 if (CurVariant == -1)
1406 O << '|'; // this is gcc's behavior for | outside a variant
1407 else
1408 ++CurVariant; // We're in the next variant.
1409 break;
1410 case ')': // $) -> same as GCC's } char.
1411 ++LastEmitted; // consume ')' character.
1412 if (CurVariant == -1)
1413 O << '}'; // this is gcc's behavior for } outside a variant
1414 else
1415 CurVariant = -1;
1416 break;
1418 if (Done) break;
1420 bool HasCurlyBraces = false;
1421 if (*LastEmitted == '{') { // ${variable}
1422 ++LastEmitted; // Consume '{' character.
1423 HasCurlyBraces = true;
1426 // If we have ${:foo}, then this is not a real operand reference, it is a
1427 // "magic" string reference, just like in .td files. Arrange to call
1428 // PrintSpecial.
1429 if (HasCurlyBraces && *LastEmitted == ':') {
1430 ++LastEmitted;
1431 const char *StrStart = LastEmitted;
1432 const char *StrEnd = strchr(StrStart, '}');
1433 if (StrEnd == 0) {
1434 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1435 + std::string(AsmStr) + "'");
1438 std::string Val(StrStart, StrEnd);
1439 PrintSpecial(MI, Val.c_str());
1440 LastEmitted = StrEnd+1;
1441 break;
1444 const char *IDStart = LastEmitted;
1445 char *IDEnd;
1446 errno = 0;
1447 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1448 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1449 llvm_report_error("Bad $ operand number in inline asm string: '"
1450 + std::string(AsmStr) + "'");
1452 LastEmitted = IDEnd;
1454 char Modifier[2] = { 0, 0 };
1456 if (HasCurlyBraces) {
1457 // If we have curly braces, check for a modifier character. This
1458 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1459 if (*LastEmitted == ':') {
1460 ++LastEmitted; // Consume ':' character.
1461 if (*LastEmitted == 0) {
1462 llvm_report_error("Bad ${:} expression in inline asm string: '"
1463 + std::string(AsmStr) + "'");
1466 Modifier[0] = *LastEmitted;
1467 ++LastEmitted; // Consume modifier character.
1470 if (*LastEmitted != '}') {
1471 llvm_report_error("Bad ${} expression in inline asm string: '"
1472 + std::string(AsmStr) + "'");
1474 ++LastEmitted; // Consume '}' character.
1477 if ((unsigned)Val >= NumOperands-1) {
1478 llvm_report_error("Invalid $ operand number in inline asm string: '"
1479 + std::string(AsmStr) + "'");
1482 // Okay, we finally have a value number. Ask the target to print this
1483 // operand!
1484 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1485 unsigned OpNo = 1;
1487 bool Error = false;
1489 // Scan to find the machine operand number for the operand.
1490 for (; Val; --Val) {
1491 if (OpNo >= MI->getNumOperands()) break;
1492 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1493 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1496 if (OpNo >= MI->getNumOperands()) {
1497 Error = true;
1498 } else {
1499 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1500 ++OpNo; // Skip over the ID number.
1502 if (Modifier[0]=='l') // labels are target independent
1503 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1504 false, false, false);
1505 else {
1506 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1507 if ((OpFlags & 7) == 4) {
1508 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1509 Modifier[0] ? Modifier : 0);
1510 } else {
1511 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1512 Modifier[0] ? Modifier : 0);
1516 if (Error) {
1517 std::string msg;
1518 raw_string_ostream Msg(msg);
1519 Msg << "Invalid operand found in inline asm: '"
1520 << AsmStr << "'\n";
1521 MI->print(Msg);
1522 llvm_report_error(Msg.str());
1525 break;
1529 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1532 /// printImplicitDef - This method prints the specified machine instruction
1533 /// that is an implicit def.
1534 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1535 if (VerboseAsm)
1536 O << '\t' << TAI->getCommentString() << " implicit-def: "
1537 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1540 /// printLabel - This method prints a local label used by debug and
1541 /// exception handling tables.
1542 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1543 printLabel(MI->getOperand(0).getImm());
1546 void AsmPrinter::printLabel(unsigned Id) const {
1547 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1550 /// printDeclare - This method prints a local variable declaration used by
1551 /// debug tables.
1552 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1553 /// entry into dwarf table.
1554 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1555 unsigned FI = MI->getOperand(0).getIndex();
1556 GlobalValue *GV = MI->getOperand(1).getGlobal();
1557 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1560 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1561 /// instruction, using the specified assembler variant. Targets should
1562 /// overried this to format as appropriate.
1563 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1564 unsigned AsmVariant, const char *ExtraCode) {
1565 // Target doesn't support this yet!
1566 return true;
1569 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1570 unsigned AsmVariant,
1571 const char *ExtraCode) {
1572 // Target doesn't support this yet!
1573 return true;
1576 /// printBasicBlockLabel - This method prints the label for the specified
1577 /// MachineBasicBlock
1578 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1579 bool printAlign,
1580 bool printColon,
1581 bool printComment) const {
1582 if (printAlign) {
1583 unsigned Align = MBB->getAlignment();
1584 if (Align)
1585 EmitAlignment(Log2_32(Align));
1588 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1589 << MBB->getNumber();
1590 if (printColon)
1591 O << ':';
1592 if (printComment && MBB->getBasicBlock())
1593 O << '\t' << TAI->getCommentString() << ' '
1594 << MBB->getBasicBlock()->getNameStr();
1597 /// printPICJumpTableSetLabel - This method prints a set label for the
1598 /// specified MachineBasicBlock for a jumptable entry.
1599 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1600 const MachineBasicBlock *MBB) const {
1601 if (!TAI->getSetDirective())
1602 return;
1604 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1605 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1606 printBasicBlockLabel(MBB, false, false, false);
1607 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1608 << '_' << uid << '\n';
1611 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1612 const MachineBasicBlock *MBB) const {
1613 if (!TAI->getSetDirective())
1614 return;
1616 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1617 << getFunctionNumber() << '_' << uid << '_' << uid2
1618 << "_set_" << MBB->getNumber() << ',';
1619 printBasicBlockLabel(MBB, false, false, false);
1620 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1621 << '_' << uid << '_' << uid2 << '\n';
1624 /// printDataDirective - This method prints the asm directive for the
1625 /// specified type.
1626 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1627 const TargetData *TD = TM.getTargetData();
1628 switch (type->getTypeID()) {
1629 case Type::FloatTyID: case Type::DoubleTyID:
1630 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1631 assert(0 && "Should have already output floating point constant.");
1632 default:
1633 assert(0 && "Can't handle printing this type of thing");
1634 case Type::IntegerTyID: {
1635 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1636 if (BitWidth <= 8)
1637 O << TAI->getData8bitsDirective(AddrSpace);
1638 else if (BitWidth <= 16)
1639 O << TAI->getData16bitsDirective(AddrSpace);
1640 else if (BitWidth <= 32)
1641 O << TAI->getData32bitsDirective(AddrSpace);
1642 else if (BitWidth <= 64) {
1643 assert(TAI->getData64bitsDirective(AddrSpace) &&
1644 "Target cannot handle 64-bit constant exprs!");
1645 O << TAI->getData64bitsDirective(AddrSpace);
1646 } else {
1647 llvm_unreachable("Target cannot handle given data directive width!");
1649 break;
1651 case Type::PointerTyID:
1652 if (TD->getPointerSize() == 8) {
1653 assert(TAI->getData64bitsDirective(AddrSpace) &&
1654 "Target cannot handle 64-bit pointer exprs!");
1655 O << TAI->getData64bitsDirective(AddrSpace);
1656 } else if (TD->getPointerSize() == 2) {
1657 O << TAI->getData16bitsDirective(AddrSpace);
1658 } else if (TD->getPointerSize() == 1) {
1659 O << TAI->getData8bitsDirective(AddrSpace);
1660 } else {
1661 O << TAI->getData32bitsDirective(AddrSpace);
1663 break;
1667 void AsmPrinter::printVisibility(const std::string& Name,
1668 unsigned Visibility) const {
1669 if (Visibility == GlobalValue::HiddenVisibility) {
1670 if (const char *Directive = TAI->getHiddenDirective())
1671 O << Directive << Name << '\n';
1672 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1673 if (const char *Directive = TAI->getProtectedDirective())
1674 O << Directive << Name << '\n';
1678 void AsmPrinter::printOffset(int64_t Offset) const {
1679 if (Offset > 0)
1680 O << '+' << Offset;
1681 else if (Offset < 0)
1682 O << Offset;
1685 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1686 if (!S->usesMetadata())
1687 return 0;
1689 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1690 if (GCPI != GCMetadataPrinters.end())
1691 return GCPI->second;
1693 const char *Name = S->getName().c_str();
1695 for (GCMetadataPrinterRegistry::iterator
1696 I = GCMetadataPrinterRegistry::begin(),
1697 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1698 if (strcmp(Name, I->getName()) == 0) {
1699 GCMetadataPrinter *GMP = I->instantiate();
1700 GMP->S = S;
1701 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1702 return GMP;
1705 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1706 llvm_unreachable(0);
1709 /// EmitComments - Pretty-print comments for instructions
1710 void AsmPrinter::EmitComments(const MachineInstr &MI) const
1712 if (VerboseAsm) {
1713 if (!MI.getDebugLoc().isUnknown()) {
1714 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1716 // Print source line info
1717 O.PadToColumn(TAI->getCommentColumn(), 1);
1718 O << TAI->getCommentString() << " SrcLine ";
1719 if (DLT.CompileUnit->hasInitializer()) {
1720 Constant *Name = DLT.CompileUnit->getInitializer();
1721 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1722 if (NameString->isString()) {
1723 O << NameString->getAsString() << " ";
1726 O << DLT.Line;
1727 if (DLT.Col != 0)
1728 O << ":" << DLT.Col;
1733 /// EmitComments - Pretty-print comments for instructions
1734 void AsmPrinter::EmitComments(const MCInst &MI) const
1736 if (VerboseAsm) {
1737 if (!MI.getDebugLoc().isUnknown()) {
1738 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1740 // Print source line info
1741 O.PadToColumn(TAI->getCommentColumn(), 1);
1742 O << TAI->getCommentString() << " SrcLine ";
1743 if (DLT.CompileUnit->hasInitializer()) {
1744 Constant *Name = DLT.CompileUnit->getInitializer();
1745 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1746 if (NameString->isString()) {
1747 O << NameString->getAsString() << " ";
1750 O << DLT.Line;
1751 if (DLT.Col != 0)
1752 O << ":" << DLT.Col;