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/MachineFunction.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/StringExtras.h"
48 static cl::opt
<cl::boolOrDefault
>
49 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
50 cl::init(cl::BOU_UNSET
));
52 char AsmPrinter::ID
= 0;
53 AsmPrinter::AsmPrinter(formatted_raw_ostream
&o
, TargetMachine
&tm
,
54 const MCAsmInfo
*T
, bool VDef
)
55 : MachineFunctionPass(&ID
), FunctionNumber(0), O(o
),
56 TM(tm
), MAI(T
), TRI(tm
.getRegisterInfo()),
58 OutContext(*new MCContext()),
59 OutStreamer(*createAsmStreamer(OutContext
, O
, *T
, this)),
61 LastMI(0), LastFn(0), Counter(~0U),
62 PrevDLT(0, ~0U, ~0U) {
65 case cl::BOU_UNSET
: VerboseAsm
= VDef
; break;
66 case cl::BOU_TRUE
: VerboseAsm
= true; break;
67 case cl::BOU_FALSE
: VerboseAsm
= false; break;
71 AsmPrinter::~AsmPrinter() {
72 for (gcp_iterator I
= GCMetadataPrinters
.begin(),
73 E
= GCMetadataPrinters
.end(); I
!= E
; ++I
)
80 TargetLoweringObjectFile
&AsmPrinter::getObjFileLowering() const {
81 return TM
.getTargetLowering()->getObjFileLowering();
84 /// getCurrentSection() - Return the current section we are emitting to.
85 const MCSection
*AsmPrinter::getCurrentSection() const {
86 return OutStreamer
.getCurrentSection();
90 void AsmPrinter::getAnalysisUsage(AnalysisUsage
&AU
) const {
92 MachineFunctionPass::getAnalysisUsage(AU
);
93 AU
.addRequired
<GCModuleInfo
>();
95 AU
.addRequired
<MachineLoopInfo
>();
98 bool AsmPrinter::doInitialization(Module
&M
) {
99 // Initialize TargetLoweringObjectFile.
100 const_cast<TargetLoweringObjectFile
&>(getObjFileLowering())
101 .Initialize(OutContext
, TM
);
103 Mang
= new Mangler(M
, MAI
->getGlobalPrefix(), MAI
->getPrivateGlobalPrefix(),
104 MAI
->getLinkerPrivateGlobalPrefix());
106 if (MAI
->doesAllowQuotesInName())
107 Mang
->setUseQuotes(true);
109 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
110 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
112 if (MAI
->hasSingleParameterDotFile()) {
113 /* Very minimal debug info. It is ignored if we emit actual
114 debug info. If we don't, this at helps the user find where
115 a function came from. */
116 O
<< "\t.file\t\"" << M
.getModuleIdentifier() << "\"\n";
119 for (GCModuleInfo::iterator I
= MI
->begin(), E
= MI
->end(); I
!= E
; ++I
)
120 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*I
))
121 MP
->beginAssembly(O
, *this, *MAI
);
123 if (!M
.getModuleInlineAsm().empty())
124 O
<< MAI
->getCommentString() << " Start of file scope inline assembly\n"
125 << M
.getModuleInlineAsm()
126 << '\n' << MAI
->getCommentString()
127 << " End of file scope inline assembly\n";
129 if (MAI
->doesSupportDebugInformation() ||
130 MAI
->doesSupportExceptionHandling()) {
131 MMI
= getAnalysisIfAvailable
<MachineModuleInfo
>();
133 MMI
->AnalyzeModule(M
);
134 DW
= getAnalysisIfAvailable
<DwarfWriter
>();
136 DW
->BeginModule(&M
, MMI
, O
, this, MAI
);
142 bool AsmPrinter::doFinalization(Module
&M
) {
143 // Emit global variables.
144 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
146 PrintGlobalVariable(I
);
148 // Emit final debug information.
149 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
152 // If the target wants to know about weak references, print them all.
153 if (MAI
->getWeakRefDirective()) {
154 // FIXME: This is not lazy, it would be nice to only print weak references
155 // to stuff that is actually used. Note that doing so would require targets
156 // to notice uses in operands (due to constant exprs etc). This should
157 // happen with the MC stuff eventually.
159 // Print out module-level global variables here.
160 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
162 if (I
->hasExternalWeakLinkage())
163 O
<< MAI
->getWeakRefDirective() << Mang
->getMangledName(I
) << '\n';
166 for (Module::const_iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
) {
167 if (I
->hasExternalWeakLinkage())
168 O
<< MAI
->getWeakRefDirective() << Mang
->getMangledName(I
) << '\n';
172 if (MAI
->getSetDirective()) {
174 for (Module::const_alias_iterator I
= M
.alias_begin(), E
= M
.alias_end();
176 std::string Name
= Mang
->getMangledName(I
);
178 const GlobalValue
*GV
= cast
<GlobalValue
>(I
->getAliasedGlobal());
179 std::string Target
= Mang
->getMangledName(GV
);
181 if (I
->hasExternalLinkage() || !MAI
->getWeakRefDirective())
182 O
<< "\t.globl\t" << Name
<< '\n';
183 else if (I
->hasWeakLinkage())
184 O
<< MAI
->getWeakRefDirective() << Name
<< '\n';
185 else if (!I
->hasLocalLinkage())
186 llvm_unreachable("Invalid alias linkage");
188 printVisibility(Name
, I
->getVisibility());
190 O
<< MAI
->getSetDirective() << ' ' << Name
<< ", " << Target
<< '\n';
194 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
195 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
196 for (GCModuleInfo::iterator I
= MI
->end(), E
= MI
->begin(); I
!= E
; )
197 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*--I
))
198 MP
->finishAssembly(O
, *this, *MAI
);
200 // If we don't have any trampolines, then we don't require stack memory
201 // to be executable. Some targets have a directive to declare this.
202 Function
*InitTrampolineIntrinsic
= M
.getFunction("llvm.init.trampoline");
203 if (!InitTrampolineIntrinsic
|| InitTrampolineIntrinsic
->use_empty())
204 if (MAI
->getNonexecutableStackDirective())
205 O
<< MAI
->getNonexecutableStackDirective() << '\n';
207 delete Mang
; Mang
= 0;
210 OutStreamer
.Finish();
215 AsmPrinter::getCurrentFunctionEHName(const MachineFunction
*MF
) const {
216 assert(MF
&& "No machine function?");
217 return Mang
->getMangledName(MF
->getFunction(), ".eh",
218 MAI
->is_EHSymbolPrivate());
221 void AsmPrinter::SetupMachineFunction(MachineFunction
&MF
) {
222 // What's my mangled name?
223 CurrentFnName
= Mang
->getMangledName(MF
.getFunction());
224 IncrementFunctionNumber();
227 LI
= &getAnalysis
<MachineLoopInfo
>();
232 // SectionCPs - Keep track the alignment, constpool entries per Section.
236 SmallVector
<unsigned, 4> CPEs
;
237 SectionCPs(const MCSection
*s
, unsigned a
) : S(s
), Alignment(a
) {};
241 /// EmitConstantPool - Print to the current output stream assembly
242 /// representations of the constants in the constant pool MCP. This is
243 /// used to print out constants which have been "spilled to memory" by
244 /// the code generator.
246 void AsmPrinter::EmitConstantPool(MachineConstantPool
*MCP
) {
247 const std::vector
<MachineConstantPoolEntry
> &CP
= MCP
->getConstants();
248 if (CP
.empty()) return;
250 // Calculate sections for constant pool entries. We collect entries to go into
251 // the same section together to reduce amount of section switch statements.
252 SmallVector
<SectionCPs
, 4> CPSections
;
253 for (unsigned i
= 0, e
= CP
.size(); i
!= e
; ++i
) {
254 const MachineConstantPoolEntry
&CPE
= CP
[i
];
255 unsigned Align
= CPE
.getAlignment();
258 switch (CPE
.getRelocationInfo()) {
259 default: llvm_unreachable("Unknown section kind");
260 case 2: Kind
= SectionKind::getReadOnlyWithRel(); break;
262 Kind
= SectionKind::getReadOnlyWithRelLocal();
265 switch (TM
.getTargetData()->getTypeAllocSize(CPE
.getType())) {
266 case 4: Kind
= SectionKind::getMergeableConst4(); break;
267 case 8: Kind
= SectionKind::getMergeableConst8(); break;
268 case 16: Kind
= SectionKind::getMergeableConst16();break;
269 default: Kind
= SectionKind::getMergeableConst(); break;
273 const MCSection
*S
= getObjFileLowering().getSectionForConstant(Kind
);
275 // The number of sections are small, just do a linear search from the
276 // last section to the first.
278 unsigned SecIdx
= CPSections
.size();
279 while (SecIdx
!= 0) {
280 if (CPSections
[--SecIdx
].S
== S
) {
286 SecIdx
= CPSections
.size();
287 CPSections
.push_back(SectionCPs(S
, Align
));
290 if (Align
> CPSections
[SecIdx
].Alignment
)
291 CPSections
[SecIdx
].Alignment
= Align
;
292 CPSections
[SecIdx
].CPEs
.push_back(i
);
295 // Now print stuff into the calculated sections.
296 for (unsigned i
= 0, e
= CPSections
.size(); i
!= e
; ++i
) {
297 OutStreamer
.SwitchSection(CPSections
[i
].S
);
298 EmitAlignment(Log2_32(CPSections
[i
].Alignment
));
301 for (unsigned j
= 0, ee
= CPSections
[i
].CPEs
.size(); j
!= ee
; ++j
) {
302 unsigned CPI
= CPSections
[i
].CPEs
[j
];
303 MachineConstantPoolEntry CPE
= CP
[CPI
];
305 // Emit inter-object padding for alignment.
306 unsigned AlignMask
= CPE
.getAlignment() - 1;
307 unsigned NewOffset
= (Offset
+ AlignMask
) & ~AlignMask
;
308 EmitZeros(NewOffset
- Offset
);
310 const Type
*Ty
= CPE
.getType();
311 Offset
= NewOffset
+ TM
.getTargetData()->getTypeAllocSize(Ty
);
313 O
<< MAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
316 O
.PadToColumn(MAI
->getCommentColumn());
317 O
<< MAI
->getCommentString() << " constant ";
318 WriteTypeSymbolic(O
, CPE
.getType(), MF
->getFunction()->getParent());
321 if (CPE
.isMachineConstantPoolEntry())
322 EmitMachineConstantPoolValue(CPE
.Val
.MachineCPVal
);
324 EmitGlobalConstant(CPE
.Val
.ConstVal
);
329 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
330 /// by the current function to the current output stream.
332 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo
*MJTI
,
333 MachineFunction
&MF
) {
334 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
335 if (JT
.empty()) return;
337 bool IsPic
= TM
.getRelocationModel() == Reloc::PIC_
;
339 // Pick the directive to use to print the jump table entries, and switch to
340 // the appropriate section.
341 TargetLowering
*LoweringInfo
= TM
.getTargetLowering();
343 const Function
*F
= MF
.getFunction();
344 bool JTInDiffSection
= false;
345 if (F
->isWeakForLinker() ||
346 (IsPic
&& !LoweringInfo
->usesGlobalOffsetTable())) {
347 // In PIC mode, we need to emit the jump table to the same section as the
348 // function body itself, otherwise the label differences won't make sense.
349 // We should also do if the section name is NULL or function is declared in
350 // discardable section.
351 OutStreamer
.SwitchSection(getObjFileLowering().SectionForGlobal(F
, Mang
,
354 // Otherwise, drop it in the readonly section.
355 const MCSection
*ReadOnlySection
=
356 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
357 OutStreamer
.SwitchSection(ReadOnlySection
);
358 JTInDiffSection
= true;
361 EmitAlignment(Log2_32(MJTI
->getAlignment()));
363 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
) {
364 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[i
].MBBs
;
366 // If this jump table was deleted, ignore it.
367 if (JTBBs
.empty()) continue;
369 // For PIC codegen, if possible we want to use the SetDirective to reduce
370 // the number of relocations the assembler will generate for the jump table.
371 // Set directives are all printed before the jump table itself.
372 SmallPtrSet
<MachineBasicBlock
*, 16> EmittedSets
;
373 if (MAI
->getSetDirective() && IsPic
)
374 for (unsigned ii
= 0, ee
= JTBBs
.size(); ii
!= ee
; ++ii
)
375 if (EmittedSets
.insert(JTBBs
[ii
]))
376 printPICJumpTableSetLabel(i
, JTBBs
[ii
]);
378 // On some targets (e.g. Darwin) we want to emit two consequtive labels
379 // before each jump table. The first label is never referenced, but tells
380 // the assembler and linker the extents of the jump table object. The
381 // second label is actually referenced by the code.
382 if (JTInDiffSection
&& MAI
->getLinkerPrivateGlobalPrefix()[0]) {
383 O
<< MAI
->getLinkerPrivateGlobalPrefix()
384 << "JTI" << getFunctionNumber() << '_' << i
<< ":\n";
387 O
<< MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
388 << '_' << i
<< ":\n";
390 for (unsigned ii
= 0, ee
= JTBBs
.size(); ii
!= ee
; ++ii
) {
391 printPICJumpTableEntry(MJTI
, JTBBs
[ii
], i
);
397 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
398 const MachineBasicBlock
*MBB
,
399 unsigned uid
) const {
400 bool isPIC
= TM
.getRelocationModel() == Reloc::PIC_
;
402 // Use JumpTableDirective otherwise honor the entry size from the jump table
404 const char *JTEntryDirective
= MAI
->getJumpTableDirective(isPIC
);
405 bool HadJTEntryDirective
= JTEntryDirective
!= NULL
;
406 if (!HadJTEntryDirective
) {
407 JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
408 MAI
->getData32bitsDirective() : MAI
->getData64bitsDirective();
411 O
<< JTEntryDirective
<< ' ';
413 // If we have emitted set directives for the jump table entries, print
414 // them rather than the entries themselves. If we're emitting PIC, then
415 // emit the table entries as differences between two text section labels.
416 // If we're emitting non-PIC code, then emit the entries as direct
417 // references to the target basic blocks.
419 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
420 } else if (MAI
->getSetDirective()) {
421 O
<< MAI
->getPrivateGlobalPrefix() << getFunctionNumber()
422 << '_' << uid
<< "_set_" << MBB
->getNumber();
424 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
425 // If the arch uses custom Jump Table directives, don't calc relative to
427 if (!HadJTEntryDirective
)
428 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI"
429 << getFunctionNumber() << '_' << uid
;
434 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
435 /// special global used by LLVM. If so, emit it and return true, otherwise
436 /// do nothing and return false.
437 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable
*GV
) {
438 if (GV
->getName() == "llvm.used") {
439 if (MAI
->getUsedDirective() != 0) // No need to emit this at all.
440 EmitLLVMUsedList(GV
->getInitializer());
444 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
445 if (GV
->getSection() == "llvm.metadata" ||
446 GV
->hasAvailableExternallyLinkage())
449 if (!GV
->hasAppendingLinkage()) return false;
451 assert(GV
->hasInitializer() && "Not a special LLVM global!");
453 const TargetData
*TD
= TM
.getTargetData();
454 unsigned Align
= Log2_32(TD
->getPointerPrefAlignment());
455 if (GV
->getName() == "llvm.global_ctors") {
456 OutStreamer
.SwitchSection(getObjFileLowering().getStaticCtorSection());
457 EmitAlignment(Align
, 0);
458 EmitXXStructorList(GV
->getInitializer());
462 if (GV
->getName() == "llvm.global_dtors") {
463 OutStreamer
.SwitchSection(getObjFileLowering().getStaticDtorSection());
464 EmitAlignment(Align
, 0);
465 EmitXXStructorList(GV
->getInitializer());
472 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
473 /// global in the specified llvm.used list for which emitUsedDirectiveFor
474 /// is true, as being used with this directive.
475 void AsmPrinter::EmitLLVMUsedList(Constant
*List
) {
476 const char *Directive
= MAI
->getUsedDirective();
478 // Should be an array of 'i8*'.
479 ConstantArray
*InitList
= dyn_cast
<ConstantArray
>(List
);
480 if (InitList
== 0) return;
482 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
483 const GlobalValue
*GV
=
484 dyn_cast
<GlobalValue
>(InitList
->getOperand(i
)->stripPointerCasts());
485 if (GV
&& getObjFileLowering().shouldEmitUsedDirectiveFor(GV
, Mang
)) {
487 EmitConstantValueOnly(InitList
->getOperand(i
));
493 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
494 /// function pointers, ignoring the init priority.
495 void AsmPrinter::EmitXXStructorList(Constant
*List
) {
496 // Should be an array of '{ int, void ()* }' structs. The first value is the
497 // init priority, which we ignore.
498 if (!isa
<ConstantArray
>(List
)) return;
499 ConstantArray
*InitList
= cast
<ConstantArray
>(List
);
500 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
)
501 if (ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(InitList
->getOperand(i
))){
502 if (CS
->getNumOperands() != 2) return; // Not array of 2-element structs.
504 if (CS
->getOperand(1)->isNullValue())
505 return; // Found a null terminator, exit printing.
506 // Emit the function pointer.
507 EmitGlobalConstant(CS
->getOperand(1));
511 /// getGlobalLinkName - Returns the asm/link name of of the specified
512 /// global variable. Should be overridden by each target asm printer to
513 /// generate the appropriate value.
514 const std::string
&AsmPrinter::getGlobalLinkName(const GlobalVariable
*GV
,
515 std::string
&LinkName
) const {
516 if (isa
<Function
>(GV
)) {
517 LinkName
+= MAI
->getFunctionAddrPrefix();
518 LinkName
+= Mang
->getMangledName(GV
);
519 LinkName
+= MAI
->getFunctionAddrSuffix();
521 LinkName
+= MAI
->getGlobalVarAddrPrefix();
522 LinkName
+= Mang
->getMangledName(GV
);
523 LinkName
+= MAI
->getGlobalVarAddrSuffix();
529 /// EmitExternalGlobal - Emit the external reference to a global variable.
530 /// Should be overridden if an indirect reference should be used.
531 void AsmPrinter::EmitExternalGlobal(const GlobalVariable
*GV
) {
533 O
<< getGlobalLinkName(GV
, GLN
);
538 //===----------------------------------------------------------------------===//
539 /// LEB 128 number encoding.
541 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
542 /// representing an unsigned leb128 value.
543 void AsmPrinter::PrintULEB128(unsigned Value
) const {
546 unsigned char Byte
= static_cast<unsigned char>(Value
& 0x7f);
548 if (Value
) Byte
|= 0x80;
549 O
<< "0x" << utohex_buffer(Byte
, Buffer
+20);
550 if (Value
) O
<< ", ";
554 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
555 /// representing a signed leb128 value.
556 void AsmPrinter::PrintSLEB128(int Value
) const {
557 int Sign
= Value
>> (8 * sizeof(Value
) - 1);
562 unsigned char Byte
= static_cast<unsigned char>(Value
& 0x7f);
564 IsMore
= Value
!= Sign
|| ((Byte
^ Sign
) & 0x40) != 0;
565 if (IsMore
) Byte
|= 0x80;
566 O
<< "0x" << utohex_buffer(Byte
, Buffer
+20);
567 if (IsMore
) O
<< ", ";
571 //===--------------------------------------------------------------------===//
572 // Emission and print routines
575 /// PrintHex - Print a value as a hexidecimal value.
577 void AsmPrinter::PrintHex(int Value
) const {
579 O
<< "0x" << utohex_buffer(static_cast<unsigned>(Value
), Buffer
+20);
582 /// EOL - Print a newline character to asm stream. If a comment is present
583 /// then it will be printed first. Comments should not contain '\n'.
584 void AsmPrinter::EOL() const {
588 void AsmPrinter::EOL(const std::string
&Comment
) const {
589 if (VerboseAsm
&& !Comment
.empty()) {
590 O
.PadToColumn(MAI
->getCommentColumn());
591 O
<< MAI
->getCommentString()
598 void AsmPrinter::EOL(const char* Comment
) const {
599 if (VerboseAsm
&& *Comment
) {
600 O
.PadToColumn(MAI
->getCommentColumn());
601 O
<< MAI
->getCommentString()
608 static const char *DecodeDWARFEncoding(unsigned Encoding
) {
610 case dwarf::DW_EH_PE_absptr
:
612 case dwarf::DW_EH_PE_omit
:
614 case dwarf::DW_EH_PE_pcrel
:
616 case dwarf::DW_EH_PE_udata4
:
618 case dwarf::DW_EH_PE_udata8
:
620 case dwarf::DW_EH_PE_sdata4
:
622 case dwarf::DW_EH_PE_sdata8
:
624 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_udata4
:
625 return "pcrel udata4";
626 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
:
627 return "pcrel sdata4";
628 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_udata8
:
629 return "pcrel udata8";
630 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata8
:
631 return "pcrel sdata8";
632 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_udata4
:
633 return "indirect pcrel udata4";
634 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_sdata4
:
635 return "indirect pcrel sdata4";
636 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_udata8
:
637 return "indirect pcrel udata8";
638 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_sdata8
:
639 return "indirect pcrel sdata8";
645 void AsmPrinter::EOL(const char *Comment
, unsigned Encoding
) const {
646 if (VerboseAsm
&& *Comment
) {
647 O
.PadToColumn(MAI
->getCommentColumn());
648 O
<< MAI
->getCommentString()
652 if (const char *EncStr
= DecodeDWARFEncoding(Encoding
))
653 O
<< " (" << EncStr
<< ')';
658 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
659 /// unsigned leb128 value.
660 void AsmPrinter::EmitULEB128Bytes(unsigned Value
) const {
661 if (MAI
->hasLEB128()) {
665 O
<< MAI
->getData8bitsDirective();
670 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
671 /// signed leb128 value.
672 void AsmPrinter::EmitSLEB128Bytes(int Value
) const {
673 if (MAI
->hasLEB128()) {
677 O
<< MAI
->getData8bitsDirective();
682 /// EmitInt8 - Emit a byte directive and value.
684 void AsmPrinter::EmitInt8(int Value
) const {
685 O
<< MAI
->getData8bitsDirective();
686 PrintHex(Value
& 0xFF);
689 /// EmitInt16 - Emit a short directive and value.
691 void AsmPrinter::EmitInt16(int Value
) const {
692 O
<< MAI
->getData16bitsDirective();
693 PrintHex(Value
& 0xFFFF);
696 /// EmitInt32 - Emit a long directive and value.
698 void AsmPrinter::EmitInt32(int Value
) const {
699 O
<< MAI
->getData32bitsDirective();
703 /// EmitInt64 - Emit a long long directive and value.
705 void AsmPrinter::EmitInt64(uint64_t Value
) const {
706 if (MAI
->getData64bitsDirective()) {
707 O
<< MAI
->getData64bitsDirective();
710 if (TM
.getTargetData()->isBigEndian()) {
711 EmitInt32(unsigned(Value
>> 32)); O
<< '\n';
712 EmitInt32(unsigned(Value
));
714 EmitInt32(unsigned(Value
)); O
<< '\n';
715 EmitInt32(unsigned(Value
>> 32));
720 /// toOctal - Convert the low order bits of X into an octal digit.
722 static inline char toOctal(int X
) {
726 /// printStringChar - Print a char, escaped if necessary.
728 static void printStringChar(formatted_raw_ostream
&O
, unsigned char C
) {
731 } else if (C
== '\\') {
733 } else if (isprint((unsigned char)C
)) {
737 case '\b': O
<< "\\b"; break;
738 case '\f': O
<< "\\f"; break;
739 case '\n': O
<< "\\n"; break;
740 case '\r': O
<< "\\r"; break;
741 case '\t': O
<< "\\t"; break;
744 O
<< toOctal(C
>> 6);
745 O
<< toOctal(C
>> 3);
746 O
<< toOctal(C
>> 0);
752 /// EmitString - Emit a string with quotes and a null terminator.
753 /// Special characters are emitted properly.
754 /// \literal (Eg. '\t') \endliteral
755 void AsmPrinter::EmitString(const std::string
&String
) const {
756 EmitString(String
.c_str(), String
.size());
759 void AsmPrinter::EmitString(const char *String
, unsigned Size
) const {
760 const char* AscizDirective
= MAI
->getAscizDirective();
764 O
<< MAI
->getAsciiDirective();
766 for (unsigned i
= 0; i
< Size
; ++i
)
767 printStringChar(O
, String
[i
]);
775 /// EmitFile - Emit a .file directive.
776 void AsmPrinter::EmitFile(unsigned Number
, const std::string
&Name
) const {
777 O
<< "\t.file\t" << Number
<< " \"";
778 for (unsigned i
= 0, N
= Name
.size(); i
< N
; ++i
)
779 printStringChar(O
, Name
[i
]);
784 //===----------------------------------------------------------------------===//
786 // EmitAlignment - Emit an alignment directive to the specified power of
787 // two boundary. For example, if you pass in 3 here, you will get an 8
788 // byte alignment. If a global value is specified, and if that global has
789 // an explicit alignment requested, it will unconditionally override the
790 // alignment request. However, if ForcedAlignBits is specified, this value
791 // has final say: the ultimate alignment will be the max of ForcedAlignBits
792 // and the alignment computed with NumBits and the global.
796 // if (GV && GV->hasalignment) Align = GV->getalignment();
797 // Align = std::max(Align, ForcedAlignBits);
799 void AsmPrinter::EmitAlignment(unsigned NumBits
, const GlobalValue
*GV
,
800 unsigned ForcedAlignBits
,
801 bool UseFillExpr
) const {
802 if (GV
&& GV
->getAlignment())
803 NumBits
= Log2_32(GV
->getAlignment());
804 NumBits
= std::max(NumBits
, ForcedAlignBits
);
806 if (NumBits
== 0) return; // No need to emit alignment.
808 unsigned FillValue
= 0;
809 if (getCurrentSection()->getKind().isText())
810 FillValue
= MAI
->getTextAlignFillValue();
812 OutStreamer
.EmitValueToAlignment(1 << NumBits
, FillValue
, 1, 0);
815 /// EmitZeros - Emit a block of zeros.
817 void AsmPrinter::EmitZeros(uint64_t NumZeros
, unsigned AddrSpace
) const {
819 if (MAI
->getZeroDirective()) {
820 O
<< MAI
->getZeroDirective() << NumZeros
;
821 if (MAI
->getZeroDirectiveSuffix())
822 O
<< MAI
->getZeroDirectiveSuffix();
825 for (; NumZeros
; --NumZeros
)
826 O
<< MAI
->getData8bitsDirective(AddrSpace
) << "0\n";
831 // Print out the specified constant, without a storage class. Only the
832 // constants valid in constant expressions can occur here.
833 void AsmPrinter::EmitConstantValueOnly(const Constant
*CV
) {
834 if (CV
->isNullValue() || isa
<UndefValue
>(CV
))
836 else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
837 O
<< CI
->getZExtValue();
838 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CV
)) {
839 // This is a constant address for a global variable or function. Use the
840 // name of the variable or function as the address value, possibly
841 // decorating it with GlobalVarAddrPrefix/Suffix or
842 // FunctionAddrPrefix/Suffix (these all default to "" )
843 if (isa
<Function
>(GV
)) {
844 O
<< MAI
->getFunctionAddrPrefix()
845 << Mang
->getMangledName(GV
)
846 << MAI
->getFunctionAddrSuffix();
848 O
<< MAI
->getGlobalVarAddrPrefix()
849 << Mang
->getMangledName(GV
)
850 << MAI
->getGlobalVarAddrSuffix();
852 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
853 const TargetData
*TD
= TM
.getTargetData();
854 unsigned Opcode
= CE
->getOpcode();
856 case Instruction::Trunc
:
857 case Instruction::ZExt
:
858 case Instruction::SExt
:
859 case Instruction::FPTrunc
:
860 case Instruction::FPExt
:
861 case Instruction::UIToFP
:
862 case Instruction::SIToFP
:
863 case Instruction::FPToUI
:
864 case Instruction::FPToSI
:
865 llvm_unreachable("FIXME: Don't support this constant cast expr");
866 case Instruction::GetElementPtr
: {
867 // generate a symbolic expression for the byte address
868 const Constant
*ptrVal
= CE
->getOperand(0);
869 SmallVector
<Value
*, 8> idxVec(CE
->op_begin()+1, CE
->op_end());
870 if (int64_t Offset
= TD
->getIndexedOffset(ptrVal
->getType(), &idxVec
[0],
872 // Truncate/sext the offset to the pointer size.
873 if (TD
->getPointerSizeInBits() != 64) {
874 int SExtAmount
= 64-TD
->getPointerSizeInBits();
875 Offset
= (Offset
<< SExtAmount
) >> SExtAmount
;
880 EmitConstantValueOnly(ptrVal
);
882 O
<< ") + " << Offset
;
884 O
<< ") - " << -Offset
;
886 EmitConstantValueOnly(ptrVal
);
890 case Instruction::BitCast
:
891 return EmitConstantValueOnly(CE
->getOperand(0));
893 case Instruction::IntToPtr
: {
894 // Handle casts to pointers by changing them into casts to the appropriate
895 // integer type. This promotes constant folding and simplifies this code.
896 Constant
*Op
= CE
->getOperand(0);
897 Op
= ConstantExpr::getIntegerCast(Op
, TD
->getIntPtrType(CV
->getContext()),
899 return EmitConstantValueOnly(Op
);
903 case Instruction::PtrToInt
: {
904 // Support only foldable casts to/from pointers that can be eliminated by
905 // changing the pointer to the appropriately sized integer type.
906 Constant
*Op
= CE
->getOperand(0);
907 const Type
*Ty
= CE
->getType();
909 // We can emit the pointer value into this slot if the slot is an
910 // integer slot greater or equal to the size of the pointer.
911 if (TD
->getTypeAllocSize(Ty
) == TD
->getTypeAllocSize(Op
->getType()))
912 return EmitConstantValueOnly(Op
);
915 EmitConstantValueOnly(Op
);
917 APInt::getAllOnesValue(TD
->getTypeAllocSizeInBits(Op
->getType()));
920 ptrMask
.toStringUnsigned(S
);
921 O
<< ") & " << S
.str() << ')';
924 case Instruction::Add
:
925 case Instruction::Sub
:
926 case Instruction::And
:
927 case Instruction::Or
:
928 case Instruction::Xor
:
930 EmitConstantValueOnly(CE
->getOperand(0));
933 case Instruction::Add
:
936 case Instruction::Sub
:
939 case Instruction::And
:
942 case Instruction::Or
:
945 case Instruction::Xor
:
952 EmitConstantValueOnly(CE
->getOperand(1));
956 llvm_unreachable("Unsupported operator!");
959 llvm_unreachable("Unknown constant value!");
963 /// printAsCString - Print the specified array as a C compatible string, only if
964 /// the predicate isString is true.
966 static void printAsCString(formatted_raw_ostream
&O
, const ConstantArray
*CVA
,
968 assert(CVA
->isString() && "Array is not string compatible!");
971 for (unsigned i
= 0; i
!= LastElt
; ++i
) {
973 (unsigned char)cast
<ConstantInt
>(CVA
->getOperand(i
))->getZExtValue();
974 printStringChar(O
, C
);
979 /// EmitString - Emit a zero-byte-terminated string constant.
981 void AsmPrinter::EmitString(const ConstantArray
*CVA
) const {
982 unsigned NumElts
= CVA
->getNumOperands();
983 if (MAI
->getAscizDirective() && NumElts
&&
984 cast
<ConstantInt
>(CVA
->getOperand(NumElts
-1))->getZExtValue() == 0) {
985 O
<< MAI
->getAscizDirective();
986 printAsCString(O
, CVA
, NumElts
-1);
988 O
<< MAI
->getAsciiDirective();
989 printAsCString(O
, CVA
, NumElts
);
994 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray
*CVA
,
995 unsigned AddrSpace
) {
996 if (CVA
->isString()) {
998 } else { // Not a string. Print the values in successive locations
999 for (unsigned i
= 0, e
= CVA
->getNumOperands(); i
!= e
; ++i
)
1000 EmitGlobalConstant(CVA
->getOperand(i
), AddrSpace
);
1004 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector
*CP
) {
1005 const VectorType
*PTy
= CP
->getType();
1007 for (unsigned I
= 0, E
= PTy
->getNumElements(); I
< E
; ++I
)
1008 EmitGlobalConstant(CP
->getOperand(I
));
1011 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct
*CVS
,
1012 unsigned AddrSpace
) {
1013 // Print the fields in successive locations. Pad to align if needed!
1014 const TargetData
*TD
= TM
.getTargetData();
1015 unsigned Size
= TD
->getTypeAllocSize(CVS
->getType());
1016 const StructLayout
*cvsLayout
= TD
->getStructLayout(CVS
->getType());
1017 uint64_t sizeSoFar
= 0;
1018 for (unsigned i
= 0, e
= CVS
->getNumOperands(); i
!= e
; ++i
) {
1019 const Constant
* field
= CVS
->getOperand(i
);
1021 // Check if padding is needed and insert one or more 0s.
1022 uint64_t fieldSize
= TD
->getTypeAllocSize(field
->getType());
1023 uint64_t padSize
= ((i
== e
-1 ? Size
: cvsLayout
->getElementOffset(i
+1))
1024 - cvsLayout
->getElementOffset(i
)) - fieldSize
;
1025 sizeSoFar
+= fieldSize
+ padSize
;
1027 // Now print the actual field value.
1028 EmitGlobalConstant(field
, AddrSpace
);
1030 // Insert padding - this may include padding to increase the size of the
1031 // current field up to the ABI size (if the struct is not packed) as well
1032 // as padding to ensure that the next field starts at the right offset.
1033 EmitZeros(padSize
, AddrSpace
);
1035 assert(sizeSoFar
== cvsLayout
->getSizeInBytes() &&
1036 "Layout of constant struct may be incorrect!");
1039 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP
*CFP
,
1040 unsigned AddrSpace
) {
1041 // FP Constants are printed as integer constants to avoid losing
1043 LLVMContext
&Context
= CFP
->getContext();
1044 const TargetData
*TD
= TM
.getTargetData();
1045 if (CFP
->getType() == Type::getDoubleTy(Context
)) {
1046 double Val
= CFP
->getValueAPF().convertToDouble(); // for comment only
1047 uint64_t i
= CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
1048 if (MAI
->getData64bitsDirective(AddrSpace
)) {
1049 O
<< MAI
->getData64bitsDirective(AddrSpace
) << i
;
1051 O
.PadToColumn(MAI
->getCommentColumn());
1052 O
<< MAI
->getCommentString() << " double " << Val
;
1055 } else if (TD
->isBigEndian()) {
1056 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
>> 32);
1058 O
.PadToColumn(MAI
->getCommentColumn());
1059 O
<< MAI
->getCommentString()
1060 << " most significant word of double " << Val
;
1063 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
);
1065 O
.PadToColumn(MAI
->getCommentColumn());
1066 O
<< MAI
->getCommentString()
1067 << " least significant word of double " << Val
;
1071 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
);
1073 O
.PadToColumn(MAI
->getCommentColumn());
1074 O
<< MAI
->getCommentString()
1075 << " least significant word of double " << Val
;
1078 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
>> 32);
1080 O
.PadToColumn(MAI
->getCommentColumn());
1081 O
<< MAI
->getCommentString()
1082 << " most significant word of double " << Val
;
1087 } else if (CFP
->getType() == Type::getFloatTy(Context
)) {
1088 float Val
= CFP
->getValueAPF().convertToFloat(); // for comment only
1089 O
<< MAI
->getData32bitsDirective(AddrSpace
)
1090 << CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
1092 O
.PadToColumn(MAI
->getCommentColumn());
1093 O
<< MAI
->getCommentString() << " float " << Val
;
1097 } else if (CFP
->getType() == Type::getX86_FP80Ty(Context
)) {
1098 // all long double variants are printed as hex
1099 // api needed to prevent premature destruction
1100 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
1101 const uint64_t *p
= api
.getRawData();
1102 // Convert to double so we can print the approximate val as a comment.
1103 APFloat DoubleVal
= CFP
->getValueAPF();
1105 DoubleVal
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
,
1107 if (TD
->isBigEndian()) {
1108 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[1]);
1110 O
.PadToColumn(MAI
->getCommentColumn());
1111 O
<< MAI
->getCommentString()
1112 << " most significant halfword of x86_fp80 ~"
1113 << DoubleVal
.convertToDouble();
1116 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 48);
1118 O
.PadToColumn(MAI
->getCommentColumn());
1119 O
<< MAI
->getCommentString() << " next halfword";
1122 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 32);
1124 O
.PadToColumn(MAI
->getCommentColumn());
1125 O
<< MAI
->getCommentString() << " next halfword";
1128 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 16);
1130 O
.PadToColumn(MAI
->getCommentColumn());
1131 O
<< MAI
->getCommentString() << " next halfword";
1134 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0]);
1136 O
.PadToColumn(MAI
->getCommentColumn());
1137 O
<< MAI
->getCommentString()
1138 << " least significant halfword";
1142 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0]);
1144 O
.PadToColumn(MAI
->getCommentColumn());
1145 O
<< MAI
->getCommentString()
1146 << " least significant halfword of x86_fp80 ~"
1147 << DoubleVal
.convertToDouble();
1150 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 16);
1152 O
.PadToColumn(MAI
->getCommentColumn());
1153 O
<< MAI
->getCommentString()
1154 << " next halfword";
1157 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 32);
1159 O
.PadToColumn(MAI
->getCommentColumn());
1160 O
<< MAI
->getCommentString()
1161 << " next halfword";
1164 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 48);
1166 O
.PadToColumn(MAI
->getCommentColumn());
1167 O
<< MAI
->getCommentString()
1168 << " next halfword";
1171 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[1]);
1173 O
.PadToColumn(MAI
->getCommentColumn());
1174 O
<< MAI
->getCommentString()
1175 << " most significant halfword";
1179 EmitZeros(TD
->getTypeAllocSize(Type::getX86_FP80Ty(Context
)) -
1180 TD
->getTypeStoreSize(Type::getX86_FP80Ty(Context
)), AddrSpace
);
1182 } else if (CFP
->getType() == Type::getPPC_FP128Ty(Context
)) {
1183 // all long double variants are printed as hex
1184 // api needed to prevent premature destruction
1185 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
1186 const uint64_t *p
= api
.getRawData();
1187 if (TD
->isBigEndian()) {
1188 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0] >> 32);
1190 O
.PadToColumn(MAI
->getCommentColumn());
1191 O
<< MAI
->getCommentString()
1192 << " most significant word of ppc_fp128";
1195 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0]);
1197 O
.PadToColumn(MAI
->getCommentColumn());
1198 O
<< MAI
->getCommentString()
1202 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1] >> 32);
1204 O
.PadToColumn(MAI
->getCommentColumn());
1205 O
<< MAI
->getCommentString()
1209 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1]);
1211 O
.PadToColumn(MAI
->getCommentColumn());
1212 O
<< MAI
->getCommentString()
1213 << " least significant word";
1217 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1]);
1219 O
.PadToColumn(MAI
->getCommentColumn());
1220 O
<< MAI
->getCommentString()
1221 << " least significant word of ppc_fp128";
1224 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1] >> 32);
1226 O
.PadToColumn(MAI
->getCommentColumn());
1227 O
<< MAI
->getCommentString()
1231 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0]);
1233 O
.PadToColumn(MAI
->getCommentColumn());
1234 O
<< MAI
->getCommentString()
1238 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0] >> 32);
1240 O
.PadToColumn(MAI
->getCommentColumn());
1241 O
<< MAI
->getCommentString()
1242 << " most significant word";
1247 } else llvm_unreachable("Floating point constant type not handled");
1250 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt
*CI
,
1251 unsigned AddrSpace
) {
1252 const TargetData
*TD
= TM
.getTargetData();
1253 unsigned BitWidth
= CI
->getBitWidth();
1254 assert(isPowerOf2_32(BitWidth
) &&
1255 "Non-power-of-2-sized integers not handled!");
1257 // We don't expect assemblers to support integer data directives
1258 // for more than 64 bits, so we emit the data in at most 64-bit
1259 // quantities at a time.
1260 const uint64_t *RawData
= CI
->getValue().getRawData();
1261 for (unsigned i
= 0, e
= BitWidth
/ 64; i
!= e
; ++i
) {
1263 if (TD
->isBigEndian())
1264 Val
= RawData
[e
- i
- 1];
1268 if (MAI
->getData64bitsDirective(AddrSpace
))
1269 O
<< MAI
->getData64bitsDirective(AddrSpace
) << Val
<< '\n';
1270 else if (TD
->isBigEndian()) {
1271 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
>> 32);
1273 O
.PadToColumn(MAI
->getCommentColumn());
1274 O
<< MAI
->getCommentString()
1275 << " most significant half of i64 " << Val
;
1278 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
);
1280 O
.PadToColumn(MAI
->getCommentColumn());
1281 O
<< MAI
->getCommentString()
1282 << " least significant half of i64 " << Val
;
1286 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
);
1288 O
.PadToColumn(MAI
->getCommentColumn());
1289 O
<< MAI
->getCommentString()
1290 << " least significant half of i64 " << Val
;
1293 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
>> 32);
1295 O
.PadToColumn(MAI
->getCommentColumn());
1296 O
<< MAI
->getCommentString()
1297 << " most significant half of i64 " << Val
;
1304 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1305 void AsmPrinter::EmitGlobalConstant(const Constant
*CV
, unsigned AddrSpace
) {
1306 const TargetData
*TD
= TM
.getTargetData();
1307 const Type
*type
= CV
->getType();
1308 unsigned Size
= TD
->getTypeAllocSize(type
);
1310 if (CV
->isNullValue() || isa
<UndefValue
>(CV
)) {
1311 EmitZeros(Size
, AddrSpace
);
1313 } else if (const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(CV
)) {
1314 EmitGlobalConstantArray(CVA
, AddrSpace
);
1316 } else if (const ConstantStruct
*CVS
= dyn_cast
<ConstantStruct
>(CV
)) {
1317 EmitGlobalConstantStruct(CVS
, AddrSpace
);
1319 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
1320 EmitGlobalConstantFP(CFP
, AddrSpace
);
1322 } else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1323 // Small integers are handled below; large integers are handled here.
1325 EmitGlobalConstantLargeInt(CI
, AddrSpace
);
1328 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CV
)) {
1329 EmitGlobalConstantVector(CP
);
1333 printDataDirective(type
, AddrSpace
);
1334 EmitConstantValueOnly(CV
);
1336 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1338 CI
->getValue().toStringUnsigned(S
, 16);
1339 O
.PadToColumn(MAI
->getCommentColumn());
1340 O
<< MAI
->getCommentString() << " 0x" << S
.str();
1346 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue
*MCPV
) {
1347 // Target doesn't support this yet!
1348 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1351 /// PrintSpecial - Print information related to the specified machine instr
1352 /// that is independent of the operand, and may be independent of the instr
1353 /// itself. This can be useful for portably encoding the comment character
1354 /// or other bits of target-specific knowledge into the asmstrings. The
1355 /// syntax used is ${:comment}. Targets can override this to add support
1356 /// for their own strange codes.
1357 void AsmPrinter::PrintSpecial(const MachineInstr
*MI
, const char *Code
) const {
1358 if (!strcmp(Code
, "private")) {
1359 O
<< MAI
->getPrivateGlobalPrefix();
1360 } else if (!strcmp(Code
, "comment")) {
1362 O
<< MAI
->getCommentString();
1363 } else if (!strcmp(Code
, "uid")) {
1364 // Comparing the address of MI isn't sufficient, because machineinstrs may
1365 // be allocated to the same address across functions.
1366 const Function
*ThisF
= MI
->getParent()->getParent()->getFunction();
1368 // If this is a new LastFn instruction, bump the counter.
1369 if (LastMI
!= MI
|| LastFn
!= ThisF
) {
1377 raw_string_ostream
Msg(msg
);
1378 Msg
<< "Unknown special formatter '" << Code
1379 << "' for machine instr: " << *MI
;
1380 llvm_report_error(Msg
.str());
1384 /// processDebugLoc - Processes the debug information of each machine
1385 /// instruction's DebugLoc.
1386 void AsmPrinter::processDebugLoc(DebugLoc DL
) {
1390 if (MAI
->doesSupportDebugInformation() && DW
->ShouldEmitDwarfDebug()) {
1391 if (!DL
.isUnknown()) {
1392 DebugLocTuple CurDLT
= MF
->getDebugLocTuple(DL
);
1394 if (CurDLT
.CompileUnit
!= 0 && PrevDLT
!= CurDLT
) {
1395 printLabel(DW
->RecordSourceLine(CurDLT
.Line
, CurDLT
.Col
,
1396 DICompileUnit(CurDLT
.CompileUnit
)));
1405 /// printInlineAsm - This method formats and prints the specified machine
1406 /// instruction that is an inline asm.
1407 void AsmPrinter::printInlineAsm(const MachineInstr
*MI
) const {
1408 unsigned NumOperands
= MI
->getNumOperands();
1410 // Count the number of register definitions.
1411 unsigned NumDefs
= 0;
1412 for (; MI
->getOperand(NumDefs
).isReg() && MI
->getOperand(NumDefs
).isDef();
1414 assert(NumDefs
!= NumOperands
-1 && "No asm string?");
1416 assert(MI
->getOperand(NumDefs
).isSymbol() && "No asm string?");
1418 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1419 const char *AsmStr
= MI
->getOperand(NumDefs
).getSymbolName();
1421 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1422 // These are useful to see where empty asm's wound up.
1423 if (AsmStr
[0] == 0) {
1424 O
<< MAI
->getCommentString() << MAI
->getInlineAsmStart() << "\n\t";
1425 O
<< MAI
->getCommentString() << MAI
->getInlineAsmEnd() << '\n';
1429 O
<< MAI
->getCommentString() << MAI
->getInlineAsmStart() << "\n\t";
1431 // The variant of the current asmprinter.
1432 int AsmPrinterVariant
= MAI
->getAssemblerDialect();
1434 int CurVariant
= -1; // The number of the {.|.|.} region we are in.
1435 const char *LastEmitted
= AsmStr
; // One past the last character emitted.
1437 while (*LastEmitted
) {
1438 switch (*LastEmitted
) {
1440 // Not a special case, emit the string section literally.
1441 const char *LiteralEnd
= LastEmitted
+1;
1442 while (*LiteralEnd
&& *LiteralEnd
!= '{' && *LiteralEnd
!= '|' &&
1443 *LiteralEnd
!= '}' && *LiteralEnd
!= '$' && *LiteralEnd
!= '\n')
1445 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
1446 O
.write(LastEmitted
, LiteralEnd
-LastEmitted
);
1447 LastEmitted
= LiteralEnd
;
1451 ++LastEmitted
; // Consume newline character.
1452 O
<< '\n'; // Indent code with newline.
1455 ++LastEmitted
; // Consume '$' character.
1459 switch (*LastEmitted
) {
1460 default: Done
= false; break;
1461 case '$': // $$ -> $
1462 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
1464 ++LastEmitted
; // Consume second '$' character.
1466 case '(': // $( -> same as GCC's { character.
1467 ++LastEmitted
; // Consume '(' character.
1468 if (CurVariant
!= -1) {
1469 llvm_report_error("Nested variants found in inline asm string: '"
1470 + std::string(AsmStr
) + "'");
1472 CurVariant
= 0; // We're in the first variant now.
1475 ++LastEmitted
; // consume '|' character.
1476 if (CurVariant
== -1)
1477 O
<< '|'; // this is gcc's behavior for | outside a variant
1479 ++CurVariant
; // We're in the next variant.
1481 case ')': // $) -> same as GCC's } char.
1482 ++LastEmitted
; // consume ')' character.
1483 if (CurVariant
== -1)
1484 O
<< '}'; // this is gcc's behavior for } outside a variant
1491 bool HasCurlyBraces
= false;
1492 if (*LastEmitted
== '{') { // ${variable}
1493 ++LastEmitted
; // Consume '{' character.
1494 HasCurlyBraces
= true;
1497 // If we have ${:foo}, then this is not a real operand reference, it is a
1498 // "magic" string reference, just like in .td files. Arrange to call
1500 if (HasCurlyBraces
&& *LastEmitted
== ':') {
1502 const char *StrStart
= LastEmitted
;
1503 const char *StrEnd
= strchr(StrStart
, '}');
1505 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1506 + std::string(AsmStr
) + "'");
1509 std::string
Val(StrStart
, StrEnd
);
1510 PrintSpecial(MI
, Val
.c_str());
1511 LastEmitted
= StrEnd
+1;
1515 const char *IDStart
= LastEmitted
;
1518 long Val
= strtol(IDStart
, &IDEnd
, 10); // We only accept numbers for IDs.
1519 if (!isdigit(*IDStart
) || (Val
== 0 && errno
== EINVAL
)) {
1520 llvm_report_error("Bad $ operand number in inline asm string: '"
1521 + std::string(AsmStr
) + "'");
1523 LastEmitted
= IDEnd
;
1525 char Modifier
[2] = { 0, 0 };
1527 if (HasCurlyBraces
) {
1528 // If we have curly braces, check for a modifier character. This
1529 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1530 if (*LastEmitted
== ':') {
1531 ++LastEmitted
; // Consume ':' character.
1532 if (*LastEmitted
== 0) {
1533 llvm_report_error("Bad ${:} expression in inline asm string: '"
1534 + std::string(AsmStr
) + "'");
1537 Modifier
[0] = *LastEmitted
;
1538 ++LastEmitted
; // Consume modifier character.
1541 if (*LastEmitted
!= '}') {
1542 llvm_report_error("Bad ${} expression in inline asm string: '"
1543 + std::string(AsmStr
) + "'");
1545 ++LastEmitted
; // Consume '}' character.
1548 if ((unsigned)Val
>= NumOperands
-1) {
1549 llvm_report_error("Invalid $ operand number in inline asm string: '"
1550 + std::string(AsmStr
) + "'");
1553 // Okay, we finally have a value number. Ask the target to print this
1555 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
) {
1560 // Scan to find the machine operand number for the operand.
1561 for (; Val
; --Val
) {
1562 if (OpNo
>= MI
->getNumOperands()) break;
1563 unsigned OpFlags
= MI
->getOperand(OpNo
).getImm();
1564 OpNo
+= InlineAsm::getNumOperandRegisters(OpFlags
) + 1;
1567 if (OpNo
>= MI
->getNumOperands()) {
1570 unsigned OpFlags
= MI
->getOperand(OpNo
).getImm();
1571 ++OpNo
; // Skip over the ID number.
1573 if (Modifier
[0]=='l') // labels are target independent
1574 GetMBBSymbol(MI
->getOperand(OpNo
).getMBB()
1575 ->getNumber())->print(O
, MAI
);
1577 AsmPrinter
*AP
= const_cast<AsmPrinter
*>(this);
1578 if ((OpFlags
& 7) == 4) {
1579 Error
= AP
->PrintAsmMemoryOperand(MI
, OpNo
, AsmPrinterVariant
,
1580 Modifier
[0] ? Modifier
: 0);
1582 Error
= AP
->PrintAsmOperand(MI
, OpNo
, AsmPrinterVariant
,
1583 Modifier
[0] ? Modifier
: 0);
1589 raw_string_ostream
Msg(msg
);
1590 Msg
<< "Invalid operand found in inline asm: '"
1593 llvm_report_error(Msg
.str());
1600 O
<< "\n\t" << MAI
->getCommentString() << MAI
->getInlineAsmEnd();
1603 /// printImplicitDef - This method prints the specified machine instruction
1604 /// that is an implicit def.
1605 void AsmPrinter::printImplicitDef(const MachineInstr
*MI
) const {
1606 if (!VerboseAsm
) return;
1607 O
.PadToColumn(MAI
->getCommentColumn());
1608 O
<< MAI
->getCommentString() << " implicit-def: "
1609 << TRI
->getName(MI
->getOperand(0).getReg());
1612 /// printLabel - This method prints a local label used by debug and
1613 /// exception handling tables.
1614 void AsmPrinter::printLabel(const MachineInstr
*MI
) const {
1615 printLabel(MI
->getOperand(0).getImm());
1618 void AsmPrinter::printLabel(unsigned Id
) const {
1619 O
<< MAI
->getPrivateGlobalPrefix() << "label" << Id
<< ':';
1622 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1623 /// instruction, using the specified assembler variant. Targets should
1624 /// overried this to format as appropriate.
1625 bool AsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
1626 unsigned AsmVariant
, const char *ExtraCode
) {
1627 // Target doesn't support this yet!
1631 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
, unsigned OpNo
,
1632 unsigned AsmVariant
,
1633 const char *ExtraCode
) {
1634 // Target doesn't support this yet!
1638 MCSymbol
*AsmPrinter::GetMBBSymbol(unsigned MBBID
) const {
1639 SmallString
<60> Name
;
1640 raw_svector_ostream(Name
) << MAI
->getPrivateGlobalPrefix() << "BB"
1641 << getFunctionNumber() << '_' << MBBID
;
1643 return OutContext
.GetOrCreateSymbol(Name
.str());
1647 /// EmitBasicBlockStart - This method prints the label for the specified
1648 /// MachineBasicBlock, an alignment (if present) and a comment describing
1649 /// it if appropriate.
1650 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock
*MBB
,
1651 bool PrintColon
) const {
1652 if (unsigned Align
= MBB
->getAlignment())
1653 EmitAlignment(Log2_32(Align
));
1655 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
1661 if (const BasicBlock
*BB
= MBB
->getBasicBlock())
1662 if (BB
->hasName()) {
1663 O
.PadToColumn(MAI
->getCommentColumn());
1664 O
<< MAI
->getCommentString() << ' ';
1665 WriteAsOperand(O
, BB
, /*PrintType=*/false);
1672 /// printPICJumpTableSetLabel - This method prints a set label for the
1673 /// specified MachineBasicBlock for a jumptable entry.
1674 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid
,
1675 const MachineBasicBlock
*MBB
) const {
1676 if (!MAI
->getSetDirective())
1679 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
1680 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
1681 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
1682 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1683 << '_' << uid
<< '\n';
1686 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid
, unsigned uid2
,
1687 const MachineBasicBlock
*MBB
) const {
1688 if (!MAI
->getSetDirective())
1691 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
1692 << getFunctionNumber() << '_' << uid
<< '_' << uid2
1693 << "_set_" << MBB
->getNumber() << ',';
1694 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
1695 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1696 << '_' << uid
<< '_' << uid2
<< '\n';
1699 /// printDataDirective - This method prints the asm directive for the
1701 void AsmPrinter::printDataDirective(const Type
*type
, unsigned AddrSpace
) {
1702 const TargetData
*TD
= TM
.getTargetData();
1703 switch (type
->getTypeID()) {
1704 case Type::FloatTyID
: case Type::DoubleTyID
:
1705 case Type::X86_FP80TyID
: case Type::FP128TyID
: case Type::PPC_FP128TyID
:
1706 assert(0 && "Should have already output floating point constant.");
1708 assert(0 && "Can't handle printing this type of thing");
1709 case Type::IntegerTyID
: {
1710 unsigned BitWidth
= cast
<IntegerType
>(type
)->getBitWidth();
1712 O
<< MAI
->getData8bitsDirective(AddrSpace
);
1713 else if (BitWidth
<= 16)
1714 O
<< MAI
->getData16bitsDirective(AddrSpace
);
1715 else if (BitWidth
<= 32)
1716 O
<< MAI
->getData32bitsDirective(AddrSpace
);
1717 else if (BitWidth
<= 64) {
1718 assert(MAI
->getData64bitsDirective(AddrSpace
) &&
1719 "Target cannot handle 64-bit constant exprs!");
1720 O
<< MAI
->getData64bitsDirective(AddrSpace
);
1722 llvm_unreachable("Target cannot handle given data directive width!");
1726 case Type::PointerTyID
:
1727 if (TD
->getPointerSize() == 8) {
1728 assert(MAI
->getData64bitsDirective(AddrSpace
) &&
1729 "Target cannot handle 64-bit pointer exprs!");
1730 O
<< MAI
->getData64bitsDirective(AddrSpace
);
1731 } else if (TD
->getPointerSize() == 2) {
1732 O
<< MAI
->getData16bitsDirective(AddrSpace
);
1733 } else if (TD
->getPointerSize() == 1) {
1734 O
<< MAI
->getData8bitsDirective(AddrSpace
);
1736 O
<< MAI
->getData32bitsDirective(AddrSpace
);
1742 void AsmPrinter::printVisibility(const std::string
& Name
,
1743 unsigned Visibility
) const {
1744 if (Visibility
== GlobalValue::HiddenVisibility
) {
1745 if (const char *Directive
= MAI
->getHiddenDirective())
1746 O
<< Directive
<< Name
<< '\n';
1747 } else if (Visibility
== GlobalValue::ProtectedVisibility
) {
1748 if (const char *Directive
= MAI
->getProtectedDirective())
1749 O
<< Directive
<< Name
<< '\n';
1753 void AsmPrinter::printOffset(int64_t Offset
) const {
1756 else if (Offset
< 0)
1760 void AsmPrinter::printMCInst(const MCInst
*MI
) {
1761 llvm_unreachable("MCInst printing unavailable on this target!");
1764 GCMetadataPrinter
*AsmPrinter::GetOrCreateGCPrinter(GCStrategy
*S
) {
1765 if (!S
->usesMetadata())
1768 gcp_iterator GCPI
= GCMetadataPrinters
.find(S
);
1769 if (GCPI
!= GCMetadataPrinters
.end())
1770 return GCPI
->second
;
1772 const char *Name
= S
->getName().c_str();
1774 for (GCMetadataPrinterRegistry::iterator
1775 I
= GCMetadataPrinterRegistry::begin(),
1776 E
= GCMetadataPrinterRegistry::end(); I
!= E
; ++I
)
1777 if (strcmp(Name
, I
->getName()) == 0) {
1778 GCMetadataPrinter
*GMP
= I
->instantiate();
1780 GCMetadataPrinters
.insert(std::make_pair(S
, GMP
));
1784 errs() << "no GCMetadataPrinter registered for GC: " << Name
<< "\n";
1785 llvm_unreachable(0);
1788 /// EmitComments - Pretty-print comments for instructions
1789 void AsmPrinter::EmitComments(const MachineInstr
&MI
) const {
1790 assert(VerboseAsm
&& !MI
.getDebugLoc().isUnknown());
1792 DebugLocTuple DLT
= MF
->getDebugLocTuple(MI
.getDebugLoc());
1794 // Print source line info.
1795 O
.PadToColumn(MAI
->getCommentColumn());
1796 O
<< MAI
->getCommentString() << " SrcLine ";
1797 if (DLT
.CompileUnit
) {
1799 DICompileUnit
CU(DLT
.CompileUnit
);
1800 O
<< CU
.getFilename(Str
) << " ";
1804 O
<< ":" << DLT
.Col
;
1807 /// PrintChildLoopComment - Print comments about child loops within
1808 /// the loop for this basic block, with nesting.
1810 static void PrintChildLoopComment(formatted_raw_ostream
&O
,
1811 const MachineLoop
*loop
,
1812 const MCAsmInfo
*MAI
,
1813 int FunctionNumber
) {
1814 // Add child loop information
1815 for(MachineLoop::iterator cl
= loop
->begin(),
1816 clend
= loop
->end();
1819 MachineBasicBlock
*Header
= (*cl
)->getHeader();
1820 assert(Header
&& "No header for loop");
1823 O
.PadToColumn(MAI
->getCommentColumn());
1825 O
<< MAI
->getCommentString();
1826 O
.indent(((*cl
)->getLoopDepth()-1)*2)
1827 << " Child Loop BB" << FunctionNumber
<< "_"
1828 << Header
->getNumber() << " Depth " << (*cl
)->getLoopDepth();
1830 PrintChildLoopComment(O
, *cl
, MAI
, FunctionNumber
);
1834 /// EmitComments - Pretty-print comments for basic blocks
1835 void AsmPrinter::EmitComments(const MachineBasicBlock
&MBB
) const
1838 // Add loop depth information
1839 const MachineLoop
*loop
= LI
->getLoopFor(&MBB
);
1842 // Print a newline after bb# annotation.
1844 O
.PadToColumn(MAI
->getCommentColumn());
1845 O
<< MAI
->getCommentString() << " Loop Depth " << loop
->getLoopDepth()
1848 O
.PadToColumn(MAI
->getCommentColumn());
1850 MachineBasicBlock
*Header
= loop
->getHeader();
1851 assert(Header
&& "No header for loop");
1853 if (Header
== &MBB
) {
1854 O
<< MAI
->getCommentString() << " Loop Header";
1855 PrintChildLoopComment(O
, loop
, MAI
, getFunctionNumber());
1858 O
<< MAI
->getCommentString() << " Loop Header is BB"
1859 << getFunctionNumber() << "_" << loop
->getHeader()->getNumber();
1862 if (loop
->empty()) {
1864 O
.PadToColumn(MAI
->getCommentColumn());
1865 O
<< MAI
->getCommentString() << " Inner Loop";
1868 // Add parent loop information
1869 for (const MachineLoop
*CurLoop
= loop
->getParentLoop();
1871 CurLoop
= CurLoop
->getParentLoop()) {
1872 MachineBasicBlock
*Header
= CurLoop
->getHeader();
1873 assert(Header
&& "No header for loop");
1876 O
.PadToColumn(MAI
->getCommentColumn());
1877 O
<< MAI
->getCommentString();
1878 O
.indent((CurLoop
->getLoopDepth()-1)*2)
1879 << " Inside Loop BB" << getFunctionNumber() << "_"
1880 << Header
->getNumber() << " Depth " << CurLoop
->getLoopDepth();