Deleted Added
sdiff udiff text old ( 261991 ) new ( 262613 )
full compact
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
15#include "llvm/CodeGen/AsmPrinter.h"
16#include "DwarfDebug.h"
17#include "DwarfException.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Assembly/Writer.h"
22#include "llvm/CodeGen/GCMetadataPrinter.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineJumpTableInfo.h"
27#include "llvm/CodeGen/MachineLoopInfo.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/DebugInfo.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/MC/MCExpr.h"
36#include "llvm/MC/MCInst.h"
37#include "llvm/MC/MCSection.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/Format.h"
42#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/Timer.h"
44#include "llvm/Target/Mangler.h"
45#include "llvm/Target/TargetFrameLowering.h"
46#include "llvm/Target/TargetInstrInfo.h"
47#include "llvm/Target/TargetLowering.h"
48#include "llvm/Target/TargetLoweringObjectFile.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Target/TargetRegisterInfo.h"
51#include "llvm/Transforms/Utils/GlobalStatus.h"
52using namespace llvm;
53
54static const char *const DWARFGroupName = "DWARF Emission";
55static const char *const DbgTimerName = "DWARF Debug Writer";
56static const char *const EHTimerName = "DWARF Exception Writer";
57
58STATISTIC(EmittedInsts, "Number of machine instrs printed");
59
60char AsmPrinter::ID = 0;
61
62typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
63static gcp_map_type &getGCMap(void *&P) {
64 if (P == 0)
65 P = new gcp_map_type();
66 return *(gcp_map_type*)P;
67}
68
69
70/// getGVAlignmentLog2 - Return the alignment to use for the specified global
71/// value in log2 form. This rounds up to the preferred alignment if possible
72/// and legal.
73static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
74 unsigned InBits = 0) {
75 unsigned NumBits = 0;
76 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77 NumBits = TD.getPreferredAlignmentLog(GVar);
78
79 // If InBits is specified, round it to it.
80 if (InBits > NumBits)
81 NumBits = InBits;
82
83 // If the GV has a specified alignment, take it into account.
84 if (GV->getAlignment() == 0)
85 return NumBits;
86
87 unsigned GVAlign = Log2_32(GV->getAlignment());
88
89 // If the GVAlign is larger than NumBits, or if we are required to obey
90 // NumBits because the GV has an assigned section, obey it.
91 if (GVAlign > NumBits || GV->hasSection())
92 NumBits = GVAlign;
93 return NumBits;
94}
95
96AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
97 : MachineFunctionPass(ID),
98 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
99 OutContext(Streamer.getContext()),
100 OutStreamer(Streamer),
101 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
102 DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0;
103 CurrentFnSym = CurrentFnSymForSize = 0;
104 GCMetadataPrinters = 0;
105 VerboseAsm = Streamer.isVerboseAsm();
106}
107
108AsmPrinter::~AsmPrinter() {
109 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
110
111 if (GCMetadataPrinters != 0) {
112 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
113
114 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
115 delete I->second;
116 delete &GCMap;
117 GCMetadataPrinters = 0;
118 }
119
120 delete &OutStreamer;
121}
122
123/// getFunctionNumber - Return a unique ID for the current function.
124///
125unsigned AsmPrinter::getFunctionNumber() const {
126 return MF->getFunctionNumber();
127}
128
129const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
130 return TM.getTargetLowering()->getObjFileLowering();
131}
132
133/// getDataLayout - Return information about data layout.
134const DataLayout &AsmPrinter::getDataLayout() const {
135 return *TM.getDataLayout();
136}
137
138StringRef AsmPrinter::getTargetTriple() const {
139 return TM.getTargetTriple();
140}
141
142/// getCurrentSection() - Return the current section we are emitting to.
143const MCSection *AsmPrinter::getCurrentSection() const {
144 return OutStreamer.getCurrentSection().first;
145}
146
147
148
149void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
150 AU.setPreservesAll();
151 MachineFunctionPass::getAnalysisUsage(AU);
152 AU.addRequired<MachineModuleInfo>();
153 AU.addRequired<GCModuleInfo>();
154 if (isVerbose())
155 AU.addRequired<MachineLoopInfo>();
156}
157
158bool AsmPrinter::doInitialization(Module &M) {
159 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
160 MMI->AnalyzeModule(M);
161
162 // Initialize TargetLoweringObjectFile.
163 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
164 .Initialize(OutContext, TM);
165
166 OutStreamer.InitStreamer();
167
168 Mang = new Mangler(&TM);
169
170 // Allow the target to emit any magic that it wants at the start of the file.
171 EmitStartOfAsmFile(M);
172
173 // Very minimal debug info. It is ignored if we emit actual debug info. If we
174 // don't, this at least helps the user find where a global came from.
175 if (MAI->hasSingleParameterDotFile()) {
176 // .file "foo.c"
177 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
178 }
179
180 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
181 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
182 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
183 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
184 MP->beginAssembly(*this);
185
186 // Emit module-level inline asm if it exists.
187 if (!M.getModuleInlineAsm().empty()) {
188 OutStreamer.AddComment("Start of file scope inline assembly");
189 OutStreamer.AddBlankLine();
190 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
191 OutStreamer.AddComment("End of file scope inline assembly");
192 OutStreamer.AddBlankLine();
193 }
194
195 if (MAI->doesSupportDebugInformation())
196 DD = new DwarfDebug(this, &M);
197
198 switch (MAI->getExceptionHandlingType()) {
199 case ExceptionHandling::None:
200 return false;
201 case ExceptionHandling::SjLj:
202 case ExceptionHandling::DwarfCFI:
203 DE = new DwarfCFIException(this);
204 return false;
205 case ExceptionHandling::ARM:
206 DE = new ARMException(this);
207 return false;
208 case ExceptionHandling::Win64:
209 DE = new Win64Exception(this);
210 return false;
211 }
212
213 llvm_unreachable("Unknown exception type.");
214}
215
216void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
217 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
218 switch (Linkage) {
219 case GlobalValue::CommonLinkage:
220 case GlobalValue::LinkOnceAnyLinkage:
221 case GlobalValue::LinkOnceODRLinkage:
222 case GlobalValue::WeakAnyLinkage:
223 case GlobalValue::WeakODRLinkage:
224 case GlobalValue::LinkerPrivateWeakLinkage:
225 if (MAI->getWeakDefDirective() != 0) {
226 // .globl _foo
227 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
228
229 bool CanBeHidden = false;
230
231 if (Linkage == GlobalValue::LinkOnceODRLinkage) {
232 if (GV->hasUnnamedAddr()) {
233 CanBeHidden = true;
234 } else {
235 GlobalStatus GS;
236 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
237 CanBeHidden = true;
238 }
239 }
240
241 if (!CanBeHidden)
242 // .weak_definition _foo
243 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
244 else
245 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
246 } else if (MAI->getLinkOnceDirective() != 0) {
247 // .globl _foo
248 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
249 //NOTE: linkonce is handled by the section the symbol was assigned to.
250 } else {
251 // .weak _foo
252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
253 }
254 return;
255 case GlobalValue::DLLExportLinkage:
256 case GlobalValue::AppendingLinkage:
257 // FIXME: appending linkage variables should go into a section of
258 // their name or something. For now, just emit them as external.
259 case GlobalValue::ExternalLinkage:
260 // If external or appending, declare as a global symbol.
261 // .globl _foo
262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
263 return;
264 case GlobalValue::PrivateLinkage:
265 case GlobalValue::InternalLinkage:
266 case GlobalValue::LinkerPrivateLinkage:
267 return;
268 case GlobalValue::AvailableExternallyLinkage:
269 llvm_unreachable("Should never emit this");
270 case GlobalValue::DLLImportLinkage:
271 case GlobalValue::ExternalWeakLinkage:
272 llvm_unreachable("Don't know how to emit these");
273 }
274 llvm_unreachable("Unknown linkage type!");
275}
276
277MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
278 return getObjFileLowering().getSymbol(*Mang, GV);
279}
280
281/// EmitGlobalVariable - Emit the specified global variable to the .s file.
282void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
283 if (GV->hasInitializer()) {
284 // Check to see if this is a special global used by LLVM, if so, emit it.
285 if (EmitSpecialLLVMGlobal(GV))
286 return;
287
288 if (isVerbose()) {
289 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
290 /*PrintType=*/false, GV->getParent());
291 OutStreamer.GetCommentOS() << '\n';
292 }
293 }
294
295 MCSymbol *GVSym = getSymbol(GV);
296 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
297
298 if (!GV->hasInitializer()) // External globals require no extra code.
299 return;
300
301 if (MAI->hasDotTypeDotSizeDirective())
302 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
303
304 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
305
306 const DataLayout *DL = TM.getDataLayout();
307 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
308
309 // If the alignment is specified, we *must* obey it. Overaligning a global
310 // with a specified alignment is a prompt way to break globals emitted to
311 // sections and expected to be contiguous (e.g. ObjC metadata).
312 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
313
314 if (DD)
315 DD->setSymbolSize(GVSym, Size);
316
317 // Handle common and BSS local symbols (.lcomm).
318 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
319 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
320 unsigned Align = 1 << AlignLog;
321
322 // Handle common symbols.
323 if (GVKind.isCommon()) {
324 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
325 Align = 0;
326
327 // .comm _foo, 42, 4
328 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
329 return;
330 }
331
332 // Handle local BSS symbols.
333 if (MAI->hasMachoZeroFillDirective()) {
334 const MCSection *TheSection =
335 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
336 // .zerofill __DATA, __bss, _foo, 400, 5
337 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
338 return;
339 }
340
341 // Use .lcomm only if it supports user-specified alignment.
342 // Otherwise, while it would still be correct to use .lcomm in some
343 // cases (e.g. when Align == 1), the external assembler might enfore
344 // some -unknown- default alignment behavior, which could cause
345 // spurious differences between external and integrated assembler.
346 // Prefer to simply fall back to .local / .comm in this case.
347 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
348 // .lcomm _foo, 42
349 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
350 return;
351 }
352
353 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
354 Align = 0;
355
356 // .local _foo
357 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
358 // .comm _foo, 42, 4
359 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
360 return;
361 }
362
363 const MCSection *TheSection =
364 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
365
366 // Handle the zerofill directive on darwin, which is a special form of BSS
367 // emission.
368 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
369 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
370
371 // .globl _foo
372 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
373 // .zerofill __DATA, __common, _foo, 400, 5
374 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
375 return;
376 }
377
378 // Handle thread local data for mach-o which requires us to output an
379 // additional structure of data and mangle the original symbol so that we
380 // can reference it later.
381 //
382 // TODO: This should become an "emit thread local global" method on TLOF.
383 // All of this macho specific stuff should be sunk down into TLOFMachO and
384 // stuff like "TLSExtraDataSection" should no longer be part of the parent
385 // TLOF class. This will also make it more obvious that stuff like
386 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
387 // specific code.
388 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
389 // Emit the .tbss symbol
390 MCSymbol *MangSym =
391 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
392
393 if (GVKind.isThreadBSS()) {
394 TheSection = getObjFileLowering().getTLSBSSSection();
395 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
396 } else if (GVKind.isThreadData()) {
397 OutStreamer.SwitchSection(TheSection);
398
399 EmitAlignment(AlignLog, GV);
400 OutStreamer.EmitLabel(MangSym);
401
402 EmitGlobalConstant(GV->getInitializer());
403 }
404
405 OutStreamer.AddBlankLine();
406
407 // Emit the variable struct for the runtime.
408 const MCSection *TLVSect
409 = getObjFileLowering().getTLSExtraDataSection();
410
411 OutStreamer.SwitchSection(TLVSect);
412 // Emit the linkage here.
413 EmitLinkage(GV, GVSym);
414 OutStreamer.EmitLabel(GVSym);
415
416 // Three pointers in size:
417 // - __tlv_bootstrap - used to make sure support exists
418 // - spare pointer, used when mapped by the runtime
419 // - pointer to mangled symbol above with initializer
420 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
421 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
422 PtrSize);
423 OutStreamer.EmitIntValue(0, PtrSize);
424 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
425
426 OutStreamer.AddBlankLine();
427 return;
428 }
429
430 OutStreamer.SwitchSection(TheSection);
431
432 EmitLinkage(GV, GVSym);
433 EmitAlignment(AlignLog, GV);
434
435 OutStreamer.EmitLabel(GVSym);
436
437 EmitGlobalConstant(GV->getInitializer());
438
439 if (MAI->hasDotTypeDotSizeDirective())
440 // .size foo, 42
441 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
442
443 OutStreamer.AddBlankLine();
444}
445
446/// EmitFunctionHeader - This method emits the header for the current
447/// function.
448void AsmPrinter::EmitFunctionHeader() {
449 // Print out constants referenced by the function
450 EmitConstantPool();
451
452 // Print the 'header' of function.
453 const Function *F = MF->getFunction();
454
455 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
456 EmitVisibility(CurrentFnSym, F->getVisibility());
457
458 EmitLinkage(F, CurrentFnSym);
459 EmitAlignment(MF->getAlignment(), F);
460
461 if (MAI->hasDotTypeDotSizeDirective())
462 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
463
464 if (isVerbose()) {
465 WriteAsOperand(OutStreamer.GetCommentOS(), F,
466 /*PrintType=*/false, F->getParent());
467 OutStreamer.GetCommentOS() << '\n';
468 }
469
470 // Emit the CurrentFnSym. This is a virtual function to allow targets to
471 // do their wild and crazy things as required.
472 EmitFunctionEntryLabel();
473
474 // If the function had address-taken blocks that got deleted, then we have
475 // references to the dangling symbols. Emit them at the start of the function
476 // so that we don't get references to undefined symbols.
477 std::vector<MCSymbol*> DeadBlockSyms;
478 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
479 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
480 OutStreamer.AddComment("Address taken block that was later removed");
481 OutStreamer.EmitLabel(DeadBlockSyms[i]);
482 }
483
484 // Emit pre-function debug and/or EH information.
485 if (DE) {
486 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
487 DE->BeginFunction(MF);
488 }
489 if (DD) {
490 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
491 DD->beginFunction(MF);
492 }
493
494 // Emit the prefix data.
495 if (F->hasPrefixData())
496 EmitGlobalConstant(F->getPrefixData());
497}
498
499/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
500/// function. This can be overridden by targets as required to do custom stuff.
501void AsmPrinter::EmitFunctionEntryLabel() {
502 // The function label could have already been emitted if two symbols end up
503 // conflicting due to asm renaming. Detect this and emit an error.
504 if (CurrentFnSym->isUndefined())
505 return OutStreamer.EmitLabel(CurrentFnSym);
506
507 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
508 "' label emitted multiple times to assembly file");
509}
510
511/// emitComments - Pretty-print comments for instructions.
512static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
513 const MachineFunction *MF = MI.getParent()->getParent();
514 const TargetMachine &TM = MF->getTarget();
515
516 // Check for spills and reloads
517 int FI;
518
519 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
520
521 // We assume a single instruction only has a spill or reload, not
522 // both.
523 const MachineMemOperand *MMO;
524 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
525 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
526 MMO = *MI.memoperands_begin();
527 CommentOS << MMO->getSize() << "-byte Reload\n";
528 }
529 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
530 if (FrameInfo->isSpillSlotObjectIndex(FI))
531 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
532 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
533 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
534 MMO = *MI.memoperands_begin();
535 CommentOS << MMO->getSize() << "-byte Spill\n";
536 }
537 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
538 if (FrameInfo->isSpillSlotObjectIndex(FI))
539 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
540 }
541
542 // Check for spill-induced copies
543 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
544 CommentOS << " Reload Reuse\n";
545}
546
547/// emitImplicitDef - This method emits the specified machine instruction
548/// that is an implicit def.
549void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
550 unsigned RegNo = MI->getOperand(0).getReg();
551 OutStreamer.AddComment(Twine("implicit-def: ") +
552 TM.getRegisterInfo()->getName(RegNo));
553 OutStreamer.AddBlankLine();
554}
555
556static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
557 std::string Str = "kill:";
558 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
559 const MachineOperand &Op = MI->getOperand(i);
560 assert(Op.isReg() && "KILL instruction must have only register operands");
561 Str += ' ';
562 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
563 Str += (Op.isDef() ? "<def>" : "<kill>");
564 }
565 AP.OutStreamer.AddComment(Str);
566 AP.OutStreamer.AddBlankLine();
567}
568
569/// emitDebugValueComment - This method handles the target-independent form
570/// of DBG_VALUE, returning true if it was able to do so. A false return
571/// means the target will need to handle MI in EmitInstruction.
572static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
573 // This code handles only the 3-operand target-independent form.
574 if (MI->getNumOperands() != 3)
575 return false;
576
577 SmallString<128> Str;
578 raw_svector_ostream OS(Str);
579 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
580
581 // cast away const; DIetc do not take const operands for some reason.
582 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
583 if (V.getContext().isSubprogram()) {
584 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
585 if (!Name.empty())
586 OS << Name << ":";
587 }
588 OS << V.getName() << " <- ";
589
590 // The second operand is only an offset if it's an immediate.
591 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
592 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
593
594 // Register or immediate value. Register 0 means undef.
595 if (MI->getOperand(0).isFPImm()) {
596 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
597 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
598 OS << (double)APF.convertToFloat();
599 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
600 OS << APF.convertToDouble();
601 } else {
602 // There is no good way to print long double. Convert a copy to
603 // double. Ah well, it's only a comment.
604 bool ignored;
605 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
606 &ignored);
607 OS << "(long double) " << APF.convertToDouble();
608 }
609 } else if (MI->getOperand(0).isImm()) {
610 OS << MI->getOperand(0).getImm();
611 } else if (MI->getOperand(0).isCImm()) {
612 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
613 } else {
614 unsigned Reg;
615 if (MI->getOperand(0).isReg()) {
616 Reg = MI->getOperand(0).getReg();
617 } else {
618 assert(MI->getOperand(0).isFI() && "Unknown operand type");
619 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
620 Offset += TFI->getFrameIndexReference(*AP.MF,
621 MI->getOperand(0).getIndex(), Reg);
622 Deref = true;
623 }
624 if (Reg == 0) {
625 // Suppress offset, it is not meaningful here.
626 OS << "undef";
627 // NOTE: Want this comment at start of line, don't emit with AddComment.
628 AP.OutStreamer.EmitRawText(OS.str());
629 return true;
630 }
631 if (Deref)
632 OS << '[';
633 OS << AP.TM.getRegisterInfo()->getName(Reg);
634 }
635
636 if (Deref)
637 OS << '+' << Offset << ']';
638
639 // NOTE: Want this comment at start of line, don't emit with AddComment.
640 AP.OutStreamer.EmitRawText(OS.str());
641 return true;
642}
643
644AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
645 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
646 MF->getFunction()->needsUnwindTableEntry())
647 return CFI_M_EH;
648
649 if (MMI->hasDebugInfo())
650 return CFI_M_Debug;
651
652 return CFI_M_None;
653}
654
655bool AsmPrinter::needsSEHMoves() {
656 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
657 MF->getFunction()->needsUnwindTableEntry();
658}
659
660bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
661 return MAI->doesDwarfUseRelocationsAcrossSections();
662}
663
664void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
665 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
666
667 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
668 return;
669
670 if (needsCFIMoves() == CFI_M_None)
671 return;
672
673 if (MMI->getCompactUnwindEncoding() != 0)
674 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
675
676 const MachineModuleInfo &MMI = MF->getMMI();
677 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
678 bool FoundOne = false;
679 (void)FoundOne;
680 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
681 E = Instrs.end(); I != E; ++I) {
682 if (I->getLabel() == Label) {
683 emitCFIInstruction(*I);
684 FoundOne = true;
685 }
686 }
687 assert(FoundOne);
688}
689
690/// EmitFunctionBody - This method emits the body and trailer for a
691/// function.
692void AsmPrinter::EmitFunctionBody() {
693 // Emit target-specific gunk before the function body.
694 EmitFunctionBodyStart();
695
696 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
697
698 // Print out code for the function.
699 bool HasAnyRealCode = false;
700 const MachineInstr *LastMI = 0;
701 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
702 I != E; ++I) {
703 // Print a label for the basic block.
704 EmitBasicBlockStart(I);
705 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
706 II != IE; ++II) {
707 LastMI = II;
708
709 // Print the assembly for the instruction.
710 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
711 !II->isDebugValue()) {
712 HasAnyRealCode = true;
713 ++EmittedInsts;
714 }
715
716 if (ShouldPrintDebugScopes) {
717 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
718 DD->beginInstruction(II);
719 }
720
721 if (isVerbose())
722 emitComments(*II, OutStreamer.GetCommentOS());
723
724 switch (II->getOpcode()) {
725 case TargetOpcode::PROLOG_LABEL:
726 emitPrologLabel(*II);
727 break;
728
729 case TargetOpcode::EH_LABEL:
730 case TargetOpcode::GC_LABEL:
731 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
732 break;
733 case TargetOpcode::INLINEASM:
734 EmitInlineAsm(II);
735 break;
736 case TargetOpcode::DBG_VALUE:
737 if (isVerbose()) {
738 if (!emitDebugValueComment(II, *this))
739 EmitInstruction(II);
740 }
741 break;
742 case TargetOpcode::IMPLICIT_DEF:
743 if (isVerbose()) emitImplicitDef(II);
744 break;
745 case TargetOpcode::KILL:
746 if (isVerbose()) emitKill(II, *this);
747 break;
748 default:
749 if (!TM.hasMCUseLoc())
750 MCLineEntry::Make(&OutStreamer, getCurrentSection());
751
752 EmitInstruction(II);
753 break;
754 }
755
756 if (ShouldPrintDebugScopes) {
757 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
758 DD->endInstruction(II);
759 }
760 }
761 }
762
763 // If the last instruction was a prolog label, then we have a situation where
764 // we emitted a prolog but no function body. This results in the ending prolog
765 // label equaling the end of function label and an invalid "row" in the
766 // FDE. We need to emit a noop in this situation so that the FDE's rows are
767 // valid.
768 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
769
770 // If the function is empty and the object file uses .subsections_via_symbols,
771 // then we need to emit *something* to the function body to prevent the
772 // labels from collapsing together. Just emit a noop.
773 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
774 MCInst Noop;
775 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
776 if (Noop.getOpcode()) {
777 OutStreamer.AddComment("avoids zero-length function");
778 OutStreamer.EmitInstruction(Noop);
779 } else // Target not mc-ized yet.
780 OutStreamer.EmitRawText(StringRef("\tnop\n"));
781 }
782
783 const Function *F = MF->getFunction();
784 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
785 const BasicBlock *BB = i;
786 if (!BB->hasAddressTaken())
787 continue;
788 MCSymbol *Sym = GetBlockAddressSymbol(BB);
789 if (Sym->isDefined())
790 continue;
791 OutStreamer.AddComment("Address of block that was removed by CodeGen");
792 OutStreamer.EmitLabel(Sym);
793 }
794
795 // Emit target-specific gunk after the function body.
796 EmitFunctionBodyEnd();
797
798 // If the target wants a .size directive for the size of the function, emit
799 // it.
800 if (MAI->hasDotTypeDotSizeDirective()) {
801 // Create a symbol for the end of function, so we can get the size as
802 // difference between the function label and the temp label.
803 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
804 OutStreamer.EmitLabel(FnEndLabel);
805
806 const MCExpr *SizeExp =
807 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
808 MCSymbolRefExpr::Create(CurrentFnSymForSize,
809 OutContext),
810 OutContext);
811 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
812 }
813
814 // Emit post-function debug information.
815 if (DD) {
816 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
817 DD->endFunction(MF);
818 }
819 if (DE) {
820 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
821 DE->EndFunction();
822 }
823 MMI->EndFunction();
824
825 // Print out jump tables referenced by the function.
826 EmitJumpTableInfo();
827
828 OutStreamer.AddBlankLine();
829}
830
831/// EmitDwarfRegOp - Emit dwarf register operation.
832void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
833 bool Indirect) const {
834 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
835 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
836
837 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
838 ++SR) {
839 Reg = TRI->getDwarfRegNum(*SR, false);
840 // FIXME: Get the bit range this register uses of the superregister
841 // so that we can produce a DW_OP_bit_piece
842 }
843
844 // FIXME: Handle cases like a super register being encoded as
845 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
846
847 // FIXME: We have no reasonable way of handling errors in here. The
848 // caller might be in the middle of an dwarf expression. We should
849 // probably assert that Reg >= 0 once debug info generation is more mature.
850
851 if (MLoc.isIndirect() || Indirect) {
852 if (Reg < 32) {
853 OutStreamer.AddComment(
854 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
855 EmitInt8(dwarf::DW_OP_breg0 + Reg);
856 } else {
857 OutStreamer.AddComment("DW_OP_bregx");
858 EmitInt8(dwarf::DW_OP_bregx);
859 OutStreamer.AddComment(Twine(Reg));
860 EmitULEB128(Reg);
861 }
862 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
863 if (MLoc.isIndirect() && Indirect)
864 EmitInt8(dwarf::DW_OP_deref);
865 } else {
866 if (Reg < 32) {
867 OutStreamer.AddComment(
868 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
869 EmitInt8(dwarf::DW_OP_reg0 + Reg);
870 } else {
871 OutStreamer.AddComment("DW_OP_regx");
872 EmitInt8(dwarf::DW_OP_regx);
873 OutStreamer.AddComment(Twine(Reg));
874 EmitULEB128(Reg);
875 }
876 }
877
878 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
879}
880
881bool AsmPrinter::doFinalization(Module &M) {
882 // Emit global variables.
883 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
884 I != E; ++I)
885 EmitGlobalVariable(I);
886
887 // Emit visibility info for declarations
888 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
889 const Function &F = *I;
890 if (!F.isDeclaration())
891 continue;
892 GlobalValue::VisibilityTypes V = F.getVisibility();
893 if (V == GlobalValue::DefaultVisibility)
894 continue;
895
896 MCSymbol *Name = getSymbol(&F);
897 EmitVisibility(Name, V, false);
898 }
899
900 // Emit module flags.
901 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
902 M.getModuleFlagsMetadata(ModuleFlags);
903 if (!ModuleFlags.empty())
904 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
905
906 // Make sure we wrote out everything we need.
907 OutStreamer.Flush();
908
909 // Finalize debug and EH information.
910 if (DE) {
911 {
912 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
913 DE->EndModule();
914 }
915 delete DE; DE = 0;
916 }
917 if (DD) {
918 {
919 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
920 DD->endModule();
921 }
922 delete DD; DD = 0;
923 }
924
925 // If the target wants to know about weak references, print them all.
926 if (MAI->getWeakRefDirective()) {
927 // FIXME: This is not lazy, it would be nice to only print weak references
928 // to stuff that is actually used. Note that doing so would require targets
929 // to notice uses in operands (due to constant exprs etc). This should
930 // happen with the MC stuff eventually.
931
932 // Print out module-level global variables here.
933 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
934 I != E; ++I) {
935 if (!I->hasExternalWeakLinkage()) continue;
936 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
937 }
938
939 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
940 if (!I->hasExternalWeakLinkage()) continue;
941 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
942 }
943 }
944
945 if (MAI->hasSetDirective()) {
946 OutStreamer.AddBlankLine();
947 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
948 I != E; ++I) {
949 MCSymbol *Name = getSymbol(I);
950
951 const GlobalValue *GV = I->getAliasedGlobal();
952 if (GV->isDeclaration()) {
953 report_fatal_error(Name->getName() +
954 ": Target doesn't support aliases to declarations");
955 }
956
957 MCSymbol *Target = getSymbol(GV);
958
959 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
960 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
961 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
962 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
963 else
964 assert(I->hasLocalLinkage() && "Invalid alias linkage");
965
966 EmitVisibility(Name, I->getVisibility());
967
968 // Emit the directives as assignments aka .set:
969 OutStreamer.EmitAssignment(Name,
970 MCSymbolRefExpr::Create(Target, OutContext));
971 }
972 }
973
974 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
975 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
976 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
977 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
978 MP->finishAssembly(*this);
979
980 // Emit llvm.ident metadata in an '.ident' directive.
981 EmitModuleIdents(M);
982
983 // If we don't have any trampolines, then we don't require stack memory
984 // to be executable. Some targets have a directive to declare this.
985 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
986 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
987 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
988 OutStreamer.SwitchSection(S);
989
990 // Allow the target to emit any magic that it wants at the end of the file,
991 // after everything else has gone out.
992 EmitEndOfAsmFile(M);
993
994 delete Mang; Mang = 0;
995 MMI = 0;
996
997 OutStreamer.Finish();
998 OutStreamer.reset();
999
1000 return false;
1001}
1002
1003void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1004 this->MF = &MF;
1005 // Get the function symbol.
1006 CurrentFnSym = getSymbol(MF.getFunction());
1007 CurrentFnSymForSize = CurrentFnSym;
1008
1009 if (isVerbose())
1010 LI = &getAnalysis<MachineLoopInfo>();
1011}
1012
1013namespace {
1014 // SectionCPs - Keep track the alignment, constpool entries per Section.
1015 struct SectionCPs {
1016 const MCSection *S;
1017 unsigned Alignment;
1018 SmallVector<unsigned, 4> CPEs;
1019 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1020 };
1021}
1022
1023/// EmitConstantPool - Print to the current output stream assembly
1024/// representations of the constants in the constant pool MCP. This is
1025/// used to print out constants which have been "spilled to memory" by
1026/// the code generator.
1027///
1028void AsmPrinter::EmitConstantPool() {
1029 const MachineConstantPool *MCP = MF->getConstantPool();
1030 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1031 if (CP.empty()) return;
1032
1033 // Calculate sections for constant pool entries. We collect entries to go into
1034 // the same section together to reduce amount of section switch statements.
1035 SmallVector<SectionCPs, 4> CPSections;
1036 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1037 const MachineConstantPoolEntry &CPE = CP[i];
1038 unsigned Align = CPE.getAlignment();
1039
1040 SectionKind Kind;
1041 switch (CPE.getRelocationInfo()) {
1042 default: llvm_unreachable("Unknown section kind");
1043 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1044 case 1:
1045 Kind = SectionKind::getReadOnlyWithRelLocal();
1046 break;
1047 case 0:
1048 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1049 case 4: Kind = SectionKind::getMergeableConst4(); break;
1050 case 8: Kind = SectionKind::getMergeableConst8(); break;
1051 case 16: Kind = SectionKind::getMergeableConst16();break;
1052 default: Kind = SectionKind::getMergeableConst(); break;
1053 }
1054 }
1055
1056 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1057
1058 // The number of sections are small, just do a linear search from the
1059 // last section to the first.
1060 bool Found = false;
1061 unsigned SecIdx = CPSections.size();
1062 while (SecIdx != 0) {
1063 if (CPSections[--SecIdx].S == S) {
1064 Found = true;
1065 break;
1066 }
1067 }
1068 if (!Found) {
1069 SecIdx = CPSections.size();
1070 CPSections.push_back(SectionCPs(S, Align));
1071 }
1072
1073 if (Align > CPSections[SecIdx].Alignment)
1074 CPSections[SecIdx].Alignment = Align;
1075 CPSections[SecIdx].CPEs.push_back(i);
1076 }
1077
1078 // Now print stuff into the calculated sections.
1079 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1080 OutStreamer.SwitchSection(CPSections[i].S);
1081 EmitAlignment(Log2_32(CPSections[i].Alignment));
1082
1083 unsigned Offset = 0;
1084 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1085 unsigned CPI = CPSections[i].CPEs[j];
1086 MachineConstantPoolEntry CPE = CP[CPI];
1087
1088 // Emit inter-object padding for alignment.
1089 unsigned AlignMask = CPE.getAlignment() - 1;
1090 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1091 OutStreamer.EmitZeros(NewOffset - Offset);
1092
1093 Type *Ty = CPE.getType();
1094 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1095 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1096
1097 if (CPE.isMachineConstantPoolEntry())
1098 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1099 else
1100 EmitGlobalConstant(CPE.Val.ConstVal);
1101 }
1102 }
1103}
1104
1105/// EmitJumpTableInfo - Print assembly representations of the jump tables used
1106/// by the current function to the current output stream.
1107///
1108void AsmPrinter::EmitJumpTableInfo() {
1109 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1110 if (MJTI == 0) return;
1111 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1112 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1113 if (JT.empty()) return;
1114
1115 // Pick the directive to use to print the jump table entries, and switch to
1116 // the appropriate section.
1117 const Function *F = MF->getFunction();
1118 bool JTInDiffSection = false;
1119 if (// In PIC mode, we need to emit the jump table to the same section as the
1120 // function body itself, otherwise the label differences won't make sense.
1121 // FIXME: Need a better predicate for this: what about custom entries?
1122 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1123 // We should also do if the section name is NULL or function is declared
1124 // in discardable section
1125 // FIXME: this isn't the right predicate, should be based on the MCSection
1126 // for the function.
1127 F->isWeakForLinker()) {
1128 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1129 } else {
1130 // Otherwise, drop it in the readonly section.
1131 const MCSection *ReadOnlySection =
1132 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1133 OutStreamer.SwitchSection(ReadOnlySection);
1134 JTInDiffSection = true;
1135 }
1136
1137 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1138
1139 // Jump tables in code sections are marked with a data_region directive
1140 // where that's supported.
1141 if (!JTInDiffSection)
1142 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1143
1144 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1145 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1146
1147 // If this jump table was deleted, ignore it.
1148 if (JTBBs.empty()) continue;
1149
1150 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1151 // .set directive for each unique entry. This reduces the number of
1152 // relocations the assembler will generate for the jump table.
1153 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1154 MAI->hasSetDirective()) {
1155 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1156 const TargetLowering *TLI = TM.getTargetLowering();
1157 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1158 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1159 const MachineBasicBlock *MBB = JTBBs[ii];
1160 if (!EmittedSets.insert(MBB)) continue;
1161
1162 // .set LJTSet, LBB32-base
1163 const MCExpr *LHS =
1164 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1165 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1166 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1167 }
1168 }
1169
1170 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1171 // before each jump table. The first label is never referenced, but tells
1172 // the assembler and linker the extents of the jump table object. The
1173 // second label is actually referenced by the code.
1174 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1175 // FIXME: This doesn't have to have any specific name, just any randomly
1176 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1177 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1178
1179 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1180
1181 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1182 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1183 }
1184 if (!JTInDiffSection)
1185 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1186}
1187
1188/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1189/// current stream.
1190void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1191 const MachineBasicBlock *MBB,
1192 unsigned UID) const {
1193 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1194 const MCExpr *Value = 0;
1195 switch (MJTI->getEntryKind()) {
1196 case MachineJumpTableInfo::EK_Inline:
1197 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1198 case MachineJumpTableInfo::EK_Custom32:
1199 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1200 OutContext);
1201 break;
1202 case MachineJumpTableInfo::EK_BlockAddress:
1203 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1204 // .word LBB123
1205 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1206 break;
1207 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1208 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1209 // with a relocation as gp-relative, e.g.:
1210 // .gprel32 LBB123
1211 MCSymbol *MBBSym = MBB->getSymbol();
1212 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1213 return;
1214 }
1215
1216 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1217 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1218 // with a relocation as gp-relative, e.g.:
1219 // .gpdword LBB123
1220 MCSymbol *MBBSym = MBB->getSymbol();
1221 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1222 return;
1223 }
1224
1225 case MachineJumpTableInfo::EK_LabelDifference32: {
1226 // EK_LabelDifference32 - Each entry is the address of the block minus
1227 // the address of the jump table. This is used for PIC jump tables where
1228 // gprel32 is not supported. e.g.:
1229 // .word LBB123 - LJTI1_2
1230 // If the .set directive is supported, this is emitted as:
1231 // .set L4_5_set_123, LBB123 - LJTI1_2
1232 // .word L4_5_set_123
1233
1234 // If we have emitted set directives for the jump table entries, print
1235 // them rather than the entries themselves. If we're emitting PIC, then
1236 // emit the table entries as differences between two text section labels.
1237 if (MAI->hasSetDirective()) {
1238 // If we used .set, reference the .set's symbol.
1239 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1240 OutContext);
1241 break;
1242 }
1243 // Otherwise, use the difference as the jump table entry.
1244 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1245 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1246 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1247 break;
1248 }
1249 }
1250
1251 assert(Value && "Unknown entry kind!");
1252
1253 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1254 OutStreamer.EmitValue(Value, EntrySize);
1255}
1256
1257
1258/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1259/// special global used by LLVM. If so, emit it and return true, otherwise
1260/// do nothing and return false.
1261bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1262 if (GV->getName() == "llvm.used") {
1263 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1264 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1265 return true;
1266 }
1267
1268 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1269 if (GV->getSection() == "llvm.metadata" ||
1270 GV->hasAvailableExternallyLinkage())
1271 return true;
1272
1273 if (!GV->hasAppendingLinkage()) return false;
1274
1275 assert(GV->hasInitializer() && "Not a special LLVM global!");
1276
1277 if (GV->getName() == "llvm.global_ctors") {
1278 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1279
1280 if (TM.getRelocationModel() == Reloc::Static &&
1281 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1282 StringRef Sym(".constructors_used");
1283 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1284 MCSA_Reference);
1285 }
1286 return true;
1287 }
1288
1289 if (GV->getName() == "llvm.global_dtors") {
1290 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1291
1292 if (TM.getRelocationModel() == Reloc::Static &&
1293 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1294 StringRef Sym(".destructors_used");
1295 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1296 MCSA_Reference);
1297 }
1298 return true;
1299 }
1300
1301 return false;
1302}
1303
1304/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1305/// global in the specified llvm.used list for which emitUsedDirectiveFor
1306/// is true, as being used with this directive.
1307void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1308 // Should be an array of 'i8*'.
1309 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1310 const GlobalValue *GV =
1311 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1312 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1313 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1314 }
1315}
1316
1317/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1318/// priority.
1319void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1320 // Should be an array of '{ int, void ()* }' structs. The first value is the
1321 // init priority.
1322 if (!isa<ConstantArray>(List)) return;
1323
1324 // Sanity check the structors list.
1325 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1326 if (!InitList) return; // Not an array!
1327 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1328 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1329 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1330 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1331
1332 // Gather the structors in a form that's convenient for sorting by priority.
1333 typedef std::pair<unsigned, Constant *> Structor;
1334 SmallVector<Structor, 8> Structors;
1335 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1336 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1337 if (!CS) continue; // Malformed.
1338 if (CS->getOperand(1)->isNullValue())
1339 break; // Found a null terminator, skip the rest.
1340 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1341 if (!Priority) continue; // Malformed.
1342 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1343 CS->getOperand(1)));
1344 }
1345
1346 // Emit the function pointers in the target-specific order
1347 const DataLayout *DL = TM.getDataLayout();
1348 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1349 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1350 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1351 const MCSection *OutputSection =
1352 (isCtor ?
1353 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1354 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1355 OutStreamer.SwitchSection(OutputSection);
1356 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1357 EmitAlignment(Align);
1358 EmitXXStructor(Structors[i].second);
1359 }
1360}
1361
1362void AsmPrinter::EmitModuleIdents(Module &M) {
1363 if (!MAI->hasIdentDirective())
1364 return;
1365
1366 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1367 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1368 const MDNode *N = NMD->getOperand(i);
1369 assert(N->getNumOperands() == 1 &&
1370 "llvm.ident metadata entry can have only one operand");
1371 const MDString *S = cast<MDString>(N->getOperand(0));
1372 OutStreamer.EmitIdent(S->getString());
1373 }
1374 }
1375}
1376
1377//===--------------------------------------------------------------------===//
1378// Emission and print routines
1379//
1380
1381/// EmitInt8 - Emit a byte directive and value.
1382///
1383void AsmPrinter::EmitInt8(int Value) const {
1384 OutStreamer.EmitIntValue(Value, 1);
1385}
1386
1387/// EmitInt16 - Emit a short directive and value.
1388///
1389void AsmPrinter::EmitInt16(int Value) const {
1390 OutStreamer.EmitIntValue(Value, 2);
1391}
1392
1393/// EmitInt32 - Emit a long directive and value.
1394///
1395void AsmPrinter::EmitInt32(int Value) const {
1396 OutStreamer.EmitIntValue(Value, 4);
1397}
1398
1399/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1400/// in bytes of the directive is specified by Size and Hi/Lo specify the
1401/// labels. This implicitly uses .set if it is available.
1402void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1403 unsigned Size) const {
1404 // Get the Hi-Lo expression.
1405 const MCExpr *Diff =
1406 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1407 MCSymbolRefExpr::Create(Lo, OutContext),
1408 OutContext);
1409
1410 if (!MAI->hasSetDirective()) {
1411 OutStreamer.EmitValue(Diff, Size);
1412 return;
1413 }
1414
1415 // Otherwise, emit with .set (aka assignment).
1416 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1417 OutStreamer.EmitAssignment(SetLabel, Diff);
1418 OutStreamer.EmitSymbolValue(SetLabel, Size);
1419}
1420
1421/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1422/// where the size in bytes of the directive is specified by Size and Hi/Lo
1423/// specify the labels. This implicitly uses .set if it is available.
1424void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1425 const MCSymbol *Lo, unsigned Size)
1426 const {
1427
1428 // Emit Hi+Offset - Lo
1429 // Get the Hi+Offset expression.
1430 const MCExpr *Plus =
1431 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1432 MCConstantExpr::Create(Offset, OutContext),
1433 OutContext);
1434
1435 // Get the Hi+Offset-Lo expression.
1436 const MCExpr *Diff =
1437 MCBinaryExpr::CreateSub(Plus,
1438 MCSymbolRefExpr::Create(Lo, OutContext),
1439 OutContext);
1440
1441 if (!MAI->hasSetDirective())
1442 OutStreamer.EmitValue(Diff, Size);
1443 else {
1444 // Otherwise, emit with .set (aka assignment).
1445 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1446 OutStreamer.EmitAssignment(SetLabel, Diff);
1447 OutStreamer.EmitSymbolValue(SetLabel, Size);
1448 }
1449}
1450
1451/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1452/// where the size in bytes of the directive is specified by Size and Label
1453/// specifies the label. This implicitly uses .set if it is available.
1454void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1455 unsigned Size, bool IsSectionRelative)
1456 const {
1457 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1458 OutStreamer.EmitCOFFSecRel32(Label);
1459 return;
1460 }
1461
1462 // Emit Label+Offset (or just Label if Offset is zero)
1463 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1464 if (Offset)
1465 Expr = MCBinaryExpr::CreateAdd(Expr,
1466 MCConstantExpr::Create(Offset, OutContext),
1467 OutContext);
1468
1469 OutStreamer.EmitValue(Expr, Size);
1470}
1471
1472
1473//===----------------------------------------------------------------------===//
1474
1475// EmitAlignment - Emit an alignment directive to the specified power of
1476// two boundary. For example, if you pass in 3 here, you will get an 8
1477// byte alignment. If a global value is specified, and if that global has
1478// an explicit alignment requested, it will override the alignment request
1479// if required for correctness.
1480//
1481void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1482 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1483
1484 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1485
1486 if (getCurrentSection()->getKind().isText())
1487 OutStreamer.EmitCodeAlignment(1 << NumBits);
1488 else
1489 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1490}
1491
1492//===----------------------------------------------------------------------===//
1493// Constant emission.
1494//===----------------------------------------------------------------------===//
1495
1496/// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1497///
1498static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1499 MCContext &Ctx = AP.OutContext;
1500
1501 if (CV->isNullValue() || isa<UndefValue>(CV))
1502 return MCConstantExpr::Create(0, Ctx);
1503
1504 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1505 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1506
1507 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1508 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1509
1510 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1511 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1512
1513 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1514 if (CE == 0) {
1515 llvm_unreachable("Unknown constant value to lower!");
1516 }
1517
1518 switch (CE->getOpcode()) {
1519 default:
1520 // If the code isn't optimized, there may be outstanding folding
1521 // opportunities. Attempt to fold the expression using DataLayout as a
1522 // last resort before giving up.
1523 if (Constant *C =
1524 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1525 if (C != CE)
1526 return lowerConstant(C, AP);
1527
1528 // Otherwise report the problem to the user.
1529 {
1530 std::string S;
1531 raw_string_ostream OS(S);
1532 OS << "Unsupported expression in static initializer: ";
1533 WriteAsOperand(OS, CE, /*PrintType=*/false,
1534 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1535 report_fatal_error(OS.str());
1536 }
1537 case Instruction::GetElementPtr: {
1538 const DataLayout &DL = *AP.TM.getDataLayout();
1539 // Generate a symbolic expression for the byte address
1540 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1541 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1542
1543 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1544 if (!OffsetAI)
1545 return Base;
1546
1547 int64_t Offset = OffsetAI.getSExtValue();
1548 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1549 Ctx);
1550 }
1551
1552 case Instruction::Trunc:
1553 // We emit the value and depend on the assembler to truncate the generated
1554 // expression properly. This is important for differences between
1555 // blockaddress labels. Since the two labels are in the same function, it
1556 // is reasonable to treat their delta as a 32-bit value.
1557 // FALL THROUGH.
1558 case Instruction::BitCast:
1559 return lowerConstant(CE->getOperand(0), AP);
1560
1561 case Instruction::IntToPtr: {
1562 const DataLayout &DL = *AP.TM.getDataLayout();
1563 // Handle casts to pointers by changing them into casts to the appropriate
1564 // integer type. This promotes constant folding and simplifies this code.
1565 Constant *Op = CE->getOperand(0);
1566 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1567 false/*ZExt*/);
1568 return lowerConstant(Op, AP);
1569 }
1570
1571 case Instruction::PtrToInt: {
1572 const DataLayout &DL = *AP.TM.getDataLayout();
1573 // Support only foldable casts to/from pointers that can be eliminated by
1574 // changing the pointer to the appropriately sized integer type.
1575 Constant *Op = CE->getOperand(0);
1576 Type *Ty = CE->getType();
1577
1578 const MCExpr *OpExpr = lowerConstant(Op, AP);
1579
1580 // We can emit the pointer value into this slot if the slot is an
1581 // integer slot equal to the size of the pointer.
1582 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1583 return OpExpr;
1584
1585 // Otherwise the pointer is smaller than the resultant integer, mask off
1586 // the high bits so we are sure to get a proper truncation if the input is
1587 // a constant expr.
1588 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1589 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1590 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1591 }
1592
1593 // The MC library also has a right-shift operator, but it isn't consistently
1594 // signed or unsigned between different targets.
1595 case Instruction::Add:
1596 case Instruction::Sub:
1597 case Instruction::Mul:
1598 case Instruction::SDiv:
1599 case Instruction::SRem:
1600 case Instruction::Shl:
1601 case Instruction::And:
1602 case Instruction::Or:
1603 case Instruction::Xor: {
1604 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1605 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1606 switch (CE->getOpcode()) {
1607 default: llvm_unreachable("Unknown binary operator constant cast expr");
1608 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1609 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1610 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1611 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1612 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1613 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1614 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1615 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1616 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1617 }
1618 }
1619 }
1620}
1621
1622static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1623
1624/// isRepeatedByteSequence - Determine whether the given value is
1625/// composed of a repeated sequence of identical bytes and return the
1626/// byte value. If it is not a repeated sequence, return -1.
1627static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1628 StringRef Data = V->getRawDataValues();
1629 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1630 char C = Data[0];
1631 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1632 if (Data[i] != C) return -1;
1633 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1634}
1635
1636
1637/// isRepeatedByteSequence - Determine whether the given value is
1638/// composed of a repeated sequence of identical bytes and return the
1639/// byte value. If it is not a repeated sequence, return -1.
1640static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1641
1642 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1643 if (CI->getBitWidth() > 64) return -1;
1644
1645 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1646 uint64_t Value = CI->getZExtValue();
1647
1648 // Make sure the constant is at least 8 bits long and has a power
1649 // of 2 bit width. This guarantees the constant bit width is
1650 // always a multiple of 8 bits, avoiding issues with padding out
1651 // to Size and other such corner cases.
1652 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1653
1654 uint8_t Byte = static_cast<uint8_t>(Value);
1655
1656 for (unsigned i = 1; i < Size; ++i) {
1657 Value >>= 8;
1658 if (static_cast<uint8_t>(Value) != Byte) return -1;
1659 }
1660 return Byte;
1661 }
1662 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1663 // Make sure all array elements are sequences of the same repeated
1664 // byte.
1665 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1666 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1667 if (Byte == -1) return -1;
1668
1669 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1670 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1671 if (ThisByte == -1) return -1;
1672 if (Byte != ThisByte) return -1;
1673 }
1674 return Byte;
1675 }
1676
1677 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1678 return isRepeatedByteSequence(CDS);
1679
1680 return -1;
1681}
1682
1683static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1684 AsmPrinter &AP){
1685
1686 // See if we can aggregate this into a .fill, if so, emit it as such.
1687 int Value = isRepeatedByteSequence(CDS, AP.TM);
1688 if (Value != -1) {
1689 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1690 // Don't emit a 1-byte object as a .fill.
1691 if (Bytes > 1)
1692 return AP.OutStreamer.EmitFill(Bytes, Value);
1693 }
1694
1695 // If this can be emitted with .ascii/.asciz, emit it as such.
1696 if (CDS->isString())
1697 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1698
1699 // Otherwise, emit the values in successive locations.
1700 unsigned ElementByteSize = CDS->getElementByteSize();
1701 if (isa<IntegerType>(CDS->getElementType())) {
1702 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1703 if (AP.isVerbose())
1704 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1705 CDS->getElementAsInteger(i));
1706 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1707 ElementByteSize);
1708 }
1709 } else if (ElementByteSize == 4) {
1710 // FP Constants are printed as integer constants to avoid losing
1711 // precision.
1712 assert(CDS->getElementType()->isFloatTy());
1713 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1714 union {
1715 float F;
1716 uint32_t I;
1717 };
1718
1719 F = CDS->getElementAsFloat(i);
1720 if (AP.isVerbose())
1721 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1722 AP.OutStreamer.EmitIntValue(I, 4);
1723 }
1724 } else {
1725 assert(CDS->getElementType()->isDoubleTy());
1726 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1727 union {
1728 double F;
1729 uint64_t I;
1730 };
1731
1732 F = CDS->getElementAsDouble(i);
1733 if (AP.isVerbose())
1734 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1735 AP.OutStreamer.EmitIntValue(I, 8);
1736 }
1737 }
1738
1739 const DataLayout &DL = *AP.TM.getDataLayout();
1740 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1741 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1742 CDS->getNumElements();
1743 if (unsigned Padding = Size - EmittedSize)
1744 AP.OutStreamer.EmitZeros(Padding);
1745
1746}
1747
1748static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1749 // See if we can aggregate some values. Make sure it can be
1750 // represented as a series of bytes of the constant value.
1751 int Value = isRepeatedByteSequence(CA, AP.TM);
1752
1753 if (Value != -1) {
1754 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1755 AP.OutStreamer.EmitFill(Bytes, Value);
1756 }
1757 else {
1758 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1759 emitGlobalConstantImpl(CA->getOperand(i), AP);
1760 }
1761}
1762
1763static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1764 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1765 emitGlobalConstantImpl(CV->getOperand(i), AP);
1766
1767 const DataLayout &DL = *AP.TM.getDataLayout();
1768 unsigned Size = DL.getTypeAllocSize(CV->getType());
1769 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1770 CV->getType()->getNumElements();
1771 if (unsigned Padding = Size - EmittedSize)
1772 AP.OutStreamer.EmitZeros(Padding);
1773}
1774
1775static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1776 // Print the fields in successive locations. Pad to align if needed!
1777 const DataLayout *DL = AP.TM.getDataLayout();
1778 unsigned Size = DL->getTypeAllocSize(CS->getType());
1779 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1780 uint64_t SizeSoFar = 0;
1781 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1782 const Constant *Field = CS->getOperand(i);
1783
1784 // Check if padding is needed and insert one or more 0s.
1785 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1786 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1787 - Layout->getElementOffset(i)) - FieldSize;
1788 SizeSoFar += FieldSize + PadSize;
1789
1790 // Now print the actual field value.
1791 emitGlobalConstantImpl(Field, AP);
1792
1793 // Insert padding - this may include padding to increase the size of the
1794 // current field up to the ABI size (if the struct is not packed) as well
1795 // as padding to ensure that the next field starts at the right offset.
1796 AP.OutStreamer.EmitZeros(PadSize);
1797 }
1798 assert(SizeSoFar == Layout->getSizeInBytes() &&
1799 "Layout of constant struct may be incorrect!");
1800}
1801
1802static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1803 APInt API = CFP->getValueAPF().bitcastToAPInt();
1804
1805 // First print a comment with what we think the original floating-point value
1806 // should have been.
1807 if (AP.isVerbose()) {
1808 SmallString<8> StrVal;
1809 CFP->getValueAPF().toString(StrVal);
1810
1811 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1812 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1813 }
1814
1815 // Now iterate through the APInt chunks, emitting them in endian-correct
1816 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1817 // floats).
1818 unsigned NumBytes = API.getBitWidth() / 8;
1819 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1820 const uint64_t *p = API.getRawData();
1821
1822 // PPC's long double has odd notions of endianness compared to how LLVM
1823 // handles it: p[0] goes first for *big* endian on PPC.
1824 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1825 int Chunk = API.getNumWords() - 1;
1826
1827 if (TrailingBytes)
1828 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1829
1830 for (; Chunk >= 0; --Chunk)
1831 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1832 } else {
1833 unsigned Chunk;
1834 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1835 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1836
1837 if (TrailingBytes)
1838 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1839 }
1840
1841 // Emit the tail padding for the long double.
1842 const DataLayout &DL = *AP.TM.getDataLayout();
1843 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1844 DL.getTypeStoreSize(CFP->getType()));
1845}
1846
1847static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1848 const DataLayout *DL = AP.TM.getDataLayout();
1849 unsigned BitWidth = CI->getBitWidth();
1850
1851 // Copy the value as we may massage the layout for constants whose bit width
1852 // is not a multiple of 64-bits.
1853 APInt Realigned(CI->getValue());
1854 uint64_t ExtraBits = 0;
1855 unsigned ExtraBitsSize = BitWidth & 63;
1856
1857 if (ExtraBitsSize) {
1858 // The bit width of the data is not a multiple of 64-bits.
1859 // The extra bits are expected to be at the end of the chunk of the memory.
1860 // Little endian:
1861 // * Nothing to be done, just record the extra bits to emit.
1862 // Big endian:
1863 // * Record the extra bits to emit.
1864 // * Realign the raw data to emit the chunks of 64-bits.
1865 if (DL->isBigEndian()) {
1866 // Basically the structure of the raw data is a chunk of 64-bits cells:
1867 // 0 1 BitWidth / 64
1868 // [chunk1][chunk2] ... [chunkN].
1869 // The most significant chunk is chunkN and it should be emitted first.
1870 // However, due to the alignment issue chunkN contains useless bits.
1871 // Realign the chunks so that they contain only useless information:
1872 // ExtraBits 0 1 (BitWidth / 64) - 1
1873 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1874 ExtraBits = Realigned.getRawData()[0] &
1875 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1876 Realigned = Realigned.lshr(ExtraBitsSize);
1877 } else
1878 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1879 }
1880
1881 // We don't expect assemblers to support integer data directives
1882 // for more than 64 bits, so we emit the data in at most 64-bit
1883 // quantities at a time.
1884 const uint64_t *RawData = Realigned.getRawData();
1885 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1886 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1887 AP.OutStreamer.EmitIntValue(Val, 8);
1888 }
1889
1890 if (ExtraBitsSize) {
1891 // Emit the extra bits after the 64-bits chunks.
1892
1893 // Emit a directive that fills the expected size.
1894 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1895 Size -= (BitWidth / 64) * 8;
1896 assert(Size && Size * 8 >= ExtraBitsSize &&
1897 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1898 == ExtraBits && "Directive too small for extra bits.");
1899 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1900 }
1901}
1902
1903static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1904 const DataLayout *DL = AP.TM.getDataLayout();
1905 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1906 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1907 return AP.OutStreamer.EmitZeros(Size);
1908
1909 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1910 switch (Size) {
1911 case 1:
1912 case 2:
1913 case 4:
1914 case 8:
1915 if (AP.isVerbose())
1916 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1917 CI->getZExtValue());
1918 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1919 return;
1920 default:
1921 emitGlobalConstantLargeInt(CI, AP);
1922 return;
1923 }
1924 }
1925
1926 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1927 return emitGlobalConstantFP(CFP, AP);
1928
1929 if (isa<ConstantPointerNull>(CV)) {
1930 AP.OutStreamer.EmitIntValue(0, Size);
1931 return;
1932 }
1933
1934 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1935 return emitGlobalConstantDataSequential(CDS, AP);
1936
1937 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1938 return emitGlobalConstantArray(CVA, AP);
1939
1940 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1941 return emitGlobalConstantStruct(CVS, AP);
1942
1943 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1944 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1945 // vectors).
1946 if (CE->getOpcode() == Instruction::BitCast)
1947 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1948
1949 if (Size > 8) {
1950 // If the constant expression's size is greater than 64-bits, then we have
1951 // to emit the value in chunks. Try to constant fold the value and emit it
1952 // that way.
1953 Constant *New = ConstantFoldConstantExpression(CE, DL);
1954 if (New && New != CE)
1955 return emitGlobalConstantImpl(New, AP);
1956 }
1957 }
1958
1959 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1960 return emitGlobalConstantVector(V, AP);
1961
1962 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1963 // thread the streamer with EmitValue.
1964 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1965}
1966
1967/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1968void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1969 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1970 if (Size)
1971 emitGlobalConstantImpl(CV, *this);
1972 else if (MAI->hasSubsectionsViaSymbols()) {
1973 // If the global has zero size, emit a single byte so that two labels don't
1974 // look like they are at the same location.
1975 OutStreamer.EmitIntValue(0, 1);
1976 }
1977}
1978
1979void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1980 // Target doesn't support this yet!
1981 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1982}
1983
1984void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1985 if (Offset > 0)
1986 OS << '+' << Offset;
1987 else if (Offset < 0)
1988 OS << Offset;
1989}
1990
1991//===----------------------------------------------------------------------===//
1992// Symbol Lowering Routines.
1993//===----------------------------------------------------------------------===//
1994
1995/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1996/// temporary label with the specified stem and unique ID.
1997MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1998 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1999 Name + Twine(ID));
2000}
2001
2002/// GetTempSymbol - Return an assembler temporary label with the specified
2003/// stem.
2004MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2005 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
2006 Name);
2007}
2008
2009
2010MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2011 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2012}
2013
2014MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2015 return MMI->getAddrLabelSymbol(BB);
2016}
2017
2018/// GetCPISymbol - Return the symbol for the specified constant pool entry.
2019MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2020 return OutContext.GetOrCreateSymbol
2021 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2022 + "_" + Twine(CPID));
2023}
2024
2025/// GetJTISymbol - Return the symbol for the specified jump table entry.
2026MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2027 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2028}
2029
2030/// GetJTSetSymbol - Return the symbol for the specified jump table .set
2031/// FIXME: privatize to AsmPrinter.
2032MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2033 return OutContext.GetOrCreateSymbol
2034 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2035 Twine(UID) + "_set_" + Twine(MBBID));
2036}
2037
2038/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
2039/// global value name as its base, with the specified suffix, and where the
2040/// symbol is forced to have private linkage if ForcePrivate is true.
2041MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
2042 StringRef Suffix,
2043 bool ForcePrivate) const {
2044 SmallString<60> NameStr;
2045 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
2046 NameStr.append(Suffix.begin(), Suffix.end());
2047 return OutContext.GetOrCreateSymbol(NameStr.str());
2048}
2049
2050/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2051/// ExternalSymbol.
2052MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2053 SmallString<60> NameStr;
2054 Mang->getNameWithPrefix(NameStr, Sym);
2055 return OutContext.GetOrCreateSymbol(NameStr.str());
2056}
2057
2058
2059
2060/// PrintParentLoopComment - Print comments about parent loops of this one.
2061static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2062 unsigned FunctionNumber) {
2063 if (Loop == 0) return;
2064 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2065 OS.indent(Loop->getLoopDepth()*2)
2066 << "Parent Loop BB" << FunctionNumber << "_"
2067 << Loop->getHeader()->getNumber()
2068 << " Depth=" << Loop->getLoopDepth() << '\n';
2069}
2070
2071
2072/// PrintChildLoopComment - Print comments about child loops within
2073/// the loop for this basic block, with nesting.
2074static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2075 unsigned FunctionNumber) {
2076 // Add child loop information
2077 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2078 OS.indent((*CL)->getLoopDepth()*2)
2079 << "Child Loop BB" << FunctionNumber << "_"
2080 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2081 << '\n';
2082 PrintChildLoopComment(OS, *CL, FunctionNumber);
2083 }
2084}
2085
2086/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2087static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2088 const MachineLoopInfo *LI,
2089 const AsmPrinter &AP) {
2090 // Add loop depth information
2091 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2092 if (Loop == 0) return;
2093
2094 MachineBasicBlock *Header = Loop->getHeader();
2095 assert(Header && "No header for loop");
2096
2097 // If this block is not a loop header, just print out what is the loop header
2098 // and return.
2099 if (Header != &MBB) {
2100 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2101 Twine(AP.getFunctionNumber())+"_" +
2102 Twine(Loop->getHeader()->getNumber())+
2103 " Depth="+Twine(Loop->getLoopDepth()));
2104 return;
2105 }
2106
2107 // Otherwise, it is a loop header. Print out information about child and
2108 // parent loops.
2109 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2110
2111 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2112
2113 OS << "=>";
2114 OS.indent(Loop->getLoopDepth()*2-2);
2115
2116 OS << "This ";
2117 if (Loop->empty())
2118 OS << "Inner ";
2119 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2120
2121 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2122}
2123
2124
2125/// EmitBasicBlockStart - This method prints the label for the specified
2126/// MachineBasicBlock, an alignment (if present) and a comment describing
2127/// it if appropriate.
2128void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2129 // Emit an alignment directive for this block, if needed.
2130 if (unsigned Align = MBB->getAlignment())
2131 EmitAlignment(Align);
2132
2133 // If the block has its address taken, emit any labels that were used to
2134 // reference the block. It is possible that there is more than one label
2135 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2136 // the references were generated.
2137 if (MBB->hasAddressTaken()) {
2138 const BasicBlock *BB = MBB->getBasicBlock();
2139 if (isVerbose())
2140 OutStreamer.AddComment("Block address taken");
2141
2142 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2143
2144 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2145 OutStreamer.EmitLabel(Syms[i]);
2146 }
2147
2148 // Print some verbose block comments.
2149 if (isVerbose()) {
2150 if (const BasicBlock *BB = MBB->getBasicBlock())
2151 if (BB->hasName())
2152 OutStreamer.AddComment("%" + BB->getName());
2153 emitBasicBlockLoopComments(*MBB, LI, *this);
2154 }
2155
2156 // Print the main label for the block.
2157 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2158 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2159 // NOTE: Want this comment at start of line, don't emit with AddComment.
2160 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2161 Twine(MBB->getNumber()) + ":");
2162 }
2163 } else {
2164 OutStreamer.EmitLabel(MBB->getSymbol());
2165 }
2166}
2167
2168void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2169 bool IsDefinition) const {
2170 MCSymbolAttr Attr = MCSA_Invalid;
2171
2172 switch (Visibility) {
2173 default: break;
2174 case GlobalValue::HiddenVisibility:
2175 if (IsDefinition)
2176 Attr = MAI->getHiddenVisibilityAttr();
2177 else
2178 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2179 break;
2180 case GlobalValue::ProtectedVisibility:
2181 Attr = MAI->getProtectedVisibilityAttr();
2182 break;
2183 }
2184
2185 if (Attr != MCSA_Invalid)
2186 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2187}
2188
2189/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2190/// exactly one predecessor and the control transfer mechanism between
2191/// the predecessor and this block is a fall-through.
2192bool AsmPrinter::
2193isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2194 // If this is a landing pad, it isn't a fall through. If it has no preds,
2195 // then nothing falls through to it.
2196 if (MBB->isLandingPad() || MBB->pred_empty())
2197 return false;
2198
2199 // If there isn't exactly one predecessor, it can't be a fall through.
2200 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2201 ++PI2;
2202 if (PI2 != MBB->pred_end())
2203 return false;
2204
2205 // The predecessor has to be immediately before this block.
2206 MachineBasicBlock *Pred = *PI;
2207
2208 if (!Pred->isLayoutSuccessor(MBB))
2209 return false;
2210
2211 // If the block is completely empty, then it definitely does fall through.
2212 if (Pred->empty())
2213 return true;
2214
2215 // Check the terminators in the previous blocks
2216 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2217 IE = Pred->end(); II != IE; ++II) {
2218 MachineInstr &MI = *II;
2219
2220 // If it is not a simple branch, we are in a table somewhere.
2221 if (!MI.isBranch() || MI.isIndirectBranch())
2222 return false;
2223
2224 // If we are the operands of one of the branches, this is not
2225 // a fall through.
2226 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2227 OE = MI.operands_end(); OI != OE; ++OI) {
2228 const MachineOperand& OP = *OI;
2229 if (OP.isJTI())
2230 return false;
2231 if (OP.isMBB() && OP.getMBB() == MBB)
2232 return false;
2233 }
2234 }
2235
2236 return true;
2237}
2238
2239
2240
2241GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2242 if (!S->usesMetadata())
2243 return 0;
2244
2245 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2246 gcp_map_type::iterator GCPI = GCMap.find(S);
2247 if (GCPI != GCMap.end())
2248 return GCPI->second;
2249
2250 const char *Name = S->getName().c_str();
2251
2252 for (GCMetadataPrinterRegistry::iterator
2253 I = GCMetadataPrinterRegistry::begin(),
2254 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2255 if (strcmp(Name, I->getName()) == 0) {
2256 GCMetadataPrinter *GMP = I->instantiate();
2257 GMP->S = S;
2258 GCMap.insert(std::make_pair(S, GMP));
2259 return GMP;
2260 }
2261
2262 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2263}