blob: c82c14f964ab333be4a4a7af167b787859163300 [file] [log] [blame]
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001//===-- 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"
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -070016#ifndef ANDROID_TARGET_BUILD
17# include "DwarfDebug.h"
18# include "DwarfException.h"
19#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -080020#include "llvm/Module.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080021#include "llvm/CodeGen/GCMetadataPrinter.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineJumpTableInfo.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/Analysis/ConstantFolding.h"
29#include "llvm/Analysis/DebugInfo.h"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070030#include "llvm/MC/MCAsmInfo.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080031#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCExpr.h"
33#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCSection.h"
35#include "llvm/MC/MCStreamer.h"
36#include "llvm/MC/MCSymbol.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080037#include "llvm/Target/Mangler.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetLoweringObjectFile.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080042#include "llvm/Target/TargetRegisterInfo.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080043#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/Statistic.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080045#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/Format.h"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070047#include "llvm/Support/Timer.h"
Shih-wei Liaoe4454322010-04-07 12:21:42 -070048#include <ctype.h>
Shih-wei Liaoe264f622010-02-10 11:10:31 -080049using namespace llvm;
50
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070051static const char *DWARFGroupName = "DWARF Emission";
52static const char *DbgTimerName = "DWARF Debug Writer";
53static const char *EHTimerName = "DWARF Exception Writer";
54
Shih-wei Liaoe264f622010-02-10 11:10:31 -080055STATISTIC(EmittedInsts, "Number of machine instrs printed");
56
57char AsmPrinter::ID = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070058
59typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
60static gcp_map_type &getGCMap(void *&P) {
61 if (P == 0)
62 P = new gcp_map_type();
63 return *(gcp_map_type*)P;
64}
65
66
Chris Lattner7516e9e2010-04-28 19:58:07 +000067/// getGVAlignmentLog2 - Return the alignment to use for the specified global
68/// value in log2 form. This rounds up to the preferred alignment if possible
69/// and legal.
70static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
71 unsigned InBits = 0) {
72 unsigned NumBits = 0;
73 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
74 NumBits = TD.getPreferredAlignmentLog(GVar);
75
76 // If InBits is specified, round it to it.
77 if (InBits > NumBits)
78 NumBits = InBits;
79
80 // If the GV has a specified alignment, take it into account.
81 if (GV->getAlignment() == 0)
82 return NumBits;
83
84 unsigned GVAlign = Log2_32(GV->getAlignment());
85
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())
89 NumBits = GVAlign;
90 return NumBits;
91}
92
93
94
95
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070096AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
Owen Anderson75693222010-08-06 18:33:48 +000097 : MachineFunctionPass(ID),
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070098 TM(tm), MAI(tm.getMCAsmInfo()),
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;
103 GCMetadataPrinters = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800104 VerboseAsm = Streamer.isVerboseAsm();
105}
106
107AsmPrinter::~AsmPrinter() {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700108 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
109
110 if (GCMetadataPrinters != 0) {
111 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
112
113 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
114 delete I->second;
115 delete &GCMap;
116 GCMetadataPrinters = 0;
117 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800118
119 delete &OutStreamer;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800120}
121
122/// getFunctionNumber - Return a unique ID for the current function.
123///
124unsigned AsmPrinter::getFunctionNumber() const {
125 return MF->getFunctionNumber();
126}
127
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700128const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800129 return TM.getTargetLowering()->getObjFileLowering();
130}
131
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700132
133/// getTargetData - Return information about data layout.
134const TargetData &AsmPrinter::getTargetData() const {
135 return *TM.getTargetData();
136}
137
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800138/// getCurrentSection() - Return the current section we are emitting to.
139const MCSection *AsmPrinter::getCurrentSection() const {
140 return OutStreamer.getCurrentSection();
141}
142
143
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700144
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800145void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
146 AU.setPreservesAll();
147 MachineFunctionPass::getAnalysisUsage(AU);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700148 AU.addRequired<MachineModuleInfo>();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800149 AU.addRequired<GCModuleInfo>();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700150 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800151 AU.addRequired<MachineLoopInfo>();
152}
153
154bool AsmPrinter::doInitialization(Module &M) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700155 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
156 MMI->AnalyzeModule(M);
157
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800158 // Initialize TargetLoweringObjectFile.
159 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
160 .Initialize(OutContext, TM);
161
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700162 Mang = new Mangler(OutContext, *TM.getTargetData());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800163
164 // Allow the target to emit any magic that it wants at the start of the file.
165 EmitStartOfAsmFile(M);
166
167 // Very minimal debug info. It is ignored if we emit actual debug info. If we
168 // don't, this at least helps the user find where a global came from.
169 if (MAI->hasSingleParameterDotFile()) {
170 // .file "foo.c"
171 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
172 }
173
174 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
175 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
176 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
177 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700178 MP->beginAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800179
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700180 // Emit module-level inline asm if it exists.
181 if (!M.getModuleInlineAsm().empty()) {
182 OutStreamer.AddComment("Start of file scope inline assembly");
183 OutStreamer.AddBlankLine();
Chris Lattnerd0c6a6b2010-07-15 00:37:34 +0000184 EmitInlineAsm(M.getModuleInlineAsm()+"\n", 0/*no loc cookie*/);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700185 OutStreamer.AddComment("End of file scope inline assembly");
186 OutStreamer.AddBlankLine();
187 }
188
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700189#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700190 if (MAI->doesSupportDebugInformation())
191 DD = new DwarfDebug(this, &M);
192
193 if (MAI->doesSupportExceptionHandling())
194 DE = new DwarfException(this);
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700195#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800196
197 return false;
198}
199
200void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
201 switch ((GlobalValue::LinkageTypes)Linkage) {
202 case GlobalValue::CommonLinkage:
203 case GlobalValue::LinkOnceAnyLinkage:
204 case GlobalValue::LinkOnceODRLinkage:
205 case GlobalValue::WeakAnyLinkage:
206 case GlobalValue::WeakODRLinkage:
Bill Wendlingf8239662010-07-01 21:55:59 +0000207 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling01085e62010-08-20 22:05:50 +0000208 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800209 if (MAI->getWeakDefDirective() != 0) {
210 // .globl _foo
211 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Bill Wendling01085e62010-08-20 22:05:50 +0000212
213 if ((GlobalValue::LinkageTypes)Linkage !=
214 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
215 // .weak_definition _foo
216 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
217 else
218 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
Duncan Sandsf01b62d2010-05-12 07:11:33 +0000219 } else if (MAI->getLinkOnceDirective() != 0) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800220 // .globl _foo
221 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Duncan Sandsf01b62d2010-05-12 07:11:33 +0000222 //NOTE: linkonce is handled by the section the symbol was assigned to.
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800223 } else {
224 // .weak _foo
225 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
226 }
227 break;
228 case GlobalValue::DLLExportLinkage:
229 case GlobalValue::AppendingLinkage:
230 // FIXME: appending linkage variables should go into a section of
231 // their name or something. For now, just emit them as external.
232 case GlobalValue::ExternalLinkage:
233 // If external or appending, declare as a global symbol.
234 // .globl _foo
235 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
236 break;
237 case GlobalValue::PrivateLinkage:
238 case GlobalValue::InternalLinkage:
Bill Wendling73b3a722010-07-01 22:38:24 +0000239 case GlobalValue::LinkerPrivateLinkage:
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800240 break;
241 default:
242 llvm_unreachable("Unknown linkage type!");
243 }
244}
245
246
247/// EmitGlobalVariable - Emit the specified global variable to the .s file.
248void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
249 if (!GV->hasInitializer()) // External globals require no code.
250 return;
251
252 // Check to see if this is a special global used by LLVM, if so, emit it.
253 if (EmitSpecialLLVMGlobal(GV))
254 return;
255
Eric Christopher3fe79fd2010-05-25 21:49:43 +0000256 if (isVerbose()) {
257 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
258 /*PrintType=*/false, GV->getParent());
259 OutStreamer.GetCommentOS() << '\n';
260 }
261
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700262 MCSymbol *GVSym = Mang->getSymbol(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800263 EmitVisibility(GVSym, GV->getVisibility());
264
265 if (MAI->hasDotTypeDotSizeDirective())
266 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
267
268 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
269
270 const TargetData *TD = TM.getTargetData();
Chris Lattner7516e9e2010-04-28 19:58:07 +0000271 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700272
273 // If the alignment is specified, we *must* obey it. Overaligning a global
274 // with a specified alignment is a prompt way to break globals emitted to
275 // sections and expected to be contiguous (e.g. ObjC metadata).
Chris Lattner7516e9e2010-04-28 19:58:07 +0000276 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800277
278 // Handle common and BSS local symbols (.lcomm).
279 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
280 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
281
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700282 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800283 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
284 /*PrintType=*/false, GV->getParent());
285 OutStreamer.GetCommentOS() << '\n';
286 }
287
288 // Handle common symbols.
289 if (GVKind.isCommon()) {
290 // .comm _foo, 42, 4
291 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
292 return;
293 }
294
295 // Handle local BSS symbols.
296 if (MAI->hasMachoZeroFillDirective()) {
297 const MCSection *TheSection =
298 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
299 // .zerofill __DATA, __bss, _foo, 400, 5
300 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
301 return;
302 }
303
304 if (MAI->hasLCOMMDirective()) {
305 // .lcomm _foo, 42
306 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
307 return;
308 }
309
310 // .local _foo
311 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
312 // .comm _foo, 42, 4
313 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
314 return;
315 }
316
317 const MCSection *TheSection =
318 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
319
320 // Handle the zerofill directive on darwin, which is a special form of BSS
321 // emission.
322 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
Chris Lattner0631a922010-04-27 07:41:44 +0000323 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
324
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800325 // .globl _foo
326 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
327 // .zerofill __DATA, __common, _foo, 400, 5
328 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
329 return;
330 }
Eric Christopher2d4ea3e2010-05-20 00:49:07 +0000331
Eric Christopherfdc794a2010-05-25 21:28:50 +0000332 // Handle thread local data for mach-o which requires us to output an
333 // additional structure of data and mangle the original symbol so that we
334 // can reference it later.
335 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
Eric Christopher0f986f62010-05-22 00:10:22 +0000336 // Emit the .tbss symbol
337 MCSymbol *MangSym =
338 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
Eric Christopherfdc794a2010-05-25 21:28:50 +0000339
340 if (GVKind.isThreadBSS())
341 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
342 else if (GVKind.isThreadData()) {
343 OutStreamer.SwitchSection(TheSection);
344
Eric Christopherfdc794a2010-05-25 21:28:50 +0000345 EmitAlignment(AlignLog, GV);
346 OutStreamer.EmitLabel(MangSym);
347
348 EmitGlobalConstant(GV->getInitializer());
349 }
350
Eric Christopher0f986f62010-05-22 00:10:22 +0000351 OutStreamer.AddBlankLine();
352
353 // Emit the variable struct for the runtime.
354 const MCSection *TLVSect
355 = getObjFileLowering().getTLSExtraDataSection();
356
357 OutStreamer.SwitchSection(TLVSect);
358 // Emit the linkage here.
359 EmitLinkage(GV->getLinkage(), GVSym);
360 OutStreamer.EmitLabel(GVSym);
361
362 // Three pointers in size:
363 // - __tlv_bootstrap - used to make sure support exists
364 // - spare pointer, used when mapped by the runtime
365 // - pointer to mangled symbol above with initializer
366 unsigned PtrSize = TD->getPointerSizeInBits()/8;
Eric Christopherdbf4b2d2010-06-03 04:02:59 +0000367 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
Eric Christopher0f986f62010-05-22 00:10:22 +0000368 PtrSize, 0);
369 OutStreamer.EmitIntValue(0, PtrSize, 0);
370 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
371
372 OutStreamer.AddBlankLine();
Eric Christopher2d4ea3e2010-05-20 00:49:07 +0000373 return;
374 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800375
376 OutStreamer.SwitchSection(TheSection);
377
378 EmitLinkage(GV->getLinkage(), GVSym);
379 EmitAlignment(AlignLog, GV);
380
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800381 OutStreamer.EmitLabel(GVSym);
382
383 EmitGlobalConstant(GV->getInitializer());
384
385 if (MAI->hasDotTypeDotSizeDirective())
386 // .size foo, 42
387 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
388
389 OutStreamer.AddBlankLine();
390}
391
392/// EmitFunctionHeader - This method emits the header for the current
393/// function.
394void AsmPrinter::EmitFunctionHeader() {
395 // Print out constants referenced by the function
396 EmitConstantPool();
397
398 // Print the 'header' of function.
399 const Function *F = MF->getFunction();
400
401 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
402 EmitVisibility(CurrentFnSym, F->getVisibility());
403
404 EmitLinkage(F->getLinkage(), CurrentFnSym);
405 EmitAlignment(MF->getAlignment(), F);
406
407 if (MAI->hasDotTypeDotSizeDirective())
408 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
409
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700410 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800411 WriteAsOperand(OutStreamer.GetCommentOS(), F,
412 /*PrintType=*/false, F->getParent());
413 OutStreamer.GetCommentOS() << '\n';
414 }
415
416 // Emit the CurrentFnSym. This is a virtual function to allow targets to
417 // do their wild and crazy things as required.
418 EmitFunctionEntryLabel();
419
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700420 // If the function had address-taken blocks that got deleted, then we have
421 // references to the dangling symbols. Emit them at the start of the function
422 // so that we don't get references to undefined symbols.
423 std::vector<MCSymbol*> DeadBlockSyms;
424 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
425 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
426 OutStreamer.AddComment("Address taken block that was later removed");
427 OutStreamer.EmitLabel(DeadBlockSyms[i]);
428 }
429
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800430 // Add some workaround for linkonce linkage on Cygwin\MinGW.
431 if (MAI->getLinkOnceDirective() != 0 &&
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700432 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800433 // FIXME: What is this?
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700434 MCSymbol *FakeStub =
435 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
436 CurrentFnSym->getName());
437 OutStreamer.EmitLabel(FakeStub);
438 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800439
440 // Emit pre-function debug and/or EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700441#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700442 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000443 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
444 DE->BeginFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700445 }
446 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000447 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
448 DD->beginFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700449 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700450#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800451}
452
453/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
454/// function. This can be overridden by targets as required to do custom stuff.
455void AsmPrinter::EmitFunctionEntryLabel() {
Chris Lattnerd095d342010-05-06 00:05:37 +0000456 // The function label could have already been emitted if two symbols end up
457 // conflicting due to asm renaming. Detect this and emit an error.
458 if (CurrentFnSym->isUndefined())
459 return OutStreamer.EmitLabel(CurrentFnSym);
460
461 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
462 "' label emitted multiple times to assembly file");
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800463}
464
465
Devang Patelabb79d92010-06-29 22:29:15 +0000466static void EmitDebugLoc(DebugLoc DL, const MachineFunction *MF,
467 raw_ostream &CommentOS) {
468 const LLVMContext &Ctx = MF->getFunction()->getContext();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700469 if (!DL.isUnknown()) { // Print source line info.
Devang Patelabb79d92010-06-29 22:29:15 +0000470 DIScope Scope(DL.getScope(Ctx));
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800471 // Omit the directory, because it's likely to be long and uninteresting.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700472 if (Scope.Verify())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800473 CommentOS << Scope.getFilename();
474 else
475 CommentOS << "<unknown>";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700476 CommentOS << ':' << DL.getLine();
477 if (DL.getCol() != 0)
478 CommentOS << ':' << DL.getCol();
Devang Patelabb79d92010-06-29 22:29:15 +0000479 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
480 if (!InlinedAtDL.isUnknown()) {
481 CommentOS << "[ ";
482 EmitDebugLoc(InlinedAtDL, MF, CommentOS);
483 CommentOS << " ]";
484 }
485 }
486}
487
488/// EmitComments - Pretty-print comments for instructions.
489static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
490 const MachineFunction *MF = MI.getParent()->getParent();
491 const TargetMachine &TM = MF->getTarget();
492
493 DebugLoc DL = MI.getDebugLoc();
494 if (!DL.isUnknown()) { // Print source line info.
495 EmitDebugLoc(DL, MF, CommentOS);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800496 CommentOS << '\n';
497 }
498
499 // Check for spills and reloads
500 int FI;
501
502 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
503
504 // We assume a single instruction only has a spill or reload, not
505 // both.
506 const MachineMemOperand *MMO;
507 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
508 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
509 MMO = *MI.memoperands_begin();
510 CommentOS << MMO->getSize() << "-byte Reload\n";
511 }
512 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
513 if (FrameInfo->isSpillSlotObjectIndex(FI))
514 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
515 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
516 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
517 MMO = *MI.memoperands_begin();
518 CommentOS << MMO->getSize() << "-byte Spill\n";
519 }
520 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
521 if (FrameInfo->isSpillSlotObjectIndex(FI))
522 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
523 }
524
525 // Check for spill-induced copies
Jakob Stoklund Olesendef3acb2010-07-16 04:45:42 +0000526 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
527 CommentOS << " Reload Reuse\n";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800528}
529
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700530/// EmitImplicitDef - This method emits the specified machine instruction
531/// that is an implicit def.
532static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
533 unsigned RegNo = MI->getOperand(0).getReg();
534 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
535 AP.TM.getRegisterInfo()->getName(RegNo));
536 AP.OutStreamer.AddBlankLine();
537}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800538
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700539static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
540 std::string Str = "kill:";
541 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
542 const MachineOperand &Op = MI->getOperand(i);
543 assert(Op.isReg() && "KILL instruction must have only register operands");
544 Str += ' ';
545 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
546 Str += (Op.isDef() ? "<def>" : "<kill>");
547 }
548 AP.OutStreamer.AddComment(Str);
549 AP.OutStreamer.AddBlankLine();
550}
551
552/// EmitDebugValueComment - This method handles the target-independent form
553/// of DBG_VALUE, returning true if it was able to do so. A false return
554/// means the target will need to handle MI in EmitInstruction.
555static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
556 // This code handles only the 3-operand target-independent form.
557 if (MI->getNumOperands() != 3)
558 return false;
559
560 SmallString<128> Str;
561 raw_svector_ostream OS(Str);
562 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
563
564 // cast away const; DIetc do not take const operands for some reason.
565 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
Devang Patel77defb52010-04-29 18:52:10 +0000566 if (V.getContext().isSubprogram())
Devang Patel19302aa2010-05-07 18:11:54 +0000567 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700568 OS << V.getName() << " <- ";
569
570 // Register or immediate value. Register 0 means undef.
571 if (MI->getOperand(0).isFPImm()) {
572 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
573 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
574 OS << (double)APF.convertToFloat();
575 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
576 OS << APF.convertToDouble();
577 } else {
578 // There is no good way to print long double. Convert a copy to
579 // double. Ah well, it's only a comment.
580 bool ignored;
581 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
582 &ignored);
583 OS << "(long double) " << APF.convertToDouble();
584 }
585 } else if (MI->getOperand(0).isImm()) {
586 OS << MI->getOperand(0).getImm();
587 } else {
588 assert(MI->getOperand(0).isReg() && "Unknown operand type");
589 if (MI->getOperand(0).getReg() == 0) {
590 // Suppress offset, it is not meaningful here.
591 OS << "undef";
592 // NOTE: Want this comment at start of line, don't emit with AddComment.
593 AP.OutStreamer.EmitRawText(OS.str());
594 return true;
595 }
596 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
597 }
598
599 OS << '+' << MI->getOperand(1).getImm();
600 // NOTE: Want this comment at start of line, don't emit with AddComment.
601 AP.OutStreamer.EmitRawText(OS.str());
602 return true;
603}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800604
605/// EmitFunctionBody - This method emits the body and trailer for a
606/// function.
607void AsmPrinter::EmitFunctionBody() {
608 // Emit target-specific gunk before the function body.
609 EmitFunctionBodyStart();
610
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700611 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
612
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800613 // Print out code for the function.
614 bool HasAnyRealCode = false;
Bill Wendling5a1bec12010-07-16 22:51:10 +0000615 const MachineInstr *LastMI = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800616 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
617 I != E; ++I) {
618 // Print a label for the basic block.
619 EmitBasicBlockStart(I);
620 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
621 II != IE; ++II) {
Bill Wendling5a1bec12010-07-16 22:51:10 +0000622 LastMI = II;
623
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800624 // Print the assembly for the instruction.
Dale Johannesen1ffdb1f2010-05-01 16:41:11 +0000625 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
626 !II->isDebugValue()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800627 HasAnyRealCode = true;
628
Evan Cheng53a0cbf2010-04-27 19:38:45 +0000629 ++EmittedInsts;
Shih-wei Liaoa95f5892010-09-11 01:42:09 -0700630 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700631#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700632 if (ShouldPrintDebugScopes) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000633 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
634 DD->beginScope(II);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700635 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700636#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800637
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700638 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800639 EmitComments(*II, OutStreamer.GetCommentOS());
640
641 switch (II->getOpcode()) {
Bill Wendlinga02effc2010-07-16 22:20:36 +0000642 case TargetOpcode::PROLOG_LABEL:
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800643 case TargetOpcode::EH_LABEL:
644 case TargetOpcode::GC_LABEL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700645 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800646 break;
647 case TargetOpcode::INLINEASM:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700648 EmitInlineAsm(II);
649 break;
650 case TargetOpcode::DBG_VALUE:
651 if (isVerbose()) {
652 if (!EmitDebugValueComment(II, *this))
653 EmitInstruction(II);
654 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800655 break;
656 case TargetOpcode::IMPLICIT_DEF:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700657 if (isVerbose()) EmitImplicitDef(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800658 break;
659 case TargetOpcode::KILL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700660 if (isVerbose()) EmitKill(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800661 break;
662 default:
663 EmitInstruction(II);
664 break;
665 }
666
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700667#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700668 if (ShouldPrintDebugScopes) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000669 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
670 DD->endScope(II);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700671 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700672#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800673 }
674 }
Bill Wendling5a1bec12010-07-16 22:51:10 +0000675
676 // If the last instruction was a prolog label, then we have a situation where
677 // we emitted a prolog but no function body. This results in the ending prolog
678 // label equaling the end of function label and an invalid "row" in the
679 // FDE. We need to emit a noop in this situation so that the FDE's rows are
680 // valid.
Bill Wendlingf7e17752010-07-17 19:18:44 +0000681 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
Bill Wendling5a1bec12010-07-16 22:51:10 +0000682
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800683 // If the function is empty and the object file uses .subsections_via_symbols,
684 // then we need to emit *something* to the function body to prevent the
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700685 // labels from collapsing together. Just emit a noop.
Bill Wendling5a1bec12010-07-16 22:51:10 +0000686 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700687 MCInst Noop;
688 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
689 if (Noop.getOpcode()) {
690 OutStreamer.AddComment("avoids zero-length function");
691 OutStreamer.EmitInstruction(Noop);
692 } else // Target not mc-ized yet.
693 OutStreamer.EmitRawText(StringRef("\tnop\n"));
694 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800695
696 // Emit target-specific gunk after the function body.
697 EmitFunctionBodyEnd();
698
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700699 // If the target wants a .size directive for the size of the function, emit
700 // it.
701 if (MAI->hasDotTypeDotSizeDirective()) {
702 // Create a symbol for the end of function, so we can get the size as
703 // difference between the function label and the temp label.
704 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
705 OutStreamer.EmitLabel(FnEndLabel);
706
707 const MCExpr *SizeExp =
708 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
709 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
710 OutContext);
711 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
712 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800713
714 // Emit post-function debug information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700715#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700716 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000717 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
718 DD->endFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700719 }
720 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000721 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
722 DE->EndFunction();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700723 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700724#endif // ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700725 MMI->EndFunction();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800726
727 // Print out jump tables referenced by the function.
728 EmitJumpTableInfo();
729
730 OutStreamer.AddBlankLine();
731}
732
Devang Patel7c3efb12010-04-28 01:39:28 +0000733/// getDebugValueLocation - Get location information encoded by DBG_VALUE
734/// operands.
735MachineLocation AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
736 // Target specific DBG_VALUE instructions are handled by each target.
737 return MachineLocation();
738}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800739
740bool AsmPrinter::doFinalization(Module &M) {
741 // Emit global variables.
742 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
743 I != E; ++I)
744 EmitGlobalVariable(I);
745
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700746 // Finalize debug and EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700747#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700748 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000749 {
750 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700751 DE->EndModule();
752 }
753 delete DE; DE = 0;
754 }
755 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000756 {
757 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700758 DD->endModule();
759 }
760 delete DD; DD = 0;
761 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700762#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800763
764 // If the target wants to know about weak references, print them all.
765 if (MAI->getWeakRefDirective()) {
766 // FIXME: This is not lazy, it would be nice to only print weak references
767 // to stuff that is actually used. Note that doing so would require targets
768 // to notice uses in operands (due to constant exprs etc). This should
769 // happen with the MC stuff eventually.
770
771 // Print out module-level global variables here.
772 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
773 I != E; ++I) {
774 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700775 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800776 }
777
778 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
779 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700780 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800781 }
782 }
783
784 if (MAI->hasSetDirective()) {
785 OutStreamer.AddBlankLine();
786 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
787 I != E; ++I) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700788 MCSymbol *Name = Mang->getSymbol(I);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800789
790 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700791 MCSymbol *Target = Mang->getSymbol(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800792
793 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
794 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
795 else if (I->hasWeakLinkage())
796 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
797 else
798 assert(I->hasLocalLinkage() && "Invalid alias linkage");
799
800 EmitVisibility(Name, I->getVisibility());
801
802 // Emit the directives as assignments aka .set:
803 OutStreamer.EmitAssignment(Name,
804 MCSymbolRefExpr::Create(Target, OutContext));
805 }
806 }
807
808 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
809 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
810 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
811 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700812 MP->finishAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800813
814 // If we don't have any trampolines, then we don't require stack memory
815 // to be executable. Some targets have a directive to declare this.
816 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
817 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700818 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800819 OutStreamer.SwitchSection(S);
820
821 // Allow the target to emit any magic that it wants at the end of the file,
822 // after everything else has gone out.
823 EmitEndOfAsmFile(M);
824
825 delete Mang; Mang = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700826 MMI = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800827
828 OutStreamer.Finish();
829 return false;
830}
831
832void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
833 this->MF = &MF;
834 // Get the function symbol.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700835 CurrentFnSym = Mang->getSymbol(MF.getFunction());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800836
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700837 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800838 LI = &getAnalysis<MachineLoopInfo>();
839}
840
841namespace {
842 // SectionCPs - Keep track the alignment, constpool entries per Section.
843 struct SectionCPs {
844 const MCSection *S;
845 unsigned Alignment;
846 SmallVector<unsigned, 4> CPEs;
847 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
848 };
849}
850
851/// EmitConstantPool - Print to the current output stream assembly
852/// representations of the constants in the constant pool MCP. This is
853/// used to print out constants which have been "spilled to memory" by
854/// the code generator.
855///
856void AsmPrinter::EmitConstantPool() {
857 const MachineConstantPool *MCP = MF->getConstantPool();
858 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
859 if (CP.empty()) return;
860
861 // Calculate sections for constant pool entries. We collect entries to go into
862 // the same section together to reduce amount of section switch statements.
863 SmallVector<SectionCPs, 4> CPSections;
864 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
865 const MachineConstantPoolEntry &CPE = CP[i];
866 unsigned Align = CPE.getAlignment();
867
868 SectionKind Kind;
869 switch (CPE.getRelocationInfo()) {
870 default: llvm_unreachable("Unknown section kind");
871 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
872 case 1:
873 Kind = SectionKind::getReadOnlyWithRelLocal();
874 break;
875 case 0:
876 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
877 case 4: Kind = SectionKind::getMergeableConst4(); break;
878 case 8: Kind = SectionKind::getMergeableConst8(); break;
879 case 16: Kind = SectionKind::getMergeableConst16();break;
880 default: Kind = SectionKind::getMergeableConst(); break;
881 }
882 }
883
884 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
885
886 // The number of sections are small, just do a linear search from the
887 // last section to the first.
888 bool Found = false;
889 unsigned SecIdx = CPSections.size();
890 while (SecIdx != 0) {
891 if (CPSections[--SecIdx].S == S) {
892 Found = true;
893 break;
894 }
895 }
896 if (!Found) {
897 SecIdx = CPSections.size();
898 CPSections.push_back(SectionCPs(S, Align));
899 }
900
901 if (Align > CPSections[SecIdx].Alignment)
902 CPSections[SecIdx].Alignment = Align;
903 CPSections[SecIdx].CPEs.push_back(i);
904 }
905
906 // Now print stuff into the calculated sections.
907 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
908 OutStreamer.SwitchSection(CPSections[i].S);
909 EmitAlignment(Log2_32(CPSections[i].Alignment));
910
911 unsigned Offset = 0;
912 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
913 unsigned CPI = CPSections[i].CPEs[j];
914 MachineConstantPoolEntry CPE = CP[CPI];
915
916 // Emit inter-object padding for alignment.
917 unsigned AlignMask = CPE.getAlignment() - 1;
918 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
919 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
920
921 const Type *Ty = CPE.getType();
922 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
923
924 // Emit the label with a comment on it.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700925 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800926 OutStreamer.GetCommentOS() << "constant pool ";
927 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
928 MF->getFunction()->getParent());
929 OutStreamer.GetCommentOS() << '\n';
930 }
931 OutStreamer.EmitLabel(GetCPISymbol(CPI));
932
933 if (CPE.isMachineConstantPoolEntry())
934 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
935 else
936 EmitGlobalConstant(CPE.Val.ConstVal);
937 }
938 }
939}
940
941/// EmitJumpTableInfo - Print assembly representations of the jump tables used
942/// by the current function to the current output stream.
943///
944void AsmPrinter::EmitJumpTableInfo() {
945 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
946 if (MJTI == 0) return;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700947 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800948 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
949 if (JT.empty()) return;
950
951 // Pick the directive to use to print the jump table entries, and switch to
952 // the appropriate section.
953 const Function *F = MF->getFunction();
954 bool JTInDiffSection = false;
955 if (// In PIC mode, we need to emit the jump table to the same section as the
956 // function body itself, otherwise the label differences won't make sense.
957 // FIXME: Need a better predicate for this: what about custom entries?
958 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
959 // We should also do if the section name is NULL or function is declared
960 // in discardable section
961 // FIXME: this isn't the right predicate, should be based on the MCSection
962 // for the function.
963 F->isWeakForLinker()) {
964 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
965 } else {
966 // Otherwise, drop it in the readonly section.
967 const MCSection *ReadOnlySection =
968 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
969 OutStreamer.SwitchSection(ReadOnlySection);
970 JTInDiffSection = true;
971 }
972
973 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
974
975 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
976 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
977
978 // If this jump table was deleted, ignore it.
979 if (JTBBs.empty()) continue;
980
981 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
982 // .set directive for each unique entry. This reduces the number of
983 // relocations the assembler will generate for the jump table.
984 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
985 MAI->hasSetDirective()) {
986 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
987 const TargetLowering *TLI = TM.getTargetLowering();
988 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
989 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
990 const MachineBasicBlock *MBB = JTBBs[ii];
991 if (!EmittedSets.insert(MBB)) continue;
992
993 // .set LJTSet, LBB32-base
994 const MCExpr *LHS =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700995 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800996 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
997 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
998 }
999 }
1000
1001 // On some targets (e.g. Darwin) we want to emit two consequtive labels
1002 // before each jump table. The first label is never referenced, but tells
1003 // the assembler and linker the extents of the jump table object. The
1004 // second label is actually referenced by the code.
1005 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1006 // FIXME: This doesn't have to have any specific name, just any randomly
1007 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1008 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1009
1010 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1011
1012 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1013 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1014 }
1015}
1016
1017/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1018/// current stream.
1019void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1020 const MachineBasicBlock *MBB,
1021 unsigned UID) const {
1022 const MCExpr *Value = 0;
1023 switch (MJTI->getEntryKind()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001024 case MachineJumpTableInfo::EK_Inline:
1025 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001026 case MachineJumpTableInfo::EK_Custom32:
1027 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1028 OutContext);
1029 break;
1030 case MachineJumpTableInfo::EK_BlockAddress:
1031 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1032 // .word LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001033 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001034 break;
1035 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1036 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1037 // with a relocation as gp-relative, e.g.:
1038 // .gprel32 LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001039 MCSymbol *MBBSym = MBB->getSymbol();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001040 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1041 return;
1042 }
1043
1044 case MachineJumpTableInfo::EK_LabelDifference32: {
1045 // EK_LabelDifference32 - Each entry is the address of the block minus
1046 // the address of the jump table. This is used for PIC jump tables where
1047 // gprel32 is not supported. e.g.:
1048 // .word LBB123 - LJTI1_2
1049 // If the .set directive is supported, this is emitted as:
1050 // .set L4_5_set_123, LBB123 - LJTI1_2
1051 // .word L4_5_set_123
1052
1053 // If we have emitted set directives for the jump table entries, print
1054 // them rather than the entries themselves. If we're emitting PIC, then
1055 // emit the table entries as differences between two text section labels.
1056 if (MAI->hasSetDirective()) {
1057 // If we used .set, reference the .set's symbol.
1058 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1059 OutContext);
1060 break;
1061 }
1062 // Otherwise, use the difference as the jump table entry.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001063 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001064 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1065 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1066 break;
1067 }
1068 }
1069
1070 assert(Value && "Unknown entry kind!");
1071
1072 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1073 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1074}
1075
1076
1077/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1078/// special global used by LLVM. If so, emit it and return true, otherwise
1079/// do nothing and return false.
1080bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1081 if (GV->getName() == "llvm.used") {
1082 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1083 EmitLLVMUsedList(GV->getInitializer());
1084 return true;
1085 }
1086
1087 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1088 if (GV->getSection() == "llvm.metadata" ||
1089 GV->hasAvailableExternallyLinkage())
1090 return true;
1091
1092 if (!GV->hasAppendingLinkage()) return false;
1093
1094 assert(GV->hasInitializer() && "Not a special LLVM global!");
1095
1096 const TargetData *TD = TM.getTargetData();
1097 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1098 if (GV->getName() == "llvm.global_ctors") {
1099 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner7516e9e2010-04-28 19:58:07 +00001100 EmitAlignment(Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001101 EmitXXStructorList(GV->getInitializer());
1102
1103 if (TM.getRelocationModel() == Reloc::Static &&
1104 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1105 StringRef Sym(".constructors_used");
1106 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1107 MCSA_Reference);
1108 }
1109 return true;
1110 }
1111
1112 if (GV->getName() == "llvm.global_dtors") {
1113 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner7516e9e2010-04-28 19:58:07 +00001114 EmitAlignment(Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001115 EmitXXStructorList(GV->getInitializer());
1116
1117 if (TM.getRelocationModel() == Reloc::Static &&
1118 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1119 StringRef Sym(".destructors_used");
1120 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1121 MCSA_Reference);
1122 }
1123 return true;
1124 }
1125
1126 return false;
1127}
1128
1129/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1130/// global in the specified llvm.used list for which emitUsedDirectiveFor
1131/// is true, as being used with this directive.
1132void AsmPrinter::EmitLLVMUsedList(Constant *List) {
1133 // Should be an array of 'i8*'.
1134 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1135 if (InitList == 0) return;
1136
1137 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1138 const GlobalValue *GV =
1139 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1140 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001141 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001142 }
1143}
1144
1145/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1146/// function pointers, ignoring the init priority.
1147void AsmPrinter::EmitXXStructorList(Constant *List) {
1148 // Should be an array of '{ int, void ()* }' structs. The first value is the
1149 // init priority, which we ignore.
1150 if (!isa<ConstantArray>(List)) return;
1151 ConstantArray *InitList = cast<ConstantArray>(List);
1152 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1153 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1154 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1155
1156 if (CS->getOperand(1)->isNullValue())
1157 return; // Found a null terminator, exit printing.
1158 // Emit the function pointer.
1159 EmitGlobalConstant(CS->getOperand(1));
1160 }
1161}
1162
1163//===--------------------------------------------------------------------===//
1164// Emission and print routines
1165//
1166
1167/// EmitInt8 - Emit a byte directive and value.
1168///
1169void AsmPrinter::EmitInt8(int Value) const {
1170 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1171}
1172
1173/// EmitInt16 - Emit a short directive and value.
1174///
1175void AsmPrinter::EmitInt16(int Value) const {
1176 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1177}
1178
1179/// EmitInt32 - Emit a long directive and value.
1180///
1181void AsmPrinter::EmitInt32(int Value) const {
1182 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1183}
1184
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001185/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1186/// in bytes of the directive is specified by Size and Hi/Lo specify the
1187/// labels. This implicitly uses .set if it is available.
1188void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1189 unsigned Size) const {
1190 // Get the Hi-Lo expression.
1191 const MCExpr *Diff =
1192 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1193 MCSymbolRefExpr::Create(Lo, OutContext),
1194 OutContext);
1195
1196 if (!MAI->hasSetDirective()) {
1197 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1198 return;
1199 }
1200
1201 // Otherwise, emit with .set (aka assignment).
1202 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1203 OutStreamer.EmitAssignment(SetLabel, Diff);
1204 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001205}
1206
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001207/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1208/// where the size in bytes of the directive is specified by Size and Hi/Lo
1209/// specify the labels. This implicitly uses .set if it is available.
1210void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1211 const MCSymbol *Lo, unsigned Size)
1212 const {
1213
1214 // Emit Hi+Offset - Lo
1215 // Get the Hi+Offset expression.
1216 const MCExpr *Plus =
1217 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1218 MCConstantExpr::Create(Offset, OutContext),
1219 OutContext);
1220
1221 // Get the Hi+Offset-Lo expression.
1222 const MCExpr *Diff =
1223 MCBinaryExpr::CreateSub(Plus,
1224 MCSymbolRefExpr::Create(Lo, OutContext),
1225 OutContext);
1226
1227 if (!MAI->hasSetDirective())
1228 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1229 else {
1230 // Otherwise, emit with .set (aka assignment).
1231 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1232 OutStreamer.EmitAssignment(SetLabel, Diff);
1233 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1234 }
1235}
1236
1237
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001238//===----------------------------------------------------------------------===//
1239
1240// EmitAlignment - Emit an alignment directive to the specified power of
1241// two boundary. For example, if you pass in 3 here, you will get an 8
1242// byte alignment. If a global value is specified, and if that global has
Chris Lattner7516e9e2010-04-28 19:58:07 +00001243// an explicit alignment requested, it will override the alignment request
1244// if required for correctness.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001245//
Chris Lattner027b9362010-04-28 01:08:40 +00001246void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
Chris Lattner7516e9e2010-04-28 19:58:07 +00001247 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001248
Chris Lattner7516e9e2010-04-28 19:58:07 +00001249 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001250
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001251 if (getCurrentSection()->getKind().isText())
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001252 OutStreamer.EmitCodeAlignment(1 << NumBits);
1253 else
1254 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001255}
1256
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001257//===----------------------------------------------------------------------===//
1258// Constant emission.
1259//===----------------------------------------------------------------------===//
1260
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001261/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1262///
1263static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1264 MCContext &Ctx = AP.OutContext;
1265
1266 if (CV->isNullValue() || isa<UndefValue>(CV))
1267 return MCConstantExpr::Create(0, Ctx);
1268
1269 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1270 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1271
1272 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001273 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
Bill Wendling021fd612010-08-18 18:41:13 +00001274
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001275 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1276 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1277
1278 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1279 if (CE == 0) {
1280 llvm_unreachable("Unknown constant value to lower!");
1281 return MCConstantExpr::Create(0, Ctx);
1282 }
1283
1284 switch (CE->getOpcode()) {
1285 default:
1286 // If the code isn't optimized, there may be outstanding folding
1287 // opportunities. Attempt to fold the expression using TargetData as a
1288 // last resort before giving up.
1289 if (Constant *C =
1290 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1291 if (C != CE)
1292 return LowerConstant(C, AP);
Dan Gohmana3f4d8f2010-08-04 18:51:09 +00001293
1294 // Otherwise report the problem to the user.
1295 {
1296 std::string S;
1297 raw_string_ostream OS(S);
1298 OS << "Unsupported expression in static initializer: ";
1299 WriteAsOperand(OS, CE, /*PrintType=*/false,
1300 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1301 report_fatal_error(OS.str());
1302 }
1303 return MCConstantExpr::Create(0, Ctx);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001304 case Instruction::GetElementPtr: {
1305 const TargetData &TD = *AP.TM.getTargetData();
1306 // Generate a symbolic expression for the byte address
1307 const Constant *PtrVal = CE->getOperand(0);
1308 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1309 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1310 IdxVec.size());
1311
1312 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1313 if (Offset == 0)
1314 return Base;
1315
1316 // Truncate/sext the offset to the pointer size.
1317 if (TD.getPointerSizeInBits() != 64) {
1318 int SExtAmount = 64-TD.getPointerSizeInBits();
1319 Offset = (Offset << SExtAmount) >> SExtAmount;
1320 }
1321
1322 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1323 Ctx);
1324 }
1325
1326 case Instruction::Trunc:
1327 // We emit the value and depend on the assembler to truncate the generated
1328 // expression properly. This is important for differences between
1329 // blockaddress labels. Since the two labels are in the same function, it
1330 // is reasonable to treat their delta as a 32-bit value.
1331 // FALL THROUGH.
1332 case Instruction::BitCast:
1333 return LowerConstant(CE->getOperand(0), AP);
1334
1335 case Instruction::IntToPtr: {
1336 const TargetData &TD = *AP.TM.getTargetData();
1337 // Handle casts to pointers by changing them into casts to the appropriate
1338 // integer type. This promotes constant folding and simplifies this code.
1339 Constant *Op = CE->getOperand(0);
1340 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1341 false/*ZExt*/);
1342 return LowerConstant(Op, AP);
1343 }
1344
1345 case Instruction::PtrToInt: {
1346 const TargetData &TD = *AP.TM.getTargetData();
1347 // Support only foldable casts to/from pointers that can be eliminated by
1348 // changing the pointer to the appropriately sized integer type.
1349 Constant *Op = CE->getOperand(0);
1350 const Type *Ty = CE->getType();
1351
1352 const MCExpr *OpExpr = LowerConstant(Op, AP);
1353
1354 // We can emit the pointer value into this slot if the slot is an
1355 // integer slot equal to the size of the pointer.
1356 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1357 return OpExpr;
1358
1359 // Otherwise the pointer is smaller than the resultant integer, mask off
1360 // the high bits so we are sure to get a proper truncation if the input is
1361 // a constant expr.
1362 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1363 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1364 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1365 }
1366
1367 // The MC library also has a right-shift operator, but it isn't consistently
1368 // signed or unsigned between different targets.
1369 case Instruction::Add:
1370 case Instruction::Sub:
1371 case Instruction::Mul:
1372 case Instruction::SDiv:
1373 case Instruction::SRem:
1374 case Instruction::Shl:
1375 case Instruction::And:
1376 case Instruction::Or:
1377 case Instruction::Xor: {
1378 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1379 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1380 switch (CE->getOpcode()) {
1381 default: llvm_unreachable("Unknown binary operator constant cast expr");
1382 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1383 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1384 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1385 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1386 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1387 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1388 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1389 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1390 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1391 }
1392 }
1393 }
1394}
1395
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001396static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1397 AsmPrinter &AP);
1398
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001399static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1400 AsmPrinter &AP) {
1401 if (AddrSpace != 0 || !CA->isString()) {
1402 // Not a string. Print the values in successive locations
1403 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001404 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001405 return;
1406 }
1407
1408 // Otherwise, it can be emitted as .ascii.
1409 SmallVector<char, 128> TmpVec;
1410 TmpVec.reserve(CA->getNumOperands());
1411 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1412 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1413
1414 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1415}
1416
1417static void EmitGlobalConstantVector(const ConstantVector *CV,
1418 unsigned AddrSpace, AsmPrinter &AP) {
1419 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001420 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001421}
1422
1423static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1424 unsigned AddrSpace, AsmPrinter &AP) {
1425 // Print the fields in successive locations. Pad to align if needed!
1426 const TargetData *TD = AP.TM.getTargetData();
1427 unsigned Size = TD->getTypeAllocSize(CS->getType());
1428 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1429 uint64_t SizeSoFar = 0;
1430 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1431 const Constant *Field = CS->getOperand(i);
1432
1433 // Check if padding is needed and insert one or more 0s.
1434 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1435 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1436 - Layout->getElementOffset(i)) - FieldSize;
1437 SizeSoFar += FieldSize + PadSize;
1438
1439 // Now print the actual field value.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001440 EmitGlobalConstantImpl(Field, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001441
1442 // Insert padding - this may include padding to increase the size of the
1443 // current field up to the ABI size (if the struct is not packed) as well
1444 // as padding to ensure that the next field starts at the right offset.
1445 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1446 }
1447 assert(SizeSoFar == Layout->getSizeInBytes() &&
1448 "Layout of constant struct may be incorrect!");
1449}
1450
1451static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1452 AsmPrinter &AP) {
1453 // FP Constants are printed as integer constants to avoid losing
1454 // precision.
1455 if (CFP->getType()->isDoubleTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001456 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001457 double Val = CFP->getValueAPF().convertToDouble();
1458 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1459 }
1460
1461 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1462 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1463 return;
1464 }
1465
1466 if (CFP->getType()->isFloatTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001467 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001468 float Val = CFP->getValueAPF().convertToFloat();
1469 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1470 }
1471 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1472 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1473 return;
1474 }
1475
1476 if (CFP->getType()->isX86_FP80Ty()) {
1477 // all long double variants are printed as hex
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001478 // API needed to prevent premature destruction
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001479 APInt API = CFP->getValueAPF().bitcastToAPInt();
1480 const uint64_t *p = API.getRawData();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001481 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001482 // Convert to double so we can print the approximate val as a comment.
1483 APFloat DoubleVal = CFP->getValueAPF();
1484 bool ignored;
1485 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1486 &ignored);
1487 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1488 << DoubleVal.convertToDouble() << '\n';
1489 }
1490
1491 if (AP.TM.getTargetData()->isBigEndian()) {
1492 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1493 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1494 } else {
1495 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1496 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1497 }
1498
1499 // Emit the tail padding for the long double.
1500 const TargetData &TD = *AP.TM.getTargetData();
1501 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1502 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1503 return;
1504 }
1505
1506 assert(CFP->getType()->isPPC_FP128Ty() &&
1507 "Floating point constant type not handled");
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001508 // All long double variants are printed as hex
1509 // API needed to prevent premature destruction.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001510 APInt API = CFP->getValueAPF().bitcastToAPInt();
1511 const uint64_t *p = API.getRawData();
1512 if (AP.TM.getTargetData()->isBigEndian()) {
1513 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1514 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1515 } else {
1516 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1517 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1518 }
1519}
1520
1521static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1522 unsigned AddrSpace, AsmPrinter &AP) {
1523 const TargetData *TD = AP.TM.getTargetData();
1524 unsigned BitWidth = CI->getBitWidth();
1525 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1526
1527 // We don't expect assemblers to support integer data directives
1528 // for more than 64 bits, so we emit the data in at most 64-bit
1529 // quantities at a time.
1530 const uint64_t *RawData = CI->getValue().getRawData();
1531 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1532 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1533 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1534 }
1535}
1536
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001537static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1538 AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001539 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001540 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1541 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001542 }
1543
1544 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001545 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001546 switch (Size) {
1547 case 1:
1548 case 2:
1549 case 4:
1550 case 8:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001551 if (AP.isVerbose())
1552 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
Bill Wendling021fd612010-08-18 18:41:13 +00001553 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001554 return;
1555 default:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001556 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001557 return;
1558 }
1559 }
1560
1561 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001562 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001563
1564 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001565 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001566
1567 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001568 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001569
1570 if (isa<ConstantPointerNull>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001571 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1572 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001573 return;
1574 }
1575
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001576 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1577 return EmitGlobalConstantVector(V, AddrSpace, AP);
1578
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001579 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1580 // thread the streamer with EmitValue.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001581 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1582 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1583 AddrSpace);
1584}
1585
1586/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1587void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1588 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1589 if (Size)
1590 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1591 else if (MAI->hasSubsectionsViaSymbols()) {
1592 // If the global has zero size, emit a single byte so that two labels don't
1593 // look like they are at the same location.
1594 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1595 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001596}
1597
1598void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1599 // Target doesn't support this yet!
1600 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1601}
1602
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001603void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1604 if (Offset > 0)
1605 OS << '+' << Offset;
1606 else if (Offset < 0)
1607 OS << Offset;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001608}
1609
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001610//===----------------------------------------------------------------------===//
1611// Symbol Lowering Routines.
1612//===----------------------------------------------------------------------===//
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001613
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001614/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1615/// temporary label with the specified stem and unique ID.
1616MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1617 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1618 Name + Twine(ID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001619}
1620
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001621/// GetTempSymbol - Return an assembler temporary label with the specified
1622/// stem.
1623MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1624 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1625 Name);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001626}
1627
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001628
1629MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001630 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001631}
1632
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001633MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1634 return MMI->getAddrLabelSymbol(BB);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001635}
1636
1637/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1638MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001639 return OutContext.GetOrCreateSymbol
1640 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1641 + "_" + Twine(CPID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001642}
1643
1644/// GetJTISymbol - Return the symbol for the specified jump table entry.
1645MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1646 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1647}
1648
1649/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1650/// FIXME: privatize to AsmPrinter.
1651MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001652 return OutContext.GetOrCreateSymbol
1653 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1654 Twine(UID) + "_set_" + Twine(MBBID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001655}
1656
1657/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1658/// global value name as its base, with the specified suffix, and where the
1659/// symbol is forced to have private linkage if ForcePrivate is true.
1660MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1661 StringRef Suffix,
1662 bool ForcePrivate) const {
1663 SmallString<60> NameStr;
1664 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1665 NameStr.append(Suffix.begin(), Suffix.end());
1666 return OutContext.GetOrCreateSymbol(NameStr.str());
1667}
1668
1669/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1670/// ExternalSymbol.
1671MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1672 SmallString<60> NameStr;
1673 Mang->getNameWithPrefix(NameStr, Sym);
1674 return OutContext.GetOrCreateSymbol(NameStr.str());
1675}
1676
1677
1678
1679/// PrintParentLoopComment - Print comments about parent loops of this one.
1680static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1681 unsigned FunctionNumber) {
1682 if (Loop == 0) return;
1683 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1684 OS.indent(Loop->getLoopDepth()*2)
1685 << "Parent Loop BB" << FunctionNumber << "_"
1686 << Loop->getHeader()->getNumber()
1687 << " Depth=" << Loop->getLoopDepth() << '\n';
1688}
1689
1690
1691/// PrintChildLoopComment - Print comments about child loops within
1692/// the loop for this basic block, with nesting.
1693static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1694 unsigned FunctionNumber) {
1695 // Add child loop information
1696 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1697 OS.indent((*CL)->getLoopDepth()*2)
1698 << "Child Loop BB" << FunctionNumber << "_"
1699 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1700 << '\n';
1701 PrintChildLoopComment(OS, *CL, FunctionNumber);
1702 }
1703}
1704
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001705/// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1706static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1707 const MachineLoopInfo *LI,
1708 const AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001709 // Add loop depth information
1710 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1711 if (Loop == 0) return;
1712
1713 MachineBasicBlock *Header = Loop->getHeader();
1714 assert(Header && "No header for loop");
1715
1716 // If this block is not a loop header, just print out what is the loop header
1717 // and return.
1718 if (Header != &MBB) {
1719 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1720 Twine(AP.getFunctionNumber())+"_" +
1721 Twine(Loop->getHeader()->getNumber())+
1722 " Depth="+Twine(Loop->getLoopDepth()));
1723 return;
1724 }
1725
1726 // Otherwise, it is a loop header. Print out information about child and
1727 // parent loops.
1728 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1729
1730 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1731
1732 OS << "=>";
1733 OS.indent(Loop->getLoopDepth()*2-2);
1734
1735 OS << "This ";
1736 if (Loop->empty())
1737 OS << "Inner ";
1738 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1739
1740 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1741}
1742
1743
1744/// EmitBasicBlockStart - This method prints the label for the specified
1745/// MachineBasicBlock, an alignment (if present) and a comment describing
1746/// it if appropriate.
1747void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1748 // Emit an alignment directive for this block, if needed.
1749 if (unsigned Align = MBB->getAlignment())
1750 EmitAlignment(Log2_32(Align));
1751
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001752 // If the block has its address taken, emit any labels that were used to
1753 // reference the block. It is possible that there is more than one label
1754 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1755 // the references were generated.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001756 if (MBB->hasAddressTaken()) {
1757 const BasicBlock *BB = MBB->getBasicBlock();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001758 if (isVerbose())
1759 OutStreamer.AddComment("Block address taken");
1760
1761 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1762
1763 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1764 OutStreamer.EmitLabel(Syms[i]);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001765 }
1766
1767 // Print the main label for the block.
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001768 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001769 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001770 if (const BasicBlock *BB = MBB->getBasicBlock())
1771 if (BB->hasName())
1772 OutStreamer.AddComment("%" + BB->getName());
1773
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001774 EmitBasicBlockLoopComments(*MBB, LI, *this);
1775
1776 // NOTE: Want this comment at start of line, don't emit with AddComment.
1777 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1778 Twine(MBB->getNumber()) + ":");
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001779 }
1780 } else {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001781 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001782 if (const BasicBlock *BB = MBB->getBasicBlock())
1783 if (BB->hasName())
1784 OutStreamer.AddComment("%" + BB->getName());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001785 EmitBasicBlockLoopComments(*MBB, LI, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001786 }
1787
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001788 OutStreamer.EmitLabel(MBB->getSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001789 }
1790}
1791
1792void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1793 MCSymbolAttr Attr = MCSA_Invalid;
1794
1795 switch (Visibility) {
1796 default: break;
1797 case GlobalValue::HiddenVisibility:
1798 Attr = MAI->getHiddenVisibilityAttr();
1799 break;
1800 case GlobalValue::ProtectedVisibility:
1801 Attr = MAI->getProtectedVisibilityAttr();
1802 break;
1803 }
1804
1805 if (Attr != MCSA_Invalid)
1806 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1807}
1808
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001809/// isBlockOnlyReachableByFallthough - Return true if the basic block has
1810/// exactly one predecessor and the control transfer mechanism between
1811/// the predecessor and this block is a fall-through.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001812bool AsmPrinter::
1813isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001814 // If this is a landing pad, it isn't a fall through. If it has no preds,
1815 // then nothing falls through to it.
1816 if (MBB->isLandingPad() || MBB->pred_empty())
1817 return false;
1818
1819 // If there isn't exactly one predecessor, it can't be a fall through.
1820 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1821 ++PI2;
1822 if (PI2 != MBB->pred_end())
1823 return false;
1824
1825 // The predecessor has to be immediately before this block.
1826 const MachineBasicBlock *Pred = *PI;
1827
1828 if (!Pred->isLayoutSuccessor(MBB))
1829 return false;
1830
1831 // If the block is completely empty, then it definitely does fall through.
1832 if (Pred->empty())
1833 return true;
1834
1835 // Otherwise, check the last instruction.
1836 const MachineInstr &LastInst = Pred->back();
1837 return !LastInst.getDesc().isBarrier();
1838}
1839
1840
1841
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001842GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1843 if (!S->usesMetadata())
1844 return 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001845
1846 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1847 gcp_map_type::iterator GCPI = GCMap.find(S);
1848 if (GCPI != GCMap.end())
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001849 return GCPI->second;
1850
1851 const char *Name = S->getName().c_str();
1852
1853 for (GCMetadataPrinterRegistry::iterator
1854 I = GCMetadataPrinterRegistry::begin(),
1855 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1856 if (strcmp(Name, I->getName()) == 0) {
1857 GCMetadataPrinter *GMP = I->instantiate();
1858 GMP->S = S;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001859 GCMap.insert(std::make_pair(S, GMP));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001860 return GMP;
1861 }
1862
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001863 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001864 return 0;
1865}
1866