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/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
47 static cl::opt
<cl::boolOrDefault
>
48 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
49 cl::init(cl::BOU_UNSET
));
51 char AsmPrinter::ID
= 0;
52 AsmPrinter::AsmPrinter(formatted_raw_ostream
&o
, TargetMachine
&tm
,
53 const MCAsmInfo
*T
, bool VDef
)
54 : MachineFunctionPass(&ID
), FunctionNumber(0), O(o
),
55 TM(tm
), MAI(T
), TRI(tm
.getRegisterInfo()),
57 OutContext(*new MCContext()),
58 OutStreamer(*createAsmStreamer(OutContext
, O
, *T
, this)),
60 LastMI(0), LastFn(0), Counter(~0U),
61 PrevDLT(0, ~0U, ~0U) {
64 case cl::BOU_UNSET
: VerboseAsm
= VDef
; break;
65 case cl::BOU_TRUE
: VerboseAsm
= true; break;
66 case cl::BOU_FALSE
: VerboseAsm
= false; break;
70 AsmPrinter::~AsmPrinter() {
71 for (gcp_iterator I
= GCMetadataPrinters
.begin(),
72 E
= GCMetadataPrinters
.end(); I
!= E
; ++I
)
79 TargetLoweringObjectFile
&AsmPrinter::getObjFileLowering() const {
80 return TM
.getTargetLowering()->getObjFileLowering();
83 /// getCurrentSection() - Return the current section we are emitting to.
84 const MCSection
*AsmPrinter::getCurrentSection() const {
85 return OutStreamer
.getCurrentSection();
89 void AsmPrinter::getAnalysisUsage(AnalysisUsage
&AU
) const {
91 MachineFunctionPass::getAnalysisUsage(AU
);
92 AU
.addRequired
<GCModuleInfo
>();
94 AU
.addRequired
<MachineLoopInfo
>();
97 bool AsmPrinter::doInitialization(Module
&M
) {
98 // Initialize TargetLoweringObjectFile.
99 const_cast<TargetLoweringObjectFile
&>(getObjFileLowering())
100 .Initialize(OutContext
, TM
);
102 Mang
= new Mangler(M
, MAI
->getGlobalPrefix(), MAI
->getPrivateGlobalPrefix(),
103 MAI
->getLinkerPrivateGlobalPrefix());
105 if (MAI
->doesAllowQuotesInName())
106 Mang
->setUseQuotes(true);
108 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
109 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
111 if (MAI
->hasSingleParameterDotFile()) {
112 /* Very minimal debug info. It is ignored if we emit actual
113 debug info. If we don't, this at helps the user find where
114 a function came from. */
115 O
<< "\t.file\t\"" << M
.getModuleIdentifier() << "\"\n";
118 for (GCModuleInfo::iterator I
= MI
->begin(), E
= MI
->end(); I
!= E
; ++I
)
119 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*I
))
120 MP
->beginAssembly(O
, *this, *MAI
);
122 if (!M
.getModuleInlineAsm().empty())
123 O
<< MAI
->getCommentString() << " Start of file scope inline assembly\n"
124 << M
.getModuleInlineAsm()
125 << '\n' << MAI
->getCommentString()
126 << " End of file scope inline assembly\n";
128 if (MAI
->doesSupportDebugInformation() ||
129 MAI
->doesSupportExceptionHandling()) {
130 MMI
= getAnalysisIfAvailable
<MachineModuleInfo
>();
132 MMI
->AnalyzeModule(M
);
133 DW
= getAnalysisIfAvailable
<DwarfWriter
>();
135 DW
->BeginModule(&M
, MMI
, O
, this, MAI
);
141 bool AsmPrinter::doFinalization(Module
&M
) {
142 // Emit global variables.
143 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
145 PrintGlobalVariable(I
);
147 // Emit final debug information.
148 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
151 // If the target wants to know about weak references, print them all.
152 if (MAI
->getWeakRefDirective()) {
153 // FIXME: This is not lazy, it would be nice to only print weak references
154 // to stuff that is actually used. Note that doing so would require targets
155 // to notice uses in operands (due to constant exprs etc). This should
156 // happen with the MC stuff eventually.
158 // Print out module-level global variables here.
159 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
161 if (I
->hasExternalWeakLinkage())
162 O
<< MAI
->getWeakRefDirective() << Mang
->getMangledName(I
) << '\n';
165 for (Module::const_iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
) {
166 if (I
->hasExternalWeakLinkage())
167 O
<< MAI
->getWeakRefDirective() << Mang
->getMangledName(I
) << '\n';
171 if (MAI
->getSetDirective()) {
173 for (Module::const_alias_iterator I
= M
.alias_begin(), E
= M
.alias_end();
175 std::string Name
= Mang
->getMangledName(I
);
177 const GlobalValue
*GV
= cast
<GlobalValue
>(I
->getAliasedGlobal());
178 std::string Target
= Mang
->getMangledName(GV
);
180 if (I
->hasExternalLinkage() || !MAI
->getWeakRefDirective())
181 O
<< "\t.globl\t" << Name
<< '\n';
182 else if (I
->hasWeakLinkage())
183 O
<< MAI
->getWeakRefDirective() << Name
<< '\n';
184 else if (!I
->hasLocalLinkage())
185 llvm_unreachable("Invalid alias linkage");
187 printVisibility(Name
, I
->getVisibility());
189 O
<< MAI
->getSetDirective() << ' ' << Name
<< ", " << Target
<< '\n';
193 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
194 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
195 for (GCModuleInfo::iterator I
= MI
->end(), E
= MI
->begin(); I
!= E
; )
196 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*--I
))
197 MP
->finishAssembly(O
, *this, *MAI
);
199 // If we don't have any trampolines, then we don't require stack memory
200 // to be executable. Some targets have a directive to declare this.
201 Function
*InitTrampolineIntrinsic
= M
.getFunction("llvm.init.trampoline");
202 if (!InitTrampolineIntrinsic
|| InitTrampolineIntrinsic
->use_empty())
203 if (MAI
->getNonexecutableStackDirective())
204 O
<< MAI
->getNonexecutableStackDirective() << '\n';
206 delete Mang
; Mang
= 0;
209 OutStreamer
.Finish();
214 AsmPrinter::getCurrentFunctionEHName(const MachineFunction
*MF
) const {
215 assert(MF
&& "No machine function?");
216 return Mang
->getMangledName(MF
->getFunction(), ".eh",
217 MAI
->is_EHSymbolPrivate());
220 void AsmPrinter::SetupMachineFunction(MachineFunction
&MF
) {
221 // What's my mangled name?
222 CurrentFnName
= Mang
->getMangledName(MF
.getFunction());
223 IncrementFunctionNumber();
226 LI
= &getAnalysis
<MachineLoopInfo
>();
231 // SectionCPs - Keep track the alignment, constpool entries per Section.
235 SmallVector
<unsigned, 4> CPEs
;
236 SectionCPs(const MCSection
*s
, unsigned a
) : S(s
), Alignment(a
) {};
240 /// EmitConstantPool - Print to the current output stream assembly
241 /// representations of the constants in the constant pool MCP. This is
242 /// used to print out constants which have been "spilled to memory" by
243 /// the code generator.
245 void AsmPrinter::EmitConstantPool(MachineConstantPool
*MCP
) {
246 const std::vector
<MachineConstantPoolEntry
> &CP
= MCP
->getConstants();
247 if (CP
.empty()) return;
249 // Calculate sections for constant pool entries. We collect entries to go into
250 // the same section together to reduce amount of section switch statements.
251 SmallVector
<SectionCPs
, 4> CPSections
;
252 for (unsigned i
= 0, e
= CP
.size(); i
!= e
; ++i
) {
253 const MachineConstantPoolEntry
&CPE
= CP
[i
];
254 unsigned Align
= CPE
.getAlignment();
257 switch (CPE
.getRelocationInfo()) {
258 default: llvm_unreachable("Unknown section kind");
259 case 2: Kind
= SectionKind::getReadOnlyWithRel(); break;
261 Kind
= SectionKind::getReadOnlyWithRelLocal();
264 switch (TM
.getTargetData()->getTypeAllocSize(CPE
.getType())) {
265 case 4: Kind
= SectionKind::getMergeableConst4(); break;
266 case 8: Kind
= SectionKind::getMergeableConst8(); break;
267 case 16: Kind
= SectionKind::getMergeableConst16();break;
268 default: Kind
= SectionKind::getMergeableConst(); break;
272 const MCSection
*S
= getObjFileLowering().getSectionForConstant(Kind
);
274 // The number of sections are small, just do a linear search from the
275 // last section to the first.
277 unsigned SecIdx
= CPSections
.size();
278 while (SecIdx
!= 0) {
279 if (CPSections
[--SecIdx
].S
== S
) {
285 SecIdx
= CPSections
.size();
286 CPSections
.push_back(SectionCPs(S
, Align
));
289 if (Align
> CPSections
[SecIdx
].Alignment
)
290 CPSections
[SecIdx
].Alignment
= Align
;
291 CPSections
[SecIdx
].CPEs
.push_back(i
);
294 // Now print stuff into the calculated sections.
295 for (unsigned i
= 0, e
= CPSections
.size(); i
!= e
; ++i
) {
296 OutStreamer
.SwitchSection(CPSections
[i
].S
);
297 EmitAlignment(Log2_32(CPSections
[i
].Alignment
));
300 for (unsigned j
= 0, ee
= CPSections
[i
].CPEs
.size(); j
!= ee
; ++j
) {
301 unsigned CPI
= CPSections
[i
].CPEs
[j
];
302 MachineConstantPoolEntry CPE
= CP
[CPI
];
304 // Emit inter-object padding for alignment.
305 unsigned AlignMask
= CPE
.getAlignment() - 1;
306 unsigned NewOffset
= (Offset
+ AlignMask
) & ~AlignMask
;
307 EmitZeros(NewOffset
- Offset
);
309 const Type
*Ty
= CPE
.getType();
310 Offset
= NewOffset
+ TM
.getTargetData()->getTypeAllocSize(Ty
);
312 O
<< MAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
315 O
.PadToColumn(MAI
->getCommentColumn());
316 O
<< MAI
->getCommentString() << " constant ";
317 WriteTypeSymbolic(O
, CPE
.getType(), MF
->getFunction()->getParent());
320 if (CPE
.isMachineConstantPoolEntry())
321 EmitMachineConstantPoolValue(CPE
.Val
.MachineCPVal
);
323 EmitGlobalConstant(CPE
.Val
.ConstVal
);
328 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
329 /// by the current function to the current output stream.
331 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo
*MJTI
,
332 MachineFunction
&MF
) {
333 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
334 if (JT
.empty()) return;
336 bool IsPic
= TM
.getRelocationModel() == Reloc::PIC_
;
338 // Pick the directive to use to print the jump table entries, and switch to
339 // the appropriate section.
340 TargetLowering
*LoweringInfo
= TM
.getTargetLowering();
342 const Function
*F
= MF
.getFunction();
343 bool JTInDiffSection
= false;
344 if (F
->isWeakForLinker() ||
345 (IsPic
&& !LoweringInfo
->usesGlobalOffsetTable())) {
346 // In PIC mode, we need to emit the jump table to the same section as the
347 // function body itself, otherwise the label differences won't make sense.
348 // We should also do if the section name is NULL or function is declared in
349 // discardable section.
350 OutStreamer
.SwitchSection(getObjFileLowering().SectionForGlobal(F
, Mang
,
353 // Otherwise, drop it in the readonly section.
354 const MCSection
*ReadOnlySection
=
355 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
356 OutStreamer
.SwitchSection(ReadOnlySection
);
357 JTInDiffSection
= true;
360 EmitAlignment(Log2_32(MJTI
->getAlignment()));
362 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
) {
363 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[i
].MBBs
;
365 // If this jump table was deleted, ignore it.
366 if (JTBBs
.empty()) continue;
368 // For PIC codegen, if possible we want to use the SetDirective to reduce
369 // the number of relocations the assembler will generate for the jump table.
370 // Set directives are all printed before the jump table itself.
371 SmallPtrSet
<MachineBasicBlock
*, 16> EmittedSets
;
372 if (MAI
->getSetDirective() && IsPic
)
373 for (unsigned ii
= 0, ee
= JTBBs
.size(); ii
!= ee
; ++ii
)
374 if (EmittedSets
.insert(JTBBs
[ii
]))
375 printPICJumpTableSetLabel(i
, JTBBs
[ii
]);
377 // On some targets (e.g. darwin) we want to emit two consequtive labels
378 // before each jump table. The first label is never referenced, but tells
379 // the assembler and linker the extents of the jump table object. The
380 // second label is actually referenced by the code.
381 if (JTInDiffSection
) {
382 if (const char *JTLabelPrefix
= MAI
->getJumpTableSpecialLabelPrefix())
383 O
<< JTLabelPrefix
<< "JTI" << getFunctionNumber() << '_' << i
<< ":\n";
386 O
<< MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
387 << '_' << i
<< ":\n";
389 for (unsigned ii
= 0, ee
= JTBBs
.size(); ii
!= ee
; ++ii
) {
390 printPICJumpTableEntry(MJTI
, JTBBs
[ii
], i
);
396 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
397 const MachineBasicBlock
*MBB
,
398 unsigned uid
) const {
399 bool isPIC
= TM
.getRelocationModel() == Reloc::PIC_
;
401 // Use JumpTableDirective otherwise honor the entry size from the jump table
403 const char *JTEntryDirective
= MAI
->getJumpTableDirective(isPIC
);
404 bool HadJTEntryDirective
= JTEntryDirective
!= NULL
;
405 if (!HadJTEntryDirective
) {
406 JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
407 MAI
->getData32bitsDirective() : MAI
->getData64bitsDirective();
410 O
<< JTEntryDirective
<< ' ';
412 // If we have emitted set directives for the jump table entries, print
413 // them rather than the entries themselves. If we're emitting PIC, then
414 // emit the table entries as differences between two text section labels.
415 // If we're emitting non-PIC code, then emit the entries as direct
416 // references to the target basic blocks.
418 printBasicBlockLabel(MBB
, false, false, false);
419 } else if (MAI
->getSetDirective()) {
420 O
<< MAI
->getPrivateGlobalPrefix() << getFunctionNumber()
421 << '_' << uid
<< "_set_" << MBB
->getNumber();
423 printBasicBlockLabel(MBB
, false, false, false);
424 // If the arch uses custom Jump Table directives, don't calc relative to
426 if (!HadJTEntryDirective
)
427 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI"
428 << getFunctionNumber() << '_' << uid
;
433 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
434 /// special global used by LLVM. If so, emit it and return true, otherwise
435 /// do nothing and return false.
436 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable
*GV
) {
437 if (GV
->getName() == "llvm.used") {
438 if (MAI
->getUsedDirective() != 0) // No need to emit this at all.
439 EmitLLVMUsedList(GV
->getInitializer());
443 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
444 if (GV
->getSection() == "llvm.metadata" ||
445 GV
->hasAvailableExternallyLinkage())
448 if (!GV
->hasAppendingLinkage()) return false;
450 assert(GV
->hasInitializer() && "Not a special LLVM global!");
452 const TargetData
*TD
= TM
.getTargetData();
453 unsigned Align
= Log2_32(TD
->getPointerPrefAlignment());
454 if (GV
->getName() == "llvm.global_ctors") {
455 OutStreamer
.SwitchSection(getObjFileLowering().getStaticCtorSection());
456 EmitAlignment(Align
, 0);
457 EmitXXStructorList(GV
->getInitializer());
461 if (GV
->getName() == "llvm.global_dtors") {
462 OutStreamer
.SwitchSection(getObjFileLowering().getStaticDtorSection());
463 EmitAlignment(Align
, 0);
464 EmitXXStructorList(GV
->getInitializer());
471 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
472 /// global in the specified llvm.used list for which emitUsedDirectiveFor
473 /// is true, as being used with this directive.
474 void AsmPrinter::EmitLLVMUsedList(Constant
*List
) {
475 const char *Directive
= MAI
->getUsedDirective();
477 // Should be an array of 'i8*'.
478 ConstantArray
*InitList
= dyn_cast
<ConstantArray
>(List
);
479 if (InitList
== 0) return;
481 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
482 const GlobalValue
*GV
=
483 dyn_cast
<GlobalValue
>(InitList
->getOperand(i
)->stripPointerCasts());
484 if (GV
&& getObjFileLowering().shouldEmitUsedDirectiveFor(GV
, Mang
)) {
486 EmitConstantValueOnly(InitList
->getOperand(i
));
492 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
493 /// function pointers, ignoring the init priority.
494 void AsmPrinter::EmitXXStructorList(Constant
*List
) {
495 // Should be an array of '{ int, void ()* }' structs. The first value is the
496 // init priority, which we ignore.
497 if (!isa
<ConstantArray
>(List
)) return;
498 ConstantArray
*InitList
= cast
<ConstantArray
>(List
);
499 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
)
500 if (ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(InitList
->getOperand(i
))){
501 if (CS
->getNumOperands() != 2) return; // Not array of 2-element structs.
503 if (CS
->getOperand(1)->isNullValue())
504 return; // Found a null terminator, exit printing.
505 // Emit the function pointer.
506 EmitGlobalConstant(CS
->getOperand(1));
510 /// getGlobalLinkName - Returns the asm/link name of of the specified
511 /// global variable. Should be overridden by each target asm printer to
512 /// generate the appropriate value.
513 const std::string
&AsmPrinter::getGlobalLinkName(const GlobalVariable
*GV
,
514 std::string
&LinkName
) const {
515 if (isa
<Function
>(GV
)) {
516 LinkName
+= MAI
->getFunctionAddrPrefix();
517 LinkName
+= Mang
->getMangledName(GV
);
518 LinkName
+= MAI
->getFunctionAddrSuffix();
520 LinkName
+= MAI
->getGlobalVarAddrPrefix();
521 LinkName
+= Mang
->getMangledName(GV
);
522 LinkName
+= MAI
->getGlobalVarAddrSuffix();
528 /// EmitExternalGlobal - Emit the external reference to a global variable.
529 /// Should be overridden if an indirect reference should be used.
530 void AsmPrinter::EmitExternalGlobal(const GlobalVariable
*GV
) {
532 O
<< getGlobalLinkName(GV
, GLN
);
537 //===----------------------------------------------------------------------===//
538 /// LEB 128 number encoding.
540 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
541 /// representing an unsigned leb128 value.
542 void AsmPrinter::PrintULEB128(unsigned Value
) const {
545 unsigned char Byte
= static_cast<unsigned char>(Value
& 0x7f);
547 if (Value
) Byte
|= 0x80;
548 O
<< "0x" << utohex_buffer(Byte
, Buffer
+20);
549 if (Value
) O
<< ", ";
553 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
554 /// representing a signed leb128 value.
555 void AsmPrinter::PrintSLEB128(int Value
) const {
556 int Sign
= Value
>> (8 * sizeof(Value
) - 1);
561 unsigned char Byte
= static_cast<unsigned char>(Value
& 0x7f);
563 IsMore
= Value
!= Sign
|| ((Byte
^ Sign
) & 0x40) != 0;
564 if (IsMore
) Byte
|= 0x80;
565 O
<< "0x" << utohex_buffer(Byte
, Buffer
+20);
566 if (IsMore
) O
<< ", ";
570 //===--------------------------------------------------------------------===//
571 // Emission and print routines
574 /// PrintHex - Print a value as a hexidecimal value.
576 void AsmPrinter::PrintHex(int Value
) const {
578 O
<< "0x" << utohex_buffer(static_cast<unsigned>(Value
), Buffer
+20);
581 /// EOL - Print a newline character to asm stream. If a comment is present
582 /// then it will be printed first. Comments should not contain '\n'.
583 void AsmPrinter::EOL() const {
587 void AsmPrinter::EOL(const std::string
&Comment
) const {
588 if (VerboseAsm
&& !Comment
.empty()) {
589 O
.PadToColumn(MAI
->getCommentColumn());
590 O
<< MAI
->getCommentString()
597 void AsmPrinter::EOL(const char* Comment
) const {
598 if (VerboseAsm
&& *Comment
) {
599 O
.PadToColumn(MAI
->getCommentColumn());
600 O
<< MAI
->getCommentString()
607 static const char *DecodeDWARFEncoding(unsigned Encoding
) {
609 case dwarf::DW_EH_PE_absptr
:
611 case dwarf::DW_EH_PE_omit
:
613 case dwarf::DW_EH_PE_pcrel
:
615 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_udata4
:
616 return "pcrel udata4";
617 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
:
618 return "pcrel sdata4";
619 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_udata8
:
620 return "pcrel udata8";
621 case dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata8
:
622 return "pcrel sdata8";
623 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_udata4
:
624 return "indirect pcrel udata4";
625 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_sdata4
:
626 return "indirect pcrel sdata4";
627 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_udata8
:
628 return "indirect pcrel udata8";
629 case dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|dwarf::DW_EH_PE_sdata8
:
630 return "indirect pcrel sdata8";
636 void AsmPrinter::EOL(const char *Comment
, unsigned Encoding
) const {
637 if (VerboseAsm
&& *Comment
) {
638 O
.PadToColumn(MAI
->getCommentColumn());
639 O
<< MAI
->getCommentString()
643 if (const char *EncStr
= DecodeDWARFEncoding(Encoding
))
644 O
<< " (" << EncStr
<< ')';
649 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
650 /// unsigned leb128 value.
651 void AsmPrinter::EmitULEB128Bytes(unsigned Value
) const {
652 if (MAI
->hasLEB128()) {
656 O
<< MAI
->getData8bitsDirective();
661 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
662 /// signed leb128 value.
663 void AsmPrinter::EmitSLEB128Bytes(int Value
) const {
664 if (MAI
->hasLEB128()) {
668 O
<< MAI
->getData8bitsDirective();
673 /// EmitInt8 - Emit a byte directive and value.
675 void AsmPrinter::EmitInt8(int Value
) const {
676 O
<< MAI
->getData8bitsDirective();
677 PrintHex(Value
& 0xFF);
680 /// EmitInt16 - Emit a short directive and value.
682 void AsmPrinter::EmitInt16(int Value
) const {
683 O
<< MAI
->getData16bitsDirective();
684 PrintHex(Value
& 0xFFFF);
687 /// EmitInt32 - Emit a long directive and value.
689 void AsmPrinter::EmitInt32(int Value
) const {
690 O
<< MAI
->getData32bitsDirective();
694 /// EmitInt64 - Emit a long long directive and value.
696 void AsmPrinter::EmitInt64(uint64_t Value
) const {
697 if (MAI
->getData64bitsDirective()) {
698 O
<< MAI
->getData64bitsDirective();
701 if (TM
.getTargetData()->isBigEndian()) {
702 EmitInt32(unsigned(Value
>> 32)); O
<< '\n';
703 EmitInt32(unsigned(Value
));
705 EmitInt32(unsigned(Value
)); O
<< '\n';
706 EmitInt32(unsigned(Value
>> 32));
711 /// toOctal - Convert the low order bits of X into an octal digit.
713 static inline char toOctal(int X
) {
717 /// printStringChar - Print a char, escaped if necessary.
719 static void printStringChar(formatted_raw_ostream
&O
, unsigned char C
) {
722 } else if (C
== '\\') {
724 } else if (isprint((unsigned char)C
)) {
728 case '\b': O
<< "\\b"; break;
729 case '\f': O
<< "\\f"; break;
730 case '\n': O
<< "\\n"; break;
731 case '\r': O
<< "\\r"; break;
732 case '\t': O
<< "\\t"; break;
735 O
<< toOctal(C
>> 6);
736 O
<< toOctal(C
>> 3);
737 O
<< toOctal(C
>> 0);
743 /// EmitString - Emit a string with quotes and a null terminator.
744 /// Special characters are emitted properly.
745 /// \literal (Eg. '\t') \endliteral
746 void AsmPrinter::EmitString(const std::string
&String
) const {
747 EmitString(String
.c_str(), String
.size());
750 void AsmPrinter::EmitString(const char *String
, unsigned Size
) const {
751 const char* AscizDirective
= MAI
->getAscizDirective();
755 O
<< MAI
->getAsciiDirective();
757 for (unsigned i
= 0; i
< Size
; ++i
)
758 printStringChar(O
, String
[i
]);
766 /// EmitFile - Emit a .file directive.
767 void AsmPrinter::EmitFile(unsigned Number
, const std::string
&Name
) const {
768 O
<< "\t.file\t" << Number
<< " \"";
769 for (unsigned i
= 0, N
= Name
.size(); i
< N
; ++i
)
770 printStringChar(O
, Name
[i
]);
775 //===----------------------------------------------------------------------===//
777 // EmitAlignment - Emit an alignment directive to the specified power of
778 // two boundary. For example, if you pass in 3 here, you will get an 8
779 // byte alignment. If a global value is specified, and if that global has
780 // an explicit alignment requested, it will unconditionally override the
781 // alignment request. However, if ForcedAlignBits is specified, this value
782 // has final say: the ultimate alignment will be the max of ForcedAlignBits
783 // and the alignment computed with NumBits and the global.
787 // if (GV && GV->hasalignment) Align = GV->getalignment();
788 // Align = std::max(Align, ForcedAlignBits);
790 void AsmPrinter::EmitAlignment(unsigned NumBits
, const GlobalValue
*GV
,
791 unsigned ForcedAlignBits
,
792 bool UseFillExpr
) const {
793 if (GV
&& GV
->getAlignment())
794 NumBits
= Log2_32(GV
->getAlignment());
795 NumBits
= std::max(NumBits
, ForcedAlignBits
);
797 if (NumBits
== 0) return; // No need to emit alignment.
799 unsigned FillValue
= 0;
800 if (getCurrentSection()->getKind().isText())
801 FillValue
= MAI
->getTextAlignFillValue();
803 OutStreamer
.EmitValueToAlignment(1 << NumBits
, FillValue
, 1, 0);
806 /// EmitZeros - Emit a block of zeros.
808 void AsmPrinter::EmitZeros(uint64_t NumZeros
, unsigned AddrSpace
) const {
810 if (MAI
->getZeroDirective()) {
811 O
<< MAI
->getZeroDirective() << NumZeros
;
812 if (MAI
->getZeroDirectiveSuffix())
813 O
<< MAI
->getZeroDirectiveSuffix();
816 for (; NumZeros
; --NumZeros
)
817 O
<< MAI
->getData8bitsDirective(AddrSpace
) << "0\n";
822 // Print out the specified constant, without a storage class. Only the
823 // constants valid in constant expressions can occur here.
824 void AsmPrinter::EmitConstantValueOnly(const Constant
*CV
) {
825 if (CV
->isNullValue() || isa
<UndefValue
>(CV
))
827 else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
828 O
<< CI
->getZExtValue();
829 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CV
)) {
830 // This is a constant address for a global variable or function. Use the
831 // name of the variable or function as the address value, possibly
832 // decorating it with GlobalVarAddrPrefix/Suffix or
833 // FunctionAddrPrefix/Suffix (these all default to "" )
834 if (isa
<Function
>(GV
)) {
835 O
<< MAI
->getFunctionAddrPrefix()
836 << Mang
->getMangledName(GV
)
837 << MAI
->getFunctionAddrSuffix();
839 O
<< MAI
->getGlobalVarAddrPrefix()
840 << Mang
->getMangledName(GV
)
841 << MAI
->getGlobalVarAddrSuffix();
843 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
844 const TargetData
*TD
= TM
.getTargetData();
845 unsigned Opcode
= CE
->getOpcode();
847 case Instruction::Trunc
:
848 case Instruction::ZExt
:
849 case Instruction::SExt
:
850 case Instruction::FPTrunc
:
851 case Instruction::FPExt
:
852 case Instruction::UIToFP
:
853 case Instruction::SIToFP
:
854 case Instruction::FPToUI
:
855 case Instruction::FPToSI
:
856 llvm_unreachable("FIXME: Don't support this constant cast expr");
857 case Instruction::GetElementPtr
: {
858 // generate a symbolic expression for the byte address
859 const Constant
*ptrVal
= CE
->getOperand(0);
860 SmallVector
<Value
*, 8> idxVec(CE
->op_begin()+1, CE
->op_end());
861 if (int64_t Offset
= TD
->getIndexedOffset(ptrVal
->getType(), &idxVec
[0],
863 // Truncate/sext the offset to the pointer size.
864 if (TD
->getPointerSizeInBits() != 64) {
865 int SExtAmount
= 64-TD
->getPointerSizeInBits();
866 Offset
= (Offset
<< SExtAmount
) >> SExtAmount
;
871 EmitConstantValueOnly(ptrVal
);
873 O
<< ") + " << Offset
;
875 O
<< ") - " << -Offset
;
877 EmitConstantValueOnly(ptrVal
);
881 case Instruction::BitCast
:
882 return EmitConstantValueOnly(CE
->getOperand(0));
884 case Instruction::IntToPtr
: {
885 // Handle casts to pointers by changing them into casts to the appropriate
886 // integer type. This promotes constant folding and simplifies this code.
887 Constant
*Op
= CE
->getOperand(0);
888 Op
= ConstantExpr::getIntegerCast(Op
, TD
->getIntPtrType(CV
->getContext()),
890 return EmitConstantValueOnly(Op
);
894 case Instruction::PtrToInt
: {
895 // Support only foldable casts to/from pointers that can be eliminated by
896 // changing the pointer to the appropriately sized integer type.
897 Constant
*Op
= CE
->getOperand(0);
898 const Type
*Ty
= CE
->getType();
900 // We can emit the pointer value into this slot if the slot is an
901 // integer slot greater or equal to the size of the pointer.
902 if (TD
->getTypeAllocSize(Ty
) == TD
->getTypeAllocSize(Op
->getType()))
903 return EmitConstantValueOnly(Op
);
906 EmitConstantValueOnly(Op
);
908 APInt::getAllOnesValue(TD
->getTypeAllocSizeInBits(Op
->getType()));
911 ptrMask
.toStringUnsigned(S
);
912 O
<< ") & " << S
.str() << ')';
915 case Instruction::Add
:
916 case Instruction::Sub
:
917 case Instruction::And
:
918 case Instruction::Or
:
919 case Instruction::Xor
:
921 EmitConstantValueOnly(CE
->getOperand(0));
924 case Instruction::Add
:
927 case Instruction::Sub
:
930 case Instruction::And
:
933 case Instruction::Or
:
936 case Instruction::Xor
:
943 EmitConstantValueOnly(CE
->getOperand(1));
947 llvm_unreachable("Unsupported operator!");
950 llvm_unreachable("Unknown constant value!");
954 /// printAsCString - Print the specified array as a C compatible string, only if
955 /// the predicate isString is true.
957 static void printAsCString(formatted_raw_ostream
&O
, const ConstantArray
*CVA
,
959 assert(CVA
->isString() && "Array is not string compatible!");
962 for (unsigned i
= 0; i
!= LastElt
; ++i
) {
964 (unsigned char)cast
<ConstantInt
>(CVA
->getOperand(i
))->getZExtValue();
965 printStringChar(O
, C
);
970 /// EmitString - Emit a zero-byte-terminated string constant.
972 void AsmPrinter::EmitString(const ConstantArray
*CVA
) const {
973 unsigned NumElts
= CVA
->getNumOperands();
974 if (MAI
->getAscizDirective() && NumElts
&&
975 cast
<ConstantInt
>(CVA
->getOperand(NumElts
-1))->getZExtValue() == 0) {
976 O
<< MAI
->getAscizDirective();
977 printAsCString(O
, CVA
, NumElts
-1);
979 O
<< MAI
->getAsciiDirective();
980 printAsCString(O
, CVA
, NumElts
);
985 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray
*CVA
,
986 unsigned AddrSpace
) {
987 if (CVA
->isString()) {
989 } else { // Not a string. Print the values in successive locations
990 for (unsigned i
= 0, e
= CVA
->getNumOperands(); i
!= e
; ++i
)
991 EmitGlobalConstant(CVA
->getOperand(i
), AddrSpace
);
995 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector
*CP
) {
996 const VectorType
*PTy
= CP
->getType();
998 for (unsigned I
= 0, E
= PTy
->getNumElements(); I
< E
; ++I
)
999 EmitGlobalConstant(CP
->getOperand(I
));
1002 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct
*CVS
,
1003 unsigned AddrSpace
) {
1004 // Print the fields in successive locations. Pad to align if needed!
1005 const TargetData
*TD
= TM
.getTargetData();
1006 unsigned Size
= TD
->getTypeAllocSize(CVS
->getType());
1007 const StructLayout
*cvsLayout
= TD
->getStructLayout(CVS
->getType());
1008 uint64_t sizeSoFar
= 0;
1009 for (unsigned i
= 0, e
= CVS
->getNumOperands(); i
!= e
; ++i
) {
1010 const Constant
* field
= CVS
->getOperand(i
);
1012 // Check if padding is needed and insert one or more 0s.
1013 uint64_t fieldSize
= TD
->getTypeAllocSize(field
->getType());
1014 uint64_t padSize
= ((i
== e
-1 ? Size
: cvsLayout
->getElementOffset(i
+1))
1015 - cvsLayout
->getElementOffset(i
)) - fieldSize
;
1016 sizeSoFar
+= fieldSize
+ padSize
;
1018 // Now print the actual field value.
1019 EmitGlobalConstant(field
, AddrSpace
);
1021 // Insert padding - this may include padding to increase the size of the
1022 // current field up to the ABI size (if the struct is not packed) as well
1023 // as padding to ensure that the next field starts at the right offset.
1024 EmitZeros(padSize
, AddrSpace
);
1026 assert(sizeSoFar
== cvsLayout
->getSizeInBytes() &&
1027 "Layout of constant struct may be incorrect!");
1030 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP
*CFP
,
1031 unsigned AddrSpace
) {
1032 // FP Constants are printed as integer constants to avoid losing
1034 LLVMContext
&Context
= CFP
->getContext();
1035 const TargetData
*TD
= TM
.getTargetData();
1036 if (CFP
->getType() == Type::getDoubleTy(Context
)) {
1037 double Val
= CFP
->getValueAPF().convertToDouble(); // for comment only
1038 uint64_t i
= CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
1039 if (MAI
->getData64bitsDirective(AddrSpace
)) {
1040 O
<< MAI
->getData64bitsDirective(AddrSpace
) << i
;
1042 O
.PadToColumn(MAI
->getCommentColumn());
1043 O
<< MAI
->getCommentString() << " double " << Val
;
1046 } else if (TD
->isBigEndian()) {
1047 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
>> 32);
1049 O
.PadToColumn(MAI
->getCommentColumn());
1050 O
<< MAI
->getCommentString()
1051 << " most significant word of double " << Val
;
1054 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
);
1056 O
.PadToColumn(MAI
->getCommentColumn());
1057 O
<< MAI
->getCommentString()
1058 << " least significant word of double " << Val
;
1062 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
);
1064 O
.PadToColumn(MAI
->getCommentColumn());
1065 O
<< MAI
->getCommentString()
1066 << " least significant word of double " << Val
;
1069 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(i
>> 32);
1071 O
.PadToColumn(MAI
->getCommentColumn());
1072 O
<< MAI
->getCommentString()
1073 << " most significant word of double " << Val
;
1078 } else if (CFP
->getType() == Type::getFloatTy(Context
)) {
1079 float Val
= CFP
->getValueAPF().convertToFloat(); // for comment only
1080 O
<< MAI
->getData32bitsDirective(AddrSpace
)
1081 << CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
1083 O
.PadToColumn(MAI
->getCommentColumn());
1084 O
<< MAI
->getCommentString() << " float " << Val
;
1088 } else if (CFP
->getType() == Type::getX86_FP80Ty(Context
)) {
1089 // all long double variants are printed as hex
1090 // api needed to prevent premature destruction
1091 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
1092 const uint64_t *p
= api
.getRawData();
1093 // Convert to double so we can print the approximate val as a comment.
1094 APFloat DoubleVal
= CFP
->getValueAPF();
1096 DoubleVal
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
,
1098 if (TD
->isBigEndian()) {
1099 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[1]);
1101 O
.PadToColumn(MAI
->getCommentColumn());
1102 O
<< MAI
->getCommentString()
1103 << " most significant halfword of x86_fp80 ~"
1104 << DoubleVal
.convertToDouble();
1107 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 48);
1109 O
.PadToColumn(MAI
->getCommentColumn());
1110 O
<< MAI
->getCommentString() << " next halfword";
1113 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 32);
1115 O
.PadToColumn(MAI
->getCommentColumn());
1116 O
<< MAI
->getCommentString() << " next halfword";
1119 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 16);
1121 O
.PadToColumn(MAI
->getCommentColumn());
1122 O
<< MAI
->getCommentString() << " next halfword";
1125 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0]);
1127 O
.PadToColumn(MAI
->getCommentColumn());
1128 O
<< MAI
->getCommentString()
1129 << " least significant halfword";
1133 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0]);
1135 O
.PadToColumn(MAI
->getCommentColumn());
1136 O
<< MAI
->getCommentString()
1137 << " least significant halfword of x86_fp80 ~"
1138 << DoubleVal
.convertToDouble();
1141 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 16);
1143 O
.PadToColumn(MAI
->getCommentColumn());
1144 O
<< MAI
->getCommentString()
1145 << " next halfword";
1148 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 32);
1150 O
.PadToColumn(MAI
->getCommentColumn());
1151 O
<< MAI
->getCommentString()
1152 << " next halfword";
1155 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[0] >> 48);
1157 O
.PadToColumn(MAI
->getCommentColumn());
1158 O
<< MAI
->getCommentString()
1159 << " next halfword";
1162 O
<< MAI
->getData16bitsDirective(AddrSpace
) << uint16_t(p
[1]);
1164 O
.PadToColumn(MAI
->getCommentColumn());
1165 O
<< MAI
->getCommentString()
1166 << " most significant halfword";
1170 EmitZeros(TD
->getTypeAllocSize(Type::getX86_FP80Ty(Context
)) -
1171 TD
->getTypeStoreSize(Type::getX86_FP80Ty(Context
)), AddrSpace
);
1173 } else if (CFP
->getType() == Type::getPPC_FP128Ty(Context
)) {
1174 // all long double variants are printed as hex
1175 // api needed to prevent premature destruction
1176 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
1177 const uint64_t *p
= api
.getRawData();
1178 if (TD
->isBigEndian()) {
1179 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0] >> 32);
1181 O
.PadToColumn(MAI
->getCommentColumn());
1182 O
<< MAI
->getCommentString()
1183 << " most significant word of ppc_fp128";
1186 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0]);
1188 O
.PadToColumn(MAI
->getCommentColumn());
1189 O
<< MAI
->getCommentString()
1193 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1] >> 32);
1195 O
.PadToColumn(MAI
->getCommentColumn());
1196 O
<< MAI
->getCommentString()
1200 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1]);
1202 O
.PadToColumn(MAI
->getCommentColumn());
1203 O
<< MAI
->getCommentString()
1204 << " least significant word";
1208 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1]);
1210 O
.PadToColumn(MAI
->getCommentColumn());
1211 O
<< MAI
->getCommentString()
1212 << " least significant word of ppc_fp128";
1215 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[1] >> 32);
1217 O
.PadToColumn(MAI
->getCommentColumn());
1218 O
<< MAI
->getCommentString()
1222 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0]);
1224 O
.PadToColumn(MAI
->getCommentColumn());
1225 O
<< MAI
->getCommentString()
1229 O
<< MAI
->getData32bitsDirective(AddrSpace
) << uint32_t(p
[0] >> 32);
1231 O
.PadToColumn(MAI
->getCommentColumn());
1232 O
<< MAI
->getCommentString()
1233 << " most significant word";
1238 } else llvm_unreachable("Floating point constant type not handled");
1241 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt
*CI
,
1242 unsigned AddrSpace
) {
1243 const TargetData
*TD
= TM
.getTargetData();
1244 unsigned BitWidth
= CI
->getBitWidth();
1245 assert(isPowerOf2_32(BitWidth
) &&
1246 "Non-power-of-2-sized integers not handled!");
1248 // We don't expect assemblers to support integer data directives
1249 // for more than 64 bits, so we emit the data in at most 64-bit
1250 // quantities at a time.
1251 const uint64_t *RawData
= CI
->getValue().getRawData();
1252 for (unsigned i
= 0, e
= BitWidth
/ 64; i
!= e
; ++i
) {
1254 if (TD
->isBigEndian())
1255 Val
= RawData
[e
- i
- 1];
1259 if (MAI
->getData64bitsDirective(AddrSpace
))
1260 O
<< MAI
->getData64bitsDirective(AddrSpace
) << Val
<< '\n';
1261 else if (TD
->isBigEndian()) {
1262 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
>> 32);
1264 O
.PadToColumn(MAI
->getCommentColumn());
1265 O
<< MAI
->getCommentString()
1266 << " most significant half of i64 " << Val
;
1269 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
);
1271 O
.PadToColumn(MAI
->getCommentColumn());
1272 O
<< MAI
->getCommentString()
1273 << " least significant half of i64 " << Val
;
1277 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
);
1279 O
.PadToColumn(MAI
->getCommentColumn());
1280 O
<< MAI
->getCommentString()
1281 << " least significant half of i64 " << Val
;
1284 O
<< MAI
->getData32bitsDirective(AddrSpace
) << unsigned(Val
>> 32);
1286 O
.PadToColumn(MAI
->getCommentColumn());
1287 O
<< MAI
->getCommentString()
1288 << " most significant half of i64 " << Val
;
1295 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1296 void AsmPrinter::EmitGlobalConstant(const Constant
*CV
, unsigned AddrSpace
) {
1297 const TargetData
*TD
= TM
.getTargetData();
1298 const Type
*type
= CV
->getType();
1299 unsigned Size
= TD
->getTypeAllocSize(type
);
1301 if (CV
->isNullValue() || isa
<UndefValue
>(CV
)) {
1302 EmitZeros(Size
, AddrSpace
);
1304 } else if (const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(CV
)) {
1305 EmitGlobalConstantArray(CVA
, AddrSpace
);
1307 } else if (const ConstantStruct
*CVS
= dyn_cast
<ConstantStruct
>(CV
)) {
1308 EmitGlobalConstantStruct(CVS
, AddrSpace
);
1310 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
1311 EmitGlobalConstantFP(CFP
, AddrSpace
);
1313 } else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1314 // Small integers are handled below; large integers are handled here.
1316 EmitGlobalConstantLargeInt(CI
, AddrSpace
);
1319 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CV
)) {
1320 EmitGlobalConstantVector(CP
);
1324 printDataDirective(type
, AddrSpace
);
1325 EmitConstantValueOnly(CV
);
1327 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1329 CI
->getValue().toStringUnsigned(S
, 16);
1330 O
.PadToColumn(MAI
->getCommentColumn());
1331 O
<< MAI
->getCommentString() << " 0x" << S
.str();
1337 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue
*MCPV
) {
1338 // Target doesn't support this yet!
1339 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1342 /// PrintSpecial - Print information related to the specified machine instr
1343 /// that is independent of the operand, and may be independent of the instr
1344 /// itself. This can be useful for portably encoding the comment character
1345 /// or other bits of target-specific knowledge into the asmstrings. The
1346 /// syntax used is ${:comment}. Targets can override this to add support
1347 /// for their own strange codes.
1348 void AsmPrinter::PrintSpecial(const MachineInstr
*MI
, const char *Code
) const {
1349 if (!strcmp(Code
, "private")) {
1350 O
<< MAI
->getPrivateGlobalPrefix();
1351 } else if (!strcmp(Code
, "comment")) {
1353 O
<< MAI
->getCommentString();
1354 } else if (!strcmp(Code
, "uid")) {
1355 // Comparing the address of MI isn't sufficient, because machineinstrs may
1356 // be allocated to the same address across functions.
1357 const Function
*ThisF
= MI
->getParent()->getParent()->getFunction();
1359 // If this is a new LastFn instruction, bump the counter.
1360 if (LastMI
!= MI
|| LastFn
!= ThisF
) {
1368 raw_string_ostream
Msg(msg
);
1369 Msg
<< "Unknown special formatter '" << Code
1370 << "' for machine instr: " << *MI
;
1371 llvm_report_error(Msg
.str());
1375 /// processDebugLoc - Processes the debug information of each machine
1376 /// instruction's DebugLoc.
1377 void AsmPrinter::processDebugLoc(DebugLoc DL
) {
1381 if (MAI
->doesSupportDebugInformation() && DW
->ShouldEmitDwarfDebug()) {
1382 if (!DL
.isUnknown()) {
1383 DebugLocTuple CurDLT
= MF
->getDebugLocTuple(DL
);
1385 if (CurDLT
.CompileUnit
!= 0 && PrevDLT
!= CurDLT
)
1386 printLabel(DW
->RecordSourceLine(CurDLT
.Line
, CurDLT
.Col
,
1387 DICompileUnit(CurDLT
.CompileUnit
)));
1394 /// printInlineAsm - This method formats and prints the specified machine
1395 /// instruction that is an inline asm.
1396 void AsmPrinter::printInlineAsm(const MachineInstr
*MI
) const {
1397 unsigned NumOperands
= MI
->getNumOperands();
1399 // Count the number of register definitions.
1400 unsigned NumDefs
= 0;
1401 for (; MI
->getOperand(NumDefs
).isReg() && MI
->getOperand(NumDefs
).isDef();
1403 assert(NumDefs
!= NumOperands
-1 && "No asm string?");
1405 assert(MI
->getOperand(NumDefs
).isSymbol() && "No asm string?");
1407 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1408 const char *AsmStr
= MI
->getOperand(NumDefs
).getSymbolName();
1410 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1411 // These are useful to see where empty asm's wound up.
1412 if (AsmStr
[0] == 0) {
1413 O
<< MAI
->getCommentString() << MAI
->getInlineAsmStart() << "\n\t";
1414 O
<< MAI
->getCommentString() << MAI
->getInlineAsmEnd() << '\n';
1418 O
<< MAI
->getCommentString() << MAI
->getInlineAsmStart() << "\n\t";
1420 // The variant of the current asmprinter.
1421 int AsmPrinterVariant
= MAI
->getAssemblerDialect();
1423 int CurVariant
= -1; // The number of the {.|.|.} region we are in.
1424 const char *LastEmitted
= AsmStr
; // One past the last character emitted.
1426 while (*LastEmitted
) {
1427 switch (*LastEmitted
) {
1429 // Not a special case, emit the string section literally.
1430 const char *LiteralEnd
= LastEmitted
+1;
1431 while (*LiteralEnd
&& *LiteralEnd
!= '{' && *LiteralEnd
!= '|' &&
1432 *LiteralEnd
!= '}' && *LiteralEnd
!= '$' && *LiteralEnd
!= '\n')
1434 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
1435 O
.write(LastEmitted
, LiteralEnd
-LastEmitted
);
1436 LastEmitted
= LiteralEnd
;
1440 ++LastEmitted
; // Consume newline character.
1441 O
<< '\n'; // Indent code with newline.
1444 ++LastEmitted
; // Consume '$' character.
1448 switch (*LastEmitted
) {
1449 default: Done
= false; break;
1450 case '$': // $$ -> $
1451 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
1453 ++LastEmitted
; // Consume second '$' character.
1455 case '(': // $( -> same as GCC's { character.
1456 ++LastEmitted
; // Consume '(' character.
1457 if (CurVariant
!= -1) {
1458 llvm_report_error("Nested variants found in inline asm string: '"
1459 + std::string(AsmStr
) + "'");
1461 CurVariant
= 0; // We're in the first variant now.
1464 ++LastEmitted
; // consume '|' character.
1465 if (CurVariant
== -1)
1466 O
<< '|'; // this is gcc's behavior for | outside a variant
1468 ++CurVariant
; // We're in the next variant.
1470 case ')': // $) -> same as GCC's } char.
1471 ++LastEmitted
; // consume ')' character.
1472 if (CurVariant
== -1)
1473 O
<< '}'; // this is gcc's behavior for } outside a variant
1480 bool HasCurlyBraces
= false;
1481 if (*LastEmitted
== '{') { // ${variable}
1482 ++LastEmitted
; // Consume '{' character.
1483 HasCurlyBraces
= true;
1486 // If we have ${:foo}, then this is not a real operand reference, it is a
1487 // "magic" string reference, just like in .td files. Arrange to call
1489 if (HasCurlyBraces
&& *LastEmitted
== ':') {
1491 const char *StrStart
= LastEmitted
;
1492 const char *StrEnd
= strchr(StrStart
, '}');
1494 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1495 + std::string(AsmStr
) + "'");
1498 std::string
Val(StrStart
, StrEnd
);
1499 PrintSpecial(MI
, Val
.c_str());
1500 LastEmitted
= StrEnd
+1;
1504 const char *IDStart
= LastEmitted
;
1507 long Val
= strtol(IDStart
, &IDEnd
, 10); // We only accept numbers for IDs.
1508 if (!isdigit(*IDStart
) || (Val
== 0 && errno
== EINVAL
)) {
1509 llvm_report_error("Bad $ operand number in inline asm string: '"
1510 + std::string(AsmStr
) + "'");
1512 LastEmitted
= IDEnd
;
1514 char Modifier
[2] = { 0, 0 };
1516 if (HasCurlyBraces
) {
1517 // If we have curly braces, check for a modifier character. This
1518 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1519 if (*LastEmitted
== ':') {
1520 ++LastEmitted
; // Consume ':' character.
1521 if (*LastEmitted
== 0) {
1522 llvm_report_error("Bad ${:} expression in inline asm string: '"
1523 + std::string(AsmStr
) + "'");
1526 Modifier
[0] = *LastEmitted
;
1527 ++LastEmitted
; // Consume modifier character.
1530 if (*LastEmitted
!= '}') {
1531 llvm_report_error("Bad ${} expression in inline asm string: '"
1532 + std::string(AsmStr
) + "'");
1534 ++LastEmitted
; // Consume '}' character.
1537 if ((unsigned)Val
>= NumOperands
-1) {
1538 llvm_report_error("Invalid $ operand number in inline asm string: '"
1539 + std::string(AsmStr
) + "'");
1542 // Okay, we finally have a value number. Ask the target to print this
1544 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
) {
1549 // Scan to find the machine operand number for the operand.
1550 for (; Val
; --Val
) {
1551 if (OpNo
>= MI
->getNumOperands()) break;
1552 unsigned OpFlags
= MI
->getOperand(OpNo
).getImm();
1553 OpNo
+= InlineAsm::getNumOperandRegisters(OpFlags
) + 1;
1556 if (OpNo
>= MI
->getNumOperands()) {
1559 unsigned OpFlags
= MI
->getOperand(OpNo
).getImm();
1560 ++OpNo
; // Skip over the ID number.
1562 if (Modifier
[0]=='l') // labels are target independent
1563 printBasicBlockLabel(MI
->getOperand(OpNo
).getMBB(),
1564 false, false, false);
1566 AsmPrinter
*AP
= const_cast<AsmPrinter
*>(this);
1567 if ((OpFlags
& 7) == 4) {
1568 Error
= AP
->PrintAsmMemoryOperand(MI
, OpNo
, AsmPrinterVariant
,
1569 Modifier
[0] ? Modifier
: 0);
1571 Error
= AP
->PrintAsmOperand(MI
, OpNo
, AsmPrinterVariant
,
1572 Modifier
[0] ? Modifier
: 0);
1578 raw_string_ostream
Msg(msg
);
1579 Msg
<< "Invalid operand found in inline asm: '"
1582 llvm_report_error(Msg
.str());
1589 O
<< "\n\t" << MAI
->getCommentString() << MAI
->getInlineAsmEnd() << '\n';
1592 /// printImplicitDef - This method prints the specified machine instruction
1593 /// that is an implicit def.
1594 void AsmPrinter::printImplicitDef(const MachineInstr
*MI
) const {
1596 O
.PadToColumn(MAI
->getCommentColumn());
1597 O
<< MAI
->getCommentString() << " implicit-def: "
1598 << TRI
->getAsmName(MI
->getOperand(0).getReg()) << '\n';
1602 /// printLabel - This method prints a local label used by debug and
1603 /// exception handling tables.
1604 void AsmPrinter::printLabel(const MachineInstr
*MI
) const {
1605 printLabel(MI
->getOperand(0).getImm());
1608 void AsmPrinter::printLabel(unsigned Id
) const {
1609 O
<< MAI
->getPrivateGlobalPrefix() << "label" << Id
<< ":\n";
1612 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1613 /// instruction, using the specified assembler variant. Targets should
1614 /// overried this to format as appropriate.
1615 bool AsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
1616 unsigned AsmVariant
, const char *ExtraCode
) {
1617 // Target doesn't support this yet!
1621 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
, unsigned OpNo
,
1622 unsigned AsmVariant
,
1623 const char *ExtraCode
) {
1624 // Target doesn't support this yet!
1628 /// printBasicBlockLabel - This method prints the label for the specified
1629 /// MachineBasicBlock
1630 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock
*MBB
,
1633 bool printComment
) const {
1635 unsigned Align
= MBB
->getAlignment();
1637 EmitAlignment(Log2_32(Align
));
1640 O
<< MAI
->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1641 << MBB
->getNumber();
1645 if (const BasicBlock
*BB
= MBB
->getBasicBlock())
1646 if (BB
->hasName()) {
1647 O
.PadToColumn(MAI
->getCommentColumn());
1648 O
<< MAI
->getCommentString() << ' ';
1649 WriteAsOperand(O
, BB
, /*PrintType=*/false);
1657 /// printPICJumpTableSetLabel - This method prints a set label for the
1658 /// specified MachineBasicBlock for a jumptable entry.
1659 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid
,
1660 const MachineBasicBlock
*MBB
) const {
1661 if (!MAI
->getSetDirective())
1664 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
1665 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
1666 printBasicBlockLabel(MBB
, false, false, false);
1667 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1668 << '_' << uid
<< '\n';
1671 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid
, unsigned uid2
,
1672 const MachineBasicBlock
*MBB
) const {
1673 if (!MAI
->getSetDirective())
1676 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
1677 << getFunctionNumber() << '_' << uid
<< '_' << uid2
1678 << "_set_" << MBB
->getNumber() << ',';
1679 printBasicBlockLabel(MBB
, false, false, false);
1680 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1681 << '_' << uid
<< '_' << uid2
<< '\n';
1684 /// printDataDirective - This method prints the asm directive for the
1686 void AsmPrinter::printDataDirective(const Type
*type
, unsigned AddrSpace
) {
1687 const TargetData
*TD
= TM
.getTargetData();
1688 switch (type
->getTypeID()) {
1689 case Type::FloatTyID
: case Type::DoubleTyID
:
1690 case Type::X86_FP80TyID
: case Type::FP128TyID
: case Type::PPC_FP128TyID
:
1691 assert(0 && "Should have already output floating point constant.");
1693 assert(0 && "Can't handle printing this type of thing");
1694 case Type::IntegerTyID
: {
1695 unsigned BitWidth
= cast
<IntegerType
>(type
)->getBitWidth();
1697 O
<< MAI
->getData8bitsDirective(AddrSpace
);
1698 else if (BitWidth
<= 16)
1699 O
<< MAI
->getData16bitsDirective(AddrSpace
);
1700 else if (BitWidth
<= 32)
1701 O
<< MAI
->getData32bitsDirective(AddrSpace
);
1702 else if (BitWidth
<= 64) {
1703 assert(MAI
->getData64bitsDirective(AddrSpace
) &&
1704 "Target cannot handle 64-bit constant exprs!");
1705 O
<< MAI
->getData64bitsDirective(AddrSpace
);
1707 llvm_unreachable("Target cannot handle given data directive width!");
1711 case Type::PointerTyID
:
1712 if (TD
->getPointerSize() == 8) {
1713 assert(MAI
->getData64bitsDirective(AddrSpace
) &&
1714 "Target cannot handle 64-bit pointer exprs!");
1715 O
<< MAI
->getData64bitsDirective(AddrSpace
);
1716 } else if (TD
->getPointerSize() == 2) {
1717 O
<< MAI
->getData16bitsDirective(AddrSpace
);
1718 } else if (TD
->getPointerSize() == 1) {
1719 O
<< MAI
->getData8bitsDirective(AddrSpace
);
1721 O
<< MAI
->getData32bitsDirective(AddrSpace
);
1727 void AsmPrinter::printVisibility(const std::string
& Name
,
1728 unsigned Visibility
) const {
1729 if (Visibility
== GlobalValue::HiddenVisibility
) {
1730 if (const char *Directive
= MAI
->getHiddenDirective())
1731 O
<< Directive
<< Name
<< '\n';
1732 } else if (Visibility
== GlobalValue::ProtectedVisibility
) {
1733 if (const char *Directive
= MAI
->getProtectedDirective())
1734 O
<< Directive
<< Name
<< '\n';
1738 void AsmPrinter::printOffset(int64_t Offset
) const {
1741 else if (Offset
< 0)
1745 void AsmPrinter::printMCInst(const MCInst
*MI
) {
1746 llvm_unreachable("MCInst printing unavailable on this target!");
1749 GCMetadataPrinter
*AsmPrinter::GetOrCreateGCPrinter(GCStrategy
*S
) {
1750 if (!S
->usesMetadata())
1753 gcp_iterator GCPI
= GCMetadataPrinters
.find(S
);
1754 if (GCPI
!= GCMetadataPrinters
.end())
1755 return GCPI
->second
;
1757 const char *Name
= S
->getName().c_str();
1759 for (GCMetadataPrinterRegistry::iterator
1760 I
= GCMetadataPrinterRegistry::begin(),
1761 E
= GCMetadataPrinterRegistry::end(); I
!= E
; ++I
)
1762 if (strcmp(Name
, I
->getName()) == 0) {
1763 GCMetadataPrinter
*GMP
= I
->instantiate();
1765 GCMetadataPrinters
.insert(std::make_pair(S
, GMP
));
1769 errs() << "no GCMetadataPrinter registered for GC: " << Name
<< "\n";
1770 llvm_unreachable(0);
1773 /// EmitComments - Pretty-print comments for instructions
1774 void AsmPrinter::EmitComments(const MachineInstr
&MI
) const {
1776 MI
.getDebugLoc().isUnknown())
1779 DebugLocTuple DLT
= MF
->getDebugLocTuple(MI
.getDebugLoc());
1781 // Print source line info.
1782 O
.PadToColumn(MAI
->getCommentColumn());
1783 O
<< MAI
->getCommentString() << " SrcLine ";
1784 if (DLT
.CompileUnit
) {
1786 DICompileUnit
CU(DLT
.CompileUnit
);
1787 O
<< CU
.getFilename(Str
) << " ";
1791 O
<< ":" << DLT
.Col
;
1794 /// EmitComments - Pretty-print comments for instructions
1795 void AsmPrinter::EmitComments(const MCInst
&MI
) const {
1797 MI
.getDebugLoc().isUnknown())
1800 DebugLocTuple DLT
= MF
->getDebugLocTuple(MI
.getDebugLoc());
1802 // Print source line info
1803 O
.PadToColumn(MAI
->getCommentColumn());
1804 O
<< MAI
->getCommentString() << " SrcLine ";
1805 if (DLT
.CompileUnit
) {
1807 DICompileUnit
CU(DLT
.CompileUnit
);
1808 O
<< CU
.getFilename(Str
) << " ";
1812 O
<< ":" << DLT
.Col
;
1815 /// PrintChildLoopComment - Print comments about child loops within
1816 /// the loop for this basic block, with nesting.
1818 static void PrintChildLoopComment(formatted_raw_ostream
&O
,
1819 const MachineLoop
*loop
,
1820 const MCAsmInfo
*MAI
,
1821 int FunctionNumber
) {
1822 // Add child loop information
1823 for(MachineLoop::iterator cl
= loop
->begin(),
1824 clend
= loop
->end();
1827 MachineBasicBlock
*Header
= (*cl
)->getHeader();
1828 assert(Header
&& "No header for loop");
1831 O
.PadToColumn(MAI
->getCommentColumn());
1833 O
<< MAI
->getCommentString();
1834 O
.indent(((*cl
)->getLoopDepth()-1)*2)
1835 << " Child Loop BB" << FunctionNumber
<< "_"
1836 << Header
->getNumber() << " Depth " << (*cl
)->getLoopDepth();
1838 PrintChildLoopComment(O
, *cl
, MAI
, FunctionNumber
);
1842 /// EmitComments - Pretty-print comments for basic blocks
1843 void AsmPrinter::EmitComments(const MachineBasicBlock
&MBB
) const
1846 // Add loop depth information
1847 const MachineLoop
*loop
= LI
->getLoopFor(&MBB
);
1850 // Print a newline after bb# annotation.
1852 O
.PadToColumn(MAI
->getCommentColumn());
1853 O
<< MAI
->getCommentString() << " Loop Depth " << loop
->getLoopDepth()
1856 O
.PadToColumn(MAI
->getCommentColumn());
1858 MachineBasicBlock
*Header
= loop
->getHeader();
1859 assert(Header
&& "No header for loop");
1861 if (Header
== &MBB
) {
1862 O
<< MAI
->getCommentString() << " Loop Header";
1863 PrintChildLoopComment(O
, loop
, MAI
, getFunctionNumber());
1866 O
<< MAI
->getCommentString() << " Loop Header is BB"
1867 << getFunctionNumber() << "_" << loop
->getHeader()->getNumber();
1870 if (loop
->empty()) {
1872 O
.PadToColumn(MAI
->getCommentColumn());
1873 O
<< MAI
->getCommentString() << " Inner Loop";
1876 // Add parent loop information
1877 for (const MachineLoop
*CurLoop
= loop
->getParentLoop();
1879 CurLoop
= CurLoop
->getParentLoop()) {
1880 MachineBasicBlock
*Header
= CurLoop
->getHeader();
1881 assert(Header
&& "No header for loop");
1884 O
.PadToColumn(MAI
->getCommentColumn());
1885 O
<< MAI
->getCommentString();
1886 O
.indent((CurLoop
->getLoopDepth()-1)*2)
1887 << " Inside Loop BB" << getFunctionNumber() << "_"
1888 << Header
->getNumber() << " Depth " << CurLoop
->getLoopDepth();