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 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Target/Mangler.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetInstrInfo.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/SmallString.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
48 STATISTIC(EmittedInsts, "Number of machine instrs printed");
50 char AsmPrinter::ID = 0;
52 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
53 static gcp_map_type &getGCMap(void *&P) {
55 P = new gcp_map_type();
56 return *(gcp_map_type*)P;
60 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
61 : MachineFunctionPass(&ID),
62 TM(tm), MAI(tm.getMCAsmInfo()),
63 OutContext(Streamer.getContext()),
64 OutStreamer(Streamer),
65 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
66 DD = 0; DE = 0; MMI = 0; LI = 0;
67 GCMetadataPrinters = 0;
68 VerboseAsm = Streamer.isVerboseAsm();
71 AsmPrinter::~AsmPrinter() {
72 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
74 if (GCMetadataPrinters != 0) {
75 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
77 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
80 GCMetadataPrinters = 0;
86 /// getFunctionNumber - Return a unique ID for the current function.
88 unsigned AsmPrinter::getFunctionNumber() const {
89 return MF->getFunctionNumber();
92 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
93 return TM.getTargetLowering()->getObjFileLowering();
97 /// getTargetData - Return information about data layout.
98 const TargetData &AsmPrinter::getTargetData() const {
99 return *TM.getTargetData();
102 /// getCurrentSection() - Return the current section we are emitting to.
103 const MCSection *AsmPrinter::getCurrentSection() const {
104 return OutStreamer.getCurrentSection();
109 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.setPreservesAll();
111 MachineFunctionPass::getAnalysisUsage(AU);
112 AU.addRequired<MachineModuleInfo>();
113 AU.addRequired<GCModuleInfo>();
115 AU.addRequired<MachineLoopInfo>();
118 bool AsmPrinter::doInitialization(Module &M) {
119 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
120 MMI->AnalyzeModule(M);
122 // Initialize TargetLoweringObjectFile.
123 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
124 .Initialize(OutContext, TM);
126 Mang = new Mangler(OutContext, *TM.getTargetData());
128 // Allow the target to emit any magic that it wants at the start of the file.
129 EmitStartOfAsmFile(M);
131 // Very minimal debug info. It is ignored if we emit actual debug info. If we
132 // don't, this at least helps the user find where a global came from.
133 if (MAI->hasSingleParameterDotFile()) {
135 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
138 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
139 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
140 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
141 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
142 MP->beginAssembly(*this);
144 // Emit module-level inline asm if it exists.
145 if (!M.getModuleInlineAsm().empty()) {
146 OutStreamer.AddComment("Start of file scope inline assembly");
147 OutStreamer.AddBlankLine();
148 EmitInlineAsm(M.getModuleInlineAsm());
149 OutStreamer.AddComment("End of file scope inline assembly");
150 OutStreamer.AddBlankLine();
153 if (MAI->doesSupportDebugInformation())
154 DD = new DwarfDebug(this, &M);
156 if (MAI->doesSupportExceptionHandling())
157 DE = new DwarfException(this);
162 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
163 switch ((GlobalValue::LinkageTypes)Linkage) {
164 case GlobalValue::CommonLinkage:
165 case GlobalValue::LinkOnceAnyLinkage:
166 case GlobalValue::LinkOnceODRLinkage:
167 case GlobalValue::WeakAnyLinkage:
168 case GlobalValue::WeakODRLinkage:
169 case GlobalValue::LinkerPrivateLinkage:
170 if (MAI->getWeakDefDirective() != 0) {
172 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
173 // .weak_definition _foo
174 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
175 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
177 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
178 // FIXME: linkonce should be a section attribute, handled by COFF Section
180 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
182 // FIXME: It would be nice to use .linkonce samesize for non-common
184 OutStreamer.EmitRawText(StringRef(LinkOnce));
187 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
190 case GlobalValue::DLLExportLinkage:
191 case GlobalValue::AppendingLinkage:
192 // FIXME: appending linkage variables should go into a section of
193 // their name or something. For now, just emit them as external.
194 case GlobalValue::ExternalLinkage:
195 // If external or appending, declare as a global symbol.
197 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
199 case GlobalValue::PrivateLinkage:
200 case GlobalValue::InternalLinkage:
203 llvm_unreachable("Unknown linkage type!");
208 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
209 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
210 if (!GV->hasInitializer()) // External globals require no code.
213 // Check to see if this is a special global used by LLVM, if so, emit it.
214 if (EmitSpecialLLVMGlobal(GV))
217 MCSymbol *GVSym = Mang->getSymbol(GV);
218 EmitVisibility(GVSym, GV->getVisibility());
220 if (MAI->hasDotTypeDotSizeDirective())
221 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
223 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
225 const TargetData *TD = TM.getTargetData();
226 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
227 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
229 // Handle common and BSS local symbols (.lcomm).
230 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
231 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
234 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
235 /*PrintType=*/false, GV->getParent());
236 OutStreamer.GetCommentOS() << '\n';
239 // Handle common symbols.
240 if (GVKind.isCommon()) {
242 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
246 // Handle local BSS symbols.
247 if (MAI->hasMachoZeroFillDirective()) {
248 const MCSection *TheSection =
249 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
250 // .zerofill __DATA, __bss, _foo, 400, 5
251 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
255 if (MAI->hasLCOMMDirective()) {
257 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
264 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
268 const MCSection *TheSection =
269 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
271 // Handle the zerofill directive on darwin, which is a special form of BSS
273 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
275 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
276 // .zerofill __DATA, __common, _foo, 400, 5
277 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
281 OutStreamer.SwitchSection(TheSection);
283 EmitLinkage(GV->getLinkage(), GVSym);
284 EmitAlignment(AlignLog, GV);
287 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
288 /*PrintType=*/false, GV->getParent());
289 OutStreamer.GetCommentOS() << '\n';
291 OutStreamer.EmitLabel(GVSym);
293 EmitGlobalConstant(GV->getInitializer());
295 if (MAI->hasDotTypeDotSizeDirective())
297 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
299 OutStreamer.AddBlankLine();
302 /// EmitFunctionHeader - This method emits the header for the current
304 void AsmPrinter::EmitFunctionHeader() {
305 // Print out constants referenced by the function
308 // Print the 'header' of function.
309 const Function *F = MF->getFunction();
311 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
312 EmitVisibility(CurrentFnSym, F->getVisibility());
314 EmitLinkage(F->getLinkage(), CurrentFnSym);
315 EmitAlignment(MF->getAlignment(), F);
317 if (MAI->hasDotTypeDotSizeDirective())
318 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
321 WriteAsOperand(OutStreamer.GetCommentOS(), F,
322 /*PrintType=*/false, F->getParent());
323 OutStreamer.GetCommentOS() << '\n';
326 // Emit the CurrentFnSym. This is a virtual function to allow targets to
327 // do their wild and crazy things as required.
328 EmitFunctionEntryLabel();
330 // If the function had address-taken blocks that got deleted, then we have
331 // references to the dangling symbols. Emit them at the start of the function
332 // so that we don't get references to undefined symbols.
333 std::vector<MCSymbol*> DeadBlockSyms;
334 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
335 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
336 OutStreamer.AddComment("Address taken block that was later removed");
337 OutStreamer.EmitLabel(DeadBlockSyms[i]);
340 // Add some workaround for linkonce linkage on Cygwin\MinGW.
341 if (MAI->getLinkOnceDirective() != 0 &&
342 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
343 // FIXME: What is this?
345 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
346 CurrentFnSym->getName());
347 OutStreamer.EmitLabel(FakeStub);
350 // Emit pre-function debug and/or EH information.
351 if (DE) DE->BeginFunction(MF);
352 if (DD) DD->beginFunction(MF);
355 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
356 /// function. This can be overridden by targets as required to do custom stuff.
357 void AsmPrinter::EmitFunctionEntryLabel() {
358 OutStreamer.EmitLabel(CurrentFnSym);
362 /// EmitComments - Pretty-print comments for instructions.
363 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
364 const MachineFunction *MF = MI.getParent()->getParent();
365 const TargetMachine &TM = MF->getTarget();
367 DebugLoc DL = MI.getDebugLoc();
368 if (!DL.isUnknown()) { // Print source line info.
369 DIScope Scope(DL.getScope(MF->getFunction()->getContext()));
370 // Omit the directory, because it's likely to be long and uninteresting.
372 CommentOS << Scope.getFilename();
374 CommentOS << "<unknown>";
375 CommentOS << ':' << DL.getLine();
376 if (DL.getCol() != 0)
377 CommentOS << ':' << DL.getCol();
381 // Check for spills and reloads
384 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
386 // We assume a single instruction only has a spill or reload, not
388 const MachineMemOperand *MMO;
389 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
390 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
391 MMO = *MI.memoperands_begin();
392 CommentOS << MMO->getSize() << "-byte Reload\n";
394 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
395 if (FrameInfo->isSpillSlotObjectIndex(FI))
396 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
397 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
398 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
399 MMO = *MI.memoperands_begin();
400 CommentOS << MMO->getSize() << "-byte Spill\n";
402 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
403 if (FrameInfo->isSpillSlotObjectIndex(FI))
404 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
407 // Check for spill-induced copies
408 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
409 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
410 SrcSubIdx, DstSubIdx)) {
411 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
412 CommentOS << " Reload Reuse\n";
416 /// EmitImplicitDef - This method emits the specified machine instruction
417 /// that is an implicit def.
418 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
419 unsigned RegNo = MI->getOperand(0).getReg();
420 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
421 AP.TM.getRegisterInfo()->getName(RegNo));
422 AP.OutStreamer.AddBlankLine();
425 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
426 std::string Str = "kill:";
427 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428 const MachineOperand &Op = MI->getOperand(i);
429 assert(Op.isReg() && "KILL instruction must have only register operands");
431 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
432 Str += (Op.isDef() ? "<def>" : "<kill>");
434 AP.OutStreamer.AddComment(Str);
435 AP.OutStreamer.AddBlankLine();
440 /// EmitFunctionBody - This method emits the body and trailer for a
442 void AsmPrinter::EmitFunctionBody() {
443 // Emit target-specific gunk before the function body.
444 EmitFunctionBodyStart();
446 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
448 // Print out code for the function.
449 bool HasAnyRealCode = false;
450 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
452 // Print a label for the basic block.
453 EmitBasicBlockStart(I);
454 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
456 // Print the assembly for the instruction.
458 HasAnyRealCode = true;
462 if (ShouldPrintDebugScopes)
466 EmitComments(*II, OutStreamer.GetCommentOS());
468 switch (II->getOpcode()) {
469 case TargetOpcode::DBG_LABEL:
470 case TargetOpcode::EH_LABEL:
471 case TargetOpcode::GC_LABEL:
472 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
474 case TargetOpcode::INLINEASM:
477 case TargetOpcode::IMPLICIT_DEF:
478 if (isVerbose()) EmitImplicitDef(II, *this);
480 case TargetOpcode::KILL:
481 if (isVerbose()) EmitKill(II, *this);
488 if (ShouldPrintDebugScopes)
493 // If the function is empty and the object file uses .subsections_via_symbols,
494 // then we need to emit *something* to the function body to prevent the
495 // labels from collapsing together. Just emit a 0 byte.
496 if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)
497 OutStreamer.EmitIntValue(0, 1, 0/*addrspace*/);
499 // Emit target-specific gunk after the function body.
500 EmitFunctionBodyEnd();
502 // If the target wants a .size directive for the size of the function, emit
504 if (MAI->hasDotTypeDotSizeDirective()) {
505 // Create a symbol for the end of function, so we can get the size as
506 // difference between the function label and the temp label.
507 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
508 OutStreamer.EmitLabel(FnEndLabel);
510 const MCExpr *SizeExp =
511 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
512 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
514 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
517 // Emit post-function debug information.
518 if (DD) DD->endFunction(MF);
519 if (DE) DE->EndFunction();
522 // Print out jump tables referenced by the function.
525 OutStreamer.AddBlankLine();
529 bool AsmPrinter::doFinalization(Module &M) {
530 // Emit global variables.
531 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
533 EmitGlobalVariable(I);
535 // Finalize debug and EH information.
545 // If the target wants to know about weak references, print them all.
546 if (MAI->getWeakRefDirective()) {
547 // FIXME: This is not lazy, it would be nice to only print weak references
548 // to stuff that is actually used. Note that doing so would require targets
549 // to notice uses in operands (due to constant exprs etc). This should
550 // happen with the MC stuff eventually.
552 // Print out module-level global variables here.
553 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
555 if (!I->hasExternalWeakLinkage()) continue;
556 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
559 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
560 if (!I->hasExternalWeakLinkage()) continue;
561 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
565 if (MAI->hasSetDirective()) {
566 OutStreamer.AddBlankLine();
567 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
569 MCSymbol *Name = Mang->getSymbol(I);
571 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
572 MCSymbol *Target = Mang->getSymbol(GV);
574 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
575 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
576 else if (I->hasWeakLinkage())
577 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
579 assert(I->hasLocalLinkage() && "Invalid alias linkage");
581 EmitVisibility(Name, I->getVisibility());
583 // Emit the directives as assignments aka .set:
584 OutStreamer.EmitAssignment(Name,
585 MCSymbolRefExpr::Create(Target, OutContext));
589 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
590 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
591 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
592 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
593 MP->finishAssembly(*this);
595 // If we don't have any trampolines, then we don't require stack memory
596 // to be executable. Some targets have a directive to declare this.
597 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
598 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
599 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
600 OutStreamer.SwitchSection(S);
602 // Allow the target to emit any magic that it wants at the end of the file,
603 // after everything else has gone out.
606 delete Mang; Mang = 0;
609 OutStreamer.Finish();
613 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
615 // Get the function symbol.
616 CurrentFnSym = Mang->getSymbol(MF.getFunction());
619 LI = &getAnalysis<MachineLoopInfo>();
623 // SectionCPs - Keep track the alignment, constpool entries per Section.
627 SmallVector<unsigned, 4> CPEs;
628 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
632 /// EmitConstantPool - Print to the current output stream assembly
633 /// representations of the constants in the constant pool MCP. This is
634 /// used to print out constants which have been "spilled to memory" by
635 /// the code generator.
637 void AsmPrinter::EmitConstantPool() {
638 const MachineConstantPool *MCP = MF->getConstantPool();
639 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
640 if (CP.empty()) return;
642 // Calculate sections for constant pool entries. We collect entries to go into
643 // the same section together to reduce amount of section switch statements.
644 SmallVector<SectionCPs, 4> CPSections;
645 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
646 const MachineConstantPoolEntry &CPE = CP[i];
647 unsigned Align = CPE.getAlignment();
650 switch (CPE.getRelocationInfo()) {
651 default: llvm_unreachable("Unknown section kind");
652 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
654 Kind = SectionKind::getReadOnlyWithRelLocal();
657 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
658 case 4: Kind = SectionKind::getMergeableConst4(); break;
659 case 8: Kind = SectionKind::getMergeableConst8(); break;
660 case 16: Kind = SectionKind::getMergeableConst16();break;
661 default: Kind = SectionKind::getMergeableConst(); break;
665 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
667 // The number of sections are small, just do a linear search from the
668 // last section to the first.
670 unsigned SecIdx = CPSections.size();
671 while (SecIdx != 0) {
672 if (CPSections[--SecIdx].S == S) {
678 SecIdx = CPSections.size();
679 CPSections.push_back(SectionCPs(S, Align));
682 if (Align > CPSections[SecIdx].Alignment)
683 CPSections[SecIdx].Alignment = Align;
684 CPSections[SecIdx].CPEs.push_back(i);
687 // Now print stuff into the calculated sections.
688 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
689 OutStreamer.SwitchSection(CPSections[i].S);
690 EmitAlignment(Log2_32(CPSections[i].Alignment));
693 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
694 unsigned CPI = CPSections[i].CPEs[j];
695 MachineConstantPoolEntry CPE = CP[CPI];
697 // Emit inter-object padding for alignment.
698 unsigned AlignMask = CPE.getAlignment() - 1;
699 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
700 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
702 const Type *Ty = CPE.getType();
703 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
705 // Emit the label with a comment on it.
707 OutStreamer.GetCommentOS() << "constant pool ";
708 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
709 MF->getFunction()->getParent());
710 OutStreamer.GetCommentOS() << '\n';
712 OutStreamer.EmitLabel(GetCPISymbol(CPI));
714 if (CPE.isMachineConstantPoolEntry())
715 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
717 EmitGlobalConstant(CPE.Val.ConstVal);
722 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
723 /// by the current function to the current output stream.
725 void AsmPrinter::EmitJumpTableInfo() {
726 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
727 if (MJTI == 0) return;
728 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
729 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
730 if (JT.empty()) return;
732 // Pick the directive to use to print the jump table entries, and switch to
733 // the appropriate section.
734 const Function *F = MF->getFunction();
735 bool JTInDiffSection = false;
736 if (// In PIC mode, we need to emit the jump table to the same section as the
737 // function body itself, otherwise the label differences won't make sense.
738 // FIXME: Need a better predicate for this: what about custom entries?
739 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
740 // We should also do if the section name is NULL or function is declared
741 // in discardable section
742 // FIXME: this isn't the right predicate, should be based on the MCSection
744 F->isWeakForLinker()) {
745 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
747 // Otherwise, drop it in the readonly section.
748 const MCSection *ReadOnlySection =
749 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
750 OutStreamer.SwitchSection(ReadOnlySection);
751 JTInDiffSection = true;
754 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
756 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
757 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
759 // If this jump table was deleted, ignore it.
760 if (JTBBs.empty()) continue;
762 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
763 // .set directive for each unique entry. This reduces the number of
764 // relocations the assembler will generate for the jump table.
765 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
766 MAI->hasSetDirective()) {
767 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
768 const TargetLowering *TLI = TM.getTargetLowering();
769 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
770 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
771 const MachineBasicBlock *MBB = JTBBs[ii];
772 if (!EmittedSets.insert(MBB)) continue;
774 // .set LJTSet, LBB32-base
776 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
777 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
778 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
782 // On some targets (e.g. Darwin) we want to emit two consequtive labels
783 // before each jump table. The first label is never referenced, but tells
784 // the assembler and linker the extents of the jump table object. The
785 // second label is actually referenced by the code.
786 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
787 // FIXME: This doesn't have to have any specific name, just any randomly
788 // named and numbered 'l' label would work. Simplify GetJTISymbol.
789 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
791 OutStreamer.EmitLabel(GetJTISymbol(JTI));
793 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
794 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
798 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
800 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
801 const MachineBasicBlock *MBB,
802 unsigned UID) const {
803 const MCExpr *Value = 0;
804 switch (MJTI->getEntryKind()) {
805 case MachineJumpTableInfo::EK_Inline:
806 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
807 case MachineJumpTableInfo::EK_Custom32:
808 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
811 case MachineJumpTableInfo::EK_BlockAddress:
812 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
814 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
816 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
817 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
818 // with a relocation as gp-relative, e.g.:
820 MCSymbol *MBBSym = MBB->getSymbol();
821 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
825 case MachineJumpTableInfo::EK_LabelDifference32: {
826 // EK_LabelDifference32 - Each entry is the address of the block minus
827 // the address of the jump table. This is used for PIC jump tables where
828 // gprel32 is not supported. e.g.:
829 // .word LBB123 - LJTI1_2
830 // If the .set directive is supported, this is emitted as:
831 // .set L4_5_set_123, LBB123 - LJTI1_2
832 // .word L4_5_set_123
834 // If we have emitted set directives for the jump table entries, print
835 // them rather than the entries themselves. If we're emitting PIC, then
836 // emit the table entries as differences between two text section labels.
837 if (MAI->hasSetDirective()) {
838 // If we used .set, reference the .set's symbol.
839 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
843 // Otherwise, use the difference as the jump table entry.
844 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
845 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
846 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
851 assert(Value && "Unknown entry kind!");
853 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
854 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
858 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
859 /// special global used by LLVM. If so, emit it and return true, otherwise
860 /// do nothing and return false.
861 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
862 if (GV->getName() == "llvm.used") {
863 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
864 EmitLLVMUsedList(GV->getInitializer());
868 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
869 if (GV->getSection() == "llvm.metadata" ||
870 GV->hasAvailableExternallyLinkage())
873 if (!GV->hasAppendingLinkage()) return false;
875 assert(GV->hasInitializer() && "Not a special LLVM global!");
877 const TargetData *TD = TM.getTargetData();
878 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
879 if (GV->getName() == "llvm.global_ctors") {
880 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
881 EmitAlignment(Align, 0);
882 EmitXXStructorList(GV->getInitializer());
884 if (TM.getRelocationModel() == Reloc::Static &&
885 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
886 StringRef Sym(".constructors_used");
887 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
893 if (GV->getName() == "llvm.global_dtors") {
894 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
895 EmitAlignment(Align, 0);
896 EmitXXStructorList(GV->getInitializer());
898 if (TM.getRelocationModel() == Reloc::Static &&
899 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
900 StringRef Sym(".destructors_used");
901 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
910 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
911 /// global in the specified llvm.used list for which emitUsedDirectiveFor
912 /// is true, as being used with this directive.
913 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
914 // Should be an array of 'i8*'.
915 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
916 if (InitList == 0) return;
918 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
919 const GlobalValue *GV =
920 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
921 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
922 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
926 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
927 /// function pointers, ignoring the init priority.
928 void AsmPrinter::EmitXXStructorList(Constant *List) {
929 // Should be an array of '{ int, void ()* }' structs. The first value is the
930 // init priority, which we ignore.
931 if (!isa<ConstantArray>(List)) return;
932 ConstantArray *InitList = cast<ConstantArray>(List);
933 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
934 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
935 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
937 if (CS->getOperand(1)->isNullValue())
938 return; // Found a null terminator, exit printing.
939 // Emit the function pointer.
940 EmitGlobalConstant(CS->getOperand(1));
944 //===--------------------------------------------------------------------===//
945 // Emission and print routines
948 /// EmitInt8 - Emit a byte directive and value.
950 void AsmPrinter::EmitInt8(int Value) const {
951 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
954 /// EmitInt16 - Emit a short directive and value.
956 void AsmPrinter::EmitInt16(int Value) const {
957 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
960 /// EmitInt32 - Emit a long directive and value.
962 void AsmPrinter::EmitInt32(int Value) const {
963 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
966 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
967 /// in bytes of the directive is specified by Size and Hi/Lo specify the
968 /// labels. This implicitly uses .set if it is available.
969 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
970 unsigned Size) const {
971 // Get the Hi-Lo expression.
973 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
974 MCSymbolRefExpr::Create(Lo, OutContext),
977 if (!MAI->hasSetDirective()) {
978 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
982 // Otherwise, emit with .set (aka assignment).
983 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
984 OutStreamer.EmitAssignment(SetLabel, Diff);
985 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
989 //===----------------------------------------------------------------------===//
991 // EmitAlignment - Emit an alignment directive to the specified power of
992 // two boundary. For example, if you pass in 3 here, you will get an 8
993 // byte alignment. If a global value is specified, and if that global has
994 // an explicit alignment requested, it will unconditionally override the
995 // alignment request. However, if ForcedAlignBits is specified, this value
996 // has final say: the ultimate alignment will be the max of ForcedAlignBits
997 // and the alignment computed with NumBits and the global.
1001 // if (GV && GV->hasalignment) Align = GV->getalignment();
1002 // Align = std::max(Align, ForcedAlignBits);
1004 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
1005 unsigned ForcedAlignBits,
1006 bool UseFillExpr) const {
1007 if (GV && GV->getAlignment())
1008 NumBits = Log2_32(GV->getAlignment());
1009 NumBits = std::max(NumBits, ForcedAlignBits);
1011 if (NumBits == 0) return; // No need to emit alignment.
1013 if (getCurrentSection()->getKind().isText())
1014 OutStreamer.EmitCodeAlignment(1 << NumBits);
1016 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1019 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1021 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1022 MCContext &Ctx = AP.OutContext;
1024 if (CV->isNullValue() || isa<UndefValue>(CV))
1025 return MCConstantExpr::Create(0, Ctx);
1027 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1028 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1030 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1031 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1032 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1033 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1035 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1037 llvm_unreachable("Unknown constant value to lower!");
1038 return MCConstantExpr::Create(0, Ctx);
1041 switch (CE->getOpcode()) {
1043 // If the code isn't optimized, there may be outstanding folding
1044 // opportunities. Attempt to fold the expression using TargetData as a
1045 // last resort before giving up.
1047 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1049 return LowerConstant(C, AP);
1053 llvm_unreachable("FIXME: Don't support this constant expr");
1054 case Instruction::GetElementPtr: {
1055 const TargetData &TD = *AP.TM.getTargetData();
1056 // Generate a symbolic expression for the byte address
1057 const Constant *PtrVal = CE->getOperand(0);
1058 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1059 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1062 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1066 // Truncate/sext the offset to the pointer size.
1067 if (TD.getPointerSizeInBits() != 64) {
1068 int SExtAmount = 64-TD.getPointerSizeInBits();
1069 Offset = (Offset << SExtAmount) >> SExtAmount;
1072 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1076 case Instruction::Trunc:
1077 // We emit the value and depend on the assembler to truncate the generated
1078 // expression properly. This is important for differences between
1079 // blockaddress labels. Since the two labels are in the same function, it
1080 // is reasonable to treat their delta as a 32-bit value.
1082 case Instruction::BitCast:
1083 return LowerConstant(CE->getOperand(0), AP);
1085 case Instruction::IntToPtr: {
1086 const TargetData &TD = *AP.TM.getTargetData();
1087 // Handle casts to pointers by changing them into casts to the appropriate
1088 // integer type. This promotes constant folding and simplifies this code.
1089 Constant *Op = CE->getOperand(0);
1090 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1092 return LowerConstant(Op, AP);
1095 case Instruction::PtrToInt: {
1096 const TargetData &TD = *AP.TM.getTargetData();
1097 // Support only foldable casts to/from pointers that can be eliminated by
1098 // changing the pointer to the appropriately sized integer type.
1099 Constant *Op = CE->getOperand(0);
1100 const Type *Ty = CE->getType();
1102 const MCExpr *OpExpr = LowerConstant(Op, AP);
1104 // We can emit the pointer value into this slot if the slot is an
1105 // integer slot equal to the size of the pointer.
1106 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1109 // Otherwise the pointer is smaller than the resultant integer, mask off
1110 // the high bits so we are sure to get a proper truncation if the input is
1112 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1113 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1114 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1117 // The MC library also has a right-shift operator, but it isn't consistently
1118 // signed or unsigned between different targets.
1119 case Instruction::Add:
1120 case Instruction::Sub:
1121 case Instruction::Mul:
1122 case Instruction::SDiv:
1123 case Instruction::SRem:
1124 case Instruction::Shl:
1125 case Instruction::And:
1126 case Instruction::Or:
1127 case Instruction::Xor: {
1128 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1129 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1130 switch (CE->getOpcode()) {
1131 default: llvm_unreachable("Unknown binary operator constant cast expr");
1132 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1133 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1134 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1135 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1136 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1137 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1138 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1139 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1140 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1146 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1148 if (AddrSpace != 0 || !CA->isString()) {
1149 // Not a string. Print the values in successive locations
1150 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1151 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
1155 // Otherwise, it can be emitted as .ascii.
1156 SmallVector<char, 128> TmpVec;
1157 TmpVec.reserve(CA->getNumOperands());
1158 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1159 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1161 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1164 static void EmitGlobalConstantVector(const ConstantVector *CV,
1165 unsigned AddrSpace, AsmPrinter &AP) {
1166 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1167 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
1170 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1171 unsigned AddrSpace, AsmPrinter &AP) {
1172 // Print the fields in successive locations. Pad to align if needed!
1173 const TargetData *TD = AP.TM.getTargetData();
1174 unsigned Size = TD->getTypeAllocSize(CS->getType());
1175 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1176 uint64_t SizeSoFar = 0;
1177 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1178 const Constant *Field = CS->getOperand(i);
1180 // Check if padding is needed and insert one or more 0s.
1181 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1182 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1183 - Layout->getElementOffset(i)) - FieldSize;
1184 SizeSoFar += FieldSize + PadSize;
1186 // Now print the actual field value.
1187 AP.EmitGlobalConstant(Field, AddrSpace);
1189 // Insert padding - this may include padding to increase the size of the
1190 // current field up to the ABI size (if the struct is not packed) as well
1191 // as padding to ensure that the next field starts at the right offset.
1192 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1194 assert(SizeSoFar == Layout->getSizeInBytes() &&
1195 "Layout of constant struct may be incorrect!");
1198 static void EmitGlobalConstantUnion(const ConstantUnion *CU,
1199 unsigned AddrSpace, AsmPrinter &AP) {
1200 const TargetData *TD = AP.TM.getTargetData();
1201 unsigned Size = TD->getTypeAllocSize(CU->getType());
1203 const Constant *Contents = CU->getOperand(0);
1204 unsigned FilledSize = TD->getTypeAllocSize(Contents->getType());
1206 // Print the actually filled part
1207 AP.EmitGlobalConstant(Contents, AddrSpace);
1209 // And pad with enough zeroes
1210 AP.OutStreamer.EmitZeros(Size-FilledSize, AddrSpace);
1213 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1215 // FP Constants are printed as integer constants to avoid losing
1217 if (CFP->getType()->isDoubleTy()) {
1218 if (AP.isVerbose()) {
1219 double Val = CFP->getValueAPF().convertToDouble();
1220 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1223 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1224 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1228 if (CFP->getType()->isFloatTy()) {
1229 if (AP.isVerbose()) {
1230 float Val = CFP->getValueAPF().convertToFloat();
1231 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1233 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1234 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1238 if (CFP->getType()->isX86_FP80Ty()) {
1239 // all long double variants are printed as hex
1240 // api needed to prevent premature destruction
1241 APInt API = CFP->getValueAPF().bitcastToAPInt();
1242 const uint64_t *p = API.getRawData();
1243 if (AP.isVerbose()) {
1244 // Convert to double so we can print the approximate val as a comment.
1245 APFloat DoubleVal = CFP->getValueAPF();
1247 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1249 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1250 << DoubleVal.convertToDouble() << '\n';
1253 if (AP.TM.getTargetData()->isBigEndian()) {
1254 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1255 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1257 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1258 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1261 // Emit the tail padding for the long double.
1262 const TargetData &TD = *AP.TM.getTargetData();
1263 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1264 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1268 assert(CFP->getType()->isPPC_FP128Ty() &&
1269 "Floating point constant type not handled");
1270 // All long double variants are printed as hex api needed to prevent
1271 // premature destruction.
1272 APInt API = CFP->getValueAPF().bitcastToAPInt();
1273 const uint64_t *p = API.getRawData();
1274 if (AP.TM.getTargetData()->isBigEndian()) {
1275 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1276 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1278 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1279 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1283 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1284 unsigned AddrSpace, AsmPrinter &AP) {
1285 const TargetData *TD = AP.TM.getTargetData();
1286 unsigned BitWidth = CI->getBitWidth();
1287 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1289 // We don't expect assemblers to support integer data directives
1290 // for more than 64 bits, so we emit the data in at most 64-bit
1291 // quantities at a time.
1292 const uint64_t *RawData = CI->getValue().getRawData();
1293 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1294 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1295 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1299 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1300 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1301 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1302 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1303 if (Size == 0) Size = 1; // An empty "_foo:" followed by a section is undef.
1304 return OutStreamer.EmitZeros(Size, AddrSpace);
1307 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1308 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1315 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1316 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1319 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1324 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1325 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1327 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1328 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1330 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1331 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1333 if (isa<ConstantPointerNull>(CV)) {
1334 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1335 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1339 if (const ConstantUnion *CVU = dyn_cast<ConstantUnion>(CV))
1340 return EmitGlobalConstantUnion(CVU, AddrSpace, *this);
1342 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1343 return EmitGlobalConstantVector(V, AddrSpace, *this);
1345 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1346 // thread the streamer with EmitValue.
1347 OutStreamer.EmitValue(LowerConstant(CV, *this),
1348 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1352 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1353 // Target doesn't support this yet!
1354 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1357 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1359 OS << '+' << Offset;
1360 else if (Offset < 0)
1364 //===----------------------------------------------------------------------===//
1365 // Symbol Lowering Routines.
1366 //===----------------------------------------------------------------------===//
1368 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1369 /// temporary label with the specified stem and unique ID.
1370 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1371 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1375 /// GetTempSymbol - Return an assembler temporary label with the specified
1377 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1378 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1383 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1384 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1387 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1388 return MMI->getAddrLabelSymbol(BB);
1391 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1392 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1393 return OutContext.GetOrCreateSymbol
1394 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1395 + "_" + Twine(CPID));
1398 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1399 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1400 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1403 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1404 /// FIXME: privatize to AsmPrinter.
1405 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1406 return OutContext.GetOrCreateSymbol
1407 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1408 Twine(UID) + "_set_" + Twine(MBBID));
1411 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1412 /// global value name as its base, with the specified suffix, and where the
1413 /// symbol is forced to have private linkage if ForcePrivate is true.
1414 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1416 bool ForcePrivate) const {
1417 SmallString<60> NameStr;
1418 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1419 NameStr.append(Suffix.begin(), Suffix.end());
1420 return OutContext.GetOrCreateSymbol(NameStr.str());
1423 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1425 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1426 SmallString<60> NameStr;
1427 Mang->getNameWithPrefix(NameStr, Sym);
1428 return OutContext.GetOrCreateSymbol(NameStr.str());
1433 /// PrintParentLoopComment - Print comments about parent loops of this one.
1434 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1435 unsigned FunctionNumber) {
1436 if (Loop == 0) return;
1437 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1438 OS.indent(Loop->getLoopDepth()*2)
1439 << "Parent Loop BB" << FunctionNumber << "_"
1440 << Loop->getHeader()->getNumber()
1441 << " Depth=" << Loop->getLoopDepth() << '\n';
1445 /// PrintChildLoopComment - Print comments about child loops within
1446 /// the loop for this basic block, with nesting.
1447 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1448 unsigned FunctionNumber) {
1449 // Add child loop information
1450 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1451 OS.indent((*CL)->getLoopDepth()*2)
1452 << "Child Loop BB" << FunctionNumber << "_"
1453 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1455 PrintChildLoopComment(OS, *CL, FunctionNumber);
1459 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1460 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1461 const MachineLoopInfo *LI,
1462 const AsmPrinter &AP) {
1463 // Add loop depth information
1464 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1465 if (Loop == 0) return;
1467 MachineBasicBlock *Header = Loop->getHeader();
1468 assert(Header && "No header for loop");
1470 // If this block is not a loop header, just print out what is the loop header
1472 if (Header != &MBB) {
1473 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1474 Twine(AP.getFunctionNumber())+"_" +
1475 Twine(Loop->getHeader()->getNumber())+
1476 " Depth="+Twine(Loop->getLoopDepth()));
1480 // Otherwise, it is a loop header. Print out information about child and
1482 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1484 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1487 OS.indent(Loop->getLoopDepth()*2-2);
1492 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1494 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1498 /// EmitBasicBlockStart - This method prints the label for the specified
1499 /// MachineBasicBlock, an alignment (if present) and a comment describing
1500 /// it if appropriate.
1501 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1502 // Emit an alignment directive for this block, if needed.
1503 if (unsigned Align = MBB->getAlignment())
1504 EmitAlignment(Log2_32(Align));
1506 // If the block has its address taken, emit any labels that were used to
1507 // reference the block. It is possible that there is more than one label
1508 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1509 // the references were generated.
1510 if (MBB->hasAddressTaken()) {
1511 const BasicBlock *BB = MBB->getBasicBlock();
1513 OutStreamer.AddComment("Block address taken");
1515 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1517 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1518 OutStreamer.EmitLabel(Syms[i]);
1521 // Print the main label for the block.
1522 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1523 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1524 if (const BasicBlock *BB = MBB->getBasicBlock())
1526 OutStreamer.AddComment("%" + BB->getName());
1528 EmitBasicBlockLoopComments(*MBB, LI, *this);
1530 // NOTE: Want this comment at start of line, don't emit with AddComment.
1531 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1532 Twine(MBB->getNumber()) + ":");
1536 if (const BasicBlock *BB = MBB->getBasicBlock())
1538 OutStreamer.AddComment("%" + BB->getName());
1539 EmitBasicBlockLoopComments(*MBB, LI, *this);
1542 OutStreamer.EmitLabel(MBB->getSymbol());
1546 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1547 MCSymbolAttr Attr = MCSA_Invalid;
1549 switch (Visibility) {
1551 case GlobalValue::HiddenVisibility:
1552 Attr = MAI->getHiddenVisibilityAttr();
1554 case GlobalValue::ProtectedVisibility:
1555 Attr = MAI->getProtectedVisibilityAttr();
1559 if (Attr != MCSA_Invalid)
1560 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1563 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1564 /// exactly one predecessor and the control transfer mechanism between
1565 /// the predecessor and this block is a fall-through.
1567 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1568 // If this is a landing pad, it isn't a fall through. If it has no preds,
1569 // then nothing falls through to it.
1570 if (MBB->isLandingPad() || MBB->pred_empty())
1573 // If there isn't exactly one predecessor, it can't be a fall through.
1574 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1576 if (PI2 != MBB->pred_end())
1579 // The predecessor has to be immediately before this block.
1580 const MachineBasicBlock *Pred = *PI;
1582 if (!Pred->isLayoutSuccessor(MBB))
1585 // If the block is completely empty, then it definitely does fall through.
1589 // Otherwise, check the last instruction.
1590 const MachineInstr &LastInst = Pred->back();
1591 return !LastInst.getDesc().isBarrier();
1596 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1597 if (!S->usesMetadata())
1600 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1601 gcp_map_type::iterator GCPI = GCMap.find(S);
1602 if (GCPI != GCMap.end())
1603 return GCPI->second;
1605 const char *Name = S->getName().c_str();
1607 for (GCMetadataPrinterRegistry::iterator
1608 I = GCMetadataPrinterRegistry::begin(),
1609 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1610 if (strcmp(Name, I->getName()) == 0) {
1611 GCMetadataPrinter *GMP = I->instantiate();
1613 GCMap.insert(std::make_pair(S, GMP));
1617 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));