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/DebugInfo.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/ConstantFolding.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/DataLayout.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/Assembly/Writer.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/Timer.h"
51 static const char *DWARFGroupName = "DWARF Emission";
52 static const char *DbgTimerName = "DWARF Debug Writer";
53 static const char *EHTimerName = "DWARF Exception Writer";
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
57 char AsmPrinter::ID = 0;
59 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
60 static gcp_map_type &getGCMap(void *&P) {
62 P = new gcp_map_type();
63 return *(gcp_map_type*)P;
67 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
68 /// value in log2 form. This rounds up to the preferred alignment if possible
70 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
71 unsigned InBits = 0) {
73 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
74 NumBits = TD.getPreferredAlignmentLog(GVar);
76 // If InBits is specified, round it to it.
80 // If the GV has a specified alignment, take it into account.
81 if (GV->getAlignment() == 0)
84 unsigned GVAlign = Log2_32(GV->getAlignment());
86 // If the GVAlign is larger than NumBits, or if we are required to obey
87 // NumBits because the GV has an assigned section, obey it.
88 if (GVAlign > NumBits || GV->hasSection())
93 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
94 : MachineFunctionPass(ID),
95 TM(tm), MAI(tm.getMCAsmInfo()),
96 OutContext(Streamer.getContext()),
97 OutStreamer(Streamer),
98 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
99 DD = 0; DE = 0; MMI = 0; LI = 0;
100 CurrentFnSym = CurrentFnSymForSize = 0;
101 GCMetadataPrinters = 0;
102 VerboseAsm = Streamer.isVerboseAsm();
105 AsmPrinter::~AsmPrinter() {
106 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
108 if (GCMetadataPrinters != 0) {
109 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
111 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
114 GCMetadataPrinters = 0;
120 /// getFunctionNumber - Return a unique ID for the current function.
122 unsigned AsmPrinter::getFunctionNumber() const {
123 return MF->getFunctionNumber();
126 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
127 return TM.getTargetLowering()->getObjFileLowering();
130 /// getDataLayout - Return information about data layout.
131 const DataLayout &AsmPrinter::getDataLayout() const {
132 return *TM.getDataLayout();
135 /// getCurrentSection() - Return the current section we are emitting to.
136 const MCSection *AsmPrinter::getCurrentSection() const {
137 return OutStreamer.getCurrentSection();
142 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
143 AU.setPreservesAll();
144 MachineFunctionPass::getAnalysisUsage(AU);
145 AU.addRequired<MachineModuleInfo>();
146 AU.addRequired<GCModuleInfo>();
148 AU.addRequired<MachineLoopInfo>();
151 bool AsmPrinter::doInitialization(Module &M) {
152 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
153 MMI->AnalyzeModule(M);
155 // Initialize TargetLoweringObjectFile.
156 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
157 .Initialize(OutContext, TM);
159 Mang = new Mangler(OutContext, *TM.getDataLayout());
161 // Allow the target to emit any magic that it wants at the start of the file.
162 EmitStartOfAsmFile(M);
164 // Very minimal debug info. It is ignored if we emit actual debug info. If we
165 // don't, this at least helps the user find where a global came from.
166 if (MAI->hasSingleParameterDotFile()) {
168 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
171 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
172 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
173 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
174 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
175 MP->beginAssembly(*this);
177 // Emit module-level inline asm if it exists.
178 if (!M.getModuleInlineAsm().empty()) {
179 OutStreamer.AddComment("Start of file scope inline assembly");
180 OutStreamer.AddBlankLine();
181 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
182 OutStreamer.AddComment("End of file scope inline assembly");
183 OutStreamer.AddBlankLine();
186 if (MAI->doesSupportDebugInformation())
187 DD = new DwarfDebug(this, &M);
189 switch (MAI->getExceptionHandlingType()) {
190 case ExceptionHandling::None:
192 case ExceptionHandling::SjLj:
193 case ExceptionHandling::DwarfCFI:
194 DE = new DwarfCFIException(this);
196 case ExceptionHandling::ARM:
197 DE = new ARMException(this);
199 case ExceptionHandling::Win64:
200 DE = new Win64Exception(this);
204 llvm_unreachable("Unknown exception type.");
207 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
208 switch ((GlobalValue::LinkageTypes)Linkage) {
209 case GlobalValue::CommonLinkage:
210 case GlobalValue::LinkOnceAnyLinkage:
211 case GlobalValue::LinkOnceODRLinkage:
212 case GlobalValue::LinkOnceODRAutoHideLinkage:
213 case GlobalValue::WeakAnyLinkage:
214 case GlobalValue::WeakODRLinkage:
215 case GlobalValue::LinkerPrivateWeakLinkage:
216 if (MAI->getWeakDefDirective() != 0) {
218 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
220 if ((GlobalValue::LinkageTypes)Linkage !=
221 GlobalValue::LinkOnceODRAutoHideLinkage)
222 // .weak_definition _foo
223 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
225 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
226 } else if (MAI->getLinkOnceDirective() != 0) {
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229 //NOTE: linkonce is handled by the section the symbol was assigned to.
232 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
235 case GlobalValue::DLLExportLinkage:
236 case GlobalValue::AppendingLinkage:
237 // FIXME: appending linkage variables should go into a section of
238 // their name or something. For now, just emit them as external.
239 case GlobalValue::ExternalLinkage:
240 // If external or appending, declare as a global symbol.
242 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
244 case GlobalValue::PrivateLinkage:
245 case GlobalValue::InternalLinkage:
246 case GlobalValue::LinkerPrivateLinkage:
249 llvm_unreachable("Unknown linkage type!");
254 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
255 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
256 if (GV->hasInitializer()) {
257 // Check to see if this is a special global used by LLVM, if so, emit it.
258 if (EmitSpecialLLVMGlobal(GV))
262 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
263 /*PrintType=*/false, GV->getParent());
264 OutStreamer.GetCommentOS() << '\n';
268 MCSymbol *GVSym = Mang->getSymbol(GV);
269 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
271 if (!GV->hasInitializer()) // External globals require no extra code.
274 if (MAI->hasDotTypeDotSizeDirective())
275 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
277 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
279 const DataLayout *TD = TM.getDataLayout();
280 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
282 // If the alignment is specified, we *must* obey it. Overaligning a global
283 // with a specified alignment is a prompt way to break globals emitted to
284 // sections and expected to be contiguous (e.g. ObjC metadata).
285 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
287 // Handle common and BSS local symbols (.lcomm).
288 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
289 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
290 unsigned Align = 1 << AlignLog;
292 // Handle common symbols.
293 if (GVKind.isCommon()) {
294 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
298 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
302 // Handle local BSS symbols.
303 if (MAI->hasMachoZeroFillDirective()) {
304 const MCSection *TheSection =
305 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
306 // .zerofill __DATA, __bss, _foo, 400, 5
307 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
312 MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
314 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
318 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
322 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
324 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
328 const MCSection *TheSection =
329 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
331 // Handle the zerofill directive on darwin, which is a special form of BSS
333 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
334 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
337 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
338 // .zerofill __DATA, __common, _foo, 400, 5
339 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
343 // Handle thread local data for mach-o which requires us to output an
344 // additional structure of data and mangle the original symbol so that we
345 // can reference it later.
347 // TODO: This should become an "emit thread local global" method on TLOF.
348 // All of this macho specific stuff should be sunk down into TLOFMachO and
349 // stuff like "TLSExtraDataSection" should no longer be part of the parent
350 // TLOF class. This will also make it more obvious that stuff like
351 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
353 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
354 // Emit the .tbss symbol
356 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
358 if (GVKind.isThreadBSS())
359 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
360 else if (GVKind.isThreadData()) {
361 OutStreamer.SwitchSection(TheSection);
363 EmitAlignment(AlignLog, GV);
364 OutStreamer.EmitLabel(MangSym);
366 EmitGlobalConstant(GV->getInitializer());
369 OutStreamer.AddBlankLine();
371 // Emit the variable struct for the runtime.
372 const MCSection *TLVSect
373 = getObjFileLowering().getTLSExtraDataSection();
375 OutStreamer.SwitchSection(TLVSect);
376 // Emit the linkage here.
377 EmitLinkage(GV->getLinkage(), GVSym);
378 OutStreamer.EmitLabel(GVSym);
380 // Three pointers in size:
381 // - __tlv_bootstrap - used to make sure support exists
382 // - spare pointer, used when mapped by the runtime
383 // - pointer to mangled symbol above with initializer
384 unsigned PtrSize = TD->getPointerSizeInBits()/8;
385 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
387 OutStreamer.EmitIntValue(0, PtrSize, 0);
388 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
390 OutStreamer.AddBlankLine();
394 OutStreamer.SwitchSection(TheSection);
396 EmitLinkage(GV->getLinkage(), GVSym);
397 EmitAlignment(AlignLog, GV);
399 OutStreamer.EmitLabel(GVSym);
401 EmitGlobalConstant(GV->getInitializer());
403 if (MAI->hasDotTypeDotSizeDirective())
405 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
407 OutStreamer.AddBlankLine();
410 /// EmitFunctionHeader - This method emits the header for the current
412 void AsmPrinter::EmitFunctionHeader() {
413 // Print out constants referenced by the function
416 // Print the 'header' of function.
417 const Function *F = MF->getFunction();
419 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
420 EmitVisibility(CurrentFnSym, F->getVisibility());
422 EmitLinkage(F->getLinkage(), CurrentFnSym);
423 EmitAlignment(MF->getAlignment(), F);
425 if (MAI->hasDotTypeDotSizeDirective())
426 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
429 WriteAsOperand(OutStreamer.GetCommentOS(), F,
430 /*PrintType=*/false, F->getParent());
431 OutStreamer.GetCommentOS() << '\n';
434 // Emit the CurrentFnSym. This is a virtual function to allow targets to
435 // do their wild and crazy things as required.
436 EmitFunctionEntryLabel();
438 // If the function had address-taken blocks that got deleted, then we have
439 // references to the dangling symbols. Emit them at the start of the function
440 // so that we don't get references to undefined symbols.
441 std::vector<MCSymbol*> DeadBlockSyms;
442 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
443 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
444 OutStreamer.AddComment("Address taken block that was later removed");
445 OutStreamer.EmitLabel(DeadBlockSyms[i]);
448 // Add some workaround for linkonce linkage on Cygwin\MinGW.
449 if (MAI->getLinkOnceDirective() != 0 &&
450 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
451 // FIXME: What is this?
453 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
454 CurrentFnSym->getName());
455 OutStreamer.EmitLabel(FakeStub);
458 // Emit pre-function debug and/or EH information.
460 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
461 DE->BeginFunction(MF);
464 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
465 DD->beginFunction(MF);
469 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
470 /// function. This can be overridden by targets as required to do custom stuff.
471 void AsmPrinter::EmitFunctionEntryLabel() {
472 // The function label could have already been emitted if two symbols end up
473 // conflicting due to asm renaming. Detect this and emit an error.
474 if (CurrentFnSym->isUndefined())
475 return OutStreamer.EmitLabel(CurrentFnSym);
477 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
478 "' label emitted multiple times to assembly file");
481 /// emitComments - Pretty-print comments for instructions.
482 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
483 const MachineFunction *MF = MI.getParent()->getParent();
484 const TargetMachine &TM = MF->getTarget();
486 // Check for spills and reloads
489 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
491 // We assume a single instruction only has a spill or reload, not
493 const MachineMemOperand *MMO;
494 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
495 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
496 MMO = *MI.memoperands_begin();
497 CommentOS << MMO->getSize() << "-byte Reload\n";
499 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
500 if (FrameInfo->isSpillSlotObjectIndex(FI))
501 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
502 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
503 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
504 MMO = *MI.memoperands_begin();
505 CommentOS << MMO->getSize() << "-byte Spill\n";
507 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
508 if (FrameInfo->isSpillSlotObjectIndex(FI))
509 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
512 // Check for spill-induced copies
513 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
514 CommentOS << " Reload Reuse\n";
517 /// emitImplicitDef - This method emits the specified machine instruction
518 /// that is an implicit def.
519 static void emitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
520 unsigned RegNo = MI->getOperand(0).getReg();
521 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
522 AP.TM.getRegisterInfo()->getName(RegNo));
523 AP.OutStreamer.AddBlankLine();
526 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
527 std::string Str = "kill:";
528 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
529 const MachineOperand &Op = MI->getOperand(i);
530 assert(Op.isReg() && "KILL instruction must have only register operands");
532 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
533 Str += (Op.isDef() ? "<def>" : "<kill>");
535 AP.OutStreamer.AddComment(Str);
536 AP.OutStreamer.AddBlankLine();
539 /// emitDebugValueComment - This method handles the target-independent form
540 /// of DBG_VALUE, returning true if it was able to do so. A false return
541 /// means the target will need to handle MI in EmitInstruction.
542 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
543 // This code handles only the 3-operand target-independent form.
544 if (MI->getNumOperands() != 3)
547 SmallString<128> Str;
548 raw_svector_ostream OS(Str);
549 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
551 // cast away const; DIetc do not take const operands for some reason.
552 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
553 if (V.getContext().isSubprogram())
554 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
555 OS << V.getName() << " <- ";
557 // Register or immediate value. Register 0 means undef.
558 if (MI->getOperand(0).isFPImm()) {
559 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
560 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
561 OS << (double)APF.convertToFloat();
562 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
563 OS << APF.convertToDouble();
565 // There is no good way to print long double. Convert a copy to
566 // double. Ah well, it's only a comment.
568 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
570 OS << "(long double) " << APF.convertToDouble();
572 } else if (MI->getOperand(0).isImm()) {
573 OS << MI->getOperand(0).getImm();
574 } else if (MI->getOperand(0).isCImm()) {
575 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
577 assert(MI->getOperand(0).isReg() && "Unknown operand type");
578 if (MI->getOperand(0).getReg() == 0) {
579 // Suppress offset, it is not meaningful here.
581 // NOTE: Want this comment at start of line, don't emit with AddComment.
582 AP.OutStreamer.EmitRawText(OS.str());
585 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
588 OS << '+' << MI->getOperand(1).getImm();
589 // NOTE: Want this comment at start of line, don't emit with AddComment.
590 AP.OutStreamer.EmitRawText(OS.str());
594 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
595 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
596 MF->getFunction()->needsUnwindTableEntry())
599 if (MMI->hasDebugInfo())
605 bool AsmPrinter::needsSEHMoves() {
606 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
607 MF->getFunction()->needsUnwindTableEntry();
610 bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
611 return MAI->doesDwarfUseRelocationsAcrossSections();
614 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
615 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
617 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
620 if (needsCFIMoves() == CFI_M_None)
623 if (MMI->getCompactUnwindEncoding() != 0)
624 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
626 MachineModuleInfo &MMI = MF->getMMI();
627 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
628 bool FoundOne = false;
630 for (std::vector<MachineMove>::iterator I = Moves.begin(),
631 E = Moves.end(); I != E; ++I) {
632 if (I->getLabel() == Label) {
633 EmitCFIFrameMove(*I);
640 /// EmitFunctionBody - This method emits the body and trailer for a
642 void AsmPrinter::EmitFunctionBody() {
643 // Emit target-specific gunk before the function body.
644 EmitFunctionBodyStart();
646 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
648 // Print out code for the function.
649 bool HasAnyRealCode = false;
650 const MachineInstr *LastMI = 0;
651 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
653 // Print a label for the basic block.
654 EmitBasicBlockStart(I);
655 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
659 // Print the assembly for the instruction.
660 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
661 !II->isDebugValue()) {
662 HasAnyRealCode = true;
666 if (ShouldPrintDebugScopes) {
667 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
668 DD->beginInstruction(II);
672 emitComments(*II, OutStreamer.GetCommentOS());
674 switch (II->getOpcode()) {
675 case TargetOpcode::PROLOG_LABEL:
676 emitPrologLabel(*II);
679 case TargetOpcode::EH_LABEL:
680 case TargetOpcode::GC_LABEL:
681 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
683 case TargetOpcode::INLINEASM:
686 case TargetOpcode::DBG_VALUE:
688 if (!emitDebugValueComment(II, *this))
692 case TargetOpcode::IMPLICIT_DEF:
693 if (isVerbose()) emitImplicitDef(II, *this);
695 case TargetOpcode::KILL:
696 if (isVerbose()) emitKill(II, *this);
699 if (!TM.hasMCUseLoc())
700 MCLineEntry::Make(&OutStreamer, getCurrentSection());
706 if (ShouldPrintDebugScopes) {
707 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
708 DD->endInstruction(II);
713 // If the last instruction was a prolog label, then we have a situation where
714 // we emitted a prolog but no function body. This results in the ending prolog
715 // label equaling the end of function label and an invalid "row" in the
716 // FDE. We need to emit a noop in this situation so that the FDE's rows are
718 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
720 // If the function is empty and the object file uses .subsections_via_symbols,
721 // then we need to emit *something* to the function body to prevent the
722 // labels from collapsing together. Just emit a noop.
723 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
725 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
726 if (Noop.getOpcode()) {
727 OutStreamer.AddComment("avoids zero-length function");
728 OutStreamer.EmitInstruction(Noop);
729 } else // Target not mc-ized yet.
730 OutStreamer.EmitRawText(StringRef("\tnop\n"));
733 const Function *F = MF->getFunction();
734 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
735 const BasicBlock *BB = i;
736 if (!BB->hasAddressTaken())
738 MCSymbol *Sym = GetBlockAddressSymbol(BB);
739 if (Sym->isDefined())
741 OutStreamer.AddComment("Address of block that was removed by CodeGen");
742 OutStreamer.EmitLabel(Sym);
745 // Emit target-specific gunk after the function body.
746 EmitFunctionBodyEnd();
748 // If the target wants a .size directive for the size of the function, emit
750 if (MAI->hasDotTypeDotSizeDirective()) {
751 // Create a symbol for the end of function, so we can get the size as
752 // difference between the function label and the temp label.
753 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
754 OutStreamer.EmitLabel(FnEndLabel);
756 const MCExpr *SizeExp =
757 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
758 MCSymbolRefExpr::Create(CurrentFnSymForSize,
761 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
764 // Emit post-function debug information.
766 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
770 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
775 // Print out jump tables referenced by the function.
778 OutStreamer.AddBlankLine();
781 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
783 MachineLocation AsmPrinter::
784 getDebugValueLocation(const MachineInstr *MI) const {
785 // Target specific DBG_VALUE instructions are handled by each target.
786 return MachineLocation();
789 /// EmitDwarfRegOp - Emit dwarf register operation.
790 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
791 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
792 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
794 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
796 Reg = TRI->getDwarfRegNum(*SR, false);
797 // FIXME: Get the bit range this register uses of the superregister
798 // so that we can produce a DW_OP_bit_piece
801 // FIXME: Handle cases like a super register being encoded as
802 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
804 // FIXME: We have no reasonable way of handling errors in here. The
805 // caller might be in the middle of an dwarf expression. We should
806 // probably assert that Reg >= 0 once debug info generation is more mature.
808 if (int Offset = MLoc.getOffset()) {
810 OutStreamer.AddComment(
811 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
812 EmitInt8(dwarf::DW_OP_breg0 + Reg);
814 OutStreamer.AddComment("DW_OP_bregx");
815 EmitInt8(dwarf::DW_OP_bregx);
816 OutStreamer.AddComment(Twine(Reg));
822 OutStreamer.AddComment(
823 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
824 EmitInt8(dwarf::DW_OP_reg0 + Reg);
826 OutStreamer.AddComment("DW_OP_regx");
827 EmitInt8(dwarf::DW_OP_regx);
828 OutStreamer.AddComment(Twine(Reg));
833 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
836 bool AsmPrinter::doFinalization(Module &M) {
837 // Emit global variables.
838 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
840 EmitGlobalVariable(I);
842 // Emit visibility info for declarations
843 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
844 const Function &F = *I;
845 if (!F.isDeclaration())
847 GlobalValue::VisibilityTypes V = F.getVisibility();
848 if (V == GlobalValue::DefaultVisibility)
851 MCSymbol *Name = Mang->getSymbol(&F);
852 EmitVisibility(Name, V, false);
855 // Emit module flags.
856 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
857 M.getModuleFlagsMetadata(ModuleFlags);
858 if (!ModuleFlags.empty())
859 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
861 // Finalize debug and EH information.
864 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
871 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
877 // If the target wants to know about weak references, print them all.
878 if (MAI->getWeakRefDirective()) {
879 // FIXME: This is not lazy, it would be nice to only print weak references
880 // to stuff that is actually used. Note that doing so would require targets
881 // to notice uses in operands (due to constant exprs etc). This should
882 // happen with the MC stuff eventually.
884 // Print out module-level global variables here.
885 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
887 if (!I->hasExternalWeakLinkage()) continue;
888 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
891 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
892 if (!I->hasExternalWeakLinkage()) continue;
893 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
897 if (MAI->hasSetDirective()) {
898 OutStreamer.AddBlankLine();
899 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
901 MCSymbol *Name = Mang->getSymbol(I);
903 const GlobalValue *GV = I->getAliasedGlobal();
904 MCSymbol *Target = Mang->getSymbol(GV);
906 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
907 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
908 else if (I->hasWeakLinkage())
909 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
911 assert(I->hasLocalLinkage() && "Invalid alias linkage");
913 EmitVisibility(Name, I->getVisibility());
915 // Emit the directives as assignments aka .set:
916 OutStreamer.EmitAssignment(Name,
917 MCSymbolRefExpr::Create(Target, OutContext));
921 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
922 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
923 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
924 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
925 MP->finishAssembly(*this);
927 // If we don't have any trampolines, then we don't require stack memory
928 // to be executable. Some targets have a directive to declare this.
929 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
930 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
931 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
932 OutStreamer.SwitchSection(S);
934 // Allow the target to emit any magic that it wants at the end of the file,
935 // after everything else has gone out.
938 delete Mang; Mang = 0;
941 OutStreamer.Finish();
945 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
947 // Get the function symbol.
948 CurrentFnSym = Mang->getSymbol(MF.getFunction());
949 CurrentFnSymForSize = CurrentFnSym;
952 LI = &getAnalysis<MachineLoopInfo>();
956 // SectionCPs - Keep track the alignment, constpool entries per Section.
960 SmallVector<unsigned, 4> CPEs;
961 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
965 /// EmitConstantPool - Print to the current output stream assembly
966 /// representations of the constants in the constant pool MCP. This is
967 /// used to print out constants which have been "spilled to memory" by
968 /// the code generator.
970 void AsmPrinter::EmitConstantPool() {
971 const MachineConstantPool *MCP = MF->getConstantPool();
972 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
973 if (CP.empty()) return;
975 // Calculate sections for constant pool entries. We collect entries to go into
976 // the same section together to reduce amount of section switch statements.
977 SmallVector<SectionCPs, 4> CPSections;
978 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
979 const MachineConstantPoolEntry &CPE = CP[i];
980 unsigned Align = CPE.getAlignment();
983 switch (CPE.getRelocationInfo()) {
984 default: llvm_unreachable("Unknown section kind");
985 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
987 Kind = SectionKind::getReadOnlyWithRelLocal();
990 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
991 case 4: Kind = SectionKind::getMergeableConst4(); break;
992 case 8: Kind = SectionKind::getMergeableConst8(); break;
993 case 16: Kind = SectionKind::getMergeableConst16();break;
994 default: Kind = SectionKind::getMergeableConst(); break;
998 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1000 // The number of sections are small, just do a linear search from the
1001 // last section to the first.
1003 unsigned SecIdx = CPSections.size();
1004 while (SecIdx != 0) {
1005 if (CPSections[--SecIdx].S == S) {
1011 SecIdx = CPSections.size();
1012 CPSections.push_back(SectionCPs(S, Align));
1015 if (Align > CPSections[SecIdx].Alignment)
1016 CPSections[SecIdx].Alignment = Align;
1017 CPSections[SecIdx].CPEs.push_back(i);
1020 // Now print stuff into the calculated sections.
1021 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1022 OutStreamer.SwitchSection(CPSections[i].S);
1023 EmitAlignment(Log2_32(CPSections[i].Alignment));
1025 unsigned Offset = 0;
1026 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1027 unsigned CPI = CPSections[i].CPEs[j];
1028 MachineConstantPoolEntry CPE = CP[CPI];
1030 // Emit inter-object padding for alignment.
1031 unsigned AlignMask = CPE.getAlignment() - 1;
1032 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1033 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1035 Type *Ty = CPE.getType();
1036 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1037 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1039 if (CPE.isMachineConstantPoolEntry())
1040 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1042 EmitGlobalConstant(CPE.Val.ConstVal);
1047 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1048 /// by the current function to the current output stream.
1050 void AsmPrinter::EmitJumpTableInfo() {
1051 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1052 if (MJTI == 0) return;
1053 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1054 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1055 if (JT.empty()) return;
1057 // Pick the directive to use to print the jump table entries, and switch to
1058 // the appropriate section.
1059 const Function *F = MF->getFunction();
1060 bool JTInDiffSection = false;
1061 if (// In PIC mode, we need to emit the jump table to the same section as the
1062 // function body itself, otherwise the label differences won't make sense.
1063 // FIXME: Need a better predicate for this: what about custom entries?
1064 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1065 // We should also do if the section name is NULL or function is declared
1066 // in discardable section
1067 // FIXME: this isn't the right predicate, should be based on the MCSection
1068 // for the function.
1069 F->isWeakForLinker()) {
1070 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1072 // Otherwise, drop it in the readonly section.
1073 const MCSection *ReadOnlySection =
1074 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1075 OutStreamer.SwitchSection(ReadOnlySection);
1076 JTInDiffSection = true;
1079 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1081 // Jump tables in code sections are marked with a data_region directive
1082 // where that's supported.
1083 if (!JTInDiffSection)
1084 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1086 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1087 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1089 // If this jump table was deleted, ignore it.
1090 if (JTBBs.empty()) continue;
1092 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1093 // .set directive for each unique entry. This reduces the number of
1094 // relocations the assembler will generate for the jump table.
1095 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1096 MAI->hasSetDirective()) {
1097 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1098 const TargetLowering *TLI = TM.getTargetLowering();
1099 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1100 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1101 const MachineBasicBlock *MBB = JTBBs[ii];
1102 if (!EmittedSets.insert(MBB)) continue;
1104 // .set LJTSet, LBB32-base
1106 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1107 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1108 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1112 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1113 // before each jump table. The first label is never referenced, but tells
1114 // the assembler and linker the extents of the jump table object. The
1115 // second label is actually referenced by the code.
1116 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1117 // FIXME: This doesn't have to have any specific name, just any randomly
1118 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1119 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1121 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1123 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1124 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1126 if (!JTInDiffSection)
1127 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1130 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1132 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1133 const MachineBasicBlock *MBB,
1134 unsigned UID) const {
1135 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1136 const MCExpr *Value = 0;
1137 switch (MJTI->getEntryKind()) {
1138 case MachineJumpTableInfo::EK_Inline:
1139 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1140 case MachineJumpTableInfo::EK_Custom32:
1141 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1144 case MachineJumpTableInfo::EK_BlockAddress:
1145 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1147 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1149 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1150 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1151 // with a relocation as gp-relative, e.g.:
1153 MCSymbol *MBBSym = MBB->getSymbol();
1154 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1158 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1159 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1160 // with a relocation as gp-relative, e.g.:
1162 MCSymbol *MBBSym = MBB->getSymbol();
1163 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1167 case MachineJumpTableInfo::EK_LabelDifference32: {
1168 // EK_LabelDifference32 - Each entry is the address of the block minus
1169 // the address of the jump table. This is used for PIC jump tables where
1170 // gprel32 is not supported. e.g.:
1171 // .word LBB123 - LJTI1_2
1172 // If the .set directive is supported, this is emitted as:
1173 // .set L4_5_set_123, LBB123 - LJTI1_2
1174 // .word L4_5_set_123
1176 // If we have emitted set directives for the jump table entries, print
1177 // them rather than the entries themselves. If we're emitting PIC, then
1178 // emit the table entries as differences between two text section labels.
1179 if (MAI->hasSetDirective()) {
1180 // If we used .set, reference the .set's symbol.
1181 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1185 // Otherwise, use the difference as the jump table entry.
1186 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1187 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1188 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1193 assert(Value && "Unknown entry kind!");
1195 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1196 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1200 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1201 /// special global used by LLVM. If so, emit it and return true, otherwise
1202 /// do nothing and return false.
1203 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1204 if (GV->getName() == "llvm.used") {
1205 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1206 EmitLLVMUsedList(GV->getInitializer());
1210 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1211 if (GV->getSection() == "llvm.metadata" ||
1212 GV->hasAvailableExternallyLinkage())
1215 if (!GV->hasAppendingLinkage()) return false;
1217 assert(GV->hasInitializer() && "Not a special LLVM global!");
1219 if (GV->getName() == "llvm.global_ctors") {
1220 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1222 if (TM.getRelocationModel() == Reloc::Static &&
1223 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1224 StringRef Sym(".constructors_used");
1225 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1231 if (GV->getName() == "llvm.global_dtors") {
1232 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1234 if (TM.getRelocationModel() == Reloc::Static &&
1235 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1236 StringRef Sym(".destructors_used");
1237 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1246 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1247 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1248 /// is true, as being used with this directive.
1249 void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
1250 // Should be an array of 'i8*'.
1251 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1252 if (InitList == 0) return;
1254 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1255 const GlobalValue *GV =
1256 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1257 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1258 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1262 typedef std::pair<unsigned, Constant*> Structor;
1264 static bool priority_order(const Structor& lhs, const Structor& rhs) {
1265 return lhs.first < rhs.first;
1268 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1270 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1271 // Should be an array of '{ int, void ()* }' structs. The first value is the
1273 if (!isa<ConstantArray>(List)) return;
1275 // Sanity check the structors list.
1276 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1277 if (!InitList) return; // Not an array!
1278 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1279 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1280 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1281 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1283 // Gather the structors in a form that's convenient for sorting by priority.
1284 SmallVector<Structor, 8> Structors;
1285 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1286 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1287 if (!CS) continue; // Malformed.
1288 if (CS->getOperand(1)->isNullValue())
1289 break; // Found a null terminator, skip the rest.
1290 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1291 if (!Priority) continue; // Malformed.
1292 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1293 CS->getOperand(1)));
1296 // Emit the function pointers in the target-specific order
1297 const DataLayout *TD = TM.getDataLayout();
1298 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1299 std::stable_sort(Structors.begin(), Structors.end(), priority_order);
1300 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1301 const MCSection *OutputSection =
1303 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1304 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1305 OutStreamer.SwitchSection(OutputSection);
1306 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1307 EmitAlignment(Align);
1308 EmitXXStructor(Structors[i].second);
1312 //===--------------------------------------------------------------------===//
1313 // Emission and print routines
1316 /// EmitInt8 - Emit a byte directive and value.
1318 void AsmPrinter::EmitInt8(int Value) const {
1319 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1322 /// EmitInt16 - Emit a short directive and value.
1324 void AsmPrinter::EmitInt16(int Value) const {
1325 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1328 /// EmitInt32 - Emit a long directive and value.
1330 void AsmPrinter::EmitInt32(int Value) const {
1331 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1334 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1335 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1336 /// labels. This implicitly uses .set if it is available.
1337 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1338 unsigned Size) const {
1339 // Get the Hi-Lo expression.
1340 const MCExpr *Diff =
1341 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1342 MCSymbolRefExpr::Create(Lo, OutContext),
1345 if (!MAI->hasSetDirective()) {
1346 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1350 // Otherwise, emit with .set (aka assignment).
1351 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1352 OutStreamer.EmitAssignment(SetLabel, Diff);
1353 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1356 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1357 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1358 /// specify the labels. This implicitly uses .set if it is available.
1359 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1360 const MCSymbol *Lo, unsigned Size)
1363 // Emit Hi+Offset - Lo
1364 // Get the Hi+Offset expression.
1365 const MCExpr *Plus =
1366 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1367 MCConstantExpr::Create(Offset, OutContext),
1370 // Get the Hi+Offset-Lo expression.
1371 const MCExpr *Diff =
1372 MCBinaryExpr::CreateSub(Plus,
1373 MCSymbolRefExpr::Create(Lo, OutContext),
1376 if (!MAI->hasSetDirective())
1377 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1379 // Otherwise, emit with .set (aka assignment).
1380 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1381 OutStreamer.EmitAssignment(SetLabel, Diff);
1382 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1386 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1387 /// where the size in bytes of the directive is specified by Size and Label
1388 /// specifies the label. This implicitly uses .set if it is available.
1389 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1393 // Emit Label+Offset (or just Label if Offset is zero)
1394 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1396 Expr = MCBinaryExpr::CreateAdd(Expr,
1397 MCConstantExpr::Create(Offset, OutContext),
1400 OutStreamer.EmitValue(Expr, Size, 0/*AddrSpace*/);
1404 //===----------------------------------------------------------------------===//
1406 // EmitAlignment - Emit an alignment directive to the specified power of
1407 // two boundary. For example, if you pass in 3 here, you will get an 8
1408 // byte alignment. If a global value is specified, and if that global has
1409 // an explicit alignment requested, it will override the alignment request
1410 // if required for correctness.
1412 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1413 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1415 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1417 if (getCurrentSection()->getKind().isText())
1418 OutStreamer.EmitCodeAlignment(1 << NumBits);
1420 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1423 //===----------------------------------------------------------------------===//
1424 // Constant emission.
1425 //===----------------------------------------------------------------------===//
1427 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1429 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1430 MCContext &Ctx = AP.OutContext;
1432 if (CV->isNullValue() || isa<UndefValue>(CV))
1433 return MCConstantExpr::Create(0, Ctx);
1435 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1436 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1438 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1439 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1441 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1442 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1444 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1446 llvm_unreachable("Unknown constant value to lower!");
1449 switch (CE->getOpcode()) {
1451 // If the code isn't optimized, there may be outstanding folding
1452 // opportunities. Attempt to fold the expression using DataLayout as a
1453 // last resort before giving up.
1455 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1457 return lowerConstant(C, AP);
1459 // Otherwise report the problem to the user.
1462 raw_string_ostream OS(S);
1463 OS << "Unsupported expression in static initializer: ";
1464 WriteAsOperand(OS, CE, /*PrintType=*/false,
1465 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1466 report_fatal_error(OS.str());
1468 case Instruction::GetElementPtr: {
1469 const DataLayout &TD = *AP.TM.getDataLayout();
1470 // Generate a symbolic expression for the byte address
1471 const Constant *PtrVal = CE->getOperand(0);
1472 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1473 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
1475 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1479 // Truncate/sext the offset to the pointer size.
1480 unsigned Width = TD.getPointerSizeInBits();
1482 Offset = SignExtend64(Offset, Width);
1484 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1488 case Instruction::Trunc:
1489 // We emit the value and depend on the assembler to truncate the generated
1490 // expression properly. This is important for differences between
1491 // blockaddress labels. Since the two labels are in the same function, it
1492 // is reasonable to treat their delta as a 32-bit value.
1494 case Instruction::BitCast:
1495 return lowerConstant(CE->getOperand(0), AP);
1497 case Instruction::IntToPtr: {
1498 const DataLayout &TD = *AP.TM.getDataLayout();
1499 // Handle casts to pointers by changing them into casts to the appropriate
1500 // integer type. This promotes constant folding and simplifies this code.
1501 Constant *Op = CE->getOperand(0);
1502 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1504 return lowerConstant(Op, AP);
1507 case Instruction::PtrToInt: {
1508 const DataLayout &TD = *AP.TM.getDataLayout();
1509 // Support only foldable casts to/from pointers that can be eliminated by
1510 // changing the pointer to the appropriately sized integer type.
1511 Constant *Op = CE->getOperand(0);
1512 Type *Ty = CE->getType();
1514 const MCExpr *OpExpr = lowerConstant(Op, AP);
1516 // We can emit the pointer value into this slot if the slot is an
1517 // integer slot equal to the size of the pointer.
1518 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1521 // Otherwise the pointer is smaller than the resultant integer, mask off
1522 // the high bits so we are sure to get a proper truncation if the input is
1524 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1525 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1526 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1529 // The MC library also has a right-shift operator, but it isn't consistently
1530 // signed or unsigned between different targets.
1531 case Instruction::Add:
1532 case Instruction::Sub:
1533 case Instruction::Mul:
1534 case Instruction::SDiv:
1535 case Instruction::SRem:
1536 case Instruction::Shl:
1537 case Instruction::And:
1538 case Instruction::Or:
1539 case Instruction::Xor: {
1540 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1541 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1542 switch (CE->getOpcode()) {
1543 default: llvm_unreachable("Unknown binary operator constant cast expr");
1544 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1545 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1546 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1547 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1548 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1549 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1550 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1551 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1552 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1558 static void emitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1561 /// isRepeatedByteSequence - Determine whether the given value is
1562 /// composed of a repeated sequence of identical bytes and return the
1563 /// byte value. If it is not a repeated sequence, return -1.
1564 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1565 StringRef Data = V->getRawDataValues();
1566 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1568 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1569 if (Data[i] != C) return -1;
1570 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1574 /// isRepeatedByteSequence - Determine whether the given value is
1575 /// composed of a repeated sequence of identical bytes and return the
1576 /// byte value. If it is not a repeated sequence, return -1.
1577 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1579 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1580 if (CI->getBitWidth() > 64) return -1;
1582 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1583 uint64_t Value = CI->getZExtValue();
1585 // Make sure the constant is at least 8 bits long and has a power
1586 // of 2 bit width. This guarantees the constant bit width is
1587 // always a multiple of 8 bits, avoiding issues with padding out
1588 // to Size and other such corner cases.
1589 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1591 uint8_t Byte = static_cast<uint8_t>(Value);
1593 for (unsigned i = 1; i < Size; ++i) {
1595 if (static_cast<uint8_t>(Value) != Byte) return -1;
1599 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1600 // Make sure all array elements are sequences of the same repeated
1602 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1603 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1604 if (Byte == -1) return -1;
1606 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1607 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1608 if (ThisByte == -1) return -1;
1609 if (Byte != ThisByte) return -1;
1614 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1615 return isRepeatedByteSequence(CDS);
1620 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1621 unsigned AddrSpace,AsmPrinter &AP){
1623 // See if we can aggregate this into a .fill, if so, emit it as such.
1624 int Value = isRepeatedByteSequence(CDS, AP.TM);
1626 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1627 // Don't emit a 1-byte object as a .fill.
1629 return AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1632 // If this can be emitted with .ascii/.asciz, emit it as such.
1633 if (CDS->isString())
1634 return AP.OutStreamer.EmitBytes(CDS->getAsString(), AddrSpace);
1636 // Otherwise, emit the values in successive locations.
1637 unsigned ElementByteSize = CDS->getElementByteSize();
1638 if (isa<IntegerType>(CDS->getElementType())) {
1639 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1641 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1642 CDS->getElementAsInteger(i));
1643 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1644 ElementByteSize, AddrSpace);
1646 } else if (ElementByteSize == 4) {
1647 // FP Constants are printed as integer constants to avoid losing
1649 assert(CDS->getElementType()->isFloatTy());
1650 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1656 F = CDS->getElementAsFloat(i);
1658 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1659 AP.OutStreamer.EmitIntValue(I, 4, AddrSpace);
1662 assert(CDS->getElementType()->isDoubleTy());
1663 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1669 F = CDS->getElementAsDouble(i);
1671 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1672 AP.OutStreamer.EmitIntValue(I, 8, AddrSpace);
1676 const DataLayout &TD = *AP.TM.getDataLayout();
1677 unsigned Size = TD.getTypeAllocSize(CDS->getType());
1678 unsigned EmittedSize = TD.getTypeAllocSize(CDS->getType()->getElementType()) *
1679 CDS->getNumElements();
1680 if (unsigned Padding = Size - EmittedSize)
1681 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1685 static void emitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1687 // See if we can aggregate some values. Make sure it can be
1688 // represented as a series of bytes of the constant value.
1689 int Value = isRepeatedByteSequence(CA, AP.TM);
1692 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1693 AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1696 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1697 emitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1701 static void emitGlobalConstantVector(const ConstantVector *CV,
1702 unsigned AddrSpace, AsmPrinter &AP) {
1703 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1704 emitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1706 const DataLayout &TD = *AP.TM.getDataLayout();
1707 unsigned Size = TD.getTypeAllocSize(CV->getType());
1708 unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1709 CV->getType()->getNumElements();
1710 if (unsigned Padding = Size - EmittedSize)
1711 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1714 static void emitGlobalConstantStruct(const ConstantStruct *CS,
1715 unsigned AddrSpace, AsmPrinter &AP) {
1716 // Print the fields in successive locations. Pad to align if needed!
1717 const DataLayout *TD = AP.TM.getDataLayout();
1718 unsigned Size = TD->getTypeAllocSize(CS->getType());
1719 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1720 uint64_t SizeSoFar = 0;
1721 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1722 const Constant *Field = CS->getOperand(i);
1724 // Check if padding is needed and insert one or more 0s.
1725 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1726 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1727 - Layout->getElementOffset(i)) - FieldSize;
1728 SizeSoFar += FieldSize + PadSize;
1730 // Now print the actual field value.
1731 emitGlobalConstantImpl(Field, AddrSpace, AP);
1733 // Insert padding - this may include padding to increase the size of the
1734 // current field up to the ABI size (if the struct is not packed) as well
1735 // as padding to ensure that the next field starts at the right offset.
1736 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1738 assert(SizeSoFar == Layout->getSizeInBytes() &&
1739 "Layout of constant struct may be incorrect!");
1742 static void emitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1744 if (CFP->getType()->isHalfTy()) {
1745 if (AP.isVerbose()) {
1746 SmallString<10> Str;
1747 CFP->getValueAPF().toString(Str);
1748 AP.OutStreamer.GetCommentOS() << "half " << Str << '\n';
1750 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1751 AP.OutStreamer.EmitIntValue(Val, 2, AddrSpace);
1755 if (CFP->getType()->isFloatTy()) {
1756 if (AP.isVerbose()) {
1757 float Val = CFP->getValueAPF().convertToFloat();
1758 uint64_t IntVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1759 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n'
1760 << " (" << format("0x%x", IntVal) << ")\n";
1762 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1763 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1767 // FP Constants are printed as integer constants to avoid losing
1769 if (CFP->getType()->isDoubleTy()) {
1770 if (AP.isVerbose()) {
1771 double Val = CFP->getValueAPF().convertToDouble();
1772 uint64_t IntVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1773 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n'
1774 << " (" << format("0x%lx", IntVal) << ")\n";
1777 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1778 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1782 if (CFP->getType()->isX86_FP80Ty()) {
1783 // all long double variants are printed as hex
1784 // API needed to prevent premature destruction
1785 APInt API = CFP->getValueAPF().bitcastToAPInt();
1786 const uint64_t *p = API.getRawData();
1787 if (AP.isVerbose()) {
1788 // Convert to double so we can print the approximate val as a comment.
1789 APFloat DoubleVal = CFP->getValueAPF();
1791 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1793 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1794 << DoubleVal.convertToDouble() << '\n';
1797 if (AP.TM.getDataLayout()->isBigEndian()) {
1798 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1799 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1801 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1802 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1805 // Emit the tail padding for the long double.
1806 const DataLayout &TD = *AP.TM.getDataLayout();
1807 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1808 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1812 assert(CFP->getType()->isPPC_FP128Ty() &&
1813 "Floating point constant type not handled");
1814 // All long double variants are printed as hex
1815 // API needed to prevent premature destruction.
1816 APInt API = CFP->getValueAPF().bitcastToAPInt();
1817 const uint64_t *p = API.getRawData();
1818 if (AP.TM.getDataLayout()->isBigEndian()) {
1819 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1820 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1822 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1823 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1827 static void emitGlobalConstantLargeInt(const ConstantInt *CI,
1828 unsigned AddrSpace, AsmPrinter &AP) {
1829 const DataLayout *TD = AP.TM.getDataLayout();
1830 unsigned BitWidth = CI->getBitWidth();
1831 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1833 // We don't expect assemblers to support integer data directives
1834 // for more than 64 bits, so we emit the data in at most 64-bit
1835 // quantities at a time.
1836 const uint64_t *RawData = CI->getValue().getRawData();
1837 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1838 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1839 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1843 static void emitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1845 const DataLayout *TD = AP.TM.getDataLayout();
1846 uint64_t Size = TD->getTypeAllocSize(CV->getType());
1847 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1848 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1850 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1857 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1858 CI->getZExtValue());
1859 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1862 emitGlobalConstantLargeInt(CI, AddrSpace, AP);
1867 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1868 return emitGlobalConstantFP(CFP, AddrSpace, AP);
1870 if (isa<ConstantPointerNull>(CV)) {
1871 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1875 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1876 return emitGlobalConstantDataSequential(CDS, AddrSpace, AP);
1878 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1879 return emitGlobalConstantArray(CVA, AddrSpace, AP);
1881 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1882 return emitGlobalConstantStruct(CVS, AddrSpace, AP);
1884 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1885 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1887 if (CE->getOpcode() == Instruction::BitCast)
1888 return emitGlobalConstantImpl(CE->getOperand(0), AddrSpace, AP);
1891 // If the constant expression's size is greater than 64-bits, then we have
1892 // to emit the value in chunks. Try to constant fold the value and emit it
1894 Constant *New = ConstantFoldConstantExpression(CE, TD);
1895 if (New && New != CE)
1896 return emitGlobalConstantImpl(New, AddrSpace, AP);
1900 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1901 return emitGlobalConstantVector(V, AddrSpace, AP);
1903 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1904 // thread the streamer with EmitValue.
1905 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size, AddrSpace);
1908 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1909 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1910 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1912 emitGlobalConstantImpl(CV, AddrSpace, *this);
1913 else if (MAI->hasSubsectionsViaSymbols()) {
1914 // If the global has zero size, emit a single byte so that two labels don't
1915 // look like they are at the same location.
1916 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1920 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1921 // Target doesn't support this yet!
1922 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1925 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1927 OS << '+' << Offset;
1928 else if (Offset < 0)
1932 //===----------------------------------------------------------------------===//
1933 // Symbol Lowering Routines.
1934 //===----------------------------------------------------------------------===//
1936 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1937 /// temporary label with the specified stem and unique ID.
1938 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1939 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1943 /// GetTempSymbol - Return an assembler temporary label with the specified
1945 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1946 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1951 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1952 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1955 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1956 return MMI->getAddrLabelSymbol(BB);
1959 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1960 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1961 return OutContext.GetOrCreateSymbol
1962 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1963 + "_" + Twine(CPID));
1966 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1967 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1968 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1971 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1972 /// FIXME: privatize to AsmPrinter.
1973 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1974 return OutContext.GetOrCreateSymbol
1975 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1976 Twine(UID) + "_set_" + Twine(MBBID));
1979 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1980 /// global value name as its base, with the specified suffix, and where the
1981 /// symbol is forced to have private linkage if ForcePrivate is true.
1982 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1984 bool ForcePrivate) const {
1985 SmallString<60> NameStr;
1986 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1987 NameStr.append(Suffix.begin(), Suffix.end());
1988 return OutContext.GetOrCreateSymbol(NameStr.str());
1991 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1993 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1994 SmallString<60> NameStr;
1995 Mang->getNameWithPrefix(NameStr, Sym);
1996 return OutContext.GetOrCreateSymbol(NameStr.str());
2001 /// PrintParentLoopComment - Print comments about parent loops of this one.
2002 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2003 unsigned FunctionNumber) {
2004 if (Loop == 0) return;
2005 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2006 OS.indent(Loop->getLoopDepth()*2)
2007 << "Parent Loop BB" << FunctionNumber << "_"
2008 << Loop->getHeader()->getNumber()
2009 << " Depth=" << Loop->getLoopDepth() << '\n';
2013 /// PrintChildLoopComment - Print comments about child loops within
2014 /// the loop for this basic block, with nesting.
2015 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2016 unsigned FunctionNumber) {
2017 // Add child loop information
2018 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2019 OS.indent((*CL)->getLoopDepth()*2)
2020 << "Child Loop BB" << FunctionNumber << "_"
2021 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2023 PrintChildLoopComment(OS, *CL, FunctionNumber);
2027 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2028 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2029 const MachineLoopInfo *LI,
2030 const AsmPrinter &AP) {
2031 // Add loop depth information
2032 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2033 if (Loop == 0) return;
2035 MachineBasicBlock *Header = Loop->getHeader();
2036 assert(Header && "No header for loop");
2038 // If this block is not a loop header, just print out what is the loop header
2040 if (Header != &MBB) {
2041 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2042 Twine(AP.getFunctionNumber())+"_" +
2043 Twine(Loop->getHeader()->getNumber())+
2044 " Depth="+Twine(Loop->getLoopDepth()));
2048 // Otherwise, it is a loop header. Print out information about child and
2050 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2052 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2055 OS.indent(Loop->getLoopDepth()*2-2);
2060 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2062 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2066 /// EmitBasicBlockStart - This method prints the label for the specified
2067 /// MachineBasicBlock, an alignment (if present) and a comment describing
2068 /// it if appropriate.
2069 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2070 // Emit an alignment directive for this block, if needed.
2071 if (unsigned Align = MBB->getAlignment())
2072 EmitAlignment(Align);
2074 // If the block has its address taken, emit any labels that were used to
2075 // reference the block. It is possible that there is more than one label
2076 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2077 // the references were generated.
2078 if (MBB->hasAddressTaken()) {
2079 const BasicBlock *BB = MBB->getBasicBlock();
2081 OutStreamer.AddComment("Block address taken");
2083 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2085 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2086 OutStreamer.EmitLabel(Syms[i]);
2089 // Print some verbose block comments.
2091 if (const BasicBlock *BB = MBB->getBasicBlock())
2093 OutStreamer.AddComment("%" + BB->getName());
2094 emitBasicBlockLoopComments(*MBB, LI, *this);
2097 // Print the main label for the block.
2098 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2099 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2100 // NOTE: Want this comment at start of line, don't emit with AddComment.
2101 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2102 Twine(MBB->getNumber()) + ":");
2105 OutStreamer.EmitLabel(MBB->getSymbol());
2109 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2110 bool IsDefinition) const {
2111 MCSymbolAttr Attr = MCSA_Invalid;
2113 switch (Visibility) {
2115 case GlobalValue::HiddenVisibility:
2117 Attr = MAI->getHiddenVisibilityAttr();
2119 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2121 case GlobalValue::ProtectedVisibility:
2122 Attr = MAI->getProtectedVisibilityAttr();
2126 if (Attr != MCSA_Invalid)
2127 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2130 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2131 /// exactly one predecessor and the control transfer mechanism between
2132 /// the predecessor and this block is a fall-through.
2134 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2135 // If this is a landing pad, it isn't a fall through. If it has no preds,
2136 // then nothing falls through to it.
2137 if (MBB->isLandingPad() || MBB->pred_empty())
2140 // If there isn't exactly one predecessor, it can't be a fall through.
2141 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2143 if (PI2 != MBB->pred_end())
2146 // The predecessor has to be immediately before this block.
2147 MachineBasicBlock *Pred = *PI;
2149 if (!Pred->isLayoutSuccessor(MBB))
2152 // If the block is completely empty, then it definitely does fall through.
2156 // Check the terminators in the previous blocks
2157 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2158 IE = Pred->end(); II != IE; ++II) {
2159 MachineInstr &MI = *II;
2161 // If it is not a simple branch, we are in a table somewhere.
2162 if (!MI.isBranch() || MI.isIndirectBranch())
2165 // If we are the operands of one of the branches, this is not
2167 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2168 OE = MI.operands_end(); OI != OE; ++OI) {
2169 const MachineOperand& OP = *OI;
2172 if (OP.isMBB() && OP.getMBB() == MBB)
2182 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2183 if (!S->usesMetadata())
2186 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2187 gcp_map_type::iterator GCPI = GCMap.find(S);
2188 if (GCPI != GCMap.end())
2189 return GCPI->second;
2191 const char *Name = S->getName().c_str();
2193 for (GCMetadataPrinterRegistry::iterator
2194 I = GCMetadataPrinterRegistry::begin(),
2195 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2196 if (strcmp(Name, I->getName()) == 0) {
2197 GCMetadataPrinter *GMP = I->instantiate();
2199 GCMap.insert(std::make_pair(S, GMP));
2203 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));