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 LastMI(0), LastFn(0), Counter(~0U),
59 PrevDLT(0, ~0U, ~0U) {
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
)
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
87 /// FIXME: Remove support for null sections.
89 void AsmPrinter::SwitchToSection(const MCSection
*NS
) {
90 // If we're already in this section, we're done.
91 if (CurrentSection
== NS
) return;
97 // If section is named we need to switch into it via special '.section'
98 // directive and also append funky flags. Otherwise - section name is just
99 // some magic assembler directive.
100 if (!NS
->isDirective()) {
101 SmallString
<32> FlagsStr
;
102 getObjFileLowering().getSectionFlagsAsString(NS
->getKind(), FlagsStr
);
104 O
<< TAI
->getSwitchToSectionDirective()
105 << CurrentSection
->getName() << FlagsStr
.c_str() << '\n';
107 O
<< CurrentSection
->getName() << '\n';
111 void AsmPrinter::getAnalysisUsage(AnalysisUsage
&AU
) const {
112 AU
.setPreservesAll();
113 MachineFunctionPass::getAnalysisUsage(AU
);
114 AU
.addRequired
<GCModuleInfo
>();
117 bool AsmPrinter::doInitialization(Module
&M
) {
118 // Initialize TargetLoweringObjectFile.
119 const_cast<TargetLoweringObjectFile
&>(getObjFileLowering())
120 .Initialize(OutContext
, TM
);
122 Mang
= new Mangler(M
, TAI
->getGlobalPrefix(), TAI
->getPrivateGlobalPrefix(),
123 TAI
->getLinkerPrivateGlobalPrefix());
125 if (TAI
->doesAllowQuotesInName())
126 Mang
->setUseQuotes(true);
128 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
129 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
131 if (TAI
->hasSingleParameterDotFile()) {
132 /* Very minimal debug info. It is ignored if we emit actual
133 debug info. If we don't, this at helps the user find where
134 a function came from. */
135 O
<< "\t.file\t\"" << M
.getModuleIdentifier() << "\"\n";
138 for (GCModuleInfo::iterator I
= MI
->begin(), E
= MI
->end(); I
!= E
; ++I
)
139 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*I
))
140 MP
->beginAssembly(O
, *this, *TAI
);
142 if (!M
.getModuleInlineAsm().empty())
143 O
<< TAI
->getCommentString() << " Start of file scope inline assembly\n"
144 << M
.getModuleInlineAsm()
145 << '\n' << TAI
->getCommentString()
146 << " End of file scope inline assembly\n";
148 SwitchToSection(0); // Reset back to no section to close off sections.
150 if (TAI
->doesSupportDebugInformation() ||
151 TAI
->doesSupportExceptionHandling()) {
152 MMI
= getAnalysisIfAvailable
<MachineModuleInfo
>();
154 MMI
->AnalyzeModule(M
);
155 DW
= getAnalysisIfAvailable
<DwarfWriter
>();
157 DW
->BeginModule(&M
, MMI
, O
, this, TAI
);
163 bool AsmPrinter::doFinalization(Module
&M
) {
164 // Emit global variables.
165 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
167 PrintGlobalVariable(I
);
169 // Emit final debug information.
170 if (TAI
->doesSupportDebugInformation() || TAI
->doesSupportExceptionHandling())
173 // If the target wants to know about weak references, print them all.
174 if (TAI
->getWeakRefDirective()) {
175 // FIXME: This is not lazy, it would be nice to only print weak references
176 // to stuff that is actually used. Note that doing so would require targets
177 // to notice uses in operands (due to constant exprs etc). This should
178 // happen with the MC stuff eventually.
181 // Print out module-level global variables here.
182 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
184 if (I
->hasExternalWeakLinkage())
185 O
<< TAI
->getWeakRefDirective() << Mang
->getMangledName(I
) << '\n';
188 for (Module::const_iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
) {
189 if (I
->hasExternalWeakLinkage())
190 O
<< TAI
->getWeakRefDirective() << Mang
->getMangledName(I
) << '\n';
194 if (TAI
->getSetDirective()) {
196 for (Module::const_alias_iterator I
= M
.alias_begin(), E
= M
.alias_end();
198 std::string Name
= Mang
->getMangledName(I
);
200 const GlobalValue
*GV
= cast
<GlobalValue
>(I
->getAliasedGlobal());
201 std::string Target
= Mang
->getMangledName(GV
);
203 if (I
->hasExternalLinkage() || !TAI
->getWeakRefDirective())
204 O
<< "\t.globl\t" << Name
<< '\n';
205 else if (I
->hasWeakLinkage())
206 O
<< TAI
->getWeakRefDirective() << Name
<< '\n';
207 else if (!I
->hasLocalLinkage())
208 llvm_unreachable("Invalid alias linkage");
210 printVisibility(Name
, I
->getVisibility());
212 O
<< TAI
->getSetDirective() << ' ' << Name
<< ", " << Target
<< '\n';
216 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
217 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
218 for (GCModuleInfo::iterator I
= MI
->end(), E
= MI
->begin(); I
!= E
; )
219 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*--I
))
220 MP
->finishAssembly(O
, *this, *TAI
);
222 // If we don't have any trampolines, then we don't require stack memory
223 // to be executable. Some targets have a directive to declare this.
224 Function
*InitTrampolineIntrinsic
= M
.getFunction("llvm.init.trampoline");
225 if (!InitTrampolineIntrinsic
|| InitTrampolineIntrinsic
->use_empty())
226 if (TAI
->getNonexecutableStackDirective())
227 O
<< TAI
->getNonexecutableStackDirective() << '\n';
229 delete Mang
; Mang
= 0;
232 OutStreamer
.Finish();
237 AsmPrinter::getCurrentFunctionEHName(const MachineFunction
*MF
) const {
238 assert(MF
&& "No machine function?");
239 return Mang
->getMangledName(MF
->getFunction(), ".eh",
240 TAI
->is_EHSymbolPrivate());
243 void AsmPrinter::SetupMachineFunction(MachineFunction
&MF
) {
244 // What's my mangled name?
245 CurrentFnName
= Mang
->getMangledName(MF
.getFunction());
246 IncrementFunctionNumber();
250 // SectionCPs - Keep track the alignment, constpool entries per Section.
254 SmallVector
<unsigned, 4> CPEs
;
255 SectionCPs(const MCSection
*s
, unsigned a
) : S(s
), Alignment(a
) {};
259 /// EmitConstantPool - Print to the current output stream assembly
260 /// representations of the constants in the constant pool MCP. This is
261 /// used to print out constants which have been "spilled to memory" by
262 /// the code generator.
264 void AsmPrinter::EmitConstantPool(MachineConstantPool
*MCP
) {
265 const std::vector
<MachineConstantPoolEntry
> &CP
= MCP
->getConstants();
266 if (CP
.empty()) return;
268 // Calculate sections for constant pool entries. We collect entries to go into
269 // the same section together to reduce amount of section switch statements.
270 SmallVector
<SectionCPs
, 4> CPSections
;
271 for (unsigned i
= 0, e
= CP
.size(); i
!= e
; ++i
) {
272 const MachineConstantPoolEntry
&CPE
= CP
[i
];
273 unsigned Align
= CPE
.getAlignment();
276 switch (CPE
.getRelocationInfo()) {
277 default: llvm_unreachable("Unknown section kind");
278 case 2: Kind
= SectionKind::getReadOnlyWithRel(); break;
280 Kind
= SectionKind::getReadOnlyWithRelLocal();
283 switch (TM
.getTargetData()->getTypeAllocSize(CPE
.getType())) {
284 case 4: Kind
= SectionKind::getMergeableConst4(); break;
285 case 8: Kind
= SectionKind::getMergeableConst8(); break;
286 case 16: Kind
= SectionKind::getMergeableConst16();break;
287 default: Kind
= SectionKind::getMergeableConst(); break;
291 const MCSection
*S
= getObjFileLowering().getSectionForConstant(Kind
);
293 // The number of sections are small, just do a linear search from the
294 // last section to the first.
296 unsigned SecIdx
= CPSections
.size();
297 while (SecIdx
!= 0) {
298 if (CPSections
[--SecIdx
].S
== S
) {
304 SecIdx
= CPSections
.size();
305 CPSections
.push_back(SectionCPs(S
, Align
));
308 if (Align
> CPSections
[SecIdx
].Alignment
)
309 CPSections
[SecIdx
].Alignment
= Align
;
310 CPSections
[SecIdx
].CPEs
.push_back(i
);
313 // Now print stuff into the calculated sections.
314 for (unsigned i
= 0, e
= CPSections
.size(); i
!= e
; ++i
) {
315 SwitchToSection(CPSections
[i
].S
);
316 EmitAlignment(Log2_32(CPSections
[i
].Alignment
));
319 for (unsigned j
= 0, ee
= CPSections
[i
].CPEs
.size(); j
!= ee
; ++j
) {
320 unsigned CPI
= CPSections
[i
].CPEs
[j
];
321 MachineConstantPoolEntry CPE
= CP
[CPI
];
323 // Emit inter-object padding for alignment.
324 unsigned AlignMask
= CPE
.getAlignment() - 1;
325 unsigned NewOffset
= (Offset
+ AlignMask
) & ~AlignMask
;
326 EmitZeros(NewOffset
- Offset
);
328 const Type
*Ty
= CPE
.getType();
329 Offset
= NewOffset
+ TM
.getTargetData()->getTypeAllocSize(Ty
);
331 O
<< TAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
332 << CPI
<< ":\t\t\t\t\t";
334 O
<< TAI
->getCommentString() << ' ';
335 WriteTypeSymbolic(O
, CPE
.getType(), 0);
338 if (CPE
.isMachineConstantPoolEntry())
339 EmitMachineConstantPoolValue(CPE
.Val
.MachineCPVal
);
341 EmitGlobalConstant(CPE
.Val
.ConstVal
);
346 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
347 /// by the current function to the current output stream.
349 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo
*MJTI
,
350 MachineFunction
&MF
) {
351 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
352 if (JT
.empty()) return;
354 bool IsPic
= TM
.getRelocationModel() == Reloc::PIC_
;
356 // Pick the directive to use to print the jump table entries, and switch to
357 // the appropriate section.
358 TargetLowering
*LoweringInfo
= TM
.getTargetLowering();
360 const Function
*F
= MF
.getFunction();
361 bool JTInDiffSection
= false;
362 if (F
->isWeakForLinker() ||
363 (IsPic
&& !LoweringInfo
->usesGlobalOffsetTable())) {
364 // In PIC mode, we need to emit the jump table to the same section as the
365 // function body itself, otherwise the label differences won't make sense.
366 // We should also do if the section name is NULL or function is declared in
367 // discardable section.
368 SwitchToSection(getObjFileLowering().SectionForGlobal(F
, Mang
, TM
));
370 // Otherwise, drop it in the readonly section.
371 const MCSection
*ReadOnlySection
=
372 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
373 SwitchToSection(ReadOnlySection
);
374 JTInDiffSection
= true;
377 EmitAlignment(Log2_32(MJTI
->getAlignment()));
379 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
) {
380 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[i
].MBBs
;
382 // If this jump table was deleted, ignore it.
383 if (JTBBs
.empty()) continue;
385 // For PIC codegen, if possible we want to use the SetDirective to reduce
386 // the number of relocations the assembler will generate for the jump table.
387 // Set directives are all printed before the jump table itself.
388 SmallPtrSet
<MachineBasicBlock
*, 16> EmittedSets
;
389 if (TAI
->getSetDirective() && IsPic
)
390 for (unsigned ii
= 0, ee
= JTBBs
.size(); ii
!= ee
; ++ii
)
391 if (EmittedSets
.insert(JTBBs
[ii
]))
392 printPICJumpTableSetLabel(i
, JTBBs
[ii
]);
394 // On some targets (e.g. darwin) we want to emit two consequtive labels
395 // before each jump table. The first label is never referenced, but tells
396 // the assembler and linker the extents of the jump table object. The
397 // second label is actually referenced by the code.
398 if (JTInDiffSection
) {
399 if (const char *JTLabelPrefix
= TAI
->getJumpTableSpecialLabelPrefix())
400 O
<< JTLabelPrefix
<< "JTI" << getFunctionNumber() << '_' << i
<< ":\n";
403 O
<< TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
404 << '_' << i
<< ":\n";
406 for (unsigned ii
= 0, ee
= JTBBs
.size(); ii
!= ee
; ++ii
) {
407 printPICJumpTableEntry(MJTI
, JTBBs
[ii
], i
);
413 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
414 const MachineBasicBlock
*MBB
,
415 unsigned uid
) const {
416 bool IsPic
= TM
.getRelocationModel() == Reloc::PIC_
;
418 // Use JumpTableDirective otherwise honor the entry size from the jump table
420 const char *JTEntryDirective
= TAI
->getJumpTableDirective();
421 bool HadJTEntryDirective
= JTEntryDirective
!= NULL
;
422 if (!HadJTEntryDirective
) {
423 JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
424 TAI
->getData32bitsDirective() : TAI
->getData64bitsDirective();
427 O
<< JTEntryDirective
<< ' ';
429 // If we have emitted set directives for the jump table entries, print
430 // them rather than the entries themselves. If we're emitting PIC, then
431 // emit the table entries as differences between two text section labels.
432 // If we're emitting non-PIC code, then emit the entries as direct
433 // references to the target basic blocks.
435 if (TAI
->getSetDirective()) {
436 O
<< TAI
->getPrivateGlobalPrefix() << getFunctionNumber()
437 << '_' << uid
<< "_set_" << MBB
->getNumber();
439 printBasicBlockLabel(MBB
, false, false, false);
440 // If the arch uses custom Jump Table directives, don't calc relative to
442 if (!HadJTEntryDirective
)
443 O
<< '-' << TAI
->getPrivateGlobalPrefix() << "JTI"
444 << getFunctionNumber() << '_' << uid
;
447 printBasicBlockLabel(MBB
, false, false, false);
452 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
453 /// special global used by LLVM. If so, emit it and return true, otherwise
454 /// do nothing and return false.
455 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable
*GV
) {
456 if (GV
->getName() == "llvm.used") {
457 if (TAI
->getUsedDirective() != 0) // No need to emit this at all.
458 EmitLLVMUsedList(GV
->getInitializer());
462 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
463 if (GV
->getSection() == "llvm.metadata" ||
464 GV
->hasAvailableExternallyLinkage())
467 if (!GV
->hasAppendingLinkage()) return false;
469 assert(GV
->hasInitializer() && "Not a special LLVM global!");
471 const TargetData
*TD
= TM
.getTargetData();
472 unsigned Align
= Log2_32(TD
->getPointerPrefAlignment());
473 if (GV
->getName() == "llvm.global_ctors") {
474 SwitchToSection(getObjFileLowering().getStaticCtorSection());
475 EmitAlignment(Align
, 0);
476 EmitXXStructorList(GV
->getInitializer());
480 if (GV
->getName() == "llvm.global_dtors") {
481 SwitchToSection(getObjFileLowering().getStaticDtorSection());
482 EmitAlignment(Align
, 0);
483 EmitXXStructorList(GV
->getInitializer());
490 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
491 /// global in the specified llvm.used list for which emitUsedDirectiveFor
492 /// is true, as being used with this directive.
493 void AsmPrinter::EmitLLVMUsedList(Constant
*List
) {
494 const char *Directive
= TAI
->getUsedDirective();
496 // Should be an array of 'i8*'.
497 ConstantArray
*InitList
= dyn_cast
<ConstantArray
>(List
);
498 if (InitList
== 0) return;
500 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
501 const GlobalValue
*GV
=
502 dyn_cast
<GlobalValue
>(InitList
->getOperand(i
)->stripPointerCasts());
503 if (GV
&& getObjFileLowering().shouldEmitUsedDirectiveFor(GV
, Mang
)) {
505 EmitConstantValueOnly(InitList
->getOperand(i
));
511 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
512 /// function pointers, ignoring the init priority.
513 void AsmPrinter::EmitXXStructorList(Constant
*List
) {
514 // Should be an array of '{ int, void ()* }' structs. The first value is the
515 // init priority, which we ignore.
516 if (!isa
<ConstantArray
>(List
)) return;
517 ConstantArray
*InitList
= cast
<ConstantArray
>(List
);
518 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
)
519 if (ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(InitList
->getOperand(i
))){
520 if (CS
->getNumOperands() != 2) return; // Not array of 2-element structs.
522 if (CS
->getOperand(1)->isNullValue())
523 return; // Found a null terminator, exit printing.
524 // Emit the function pointer.
525 EmitGlobalConstant(CS
->getOperand(1));
529 /// getGlobalLinkName - Returns the asm/link name of of the specified
530 /// global variable. Should be overridden by each target asm printer to
531 /// generate the appropriate value.
532 const std::string
&AsmPrinter::getGlobalLinkName(const GlobalVariable
*GV
,
533 std::string
&LinkName
) const {
534 if (isa
<Function
>(GV
)) {
535 LinkName
+= TAI
->getFunctionAddrPrefix();
536 LinkName
+= Mang
->getMangledName(GV
);
537 LinkName
+= TAI
->getFunctionAddrSuffix();
539 LinkName
+= TAI
->getGlobalVarAddrPrefix();
540 LinkName
+= Mang
->getMangledName(GV
);
541 LinkName
+= TAI
->getGlobalVarAddrSuffix();
547 /// EmitExternalGlobal - Emit the external reference to a global variable.
548 /// Should be overridden if an indirect reference should be used.
549 void AsmPrinter::EmitExternalGlobal(const GlobalVariable
*GV
) {
551 O
<< getGlobalLinkName(GV
, GLN
);
556 //===----------------------------------------------------------------------===//
557 /// LEB 128 number encoding.
559 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
560 /// representing an unsigned leb128 value.
561 void AsmPrinter::PrintULEB128(unsigned Value
) const {
564 unsigned char Byte
= static_cast<unsigned char>(Value
& 0x7f);
566 if (Value
) Byte
|= 0x80;
567 O
<< "0x" << utohex_buffer(Byte
, Buffer
+20);
568 if (Value
) O
<< ", ";
572 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
573 /// representing a signed leb128 value.
574 void AsmPrinter::PrintSLEB128(int Value
) const {
575 int Sign
= Value
>> (8 * sizeof(Value
) - 1);
580 unsigned char Byte
= static_cast<unsigned char>(Value
& 0x7f);
582 IsMore
= Value
!= Sign
|| ((Byte
^ Sign
) & 0x40) != 0;
583 if (IsMore
) Byte
|= 0x80;
584 O
<< "0x" << utohex_buffer(Byte
, Buffer
+20);
585 if (IsMore
) O
<< ", ";
589 //===--------------------------------------------------------------------===//
590 // Emission and print routines
593 /// PrintHex - Print a value as a hexidecimal value.
595 void AsmPrinter::PrintHex(int Value
) const {
597 O
<< "0x" << utohex_buffer(static_cast<unsigned>(Value
), Buffer
+20);
600 /// EOL - Print a newline character to asm stream. If a comment is present
601 /// then it will be printed first. Comments should not contain '\n'.
602 void AsmPrinter::EOL() const {
606 void AsmPrinter::EOL(const std::string
&Comment
) const {
607 if (VerboseAsm
&& !Comment
.empty()) {
609 << TAI
->getCommentString()
616 void AsmPrinter::EOL(const char* Comment
) const {
617 if (VerboseAsm
&& *Comment
) {
619 << TAI
->getCommentString()
626 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
627 /// unsigned leb128 value.
628 void AsmPrinter::EmitULEB128Bytes(unsigned Value
) const {
629 if (TAI
->hasLEB128()) {
633 O
<< TAI
->getData8bitsDirective();
638 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
639 /// signed leb128 value.
640 void AsmPrinter::EmitSLEB128Bytes(int Value
) const {
641 if (TAI
->hasLEB128()) {
645 O
<< TAI
->getData8bitsDirective();
650 /// EmitInt8 - Emit a byte directive and value.
652 void AsmPrinter::EmitInt8(int Value
) const {
653 O
<< TAI
->getData8bitsDirective();
654 PrintHex(Value
& 0xFF);
657 /// EmitInt16 - Emit a short directive and value.
659 void AsmPrinter::EmitInt16(int Value
) const {
660 O
<< TAI
->getData16bitsDirective();
661 PrintHex(Value
& 0xFFFF);
664 /// EmitInt32 - Emit a long directive and value.
666 void AsmPrinter::EmitInt32(int Value
) const {
667 O
<< TAI
->getData32bitsDirective();
671 /// EmitInt64 - Emit a long long directive and value.
673 void AsmPrinter::EmitInt64(uint64_t Value
) const {
674 if (TAI
->getData64bitsDirective()) {
675 O
<< TAI
->getData64bitsDirective();
678 if (TM
.getTargetData()->isBigEndian()) {
679 EmitInt32(unsigned(Value
>> 32)); O
<< '\n';
680 EmitInt32(unsigned(Value
));
682 EmitInt32(unsigned(Value
)); O
<< '\n';
683 EmitInt32(unsigned(Value
>> 32));
688 /// toOctal - Convert the low order bits of X into an octal digit.
690 static inline char toOctal(int X
) {
694 /// printStringChar - Print a char, escaped if necessary.
696 static void printStringChar(formatted_raw_ostream
&O
, unsigned char C
) {
699 } else if (C
== '\\') {
701 } else if (isprint((unsigned char)C
)) {
705 case '\b': O
<< "\\b"; break;
706 case '\f': O
<< "\\f"; break;
707 case '\n': O
<< "\\n"; break;
708 case '\r': O
<< "\\r"; break;
709 case '\t': O
<< "\\t"; break;
712 O
<< toOctal(C
>> 6);
713 O
<< toOctal(C
>> 3);
714 O
<< toOctal(C
>> 0);
720 /// EmitString - Emit a string with quotes and a null terminator.
721 /// Special characters are emitted properly.
722 /// \literal (Eg. '\t') \endliteral
723 void AsmPrinter::EmitString(const std::string
&String
) const {
724 EmitString(String
.c_str(), String
.size());
727 void AsmPrinter::EmitString(const char *String
, unsigned Size
) const {
728 const char* AscizDirective
= TAI
->getAscizDirective();
732 O
<< TAI
->getAsciiDirective();
734 for (unsigned i
= 0; i
< Size
; ++i
)
735 printStringChar(O
, String
[i
]);
743 /// EmitFile - Emit a .file directive.
744 void AsmPrinter::EmitFile(unsigned Number
, const std::string
&Name
) const {
745 O
<< "\t.file\t" << Number
<< " \"";
746 for (unsigned i
= 0, N
= Name
.size(); i
< N
; ++i
)
747 printStringChar(O
, Name
[i
]);
752 //===----------------------------------------------------------------------===//
754 // EmitAlignment - Emit an alignment directive to the specified power of
755 // two boundary. For example, if you pass in 3 here, you will get an 8
756 // byte alignment. If a global value is specified, and if that global has
757 // an explicit alignment requested, it will unconditionally override the
758 // alignment request. However, if ForcedAlignBits is specified, this value
759 // has final say: the ultimate alignment will be the max of ForcedAlignBits
760 // and the alignment computed with NumBits and the global.
764 // if (GV && GV->hasalignment) Align = GV->getalignment();
765 // Align = std::max(Align, ForcedAlignBits);
767 void AsmPrinter::EmitAlignment(unsigned NumBits
, const GlobalValue
*GV
,
768 unsigned ForcedAlignBits
,
769 bool UseFillExpr
) const {
770 if (GV
&& GV
->getAlignment())
771 NumBits
= Log2_32(GV
->getAlignment());
772 NumBits
= std::max(NumBits
, ForcedAlignBits
);
774 if (NumBits
== 0) return; // No need to emit alignment.
775 if (TAI
->getAlignmentIsInBytes()) NumBits
= 1 << NumBits
;
776 O
<< TAI
->getAlignDirective() << NumBits
;
778 if (CurrentSection
&& CurrentSection
->getKind().isText())
779 if (unsigned FillValue
= TAI
->getTextAlignFillValue()) {
786 /// getOperandColumn - Return the output column number (zero-based)
787 /// for operand % "operand." If TargetAsmInfo has FirstOperandColumn
788 /// == 0 or MaxOperandLength == 0, return 0, meaning column alignment
790 unsigned AsmPrinter::getOperandColumn(int operand
) const {
791 if (TAI
->getFirstOperandColumn() > 0 && TAI
->getMaxOperandLength() > 0) {
792 return TAI
->getFirstOperandColumn()
793 + (TAI
->getMaxOperandLength()+1)*(operand
-1);
800 /// PadToColumn - This gets called every time a tab is emitted. If
801 /// column padding is turned on, we replace the tab with the
802 /// appropriate amount of padding. If not, we replace the tab with a
803 /// space, except for the first operand so that initial operands are
804 /// always lined up by tabs.
805 void AsmPrinter::PadToColumn(unsigned Operand
) const {
806 if (getOperandColumn(Operand
) > 0) {
807 O
.PadToColumn(getOperandColumn(Operand
), 1);
811 // Emit the tab after the mnemonic.
815 // Replace the tab with a space.
821 /// EmitZeros - Emit a block of zeros.
823 void AsmPrinter::EmitZeros(uint64_t NumZeros
, unsigned AddrSpace
) const {
825 if (TAI
->getZeroDirective()) {
826 O
<< TAI
->getZeroDirective() << NumZeros
;
827 if (TAI
->getZeroDirectiveSuffix())
828 O
<< TAI
->getZeroDirectiveSuffix();
831 for (; NumZeros
; --NumZeros
)
832 O
<< TAI
->getData8bitsDirective(AddrSpace
) << "0\n";
837 // Print out the specified constant, without a storage class. Only the
838 // constants valid in constant expressions can occur here.
839 void AsmPrinter::EmitConstantValueOnly(const Constant
*CV
) {
840 if (CV
->isNullValue() || isa
<UndefValue
>(CV
))
842 else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
843 O
<< CI
->getZExtValue();
844 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CV
)) {
845 // This is a constant address for a global variable or function. Use the
846 // name of the variable or function as the address value, possibly
847 // decorating it with GlobalVarAddrPrefix/Suffix or
848 // FunctionAddrPrefix/Suffix (these all default to "" )
849 if (isa
<Function
>(GV
)) {
850 O
<< TAI
->getFunctionAddrPrefix()
851 << Mang
->getMangledName(GV
)
852 << TAI
->getFunctionAddrSuffix();
854 O
<< TAI
->getGlobalVarAddrPrefix()
855 << Mang
->getMangledName(GV
)
856 << TAI
->getGlobalVarAddrSuffix();
858 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
859 const TargetData
*TD
= TM
.getTargetData();
860 unsigned Opcode
= CE
->getOpcode();
862 case Instruction::Trunc
:
863 case Instruction::ZExt
:
864 case Instruction::SExt
:
865 case Instruction::FPTrunc
:
866 case Instruction::FPExt
:
867 case Instruction::UIToFP
:
868 case Instruction::SIToFP
:
869 case Instruction::FPToUI
:
870 case Instruction::FPToSI
:
871 llvm_unreachable("FIXME: Don't support this constant cast expr");
872 case Instruction::GetElementPtr
: {
873 // generate a symbolic expression for the byte address
874 const Constant
*ptrVal
= CE
->getOperand(0);
875 SmallVector
<Value
*, 8> idxVec(CE
->op_begin()+1, CE
->op_end());
876 if (int64_t Offset
= TD
->getIndexedOffset(ptrVal
->getType(), &idxVec
[0],
878 // Truncate/sext the offset to the pointer size.
879 if (TD
->getPointerSizeInBits() != 64) {
880 int SExtAmount
= 64-TD
->getPointerSizeInBits();
881 Offset
= (Offset
<< SExtAmount
) >> SExtAmount
;
886 EmitConstantValueOnly(ptrVal
);
888 O
<< ") + " << Offset
;
890 O
<< ") - " << -Offset
;
892 EmitConstantValueOnly(ptrVal
);
896 case Instruction::BitCast
:
897 return EmitConstantValueOnly(CE
->getOperand(0));
899 case Instruction::IntToPtr
: {
900 // Handle casts to pointers by changing them into casts to the appropriate
901 // integer type. This promotes constant folding and simplifies this code.
902 Constant
*Op
= CE
->getOperand(0);
903 Op
= ConstantExpr::getIntegerCast(Op
, TD
->getIntPtrType(), false/*ZExt*/);
904 return EmitConstantValueOnly(Op
);
908 case Instruction::PtrToInt
: {
909 // Support only foldable casts to/from pointers that can be eliminated by
910 // changing the pointer to the appropriately sized integer type.
911 Constant
*Op
= CE
->getOperand(0);
912 const Type
*Ty
= CE
->getType();
914 // We can emit the pointer value into this slot if the slot is an
915 // integer slot greater or equal to the size of the pointer.
916 if (TD
->getTypeAllocSize(Ty
) == TD
->getTypeAllocSize(Op
->getType()))
917 return EmitConstantValueOnly(Op
);
920 EmitConstantValueOnly(Op
);
922 APInt::getAllOnesValue(TD
->getTypeAllocSizeInBits(Op
->getType()));
925 ptrMask
.toStringUnsigned(S
);
926 O
<< ") & " << S
.c_str() << ')';
929 case Instruction::Add
:
930 case Instruction::Sub
:
931 case Instruction::And
:
932 case Instruction::Or
:
933 case Instruction::Xor
:
935 EmitConstantValueOnly(CE
->getOperand(0));
938 case Instruction::Add
:
941 case Instruction::Sub
:
944 case Instruction::And
:
947 case Instruction::Or
:
950 case Instruction::Xor
:
957 EmitConstantValueOnly(CE
->getOperand(1));
961 llvm_unreachable("Unsupported operator!");
964 llvm_unreachable("Unknown constant value!");
968 /// printAsCString - Print the specified array as a C compatible string, only if
969 /// the predicate isString is true.
971 static void printAsCString(formatted_raw_ostream
&O
, const ConstantArray
*CVA
,
973 assert(CVA
->isString() && "Array is not string compatible!");
976 for (unsigned i
= 0; i
!= LastElt
; ++i
) {
978 (unsigned char)cast
<ConstantInt
>(CVA
->getOperand(i
))->getZExtValue();
979 printStringChar(O
, C
);
984 /// EmitString - Emit a zero-byte-terminated string constant.
986 void AsmPrinter::EmitString(const ConstantArray
*CVA
) const {
987 unsigned NumElts
= CVA
->getNumOperands();
988 if (TAI
->getAscizDirective() && NumElts
&&
989 cast
<ConstantInt
>(CVA
->getOperand(NumElts
-1))->getZExtValue() == 0) {
990 O
<< TAI
->getAscizDirective();
991 printAsCString(O
, CVA
, NumElts
-1);
993 O
<< TAI
->getAsciiDirective();
994 printAsCString(O
, CVA
, NumElts
);
999 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray
*CVA
,
1000 unsigned AddrSpace
) {
1001 if (CVA
->isString()) {
1003 } else { // Not a string. Print the values in successive locations
1004 for (unsigned i
= 0, e
= CVA
->getNumOperands(); i
!= e
; ++i
)
1005 EmitGlobalConstant(CVA
->getOperand(i
), AddrSpace
);
1009 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector
*CP
) {
1010 const VectorType
*PTy
= CP
->getType();
1012 for (unsigned I
= 0, E
= PTy
->getNumElements(); I
< E
; ++I
)
1013 EmitGlobalConstant(CP
->getOperand(I
));
1016 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct
*CVS
,
1017 unsigned AddrSpace
) {
1018 // Print the fields in successive locations. Pad to align if needed!
1019 const TargetData
*TD
= TM
.getTargetData();
1020 unsigned Size
= TD
->getTypeAllocSize(CVS
->getType());
1021 const StructLayout
*cvsLayout
= TD
->getStructLayout(CVS
->getType());
1022 uint64_t sizeSoFar
= 0;
1023 for (unsigned i
= 0, e
= CVS
->getNumOperands(); i
!= e
; ++i
) {
1024 const Constant
* field
= CVS
->getOperand(i
);
1026 // Check if padding is needed and insert one or more 0s.
1027 uint64_t fieldSize
= TD
->getTypeAllocSize(field
->getType());
1028 uint64_t padSize
= ((i
== e
-1 ? Size
: cvsLayout
->getElementOffset(i
+1))
1029 - cvsLayout
->getElementOffset(i
)) - fieldSize
;
1030 sizeSoFar
+= fieldSize
+ padSize
;
1032 // Now print the actual field value.
1033 EmitGlobalConstant(field
, AddrSpace
);
1035 // Insert padding - this may include padding to increase the size of the
1036 // current field up to the ABI size (if the struct is not packed) as well
1037 // as padding to ensure that the next field starts at the right offset.
1038 EmitZeros(padSize
, AddrSpace
);
1040 assert(sizeSoFar
== cvsLayout
->getSizeInBytes() &&
1041 "Layout of constant struct may be incorrect!");
1044 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP
*CFP
,
1045 unsigned AddrSpace
) {
1046 // FP Constants are printed as integer constants to avoid losing
1048 const TargetData
*TD
= TM
.getTargetData();
1049 if (CFP
->getType() == Type::DoubleTy
) {
1050 double Val
= CFP
->getValueAPF().convertToDouble(); // for comment only
1051 uint64_t i
= CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
1052 if (TAI
->getData64bitsDirective(AddrSpace
)) {
1053 O
<< TAI
->getData64bitsDirective(AddrSpace
) << i
;
1055 O
<< '\t' << TAI
->getCommentString() << " double value: " << Val
;
1057 } else if (TD
->isBigEndian()) {
1058 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
>> 32);
1060 O
<< '\t' << TAI
->getCommentString()
1061 << " double most significant word " << Val
;
1063 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
);
1065 O
<< '\t' << TAI
->getCommentString()
1066 << " double least significant word " << Val
;
1069 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
);
1071 O
<< '\t' << TAI
->getCommentString()
1072 << " double least significant word " << Val
;
1074 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
>> 32);
1076 O
<< '\t' << TAI
->getCommentString()
1077 << " double most significant word " << Val
;
1081 } else if (CFP
->getType() == Type::FloatTy
) {
1082 float Val
= CFP
->getValueAPF().convertToFloat(); // for comment only
1083 O
<< TAI
->getData32bitsDirective(AddrSpace
)
1084 << CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
1086 O
<< '\t' << TAI
->getCommentString() << " float " << Val
;
1089 } else if (CFP
->getType() == Type::X86_FP80Ty
) {
1090 // all long double variants are printed as hex
1091 // api needed to prevent premature destruction
1092 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
1093 const uint64_t *p
= api
.getRawData();
1094 // Convert to double so we can print the approximate val as a comment.
1095 APFloat DoubleVal
= CFP
->getValueAPF();
1097 DoubleVal
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
,
1099 if (TD
->isBigEndian()) {
1100 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[1]);
1102 O
<< '\t' << TAI
->getCommentString()
1103 << " long double most significant halfword of ~"
1104 << DoubleVal
.convertToDouble();
1106 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 48);
1108 O
<< '\t' << TAI
->getCommentString() << " long double next halfword";
1110 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 32);
1112 O
<< '\t' << TAI
->getCommentString() << " long double next halfword";
1114 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 16);
1116 O
<< '\t' << TAI
->getCommentString() << " long double next halfword";
1118 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0]);
1120 O
<< '\t' << TAI
->getCommentString()
1121 << " long double least significant halfword";
1124 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0]);
1126 O
<< '\t' << TAI
->getCommentString()
1127 << " long double least significant halfword of ~"
1128 << DoubleVal
.convertToDouble();
1130 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 16);
1132 O
<< '\t' << TAI
->getCommentString()
1133 << " long double next halfword";
1135 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 32);
1137 O
<< '\t' << TAI
->getCommentString()
1138 << " long double next halfword";
1140 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 48);
1142 O
<< '\t' << TAI
->getCommentString()
1143 << " long double next halfword";
1145 O
<< TAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[1]);
1147 O
<< '\t' << TAI
->getCommentString()
1148 << " long double most significant halfword";
1151 EmitZeros(TD
->getTypeAllocSize(Type::X86_FP80Ty
) -
1152 TD
->getTypeStoreSize(Type::X86_FP80Ty
), AddrSpace
);
1154 } else if (CFP
->getType() == Type::PPC_FP128Ty
) {
1155 // all long double variants are printed as hex
1156 // api needed to prevent premature destruction
1157 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
1158 const uint64_t *p
= api
.getRawData();
1159 if (TD
->isBigEndian()) {
1160 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0] >> 32);
1162 O
<< '\t' << TAI
->getCommentString()
1163 << " long double most significant word";
1165 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0]);
1167 O
<< '\t' << TAI
->getCommentString()
1168 << " long double next word";
1170 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1] >> 32);
1172 O
<< '\t' << TAI
->getCommentString()
1173 << " long double next word";
1175 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1]);
1177 O
<< '\t' << TAI
->getCommentString()
1178 << " long double least significant word";
1181 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1]);
1183 O
<< '\t' << TAI
->getCommentString()
1184 << " long double least significant word";
1186 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1] >> 32);
1188 O
<< '\t' << TAI
->getCommentString()
1189 << " long double next word";
1191 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0]);
1193 O
<< '\t' << TAI
->getCommentString()
1194 << " long double next word";
1196 O
<< TAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0] >> 32);
1198 O
<< '\t' << TAI
->getCommentString()
1199 << " long double most significant word";
1203 } else llvm_unreachable("Floating point constant type not handled");
1206 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt
*CI
,
1207 unsigned AddrSpace
) {
1208 const TargetData
*TD
= TM
.getTargetData();
1209 unsigned BitWidth
= CI
->getBitWidth();
1210 assert(isPowerOf2_32(BitWidth
) &&
1211 "Non-power-of-2-sized integers not handled!");
1213 // We don't expect assemblers to support integer data directives
1214 // for more than 64 bits, so we emit the data in at most 64-bit
1215 // quantities at a time.
1216 const uint64_t *RawData
= CI
->getValue().getRawData();
1217 for (unsigned i
= 0, e
= BitWidth
/ 64; i
!= e
; ++i
) {
1219 if (TD
->isBigEndian())
1220 Val
= RawData
[e
- i
- 1];
1224 if (TAI
->getData64bitsDirective(AddrSpace
))
1225 O
<< TAI
->getData64bitsDirective(AddrSpace
) << Val
<< '\n';
1226 else if (TD
->isBigEndian()) {
1227 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
>> 32);
1229 O
<< '\t' << TAI
->getCommentString()
1230 << " Double-word most significant word " << Val
;
1232 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
);
1234 O
<< '\t' << TAI
->getCommentString()
1235 << " Double-word least significant word " << Val
;
1238 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
);
1240 O
<< '\t' << TAI
->getCommentString()
1241 << " Double-word least significant word " << Val
;
1243 O
<< TAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
>> 32);
1245 O
<< '\t' << TAI
->getCommentString()
1246 << " Double-word most significant word " << Val
;
1252 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1253 void AsmPrinter::EmitGlobalConstant(const Constant
*CV
, unsigned AddrSpace
) {
1254 const TargetData
*TD
= TM
.getTargetData();
1255 const Type
*type
= CV
->getType();
1256 unsigned Size
= TD
->getTypeAllocSize(type
);
1258 if (CV
->isNullValue() || isa
<UndefValue
>(CV
)) {
1259 EmitZeros(Size
, AddrSpace
);
1261 } else if (const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(CV
)) {
1262 EmitGlobalConstantArray(CVA
, AddrSpace
);
1264 } else if (const ConstantStruct
*CVS
= dyn_cast
<ConstantStruct
>(CV
)) {
1265 EmitGlobalConstantStruct(CVS
, AddrSpace
);
1267 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
1268 EmitGlobalConstantFP(CFP
, AddrSpace
);
1270 } else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1271 // Small integers are handled below; large integers are handled here.
1273 EmitGlobalConstantLargeInt(CI
, AddrSpace
);
1276 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CV
)) {
1277 EmitGlobalConstantVector(CP
);
1281 printDataDirective(type
, AddrSpace
);
1282 EmitConstantValueOnly(CV
);
1284 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1286 CI
->getValue().toStringUnsigned(S
, 16);
1287 O
<< "\t\t\t" << TAI
->getCommentString() << " 0x" << S
.c_str();
1293 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue
*MCPV
) {
1294 // Target doesn't support this yet!
1295 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1298 /// PrintSpecial - Print information related to the specified machine instr
1299 /// that is independent of the operand, and may be independent of the instr
1300 /// itself. This can be useful for portably encoding the comment character
1301 /// or other bits of target-specific knowledge into the asmstrings. The
1302 /// syntax used is ${:comment}. Targets can override this to add support
1303 /// for their own strange codes.
1304 void AsmPrinter::PrintSpecial(const MachineInstr
*MI
, const char *Code
) const {
1305 if (!strcmp(Code
, "private")) {
1306 O
<< TAI
->getPrivateGlobalPrefix();
1307 } else if (!strcmp(Code
, "comment")) {
1309 O
<< TAI
->getCommentString();
1310 } else if (!strcmp(Code
, "uid")) {
1311 // Comparing the address of MI isn't sufficient, because machineinstrs may
1312 // be allocated to the same address across functions.
1313 const Function
*ThisF
= MI
->getParent()->getParent()->getFunction();
1315 // If this is a new LastFn instruction, bump the counter.
1316 if (LastMI
!= MI
|| LastFn
!= ThisF
) {
1324 raw_string_ostream
Msg(msg
);
1325 Msg
<< "Unknown special formatter '" << Code
1326 << "' for machine instr: " << *MI
;
1327 llvm_report_error(Msg
.str());
1331 /// processDebugLoc - Processes the debug information of each machine
1332 /// instruction's DebugLoc.
1333 void AsmPrinter::processDebugLoc(DebugLoc DL
) {
1337 if (TAI
->doesSupportDebugInformation() && DW
->ShouldEmitDwarfDebug()) {
1338 if (!DL
.isUnknown()) {
1339 DebugLocTuple CurDLT
= MF
->getDebugLocTuple(DL
);
1341 if (CurDLT
.CompileUnit
!= 0 && PrevDLT
!= CurDLT
)
1342 printLabel(DW
->RecordSourceLine(CurDLT
.Line
, CurDLT
.Col
,
1343 DICompileUnit(CurDLT
.CompileUnit
)));
1350 /// printInlineAsm - This method formats and prints the specified machine
1351 /// instruction that is an inline asm.
1352 void AsmPrinter::printInlineAsm(const MachineInstr
*MI
) const {
1353 unsigned NumOperands
= MI
->getNumOperands();
1355 // Count the number of register definitions.
1356 unsigned NumDefs
= 0;
1357 for (; MI
->getOperand(NumDefs
).isReg() && MI
->getOperand(NumDefs
).isDef();
1359 assert(NumDefs
!= NumOperands
-1 && "No asm string?");
1361 assert(MI
->getOperand(NumDefs
).isSymbol() && "No asm string?");
1363 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1364 const char *AsmStr
= MI
->getOperand(NumDefs
).getSymbolName();
1366 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1367 // These are useful to see where empty asm's wound up.
1368 if (AsmStr
[0] == 0) {
1369 O
<< TAI
->getInlineAsmStart() << "\n\t" << TAI
->getInlineAsmEnd() << '\n';
1373 O
<< TAI
->getInlineAsmStart() << "\n\t";
1375 // The variant of the current asmprinter.
1376 int AsmPrinterVariant
= TAI
->getAssemblerDialect();
1378 int CurVariant
= -1; // The number of the {.|.|.} region we are in.
1379 const char *LastEmitted
= AsmStr
; // One past the last character emitted.
1381 while (*LastEmitted
) {
1382 switch (*LastEmitted
) {
1384 // Not a special case, emit the string section literally.
1385 const char *LiteralEnd
= LastEmitted
+1;
1386 while (*LiteralEnd
&& *LiteralEnd
!= '{' && *LiteralEnd
!= '|' &&
1387 *LiteralEnd
!= '}' && *LiteralEnd
!= '$' && *LiteralEnd
!= '\n')
1389 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
1390 O
.write(LastEmitted
, LiteralEnd
-LastEmitted
);
1391 LastEmitted
= LiteralEnd
;
1395 ++LastEmitted
; // Consume newline character.
1396 O
<< '\n'; // Indent code with newline.
1399 ++LastEmitted
; // Consume '$' character.
1403 switch (*LastEmitted
) {
1404 default: Done
= false; break;
1405 case '$': // $$ -> $
1406 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
1408 ++LastEmitted
; // Consume second '$' character.
1410 case '(': // $( -> same as GCC's { character.
1411 ++LastEmitted
; // Consume '(' character.
1412 if (CurVariant
!= -1) {
1413 llvm_report_error("Nested variants found in inline asm string: '"
1414 + std::string(AsmStr
) + "'");
1416 CurVariant
= 0; // We're in the first variant now.
1419 ++LastEmitted
; // consume '|' character.
1420 if (CurVariant
== -1)
1421 O
<< '|'; // this is gcc's behavior for | outside a variant
1423 ++CurVariant
; // We're in the next variant.
1425 case ')': // $) -> same as GCC's } char.
1426 ++LastEmitted
; // consume ')' character.
1427 if (CurVariant
== -1)
1428 O
<< '}'; // this is gcc's behavior for } outside a variant
1435 bool HasCurlyBraces
= false;
1436 if (*LastEmitted
== '{') { // ${variable}
1437 ++LastEmitted
; // Consume '{' character.
1438 HasCurlyBraces
= true;
1441 // If we have ${:foo}, then this is not a real operand reference, it is a
1442 // "magic" string reference, just like in .td files. Arrange to call
1444 if (HasCurlyBraces
&& *LastEmitted
== ':') {
1446 const char *StrStart
= LastEmitted
;
1447 const char *StrEnd
= strchr(StrStart
, '}');
1449 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1450 + std::string(AsmStr
) + "'");
1453 std::string
Val(StrStart
, StrEnd
);
1454 PrintSpecial(MI
, Val
.c_str());
1455 LastEmitted
= StrEnd
+1;
1459 const char *IDStart
= LastEmitted
;
1462 long Val
= strtol(IDStart
, &IDEnd
, 10); // We only accept numbers for IDs.
1463 if (!isdigit(*IDStart
) || (Val
== 0 && errno
== EINVAL
)) {
1464 llvm_report_error("Bad $ operand number in inline asm string: '"
1465 + std::string(AsmStr
) + "'");
1467 LastEmitted
= IDEnd
;
1469 char Modifier
[2] = { 0, 0 };
1471 if (HasCurlyBraces
) {
1472 // If we have curly braces, check for a modifier character. This
1473 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1474 if (*LastEmitted
== ':') {
1475 ++LastEmitted
; // Consume ':' character.
1476 if (*LastEmitted
== 0) {
1477 llvm_report_error("Bad ${:} expression in inline asm string: '"
1478 + std::string(AsmStr
) + "'");
1481 Modifier
[0] = *LastEmitted
;
1482 ++LastEmitted
; // Consume modifier character.
1485 if (*LastEmitted
!= '}') {
1486 llvm_report_error("Bad ${} expression in inline asm string: '"
1487 + std::string(AsmStr
) + "'");
1489 ++LastEmitted
; // Consume '}' character.
1492 if ((unsigned)Val
>= NumOperands
-1) {
1493 llvm_report_error("Invalid $ operand number in inline asm string: '"
1494 + std::string(AsmStr
) + "'");
1497 // Okay, we finally have a value number. Ask the target to print this
1499 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
) {
1504 // Scan to find the machine operand number for the operand.
1505 for (; Val
; --Val
) {
1506 if (OpNo
>= MI
->getNumOperands()) break;
1507 unsigned OpFlags
= MI
->getOperand(OpNo
).getImm();
1508 OpNo
+= InlineAsm::getNumOperandRegisters(OpFlags
) + 1;
1511 if (OpNo
>= MI
->getNumOperands()) {
1514 unsigned OpFlags
= MI
->getOperand(OpNo
).getImm();
1515 ++OpNo
; // Skip over the ID number.
1517 if (Modifier
[0]=='l') // labels are target independent
1518 printBasicBlockLabel(MI
->getOperand(OpNo
).getMBB(),
1519 false, false, false);
1521 AsmPrinter
*AP
= const_cast<AsmPrinter
*>(this);
1522 if ((OpFlags
& 7) == 4) {
1523 Error
= AP
->PrintAsmMemoryOperand(MI
, OpNo
, AsmPrinterVariant
,
1524 Modifier
[0] ? Modifier
: 0);
1526 Error
= AP
->PrintAsmOperand(MI
, OpNo
, AsmPrinterVariant
,
1527 Modifier
[0] ? Modifier
: 0);
1533 raw_string_ostream
Msg(msg
);
1534 Msg
<< "Invalid operand found in inline asm: '"
1537 llvm_report_error(Msg
.str());
1544 O
<< "\n\t" << TAI
->getInlineAsmEnd() << '\n';
1547 /// printImplicitDef - This method prints the specified machine instruction
1548 /// that is an implicit def.
1549 void AsmPrinter::printImplicitDef(const MachineInstr
*MI
) const {
1551 O
<< '\t' << TAI
->getCommentString() << " implicit-def: "
1552 << TRI
->getAsmName(MI
->getOperand(0).getReg()) << '\n';
1555 /// printLabel - This method prints a local label used by debug and
1556 /// exception handling tables.
1557 void AsmPrinter::printLabel(const MachineInstr
*MI
) const {
1558 printLabel(MI
->getOperand(0).getImm());
1561 void AsmPrinter::printLabel(unsigned Id
) const {
1562 O
<< TAI
->getPrivateGlobalPrefix() << "label" << Id
<< ":\n";
1565 /// printDeclare - This method prints a local variable declaration used by
1567 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1568 /// entry into dwarf table.
1569 void AsmPrinter::printDeclare(const MachineInstr
*MI
) const {
1570 unsigned FI
= MI
->getOperand(0).getIndex();
1571 GlobalValue
*GV
= MI
->getOperand(1).getGlobal();
1572 DW
->RecordVariable(cast
<GlobalVariable
>(GV
), FI
, MI
);
1575 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1576 /// instruction, using the specified assembler variant. Targets should
1577 /// overried this to format as appropriate.
1578 bool AsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
1579 unsigned AsmVariant
, const char *ExtraCode
) {
1580 // Target doesn't support this yet!
1584 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
, unsigned OpNo
,
1585 unsigned AsmVariant
,
1586 const char *ExtraCode
) {
1587 // Target doesn't support this yet!
1591 /// printBasicBlockLabel - This method prints the label for the specified
1592 /// MachineBasicBlock
1593 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock
*MBB
,
1596 bool printComment
) const {
1598 unsigned Align
= MBB
->getAlignment();
1600 EmitAlignment(Log2_32(Align
));
1603 O
<< TAI
->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1604 << MBB
->getNumber();
1607 if (printComment
&& MBB
->getBasicBlock())
1608 O
<< '\t' << TAI
->getCommentString() << ' '
1609 << MBB
->getBasicBlock()->getNameStr();
1612 /// printPICJumpTableSetLabel - This method prints a set label for the
1613 /// specified MachineBasicBlock for a jumptable entry.
1614 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid
,
1615 const MachineBasicBlock
*MBB
) const {
1616 if (!TAI
->getSetDirective())
1619 O
<< TAI
->getSetDirective() << ' ' << TAI
->getPrivateGlobalPrefix()
1620 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
1621 printBasicBlockLabel(MBB
, false, false, false);
1622 O
<< '-' << TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1623 << '_' << uid
<< '\n';
1626 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid
, unsigned uid2
,
1627 const MachineBasicBlock
*MBB
) const {
1628 if (!TAI
->getSetDirective())
1631 O
<< TAI
->getSetDirective() << ' ' << TAI
->getPrivateGlobalPrefix()
1632 << getFunctionNumber() << '_' << uid
<< '_' << uid2
1633 << "_set_" << MBB
->getNumber() << ',';
1634 printBasicBlockLabel(MBB
, false, false, false);
1635 O
<< '-' << TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1636 << '_' << uid
<< '_' << uid2
<< '\n';
1639 /// printDataDirective - This method prints the asm directive for the
1641 void AsmPrinter::printDataDirective(const Type
*type
, unsigned AddrSpace
) {
1642 const TargetData
*TD
= TM
.getTargetData();
1643 switch (type
->getTypeID()) {
1644 case Type::FloatTyID
: case Type::DoubleTyID
:
1645 case Type::X86_FP80TyID
: case Type::FP128TyID
: case Type::PPC_FP128TyID
:
1646 assert(0 && "Should have already output floating point constant.");
1648 assert(0 && "Can't handle printing this type of thing");
1649 case Type::IntegerTyID
: {
1650 unsigned BitWidth
= cast
<IntegerType
>(type
)->getBitWidth();
1652 O
<< TAI
->getData8bitsDirective(AddrSpace
);
1653 else if (BitWidth
<= 16)
1654 O
<< TAI
->getData16bitsDirective(AddrSpace
);
1655 else if (BitWidth
<= 32)
1656 O
<< TAI
->getData32bitsDirective(AddrSpace
);
1657 else if (BitWidth
<= 64) {
1658 assert(TAI
->getData64bitsDirective(AddrSpace
) &&
1659 "Target cannot handle 64-bit constant exprs!");
1660 O
<< TAI
->getData64bitsDirective(AddrSpace
);
1662 llvm_unreachable("Target cannot handle given data directive width!");
1666 case Type::PointerTyID
:
1667 if (TD
->getPointerSize() == 8) {
1668 assert(TAI
->getData64bitsDirective(AddrSpace
) &&
1669 "Target cannot handle 64-bit pointer exprs!");
1670 O
<< TAI
->getData64bitsDirective(AddrSpace
);
1671 } else if (TD
->getPointerSize() == 2) {
1672 O
<< TAI
->getData16bitsDirective(AddrSpace
);
1673 } else if (TD
->getPointerSize() == 1) {
1674 O
<< TAI
->getData8bitsDirective(AddrSpace
);
1676 O
<< TAI
->getData32bitsDirective(AddrSpace
);
1682 void AsmPrinter::printVisibility(const std::string
& Name
,
1683 unsigned Visibility
) const {
1684 if (Visibility
== GlobalValue::HiddenVisibility
) {
1685 if (const char *Directive
= TAI
->getHiddenDirective())
1686 O
<< Directive
<< Name
<< '\n';
1687 } else if (Visibility
== GlobalValue::ProtectedVisibility
) {
1688 if (const char *Directive
= TAI
->getProtectedDirective())
1689 O
<< Directive
<< Name
<< '\n';
1693 void AsmPrinter::printOffset(int64_t Offset
) const {
1696 else if (Offset
< 0)
1700 GCMetadataPrinter
*AsmPrinter::GetOrCreateGCPrinter(GCStrategy
*S
) {
1701 if (!S
->usesMetadata())
1704 gcp_iterator GCPI
= GCMetadataPrinters
.find(S
);
1705 if (GCPI
!= GCMetadataPrinters
.end())
1706 return GCPI
->second
;
1708 const char *Name
= S
->getName().c_str();
1710 for (GCMetadataPrinterRegistry::iterator
1711 I
= GCMetadataPrinterRegistry::begin(),
1712 E
= GCMetadataPrinterRegistry::end(); I
!= E
; ++I
)
1713 if (strcmp(Name
, I
->getName()) == 0) {
1714 GCMetadataPrinter
*GMP
= I
->instantiate();
1716 GCMetadataPrinters
.insert(std::make_pair(S
, GMP
));
1720 cerr
<< "no GCMetadataPrinter registered for GC: " << Name
<< "\n";
1721 llvm_unreachable(0);
1724 /// EmitComments - Pretty-print comments for instructions
1725 void AsmPrinter::EmitComments(const MachineInstr
&MI
) const
1728 if (!MI
.getDebugLoc().isUnknown()) {
1729 DebugLocTuple DLT
= MF
->getDebugLocTuple(MI
.getDebugLoc());
1731 // Print source line info
1732 O
.PadToColumn(TAI
->getCommentColumn(), 1);
1733 O
<< TAI
->getCommentString() << " SrcLine ";
1734 if (DLT
.CompileUnit
->hasInitializer()) {
1735 Constant
*Name
= DLT
.CompileUnit
->getInitializer();
1736 if (ConstantArray
*NameString
= dyn_cast
<ConstantArray
>(Name
))
1737 if (NameString
->isString()) {
1738 O
<< NameString
->getAsString() << " ";
1743 O
<< ":" << DLT
.Col
;
1748 /// EmitComments - Pretty-print comments for instructions
1749 void AsmPrinter::EmitComments(const MCInst
&MI
) const
1752 if (!MI
.getDebugLoc().isUnknown()) {
1753 DebugLocTuple DLT
= MF
->getDebugLocTuple(MI
.getDebugLoc());
1755 // Print source line info
1756 O
.PadToColumn(TAI
->getCommentColumn(), 1);
1757 O
<< TAI
->getCommentString() << " SrcLine ";
1758 if (DLT
.CompileUnit
->hasInitializer()) {
1759 Constant
*Name
= DLT
.CompileUnit
->getInitializer();
1760 if (ConstantArray
*NameString
= dyn_cast
<ConstantArray
>(Name
))
1761 if (NameString
->isString()) {
1762 O
<< NameString
->getAsString() << " ";
1767 O
<< ":" << DLT
.Col
;