blob: a08b61c267cc2265e46c257b4555e8b977f2b3a3 [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"
Rafael Espindolaa4329972011-04-29 14:14:06 +000042#include "llvm/Target/TargetOptions.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080043#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner9fc5cdf2011-01-02 22:09:33 +000044#include "llvm/Assembly/Writer.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080045#include "llvm/ADT/SmallString.h"
46#include "llvm/ADT/Statistic.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080047#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/Format.h"
David Greened92e2e42011-08-31 17:30:56 +000049#include "llvm/Support/MathExtras.h"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070050#include "llvm/Support/Timer.h"
Shih-wei Liaoe4454322010-04-07 12:21:42 -070051#include <ctype.h>
Shih-wei Liaoe264f622010-02-10 11:10:31 -080052using namespace llvm;
53
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070054static const char *DWARFGroupName = "DWARF Emission";
55static const char *DbgTimerName = "DWARF Debug Writer";
56static const char *EHTimerName = "DWARF Exception Writer";
57
Shih-wei Liaoe264f622010-02-10 11:10:31 -080058STATISTIC(EmittedInsts, "Number of machine instrs printed");
59
60char AsmPrinter::ID = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070061
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
Chris Lattner7516e9e2010-04-28 19:58:07 +000070/// 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 TargetData &TD,
74 unsigned InBits = 0) {
75 unsigned NumBits = 0;
76 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77 NumBits = TD.getPreferredAlignmentLog(GVar);
Jim Grosbach83d80832011-03-29 23:20:22 +000078
Chris Lattner7516e9e2010-04-28 19:58:07 +000079 // If InBits is specified, round it to it.
80 if (InBits > NumBits)
81 NumBits = InBits;
Jim Grosbach83d80832011-03-29 23:20:22 +000082
Chris Lattner7516e9e2010-04-28 19:58:07 +000083 // If the GV has a specified alignment, take it into account.
84 if (GV->getAlignment() == 0)
85 return NumBits;
Jim Grosbach83d80832011-03-29 23:20:22 +000086
Chris Lattner7516e9e2010-04-28 19:58:07 +000087 unsigned GVAlign = Log2_32(GV->getAlignment());
Jim Grosbach83d80832011-03-29 23:20:22 +000088
Chris Lattner7516e9e2010-04-28 19:58:07 +000089 // 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
96
97
98
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070099AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
Owen Anderson75693222010-08-06 18:33:48 +0000100 : MachineFunctionPass(ID),
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700101 TM(tm), MAI(tm.getMCAsmInfo()),
102 OutContext(Streamer.getContext()),
103 OutStreamer(Streamer),
104 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105 DD = 0; DE = 0; MMI = 0; LI = 0;
106 GCMetadataPrinters = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800107 VerboseAsm = Streamer.isVerboseAsm();
108}
109
110AsmPrinter::~AsmPrinter() {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700111 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
Jim Grosbach83d80832011-03-29 23:20:22 +0000112
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700113 if (GCMetadataPrinters != 0) {
114 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
Jim Grosbach83d80832011-03-29 23:20:22 +0000115
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700116 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
117 delete I->second;
118 delete &GCMap;
119 GCMetadataPrinters = 0;
120 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000121
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800122 delete &OutStreamer;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800123}
124
125/// getFunctionNumber - Return a unique ID for the current function.
126///
127unsigned AsmPrinter::getFunctionNumber() const {
128 return MF->getFunctionNumber();
129}
130
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700131const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800132 return TM.getTargetLowering()->getObjFileLowering();
133}
134
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700135
136/// getTargetData - Return information about data layout.
137const TargetData &AsmPrinter::getTargetData() const {
138 return *TM.getTargetData();
139}
140
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800141/// getCurrentSection() - Return the current section we are emitting to.
142const MCSection *AsmPrinter::getCurrentSection() const {
143 return OutStreamer.getCurrentSection();
144}
145
146
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700147
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800148void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.setPreservesAll();
150 MachineFunctionPass::getAnalysisUsage(AU);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700151 AU.addRequired<MachineModuleInfo>();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800152 AU.addRequired<GCModuleInfo>();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700153 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800154 AU.addRequired<MachineLoopInfo>();
155}
156
157bool AsmPrinter::doInitialization(Module &M) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700158 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
159 MMI->AnalyzeModule(M);
160
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800161 // Initialize TargetLoweringObjectFile.
162 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
163 .Initialize(OutContext, TM);
Jim Grosbach83d80832011-03-29 23:20:22 +0000164
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700165 Mang = new Mangler(OutContext, *TM.getTargetData());
Jim Grosbach83d80832011-03-29 23:20:22 +0000166
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800167 // Allow the target to emit any magic that it wants at the start of the file.
168 EmitStartOfAsmFile(M);
169
170 // Very minimal debug info. It is ignored if we emit actual debug info. If we
171 // don't, this at least helps the user find where a global came from.
172 if (MAI->hasSingleParameterDotFile()) {
173 // .file "foo.c"
174 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
175 }
176
177 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
178 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
179 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
180 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700181 MP->beginAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800182
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700183 // Emit module-level inline asm if it exists.
184 if (!M.getModuleInlineAsm().empty()) {
185 OutStreamer.AddComment("Start of file scope inline assembly");
186 OutStreamer.AddBlankLine();
Chris Lattnera38941d2010-11-17 07:53:40 +0000187 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700188 OutStreamer.AddComment("End of file scope inline assembly");
189 OutStreamer.AddBlankLine();
190 }
191
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700192#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700193 if (MAI->doesSupportDebugInformation())
194 DD = new DwarfDebug(this, &M);
Anton Korobeynikovd7e8ddc2011-01-14 21:57:45 +0000195
Rafael Espindola2d57a642011-05-05 19:48:34 +0000196 switch (MAI->getExceptionHandlingType()) {
197 case ExceptionHandling::None:
198 return false;
199 case ExceptionHandling::SjLj:
Rafael Espindola2d57a642011-05-05 19:48:34 +0000200 case ExceptionHandling::DwarfCFI:
201 DE = new DwarfCFIException(this);
202 return false;
203 case ExceptionHandling::ARM:
204 DE = new ARMException(this);
205 return false;
Charles Davisd652b132011-05-27 23:47:32 +0000206 case ExceptionHandling::Win64:
207 DE = new Win64Exception(this);
208 return false;
Rafael Espindola2d57a642011-05-05 19:48:34 +0000209 }
Nowar Gu907af0f2011-06-17 14:29:24 +0800210#else
211 return false;
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700212#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800213
Rafael Espindola2d57a642011-05-05 19:48:34 +0000214 llvm_unreachable("Unknown exception type.");
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800215}
216
217void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
218 switch ((GlobalValue::LinkageTypes)Linkage) {
219 case GlobalValue::CommonLinkage:
220 case GlobalValue::LinkOnceAnyLinkage:
221 case GlobalValue::LinkOnceODRLinkage:
222 case GlobalValue::WeakAnyLinkage:
223 case GlobalValue::WeakODRLinkage:
Bill Wendlingf8239662010-07-01 21:55:59 +0000224 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling01085e62010-08-20 22:05:50 +0000225 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800226 if (MAI->getWeakDefDirective() != 0) {
227 // .globl _foo
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Bill Wendling01085e62010-08-20 22:05:50 +0000229
230 if ((GlobalValue::LinkageTypes)Linkage !=
231 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
232 // .weak_definition _foo
233 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
234 else
235 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
Duncan Sandsf01b62d2010-05-12 07:11:33 +0000236 } else if (MAI->getLinkOnceDirective() != 0) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800237 // .globl _foo
238 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Duncan Sandsf01b62d2010-05-12 07:11:33 +0000239 //NOTE: linkonce is handled by the section the symbol was assigned to.
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800240 } else {
241 // .weak _foo
242 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
243 }
244 break;
245 case GlobalValue::DLLExportLinkage:
246 case GlobalValue::AppendingLinkage:
247 // FIXME: appending linkage variables should go into a section of
248 // their name or something. For now, just emit them as external.
249 case GlobalValue::ExternalLinkage:
250 // If external or appending, declare as a global symbol.
251 // .globl _foo
252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
253 break;
254 case GlobalValue::PrivateLinkage:
255 case GlobalValue::InternalLinkage:
Bill Wendling73b3a722010-07-01 22:38:24 +0000256 case GlobalValue::LinkerPrivateLinkage:
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800257 break;
258 default:
259 llvm_unreachable("Unknown linkage type!");
260 }
261}
262
263
264/// EmitGlobalVariable - Emit the specified global variable to the .s file.
265void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
Rafael Espindola84397472011-04-05 15:51:32 +0000266 if (GV->hasInitializer()) {
267 // Check to see if this is a special global used by LLVM, if so, emit it.
268 if (EmitSpecialLLVMGlobal(GV))
269 return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800270
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700271 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800272 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
273 /*PrintType=*/false, GV->getParent());
274 OutStreamer.GetCommentOS() << '\n';
275 }
Eric Christopher04386ca2010-05-25 21:49:43 +0000276 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000277
Chris Lattnerdeb0cba2010-03-12 21:09:07 +0000278 MCSymbol *GVSym = Mang->getSymbol(GV);
Chad Rosier348d5422011-06-10 00:53:15 +0000279 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
Chris Lattner74bfe212010-01-19 05:38:33 +0000280
Rafael Espindola84397472011-04-05 15:51:32 +0000281 if (!GV->hasInitializer()) // External globals require no extra code.
282 return;
283
Chris Lattnera800f7c2010-01-25 18:33:40 +0000284 if (MAI->hasDotTypeDotSizeDirective())
285 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
Jim Grosbach83d80832011-03-29 23:20:22 +0000286
Chris Lattner74bfe212010-01-19 05:38:33 +0000287 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
288
289 const TargetData *TD = TM.getTargetData();
Chris Lattnere87f7bb2010-04-28 19:58:07 +0000290 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
Jim Grosbach83d80832011-03-29 23:20:22 +0000291
Chris Lattner567dd1f2010-04-26 18:46:46 +0000292 // If the alignment is specified, we *must* obey it. Overaligning a global
293 // with a specified alignment is a prompt way to break globals emitted to
294 // sections and expected to be contiguous (e.g. ObjC metadata).
Chris Lattnere87f7bb2010-04-28 19:58:07 +0000295 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
Jim Grosbach83d80832011-03-29 23:20:22 +0000296
Chris Lattner9744d612010-01-19 05:51:42 +0000297 // Handle common and BSS local symbols (.lcomm).
298 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner74bfe212010-01-19 05:38:33 +0000299 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
Benjamin Kramer36a16012011-09-01 23:04:27 +0000300 unsigned Align = 1 << AlignLog;
Jim Grosbach83d80832011-03-29 23:20:22 +0000301
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800302 // Handle common symbols.
303 if (GVKind.isCommon()) {
Chris Lattner82f9a8e2010-09-27 06:44:54 +0000304 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
305 Align = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000306
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800307 // .comm _foo, 42, 4
Chris Lattner82f9a8e2010-09-27 06:44:54 +0000308 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800309 return;
310 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000311
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800312 // Handle local BSS symbols.
313 if (MAI->hasMachoZeroFillDirective()) {
314 const MCSection *TheSection =
315 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
316 // .zerofill __DATA, __bss, _foo, 400, 5
Benjamin Kramer36a16012011-09-01 23:04:27 +0000317 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800318 return;
319 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000320
Benjamin Kramer36a16012011-09-01 23:04:27 +0000321 if (MAI->getLCOMMDirectiveType() != LCOMM::None &&
322 (MAI->getLCOMMDirectiveType() != LCOMM::NoAlignment || Align == 1)) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800323 // .lcomm _foo, 42
Benjamin Kramer36a16012011-09-01 23:04:27 +0000324 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800325 return;
326 }
Chris Lattner82f9a8e2010-09-27 06:44:54 +0000327
Chris Lattner82f9a8e2010-09-27 06:44:54 +0000328 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
329 Align = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000330
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800331 // .local _foo
332 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
333 // .comm _foo, 42, 4
Chris Lattner82f9a8e2010-09-27 06:44:54 +0000334 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800335 return;
336 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000337
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800338 const MCSection *TheSection =
339 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
340
341 // Handle the zerofill directive on darwin, which is a special form of BSS
342 // emission.
343 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
Chris Lattner0631a922010-04-27 07:41:44 +0000344 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
Jim Grosbach83d80832011-03-29 23:20:22 +0000345
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800346 // .globl _foo
347 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
348 // .zerofill __DATA, __common, _foo, 400, 5
349 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
350 return;
351 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000352
Eric Christopherfdc794a2010-05-25 21:28:50 +0000353 // Handle thread local data for mach-o which requires us to output an
354 // additional structure of data and mangle the original symbol so that we
355 // can reference it later.
Chris Lattnerc1f3acb2010-09-05 20:33:40 +0000356 //
357 // TODO: This should become an "emit thread local global" method on TLOF.
358 // All of this macho specific stuff should be sunk down into TLOFMachO and
359 // stuff like "TLSExtraDataSection" should no longer be part of the parent
360 // TLOF class. This will also make it more obvious that stuff like
361 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
362 // specific code.
Eric Christopherfdc794a2010-05-25 21:28:50 +0000363 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
Eric Christopher0f986f62010-05-22 00:10:22 +0000364 // Emit the .tbss symbol
Jim Grosbach83d80832011-03-29 23:20:22 +0000365 MCSymbol *MangSym =
Eric Christopher0f986f62010-05-22 00:10:22 +0000366 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
Jim Grosbach83d80832011-03-29 23:20:22 +0000367
Eric Christopherfdc794a2010-05-25 21:28:50 +0000368 if (GVKind.isThreadBSS())
369 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
370 else if (GVKind.isThreadData()) {
371 OutStreamer.SwitchSection(TheSection);
372
Jim Grosbach83d80832011-03-29 23:20:22 +0000373 EmitAlignment(AlignLog, GV);
Eric Christopherfdc794a2010-05-25 21:28:50 +0000374 OutStreamer.EmitLabel(MangSym);
Jim Grosbach83d80832011-03-29 23:20:22 +0000375
Eric Christopherfdc794a2010-05-25 21:28:50 +0000376 EmitGlobalConstant(GV->getInitializer());
377 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000378
Eric Christopher0f986f62010-05-22 00:10:22 +0000379 OutStreamer.AddBlankLine();
Jim Grosbach83d80832011-03-29 23:20:22 +0000380
Eric Christopher0f986f62010-05-22 00:10:22 +0000381 // Emit the variable struct for the runtime.
Jim Grosbach83d80832011-03-29 23:20:22 +0000382 const MCSection *TLVSect
Eric Christopher0f986f62010-05-22 00:10:22 +0000383 = getObjFileLowering().getTLSExtraDataSection();
Jim Grosbach83d80832011-03-29 23:20:22 +0000384
Eric Christopher0f986f62010-05-22 00:10:22 +0000385 OutStreamer.SwitchSection(TLVSect);
386 // Emit the linkage here.
387 EmitLinkage(GV->getLinkage(), GVSym);
388 OutStreamer.EmitLabel(GVSym);
Jim Grosbach83d80832011-03-29 23:20:22 +0000389
Eric Christopher0f986f62010-05-22 00:10:22 +0000390 // Three pointers in size:
391 // - __tlv_bootstrap - used to make sure support exists
392 // - spare pointer, used when mapped by the runtime
393 // - pointer to mangled symbol above with initializer
394 unsigned PtrSize = TD->getPointerSizeInBits()/8;
Eric Christopherdbf4b2d2010-06-03 04:02:59 +0000395 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
Eric Christopher0f986f62010-05-22 00:10:22 +0000396 PtrSize, 0);
397 OutStreamer.EmitIntValue(0, PtrSize, 0);
398 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
Jim Grosbach83d80832011-03-29 23:20:22 +0000399
Eric Christopher0f986f62010-05-22 00:10:22 +0000400 OutStreamer.AddBlankLine();
Eric Christopher2d4ea3e2010-05-20 00:49:07 +0000401 return;
402 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800403
404 OutStreamer.SwitchSection(TheSection);
405
406 EmitLinkage(GV->getLinkage(), GVSym);
407 EmitAlignment(AlignLog, GV);
408
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800409 OutStreamer.EmitLabel(GVSym);
410
411 EmitGlobalConstant(GV->getInitializer());
412
413 if (MAI->hasDotTypeDotSizeDirective())
414 // .size foo, 42
415 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
Jim Grosbach83d80832011-03-29 23:20:22 +0000416
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800417 OutStreamer.AddBlankLine();
418}
419
420/// EmitFunctionHeader - This method emits the header for the current
421/// function.
422void AsmPrinter::EmitFunctionHeader() {
423 // Print out constants referenced by the function
424 EmitConstantPool();
Jim Grosbach83d80832011-03-29 23:20:22 +0000425
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800426 // Print the 'header' of function.
427 const Function *F = MF->getFunction();
428
429 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
430 EmitVisibility(CurrentFnSym, F->getVisibility());
431
432 EmitLinkage(F->getLinkage(), CurrentFnSym);
433 EmitAlignment(MF->getAlignment(), F);
434
435 if (MAI->hasDotTypeDotSizeDirective())
436 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
437
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700438 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800439 WriteAsOperand(OutStreamer.GetCommentOS(), F,
440 /*PrintType=*/false, F->getParent());
441 OutStreamer.GetCommentOS() << '\n';
442 }
443
444 // Emit the CurrentFnSym. This is a virtual function to allow targets to
445 // do their wild and crazy things as required.
446 EmitFunctionEntryLabel();
Jim Grosbach83d80832011-03-29 23:20:22 +0000447
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700448 // If the function had address-taken blocks that got deleted, then we have
449 // references to the dangling symbols. Emit them at the start of the function
450 // so that we don't get references to undefined symbols.
451 std::vector<MCSymbol*> DeadBlockSyms;
452 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
453 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
454 OutStreamer.AddComment("Address taken block that was later removed");
455 OutStreamer.EmitLabel(DeadBlockSyms[i]);
456 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000457
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800458 // Add some workaround for linkonce linkage on Cygwin\MinGW.
459 if (MAI->getLinkOnceDirective() != 0 &&
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700460 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800461 // FIXME: What is this?
Jim Grosbach83d80832011-03-29 23:20:22 +0000462 MCSymbol *FakeStub =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700463 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
464 CurrentFnSym->getName());
465 OutStreamer.EmitLabel(FakeStub);
466 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000467
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800468 // Emit pre-function debug and/or EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700469#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700470 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000471 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
472 DE->BeginFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700473 }
474 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000475 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
476 DD->beginFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700477 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700478#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800479}
480
481/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
482/// function. This can be overridden by targets as required to do custom stuff.
483void AsmPrinter::EmitFunctionEntryLabel() {
Chris Lattnerd095d342010-05-06 00:05:37 +0000484 // The function label could have already been emitted if two symbols end up
485 // conflicting due to asm renaming. Detect this and emit an error.
Owen Anderson2fec6c52011-10-04 23:26:17 +0000486 if (CurrentFnSym->isUndefined()) {
487 OutStreamer.ForceCodeRegion();
Chris Lattnerd095d342010-05-06 00:05:37 +0000488 return OutStreamer.EmitLabel(CurrentFnSym);
Owen Anderson2fec6c52011-10-04 23:26:17 +0000489 }
Chris Lattnerd095d342010-05-06 00:05:37 +0000490
491 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
492 "' label emitted multiple times to assembly file");
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800493}
494
495
Devang Patelabb79d92010-06-29 22:29:15 +0000496/// EmitComments - Pretty-print comments for instructions.
497static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
498 const MachineFunction *MF = MI.getParent()->getParent();
499 const TargetMachine &TM = MF->getTarget();
Jim Grosbach83d80832011-03-29 23:20:22 +0000500
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800501 // Check for spills and reloads
502 int FI;
Jim Grosbach83d80832011-03-29 23:20:22 +0000503
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800504 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000505
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800506 // We assume a single instruction only has a spill or reload, not
507 // both.
508 const MachineMemOperand *MMO;
509 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
510 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
511 MMO = *MI.memoperands_begin();
512 CommentOS << MMO->getSize() << "-byte Reload\n";
513 }
514 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
515 if (FrameInfo->isSpillSlotObjectIndex(FI))
516 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
517 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
518 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
519 MMO = *MI.memoperands_begin();
520 CommentOS << MMO->getSize() << "-byte Spill\n";
521 }
522 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
523 if (FrameInfo->isSpillSlotObjectIndex(FI))
524 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
525 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000526
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800527 // Check for spill-induced copies
Jakob Stoklund Olesendef3acb2010-07-16 04:45:42 +0000528 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
529 CommentOS << " Reload Reuse\n";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800530}
531
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700532/// EmitImplicitDef - This method emits the specified machine instruction
533/// that is an implicit def.
534static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
535 unsigned RegNo = MI->getOperand(0).getReg();
536 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
537 AP.TM.getRegisterInfo()->getName(RegNo));
538 AP.OutStreamer.AddBlankLine();
539}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800540
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700541static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
542 std::string Str = "kill:";
543 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
544 const MachineOperand &Op = MI->getOperand(i);
545 assert(Op.isReg() && "KILL instruction must have only register operands");
546 Str += ' ';
547 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
548 Str += (Op.isDef() ? "<def>" : "<kill>");
549 }
550 AP.OutStreamer.AddComment(Str);
551 AP.OutStreamer.AddBlankLine();
552}
553
554/// EmitDebugValueComment - This method handles the target-independent form
555/// of DBG_VALUE, returning true if it was able to do so. A false return
556/// means the target will need to handle MI in EmitInstruction.
557static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
558 // This code handles only the 3-operand target-independent form.
559 if (MI->getNumOperands() != 3)
560 return false;
561
562 SmallString<128> Str;
563 raw_svector_ostream OS(Str);
564 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
565
566 // cast away const; DIetc do not take const operands for some reason.
567 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
Devang Patel77defb52010-04-29 18:52:10 +0000568 if (V.getContext().isSubprogram())
Devang Patel19302aa2010-05-07 18:11:54 +0000569 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700570 OS << V.getName() << " <- ";
571
572 // Register or immediate value. Register 0 means undef.
573 if (MI->getOperand(0).isFPImm()) {
574 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
575 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
576 OS << (double)APF.convertToFloat();
577 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
578 OS << APF.convertToDouble();
579 } else {
580 // There is no good way to print long double. Convert a copy to
581 // double. Ah well, it's only a comment.
582 bool ignored;
583 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
584 &ignored);
585 OS << "(long double) " << APF.convertToDouble();
586 }
587 } else if (MI->getOperand(0).isImm()) {
588 OS << MI->getOperand(0).getImm();
Devang Patel8594d422011-06-24 20:46:11 +0000589 } else if (MI->getOperand(0).isCImm()) {
590 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700591 } else {
592 assert(MI->getOperand(0).isReg() && "Unknown operand type");
593 if (MI->getOperand(0).getReg() == 0) {
594 // Suppress offset, it is not meaningful here.
595 OS << "undef";
596 // NOTE: Want this comment at start of line, don't emit with AddComment.
597 AP.OutStreamer.EmitRawText(OS.str());
598 return true;
599 }
600 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
601 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000602
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700603 OS << '+' << MI->getOperand(1).getImm();
604 // NOTE: Want this comment at start of line, don't emit with AddComment.
605 AP.OutStreamer.EmitRawText(OS.str());
606 return true;
607}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800608
Rafael Espindolae29887b2011-05-10 18:39:09 +0000609AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000610 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
611 MF->getFunction()->needsUnwindTableEntry())
612 return CFI_M_EH;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000613
Rafael Espindolaf2b04232011-05-06 14:56:22 +0000614 if (MMI->hasDebugInfo())
Rafael Espindolae29887b2011-05-10 18:39:09 +0000615 return CFI_M_Debug;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000616
Rafael Espindolae29887b2011-05-10 18:39:09 +0000617 return CFI_M_None;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000618}
619
Charles Davisf4633702011-05-28 04:21:04 +0000620bool AsmPrinter::needsSEHMoves() {
621 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
622 MF->getFunction()->needsUnwindTableEntry();
623}
624
Nick Lewycky2be084a2011-10-27 06:44:11 +0000625bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
626 return MAI->doesDwarfUseRelocationsForStringPool();
627}
628
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000629void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
630 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
Rafael Espindolafea8fea2011-04-26 19:26:53 +0000631
Rafael Espindolaf2b04232011-05-06 14:56:22 +0000632 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000633 return;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000634
Rafael Espindolae29887b2011-05-10 18:39:09 +0000635 if (needsCFIMoves() == CFI_M_None)
Rafael Espindolaa4329972011-04-29 14:14:06 +0000636 return;
637
Bill Wendlinge060a5c2011-07-19 00:02:51 +0000638 if (MMI->getCompactUnwindEncoding() != 0)
639 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
640
Rafael Espindolaa4329972011-04-29 14:14:06 +0000641 MachineModuleInfo &MMI = MF->getMMI();
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000642 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000643 bool FoundOne = false;
644 (void)FoundOne;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000645 for (std::vector<MachineMove>::iterator I = Moves.begin(),
646 E = Moves.end(); I != E; ++I) {
647 if (I->getLabel() == Label) {
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000648 EmitCFIFrameMove(*I);
649 FoundOne = true;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000650 }
651 }
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000652 assert(FoundOne);
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000653}
654
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800655/// EmitFunctionBody - This method emits the body and trailer for a
656/// function.
657void AsmPrinter::EmitFunctionBody() {
658 // Emit target-specific gunk before the function body.
659 EmitFunctionBodyStart();
Jim Grosbach83d80832011-03-29 23:20:22 +0000660
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700661 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000662
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800663 // Print out code for the function.
664 bool HasAnyRealCode = false;
Bill Wendling5a1bec12010-07-16 22:51:10 +0000665 const MachineInstr *LastMI = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800666 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
667 I != E; ++I) {
668 // Print a label for the basic block.
669 EmitBasicBlockStart(I);
670 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
671 II != IE; ++II) {
Bill Wendling5a1bec12010-07-16 22:51:10 +0000672 LastMI = II;
673
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800674 // Print the assembly for the instruction.
Dale Johannesen1ffdb1f2010-05-01 16:41:11 +0000675 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
676 !II->isDebugValue()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800677 HasAnyRealCode = true;
678
Evan Cheng53a0cbf2010-04-27 19:38:45 +0000679 ++EmittedInsts;
Shih-wei Liaoa95f5892010-09-11 01:42:09 -0700680 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700681#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700682 if (ShouldPrintDebugScopes) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000683 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Devang Patel2bfdc272010-10-26 17:49:02 +0000684 DD->beginInstruction(II);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700685 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700686#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800687
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700688 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800689 EmitComments(*II, OutStreamer.GetCommentOS());
690
691 switch (II->getOpcode()) {
Bill Wendlinga02effc2010-07-16 22:20:36 +0000692 case TargetOpcode::PROLOG_LABEL:
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000693 emitPrologLabel(*II);
694 break;
695
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800696 case TargetOpcode::EH_LABEL:
697 case TargetOpcode::GC_LABEL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700698 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800699 break;
700 case TargetOpcode::INLINEASM:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700701 EmitInlineAsm(II);
702 break;
703 case TargetOpcode::DBG_VALUE:
704 if (isVerbose()) {
705 if (!EmitDebugValueComment(II, *this))
706 EmitInstruction(II);
707 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800708 break;
709 case TargetOpcode::IMPLICIT_DEF:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700710 if (isVerbose()) EmitImplicitDef(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800711 break;
712 case TargetOpcode::KILL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700713 if (isVerbose()) EmitKill(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800714 break;
715 default:
Devang Patel49a3ff92011-04-29 18:00:54 +0000716 if (!TM.hasMCUseLoc())
717 MCLineEntry::Make(&OutStreamer, getCurrentSection());
718
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800719 EmitInstruction(II);
720 break;
721 }
722
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700723#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700724 if (ShouldPrintDebugScopes) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000725 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Devang Patel2bfdc272010-10-26 17:49:02 +0000726 DD->endInstruction(II);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700727 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700728#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800729 }
730 }
Bill Wendling5a1bec12010-07-16 22:51:10 +0000731
732 // If the last instruction was a prolog label, then we have a situation where
733 // we emitted a prolog but no function body. This results in the ending prolog
734 // label equaling the end of function label and an invalid "row" in the
735 // FDE. We need to emit a noop in this situation so that the FDE's rows are
736 // valid.
Bill Wendlingf7e17752010-07-17 19:18:44 +0000737 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
Bill Wendling5a1bec12010-07-16 22:51:10 +0000738
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800739 // If the function is empty and the object file uses .subsections_via_symbols,
740 // then we need to emit *something* to the function body to prevent the
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700741 // labels from collapsing together. Just emit a noop.
Bill Wendling5a1bec12010-07-16 22:51:10 +0000742 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700743 MCInst Noop;
744 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
745 if (Noop.getOpcode()) {
746 OutStreamer.AddComment("avoids zero-length function");
747 OutStreamer.EmitInstruction(Noop);
748 } else // Target not mc-ized yet.
749 OutStreamer.EmitRawText(StringRef("\tnop\n"));
750 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000751
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800752 // Emit target-specific gunk after the function body.
753 EmitFunctionBodyEnd();
Jim Grosbach83d80832011-03-29 23:20:22 +0000754
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700755 // If the target wants a .size directive for the size of the function, emit
756 // it.
757 if (MAI->hasDotTypeDotSizeDirective()) {
758 // Create a symbol for the end of function, so we can get the size as
759 // difference between the function label and the temp label.
760 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
761 OutStreamer.EmitLabel(FnEndLabel);
Jim Grosbach83d80832011-03-29 23:20:22 +0000762
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700763 const MCExpr *SizeExp =
764 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
765 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
766 OutContext);
767 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
768 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000769
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800770 // Emit post-function debug information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700771#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700772 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000773 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
774 DD->endFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700775 }
776 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000777 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
778 DE->EndFunction();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700779 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700780#endif // ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700781 MMI->EndFunction();
Jim Grosbach83d80832011-03-29 23:20:22 +0000782
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800783 // Print out jump tables referenced by the function.
784 EmitJumpTableInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000785
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800786 OutStreamer.AddBlankLine();
787}
788
Devang Patel7c3efb12010-04-28 01:39:28 +0000789/// getDebugValueLocation - Get location information encoded by DBG_VALUE
790/// operands.
Jim Grosbach83d80832011-03-29 23:20:22 +0000791MachineLocation AsmPrinter::
792getDebugValueLocation(const MachineInstr *MI) const {
Devang Patel7c3efb12010-04-28 01:39:28 +0000793 // Target specific DBG_VALUE instructions are handled by each target.
794 return MachineLocation();
795}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800796
Devang Patelacc381b2011-04-21 21:07:35 +0000797/// EmitDwarfRegOp - Emit dwarf register operation.
Devang Patel0be77df2011-04-27 20:29:27 +0000798void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
Devang Patelc26f5442011-04-28 02:22:40 +0000799 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Rafael Espindola37afca12011-05-27 22:15:01 +0000800 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
801
802 for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
Rafael Espindola7bf114c2011-05-28 00:13:01 +0000803 *SR && Reg < 0; ++SR) {
Rafael Espindola37afca12011-05-27 22:15:01 +0000804 Reg = TRI->getDwarfRegNum(*SR, false);
805 // FIXME: Get the bit range this register uses of the superregister
806 // so that we can produce a DW_OP_bit_piece
807 }
808
809 // FIXME: Handle cases like a super register being encoded as
810 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
811
812 // FIXME: We have no reasonable way of handling errors in here. The
813 // caller might be in the middle of an dwarf expression. We should
814 // probably assert that Reg >= 0 once debug info generation is more mature.
815
Devang Patelacc381b2011-04-21 21:07:35 +0000816 if (int Offset = MLoc.getOffset()) {
Devang Patelc26f5442011-04-28 02:22:40 +0000817 if (Reg < 32) {
818 OutStreamer.AddComment(
819 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
820 EmitInt8(dwarf::DW_OP_breg0 + Reg);
821 } else {
822 OutStreamer.AddComment("DW_OP_bregx");
823 EmitInt8(dwarf::DW_OP_bregx);
824 OutStreamer.AddComment(Twine(Reg));
825 EmitULEB128(Reg);
826 }
Devang Patelacc381b2011-04-21 21:07:35 +0000827 EmitSLEB128(Offset);
828 } else {
829 if (Reg < 32) {
Devang Patelacc381b2011-04-21 21:07:35 +0000830 OutStreamer.AddComment(
831 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
832 EmitInt8(dwarf::DW_OP_reg0 + Reg);
833 } else {
Devang Patelc26f5442011-04-28 02:22:40 +0000834 OutStreamer.AddComment("DW_OP_regx");
Devang Patelacc381b2011-04-21 21:07:35 +0000835 EmitInt8(dwarf::DW_OP_regx);
836 OutStreamer.AddComment(Twine(Reg));
837 EmitULEB128(Reg);
838 }
839 }
Rafael Espindola37afca12011-05-27 22:15:01 +0000840
841 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
Devang Patelacc381b2011-04-21 21:07:35 +0000842}
843
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800844bool AsmPrinter::doFinalization(Module &M) {
845 // Emit global variables.
846 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
847 I != E; ++I)
848 EmitGlobalVariable(I);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000849
850 // Emit visibility info for declarations
851 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
852 const Function &F = *I;
853 if (!F.isDeclaration())
854 continue;
855 GlobalValue::VisibilityTypes V = F.getVisibility();
856 if (V == GlobalValue::DefaultVisibility)
857 continue;
858
859 MCSymbol *Name = Mang->getSymbol(&F);
Stuart Hastings5129bde2011-02-23 02:27:05 +0000860 EmitVisibility(Name, V, false);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000861 }
862
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700863 // Finalize debug and EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700864#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700865 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000866 {
867 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700868 DE->EndModule();
869 }
870 delete DE; DE = 0;
871 }
872 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000873 {
874 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700875 DD->endModule();
876 }
877 delete DD; DD = 0;
878 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700879#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800880
881 // If the target wants to know about weak references, print them all.
882 if (MAI->getWeakRefDirective()) {
883 // FIXME: This is not lazy, it would be nice to only print weak references
884 // to stuff that is actually used. Note that doing so would require targets
885 // to notice uses in operands (due to constant exprs etc). This should
886 // happen with the MC stuff eventually.
887
888 // Print out module-level global variables here.
889 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
890 I != E; ++I) {
891 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700892 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800893 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000894
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800895 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
896 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700897 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800898 }
899 }
900
901 if (MAI->hasSetDirective()) {
902 OutStreamer.AddBlankLine();
903 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
904 I != E; ++I) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700905 MCSymbol *Name = Mang->getSymbol(I);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800906
Jay Foadb899d952011-08-01 12:27:15 +0000907 const GlobalValue *GV = I->getAliasedGlobal();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700908 MCSymbol *Target = Mang->getSymbol(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800909
910 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
911 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
912 else if (I->hasWeakLinkage())
913 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
914 else
915 assert(I->hasLocalLinkage() && "Invalid alias linkage");
916
917 EmitVisibility(Name, I->getVisibility());
918
919 // Emit the directives as assignments aka .set:
Jim Grosbach83d80832011-03-29 23:20:22 +0000920 OutStreamer.EmitAssignment(Name,
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800921 MCSymbolRefExpr::Create(Target, OutContext));
922 }
923 }
924
925 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
926 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
927 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
928 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700929 MP->finishAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800930
931 // If we don't have any trampolines, then we don't require stack memory
932 // to be executable. Some targets have a directive to declare this.
933 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
934 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700935 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800936 OutStreamer.SwitchSection(S);
Jim Grosbach83d80832011-03-29 23:20:22 +0000937
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800938 // Allow the target to emit any magic that it wants at the end of the file,
939 // after everything else has gone out.
940 EmitEndOfAsmFile(M);
Jim Grosbach83d80832011-03-29 23:20:22 +0000941
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800942 delete Mang; Mang = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700943 MMI = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000944
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800945 OutStreamer.Finish();
946 return false;
947}
948
949void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
950 this->MF = &MF;
951 // Get the function symbol.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700952 CurrentFnSym = Mang->getSymbol(MF.getFunction());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800953
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700954 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800955 LI = &getAnalysis<MachineLoopInfo>();
956}
957
958namespace {
959 // SectionCPs - Keep track the alignment, constpool entries per Section.
960 struct SectionCPs {
961 const MCSection *S;
962 unsigned Alignment;
963 SmallVector<unsigned, 4> CPEs;
964 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
965 };
966}
967
968/// EmitConstantPool - Print to the current output stream assembly
969/// representations of the constants in the constant pool MCP. This is
970/// used to print out constants which have been "spilled to memory" by
971/// the code generator.
972///
973void AsmPrinter::EmitConstantPool() {
974 const MachineConstantPool *MCP = MF->getConstantPool();
975 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
976 if (CP.empty()) return;
977
978 // Calculate sections for constant pool entries. We collect entries to go into
979 // the same section together to reduce amount of section switch statements.
980 SmallVector<SectionCPs, 4> CPSections;
981 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
982 const MachineConstantPoolEntry &CPE = CP[i];
983 unsigned Align = CPE.getAlignment();
Jim Grosbach83d80832011-03-29 23:20:22 +0000984
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800985 SectionKind Kind;
986 switch (CPE.getRelocationInfo()) {
987 default: llvm_unreachable("Unknown section kind");
988 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
989 case 1:
990 Kind = SectionKind::getReadOnlyWithRelLocal();
991 break;
992 case 0:
993 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
994 case 4: Kind = SectionKind::getMergeableConst4(); break;
995 case 8: Kind = SectionKind::getMergeableConst8(); break;
996 case 16: Kind = SectionKind::getMergeableConst16();break;
997 default: Kind = SectionKind::getMergeableConst(); break;
998 }
999 }
1000
1001 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Jim Grosbach83d80832011-03-29 23:20:22 +00001002
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001003 // The number of sections are small, just do a linear search from the
1004 // last section to the first.
1005 bool Found = false;
1006 unsigned SecIdx = CPSections.size();
1007 while (SecIdx != 0) {
1008 if (CPSections[--SecIdx].S == S) {
1009 Found = true;
1010 break;
1011 }
1012 }
1013 if (!Found) {
1014 SecIdx = CPSections.size();
1015 CPSections.push_back(SectionCPs(S, Align));
1016 }
1017
1018 if (Align > CPSections[SecIdx].Alignment)
1019 CPSections[SecIdx].Alignment = Align;
1020 CPSections[SecIdx].CPEs.push_back(i);
1021 }
1022
1023 // Now print stuff into the calculated sections.
1024 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1025 OutStreamer.SwitchSection(CPSections[i].S);
1026 EmitAlignment(Log2_32(CPSections[i].Alignment));
1027
1028 unsigned Offset = 0;
1029 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1030 unsigned CPI = CPSections[i].CPEs[j];
1031 MachineConstantPoolEntry CPE = CP[CPI];
1032
1033 // Emit inter-object padding for alignment.
1034 unsigned AlignMask = CPE.getAlignment() - 1;
1035 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1036 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1037
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001038 Type *Ty = CPE.getType();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001039 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001040 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1041
1042 if (CPE.isMachineConstantPoolEntry())
1043 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1044 else
1045 EmitGlobalConstant(CPE.Val.ConstVal);
1046 }
1047 }
1048}
1049
1050/// EmitJumpTableInfo - Print assembly representations of the jump tables used
Jim Grosbach83d80832011-03-29 23:20:22 +00001051/// by the current function to the current output stream.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001052///
1053void AsmPrinter::EmitJumpTableInfo() {
1054 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1055 if (MJTI == 0) return;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001056 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001057 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1058 if (JT.empty()) return;
1059
Jim Grosbach83d80832011-03-29 23:20:22 +00001060 // Pick the directive to use to print the jump table entries, and switch to
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001061 // the appropriate section.
1062 const Function *F = MF->getFunction();
1063 bool JTInDiffSection = false;
1064 if (// In PIC mode, we need to emit the jump table to the same section as the
1065 // function body itself, otherwise the label differences won't make sense.
1066 // FIXME: Need a better predicate for this: what about custom entries?
1067 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1068 // We should also do if the section name is NULL or function is declared
1069 // in discardable section
1070 // FIXME: this isn't the right predicate, should be based on the MCSection
1071 // for the function.
1072 F->isWeakForLinker()) {
1073 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1074 } else {
1075 // Otherwise, drop it in the readonly section.
Jim Grosbach83d80832011-03-29 23:20:22 +00001076 const MCSection *ReadOnlySection =
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001077 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1078 OutStreamer.SwitchSection(ReadOnlySection);
1079 JTInDiffSection = true;
1080 }
1081
1082 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
Jim Grosbach83d80832011-03-29 23:20:22 +00001083
Owen Anderson2fec6c52011-10-04 23:26:17 +00001084 // If we know the form of the jump table, go ahead and tag it as such.
1085 if (!JTInDiffSection) {
1086 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32) {
1087 OutStreamer.EmitJumpTable32Region();
1088 } else {
1089 OutStreamer.EmitDataRegion();
1090 }
1091 }
1092
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001093 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1094 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Jim Grosbach83d80832011-03-29 23:20:22 +00001095
1096 // If this jump table was deleted, ignore it.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001097 if (JTBBs.empty()) continue;
1098
1099 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1100 // .set directive for each unique entry. This reduces the number of
1101 // relocations the assembler will generate for the jump table.
1102 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1103 MAI->hasSetDirective()) {
1104 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1105 const TargetLowering *TLI = TM.getTargetLowering();
1106 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1107 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1108 const MachineBasicBlock *MBB = JTBBs[ii];
1109 if (!EmittedSets.insert(MBB)) continue;
Jim Grosbach83d80832011-03-29 23:20:22 +00001110
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001111 // .set LJTSet, LBB32-base
1112 const MCExpr *LHS =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001113 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001114 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1115 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1116 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001117 }
1118
Duncan Sandsab4c3662011-02-15 09:23:02 +00001119 // On some targets (e.g. Darwin) we want to emit two consecutive labels
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001120 // before each jump table. The first label is never referenced, but tells
1121 // the assembler and linker the extents of the jump table object. The
1122 // second label is actually referenced by the code.
1123 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1124 // FIXME: This doesn't have to have any specific name, just any randomly
1125 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1126 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1127
1128 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1129
1130 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1131 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1132 }
1133}
1134
1135/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1136/// current stream.
1137void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1138 const MachineBasicBlock *MBB,
1139 unsigned UID) const {
Jakob Stoklund Olesene5005d02011-02-09 21:52:06 +00001140 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001141 const MCExpr *Value = 0;
1142 switch (MJTI->getEntryKind()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001143 case MachineJumpTableInfo::EK_Inline:
1144 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001145 case MachineJumpTableInfo::EK_Custom32:
1146 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1147 OutContext);
1148 break;
1149 case MachineJumpTableInfo::EK_BlockAddress:
1150 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1151 // .word LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001152 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001153 break;
1154 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1155 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1156 // with a relocation as gp-relative, e.g.:
1157 // .gprel32 LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001158 MCSymbol *MBBSym = MBB->getSymbol();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001159 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1160 return;
1161 }
1162
1163 case MachineJumpTableInfo::EK_LabelDifference32: {
1164 // EK_LabelDifference32 - Each entry is the address of the block minus
1165 // the address of the jump table. This is used for PIC jump tables where
1166 // gprel32 is not supported. e.g.:
1167 // .word LBB123 - LJTI1_2
1168 // If the .set directive is supported, this is emitted as:
1169 // .set L4_5_set_123, LBB123 - LJTI1_2
1170 // .word L4_5_set_123
Jim Grosbach83d80832011-03-29 23:20:22 +00001171
1172 // If we have emitted set directives for the jump table entries, print
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001173 // them rather than the entries themselves. If we're emitting PIC, then
1174 // emit the table entries as differences between two text section labels.
1175 if (MAI->hasSetDirective()) {
1176 // If we used .set, reference the .set's symbol.
1177 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1178 OutContext);
1179 break;
1180 }
1181 // Otherwise, use the difference as the jump table entry.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001182 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001183 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1184 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1185 break;
1186 }
1187 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001188
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001189 assert(Value && "Unknown entry kind!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001190
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001191 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1192 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1193}
1194
1195
1196/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1197/// special global used by LLVM. If so, emit it and return true, otherwise
1198/// do nothing and return false.
1199bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1200 if (GV->getName() == "llvm.used") {
1201 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1202 EmitLLVMUsedList(GV->getInitializer());
1203 return true;
1204 }
1205
1206 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1207 if (GV->getSection() == "llvm.metadata" ||
1208 GV->hasAvailableExternallyLinkage())
1209 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001210
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001211 if (!GV->hasAppendingLinkage()) return false;
1212
1213 assert(GV->hasInitializer() && "Not a special LLVM global!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001214
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001215 const TargetData *TD = TM.getTargetData();
1216 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1217 if (GV->getName() == "llvm.global_ctors") {
1218 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner7516e9e2010-04-28 19:58:07 +00001219 EmitAlignment(Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001220 EmitXXStructorList(GV->getInitializer());
Jim Grosbach83d80832011-03-29 23:20:22 +00001221
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001222 if (TM.getRelocationModel() == Reloc::Static &&
1223 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1224 StringRef Sym(".constructors_used");
1225 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1226 MCSA_Reference);
1227 }
1228 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001229 }
1230
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001231 if (GV->getName() == "llvm.global_dtors") {
1232 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner7516e9e2010-04-28 19:58:07 +00001233 EmitAlignment(Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001234 EmitXXStructorList(GV->getInitializer());
1235
1236 if (TM.getRelocationModel() == Reloc::Static &&
1237 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1238 StringRef Sym(".destructors_used");
1239 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1240 MCSA_Reference);
1241 }
1242 return true;
1243 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001244
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001245 return false;
1246}
1247
1248/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1249/// global in the specified llvm.used list for which emitUsedDirectiveFor
1250/// is true, as being used with this directive.
Jay Foad7d715df2011-06-19 18:37:11 +00001251void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001252 // Should be an array of 'i8*'.
Jay Foad7d715df2011-06-19 18:37:11 +00001253 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001254 if (InitList == 0) return;
Jim Grosbach83d80832011-03-29 23:20:22 +00001255
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001256 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1257 const GlobalValue *GV =
1258 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1259 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001260 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001261 }
1262}
1263
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001264typedef std::pair<int, Constant*> Structor;
1265
Duncan Sands9a7d48a2011-09-29 16:01:46 +00001266static bool priority_order(const Structor& lhs, const Structor& rhs) {
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001267 return lhs.first < rhs.first;
1268}
1269
1270/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1271/// priority.
Jay Foad7d715df2011-06-19 18:37:11 +00001272void AsmPrinter::EmitXXStructorList(const Constant *List) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001273 // Should be an array of '{ int, void ()* }' structs. The first value is the
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001274 // init priority.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001275 if (!isa<ConstantArray>(List)) return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001276
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001277 // Sanity check the structors list.
1278 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1279 if (!InitList) return; // Not an array!
1280 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1281 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1282 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1283 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1284
1285 // Gather the structors in a form that's convenient for sorting by priority.
1286 SmallVector<Structor, 8> Structors;
1287 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1288 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1289 if (!CS) continue; // Malformed.
1290 if (CS->getOperand(1)->isNullValue())
1291 break; // Found a null terminator, skip the rest.
1292 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1293 if (!Priority) continue; // Malformed.
1294 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1295 CS->getOperand(1)));
1296 }
1297
1298 // Emit the function pointers in reverse priority order.
Duncan Sands147272b2011-09-02 18:07:19 +00001299 switch (MAI->getStructorOutputOrder()) {
1300 case Structors::None:
1301 break;
1302 case Structors::PriorityOrder:
1303 std::sort(Structors.begin(), Structors.end(), priority_order);
1304 break;
1305 case Structors::ReversePriorityOrder:
1306 std::sort(Structors.rbegin(), Structors.rend(), priority_order);
1307 break;
1308 }
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001309 for (unsigned i = 0, e = Structors.size(); i != e; ++i)
1310 EmitGlobalConstant(Structors[i].second);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001311}
1312
1313//===--------------------------------------------------------------------===//
1314// Emission and print routines
1315//
1316
1317/// EmitInt8 - Emit a byte directive and value.
1318///
1319void AsmPrinter::EmitInt8(int Value) const {
1320 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1321}
1322
1323/// EmitInt16 - Emit a short directive and value.
1324///
1325void AsmPrinter::EmitInt16(int Value) const {
1326 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1327}
1328
1329/// EmitInt32 - Emit a long directive and value.
1330///
1331void AsmPrinter::EmitInt32(int Value) const {
1332 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1333}
1334
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001335/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1336/// in bytes of the directive is specified by Size and Hi/Lo specify the
1337/// labels. This implicitly uses .set if it is available.
1338void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1339 unsigned Size) const {
1340 // Get the Hi-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001341 const MCExpr *Diff =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001342 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1343 MCSymbolRefExpr::Create(Lo, OutContext),
1344 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001345
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001346 if (!MAI->hasSetDirective()) {
1347 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1348 return;
1349 }
1350
1351 // Otherwise, emit with .set (aka assignment).
1352 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1353 OutStreamer.EmitAssignment(SetLabel, Diff);
1354 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001355}
1356
Jim Grosbach83d80832011-03-29 23:20:22 +00001357/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001358/// where the size in bytes of the directive is specified by Size and Hi/Lo
1359/// specify the labels. This implicitly uses .set if it is available.
1360void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
Jim Grosbach83d80832011-03-29 23:20:22 +00001361 const MCSymbol *Lo, unsigned Size)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001362 const {
Jim Grosbach83d80832011-03-29 23:20:22 +00001363
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001364 // Emit Hi+Offset - Lo
1365 // Get the Hi+Offset expression.
1366 const MCExpr *Plus =
Jim Grosbach83d80832011-03-29 23:20:22 +00001367 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001368 MCConstantExpr::Create(Offset, OutContext),
1369 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001370
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001371 // Get the Hi+Offset-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001372 const MCExpr *Diff =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001373 MCBinaryExpr::CreateSub(Plus,
1374 MCSymbolRefExpr::Create(Lo, OutContext),
1375 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001376
1377 if (!MAI->hasSetDirective())
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001378 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1379 else {
1380 // Otherwise, emit with .set (aka assignment).
1381 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1382 OutStreamer.EmitAssignment(SetLabel, Diff);
1383 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1384 }
1385}
Devang Patel17e9a622010-09-02 16:43:44 +00001386
Jim Grosbach83d80832011-03-29 23:20:22 +00001387/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
Devang Patel17e9a622010-09-02 16:43:44 +00001388/// where the size in bytes of the directive is specified by Size and Label
1389/// specifies the label. This implicitly uses .set if it is available.
1390void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
Jim Grosbach83d80832011-03-29 23:20:22 +00001391 unsigned Size)
Devang Patel17e9a622010-09-02 16:43:44 +00001392 const {
Jim Grosbach83d80832011-03-29 23:20:22 +00001393
Devang Patel17e9a622010-09-02 16:43:44 +00001394 // Emit Label+Offset
1395 const MCExpr *Plus =
Jim Grosbach83d80832011-03-29 23:20:22 +00001396 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
Devang Patel17e9a622010-09-02 16:43:44 +00001397 MCConstantExpr::Create(Offset, OutContext),
1398 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001399
Devang Patele5e909f2010-09-02 23:01:10 +00001400 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
Devang Patel17e9a622010-09-02 16:43:44 +00001401}
Jim Grosbach83d80832011-03-29 23:20:22 +00001402
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001403
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001404//===----------------------------------------------------------------------===//
1405
1406// EmitAlignment - Emit an alignment directive to the specified power of
1407// two boundary. For example, if you pass in 3 here, you will get an 8
1408// byte alignment. If a global value is specified, and if that global has
Chris Lattner7516e9e2010-04-28 19:58:07 +00001409// an explicit alignment requested, it will override the alignment request
1410// if required for correctness.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001411//
Chris Lattner027b9362010-04-28 01:08:40 +00001412void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
Chris Lattner7516e9e2010-04-28 19:58:07 +00001413 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
Jim Grosbach83d80832011-03-29 23:20:22 +00001414
Chris Lattner7516e9e2010-04-28 19:58:07 +00001415 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
Jim Grosbach83d80832011-03-29 23:20:22 +00001416
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001417 if (getCurrentSection()->getKind().isText())
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001418 OutStreamer.EmitCodeAlignment(1 << NumBits);
1419 else
1420 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001421}
1422
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001423//===----------------------------------------------------------------------===//
1424// Constant emission.
1425//===----------------------------------------------------------------------===//
1426
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001427/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1428///
1429static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1430 MCContext &Ctx = AP.OutContext;
Jim Grosbach83d80832011-03-29 23:20:22 +00001431
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001432 if (CV->isNullValue() || isa<UndefValue>(CV))
1433 return MCConstantExpr::Create(0, Ctx);
1434
1435 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1436 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001437
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001438 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001439 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
Bill Wendling021fd612010-08-18 18:41:13 +00001440
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001441 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1442 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001443
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001444 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1445 if (CE == 0) {
1446 llvm_unreachable("Unknown constant value to lower!");
1447 return MCConstantExpr::Create(0, Ctx);
1448 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001449
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001450 switch (CE->getOpcode()) {
1451 default:
1452 // If the code isn't optimized, there may be outstanding folding
1453 // opportunities. Attempt to fold the expression using TargetData as a
1454 // last resort before giving up.
1455 if (Constant *C =
1456 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1457 if (C != CE)
1458 return LowerConstant(C, AP);
Dan Gohmana3f4d8f2010-08-04 18:51:09 +00001459
1460 // Otherwise report the problem to the user.
1461 {
1462 std::string S;
1463 raw_string_ostream OS(S);
1464 OS << "Unsupported expression in static initializer: ";
1465 WriteAsOperand(OS, CE, /*PrintType=*/false,
1466 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1467 report_fatal_error(OS.str());
1468 }
1469 return MCConstantExpr::Create(0, Ctx);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001470 case Instruction::GetElementPtr: {
1471 const TargetData &TD = *AP.TM.getTargetData();
1472 // Generate a symbolic expression for the byte address
1473 const Constant *PtrVal = CE->getOperand(0);
1474 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001475 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
Jim Grosbach83d80832011-03-29 23:20:22 +00001476
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001477 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1478 if (Offset == 0)
1479 return Base;
Jim Grosbach83d80832011-03-29 23:20:22 +00001480
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001481 // Truncate/sext the offset to the pointer size.
1482 if (TD.getPointerSizeInBits() != 64) {
1483 int SExtAmount = 64-TD.getPointerSizeInBits();
1484 Offset = (Offset << SExtAmount) >> SExtAmount;
1485 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001486
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001487 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1488 Ctx);
1489 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001490
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001491 case Instruction::Trunc:
1492 // We emit the value and depend on the assembler to truncate the generated
1493 // expression properly. This is important for differences between
1494 // blockaddress labels. Since the two labels are in the same function, it
1495 // is reasonable to treat their delta as a 32-bit value.
1496 // FALL THROUGH.
1497 case Instruction::BitCast:
1498 return LowerConstant(CE->getOperand(0), AP);
1499
1500 case Instruction::IntToPtr: {
1501 const TargetData &TD = *AP.TM.getTargetData();
1502 // Handle casts to pointers by changing them into casts to the appropriate
1503 // integer type. This promotes constant folding and simplifies this code.
1504 Constant *Op = CE->getOperand(0);
1505 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1506 false/*ZExt*/);
1507 return LowerConstant(Op, AP);
1508 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001509
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001510 case Instruction::PtrToInt: {
1511 const TargetData &TD = *AP.TM.getTargetData();
1512 // Support only foldable casts to/from pointers that can be eliminated by
1513 // changing the pointer to the appropriately sized integer type.
1514 Constant *Op = CE->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001515 Type *Ty = CE->getType();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001516
1517 const MCExpr *OpExpr = LowerConstant(Op, AP);
1518
1519 // We can emit the pointer value into this slot if the slot is an
1520 // integer slot equal to the size of the pointer.
1521 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1522 return OpExpr;
1523
1524 // Otherwise the pointer is smaller than the resultant integer, mask off
1525 // the high bits so we are sure to get a proper truncation if the input is
1526 // a constant expr.
1527 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1528 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1529 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1530 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001531
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001532 // The MC library also has a right-shift operator, but it isn't consistently
1533 // signed or unsigned between different targets.
1534 case Instruction::Add:
1535 case Instruction::Sub:
1536 case Instruction::Mul:
1537 case Instruction::SDiv:
1538 case Instruction::SRem:
1539 case Instruction::Shl:
1540 case Instruction::And:
1541 case Instruction::Or:
1542 case Instruction::Xor: {
1543 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1544 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1545 switch (CE->getOpcode()) {
1546 default: llvm_unreachable("Unknown binary operator constant cast expr");
1547 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1548 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1549 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1550 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1551 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1552 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1553 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1554 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1555 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1556 }
1557 }
1558 }
1559}
1560
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001561static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1562 AsmPrinter &AP);
1563
David Greened92e2e42011-08-31 17:30:56 +00001564/// isRepeatedByteSequence - Determine whether the given value is
1565/// composed of a repeated sequence of identical bytes and return the
1566/// byte value. If it is not a repeated sequence, return -1.
1567static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1568
1569 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1570 if (CI->getBitWidth() > 64) return -1;
1571
1572 uint64_t Size = TM.getTargetData()->getTypeAllocSize(V->getType());
1573 uint64_t Value = CI->getZExtValue();
1574
1575 // Make sure the constant is at least 8 bits long and has a power
1576 // of 2 bit width. This guarantees the constant bit width is
1577 // always a multiple of 8 bits, avoiding issues with padding out
1578 // to Size and other such corner cases.
1579 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1580
1581 uint8_t Byte = static_cast<uint8_t>(Value);
1582
1583 for (unsigned i = 1; i < Size; ++i) {
1584 Value >>= 8;
1585 if (static_cast<uint8_t>(Value) != Byte) return -1;
1586 }
1587 return Byte;
1588 }
1589 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1590 // Make sure all array elements are sequences of the same repeated
1591 // byte.
1592 if (CA->getNumOperands() == 0) return -1;
1593
1594 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1595 if (Byte == -1) return -1;
1596
1597 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1598 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1599 if (ThisByte == -1) return -1;
1600 if (Byte != ThisByte) return -1;
1601 }
1602 return Byte;
1603 }
1604
1605 return -1;
1606}
1607
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001608static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1609 AsmPrinter &AP) {
1610 if (AddrSpace != 0 || !CA->isString()) {
David Greened92e2e42011-08-31 17:30:56 +00001611 // Not a string. Print the values in successive locations.
1612
1613 // See if we can aggregate some values. Make sure it can be
1614 // represented as a series of bytes of the constant value.
1615 int Value = isRepeatedByteSequence(CA, AP.TM);
1616
1617 if (Value != -1) {
David Greene94fca832011-08-31 21:34:20 +00001618 uint64_t Bytes = AP.TM.getTargetData()->getTypeAllocSize(CA->getType());
David Greened92e2e42011-08-31 17:30:56 +00001619 AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1620 }
1621 else {
1622 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1623 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1624 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001625 return;
1626 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001627
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001628 // Otherwise, it can be emitted as .ascii.
1629 SmallVector<char, 128> TmpVec;
1630 TmpVec.reserve(CA->getNumOperands());
1631 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1632 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1633
1634 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1635}
1636
1637static void EmitGlobalConstantVector(const ConstantVector *CV,
1638 unsigned AddrSpace, AsmPrinter &AP) {
1639 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001640 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
Nick Lewycky5b7ac142011-06-22 18:55:03 +00001641
1642 const TargetData &TD = *AP.TM.getTargetData();
1643 unsigned Size = TD.getTypeAllocSize(CV->getType());
1644 unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1645 CV->getType()->getNumElements();
1646 if (unsigned Padding = Size - EmittedSize)
1647 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001648}
1649
1650static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1651 unsigned AddrSpace, AsmPrinter &AP) {
1652 // Print the fields in successive locations. Pad to align if needed!
1653 const TargetData *TD = AP.TM.getTargetData();
1654 unsigned Size = TD->getTypeAllocSize(CS->getType());
1655 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1656 uint64_t SizeSoFar = 0;
1657 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1658 const Constant *Field = CS->getOperand(i);
1659
1660 // Check if padding is needed and insert one or more 0s.
1661 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1662 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1663 - Layout->getElementOffset(i)) - FieldSize;
1664 SizeSoFar += FieldSize + PadSize;
1665
1666 // Now print the actual field value.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001667 EmitGlobalConstantImpl(Field, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001668
1669 // Insert padding - this may include padding to increase the size of the
1670 // current field up to the ABI size (if the struct is not packed) as well
1671 // as padding to ensure that the next field starts at the right offset.
1672 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1673 }
1674 assert(SizeSoFar == Layout->getSizeInBytes() &&
1675 "Layout of constant struct may be incorrect!");
1676}
1677
1678static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1679 AsmPrinter &AP) {
1680 // FP Constants are printed as integer constants to avoid losing
1681 // precision.
1682 if (CFP->getType()->isDoubleTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001683 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001684 double Val = CFP->getValueAPF().convertToDouble();
1685 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1686 }
1687
1688 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1689 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1690 return;
1691 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001692
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001693 if (CFP->getType()->isFloatTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001694 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001695 float Val = CFP->getValueAPF().convertToFloat();
1696 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1697 }
1698 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1699 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1700 return;
1701 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001702
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001703 if (CFP->getType()->isX86_FP80Ty()) {
1704 // all long double variants are printed as hex
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001705 // API needed to prevent premature destruction
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001706 APInt API = CFP->getValueAPF().bitcastToAPInt();
1707 const uint64_t *p = API.getRawData();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001708 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001709 // Convert to double so we can print the approximate val as a comment.
1710 APFloat DoubleVal = CFP->getValueAPF();
1711 bool ignored;
1712 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1713 &ignored);
1714 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1715 << DoubleVal.convertToDouble() << '\n';
1716 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001717
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001718 if (AP.TM.getTargetData()->isBigEndian()) {
1719 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1720 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1721 } else {
1722 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1723 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1724 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001725
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001726 // Emit the tail padding for the long double.
1727 const TargetData &TD = *AP.TM.getTargetData();
1728 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1729 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1730 return;
1731 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001732
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001733 assert(CFP->getType()->isPPC_FP128Ty() &&
1734 "Floating point constant type not handled");
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001735 // All long double variants are printed as hex
1736 // API needed to prevent premature destruction.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001737 APInt API = CFP->getValueAPF().bitcastToAPInt();
1738 const uint64_t *p = API.getRawData();
1739 if (AP.TM.getTargetData()->isBigEndian()) {
1740 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1741 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1742 } else {
1743 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1744 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1745 }
1746}
1747
1748static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1749 unsigned AddrSpace, AsmPrinter &AP) {
1750 const TargetData *TD = AP.TM.getTargetData();
1751 unsigned BitWidth = CI->getBitWidth();
1752 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1753
1754 // We don't expect assemblers to support integer data directives
1755 // for more than 64 bits, so we emit the data in at most 64-bit
1756 // quantities at a time.
1757 const uint64_t *RawData = CI->getValue().getRawData();
1758 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1759 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1760 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1761 }
1762}
1763
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001764static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1765 AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001766 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001767 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1768 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001769 }
1770
1771 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001772 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001773 switch (Size) {
1774 case 1:
1775 case 2:
1776 case 4:
1777 case 8:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001778 if (AP.isVerbose())
Benjamin Kramer4eb73c52011-11-05 08:57:40 +00001779 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1780 CI->getZExtValue());
Bill Wendling021fd612010-08-18 18:41:13 +00001781 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001782 return;
1783 default:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001784 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001785 return;
1786 }
1787 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001788
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001789 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001790 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
Jim Grosbach83d80832011-03-29 23:20:22 +00001791
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001792 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001793 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001794
1795 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001796 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001797
1798 if (isa<ConstantPointerNull>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001799 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1800 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001801 return;
1802 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001803
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001804 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1805 return EmitGlobalConstantVector(V, AddrSpace, AP);
Jim Grosbach83d80832011-03-29 23:20:22 +00001806
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001807 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1808 // thread the streamer with EmitValue.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001809 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1810 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1811 AddrSpace);
1812}
1813
1814/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1815void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1816 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1817 if (Size)
1818 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1819 else if (MAI->hasSubsectionsViaSymbols()) {
1820 // If the global has zero size, emit a single byte so that two labels don't
1821 // look like they are at the same location.
1822 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1823 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001824}
1825
1826void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1827 // Target doesn't support this yet!
1828 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1829}
1830
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001831void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1832 if (Offset > 0)
1833 OS << '+' << Offset;
1834 else if (Offset < 0)
1835 OS << Offset;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001836}
1837
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001838//===----------------------------------------------------------------------===//
1839// Symbol Lowering Routines.
1840//===----------------------------------------------------------------------===//
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001841
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001842/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1843/// temporary label with the specified stem and unique ID.
1844MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1845 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1846 Name + Twine(ID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001847}
1848
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001849/// GetTempSymbol - Return an assembler temporary label with the specified
1850/// stem.
1851MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1852 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1853 Name);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001854}
1855
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001856
1857MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001858 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001859}
1860
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001861MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1862 return MMI->getAddrLabelSymbol(BB);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001863}
1864
1865/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1866MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001867 return OutContext.GetOrCreateSymbol
1868 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1869 + "_" + Twine(CPID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001870}
1871
1872/// GetJTISymbol - Return the symbol for the specified jump table entry.
1873MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1874 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1875}
1876
1877/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1878/// FIXME: privatize to AsmPrinter.
1879MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001880 return OutContext.GetOrCreateSymbol
1881 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1882 Twine(UID) + "_set_" + Twine(MBBID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001883}
1884
1885/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1886/// global value name as its base, with the specified suffix, and where the
1887/// symbol is forced to have private linkage if ForcePrivate is true.
1888MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1889 StringRef Suffix,
1890 bool ForcePrivate) const {
1891 SmallString<60> NameStr;
1892 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1893 NameStr.append(Suffix.begin(), Suffix.end());
1894 return OutContext.GetOrCreateSymbol(NameStr.str());
1895}
1896
1897/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1898/// ExternalSymbol.
1899MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1900 SmallString<60> NameStr;
1901 Mang->getNameWithPrefix(NameStr, Sym);
1902 return OutContext.GetOrCreateSymbol(NameStr.str());
Jim Grosbach83d80832011-03-29 23:20:22 +00001903}
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001904
1905
1906
1907/// PrintParentLoopComment - Print comments about parent loops of this one.
1908static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1909 unsigned FunctionNumber) {
1910 if (Loop == 0) return;
1911 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1912 OS.indent(Loop->getLoopDepth()*2)
1913 << "Parent Loop BB" << FunctionNumber << "_"
1914 << Loop->getHeader()->getNumber()
1915 << " Depth=" << Loop->getLoopDepth() << '\n';
1916}
1917
1918
1919/// PrintChildLoopComment - Print comments about child loops within
1920/// the loop for this basic block, with nesting.
1921static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1922 unsigned FunctionNumber) {
1923 // Add child loop information
1924 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1925 OS.indent((*CL)->getLoopDepth()*2)
1926 << "Child Loop BB" << FunctionNumber << "_"
1927 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1928 << '\n';
1929 PrintChildLoopComment(OS, *CL, FunctionNumber);
1930 }
1931}
1932
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001933/// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1934static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1935 const MachineLoopInfo *LI,
1936 const AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001937 // Add loop depth information
1938 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1939 if (Loop == 0) return;
Jim Grosbach83d80832011-03-29 23:20:22 +00001940
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001941 MachineBasicBlock *Header = Loop->getHeader();
1942 assert(Header && "No header for loop");
Jim Grosbach83d80832011-03-29 23:20:22 +00001943
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001944 // If this block is not a loop header, just print out what is the loop header
1945 // and return.
1946 if (Header != &MBB) {
1947 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1948 Twine(AP.getFunctionNumber())+"_" +
1949 Twine(Loop->getHeader()->getNumber())+
1950 " Depth="+Twine(Loop->getLoopDepth()));
1951 return;
1952 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001953
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001954 // Otherwise, it is a loop header. Print out information about child and
1955 // parent loops.
1956 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
Jim Grosbach83d80832011-03-29 23:20:22 +00001957
1958 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1959
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001960 OS << "=>";
1961 OS.indent(Loop->getLoopDepth()*2-2);
Jim Grosbach83d80832011-03-29 23:20:22 +00001962
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001963 OS << "This ";
1964 if (Loop->empty())
1965 OS << "Inner ";
1966 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
Jim Grosbach83d80832011-03-29 23:20:22 +00001967
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001968 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1969}
1970
1971
1972/// EmitBasicBlockStart - This method prints the label for the specified
1973/// MachineBasicBlock, an alignment (if present) and a comment describing
1974/// it if appropriate.
1975void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1976 // Emit an alignment directive for this block, if needed.
1977 if (unsigned Align = MBB->getAlignment())
1978 EmitAlignment(Log2_32(Align));
1979
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001980 // If the block has its address taken, emit any labels that were used to
1981 // reference the block. It is possible that there is more than one label
1982 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1983 // the references were generated.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001984 if (MBB->hasAddressTaken()) {
1985 const BasicBlock *BB = MBB->getBasicBlock();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001986 if (isVerbose())
1987 OutStreamer.AddComment("Block address taken");
Jim Grosbach83d80832011-03-29 23:20:22 +00001988
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001989 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1990
1991 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1992 OutStreamer.EmitLabel(Syms[i]);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001993 }
1994
1995 // Print the main label for the block.
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001996 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001997 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001998 if (const BasicBlock *BB = MBB->getBasicBlock())
1999 if (BB->hasName())
2000 OutStreamer.AddComment("%" + BB->getName());
Jim Grosbach83d80832011-03-29 23:20:22 +00002001
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002002 EmitBasicBlockLoopComments(*MBB, LI, *this);
Jim Grosbach83d80832011-03-29 23:20:22 +00002003
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002004 // NOTE: Want this comment at start of line, don't emit with AddComment.
2005 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2006 Twine(MBB->getNumber()) + ":");
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002007 }
2008 } else {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002009 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002010 if (const BasicBlock *BB = MBB->getBasicBlock())
2011 if (BB->hasName())
2012 OutStreamer.AddComment("%" + BB->getName());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002013 EmitBasicBlockLoopComments(*MBB, LI, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002014 }
2015
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002016 OutStreamer.EmitLabel(MBB->getSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002017 }
2018}
2019
Stuart Hastings5129bde2011-02-23 02:27:05 +00002020void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2021 bool IsDefinition) const {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002022 MCSymbolAttr Attr = MCSA_Invalid;
Jim Grosbach83d80832011-03-29 23:20:22 +00002023
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002024 switch (Visibility) {
2025 default: break;
2026 case GlobalValue::HiddenVisibility:
Stuart Hastings5129bde2011-02-23 02:27:05 +00002027 if (IsDefinition)
2028 Attr = MAI->getHiddenVisibilityAttr();
2029 else
2030 Attr = MAI->getHiddenDeclarationVisibilityAttr();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002031 break;
2032 case GlobalValue::ProtectedVisibility:
2033 Attr = MAI->getProtectedVisibilityAttr();
2034 break;
2035 }
2036
2037 if (Attr != MCSA_Invalid)
2038 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2039}
2040
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002041/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2042/// exactly one predecessor and the control transfer mechanism between
2043/// the predecessor and this block is a fall-through.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002044bool AsmPrinter::
2045isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002046 // If this is a landing pad, it isn't a fall through. If it has no preds,
2047 // then nothing falls through to it.
2048 if (MBB->isLandingPad() || MBB->pred_empty())
2049 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002050
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002051 // If there isn't exactly one predecessor, it can't be a fall through.
2052 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2053 ++PI2;
2054 if (PI2 != MBB->pred_end())
2055 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002056
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002057 // The predecessor has to be immediately before this block.
Eli Friedman0fc30152011-06-14 19:30:33 +00002058 MachineBasicBlock *Pred = *PI;
Jim Grosbach83d80832011-03-29 23:20:22 +00002059
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002060 if (!Pred->isLayoutSuccessor(MBB))
2061 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002062
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002063 // If the block is completely empty, then it definitely does fall through.
2064 if (Pred->empty())
2065 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00002066
Eli Friedman0fc30152011-06-14 19:30:33 +00002067 // Check the terminators in the previous blocks
2068 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2069 IE = Pred->end(); II != IE; ++II) {
2070 MachineInstr &MI = *II;
2071
2072 // If it is not a simple branch, we are in a table somewhere.
2073 if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
2074 return false;
2075
2076 // If we are the operands of one of the branches, this is not
2077 // a fall through.
2078 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2079 OE = MI.operands_end(); OI != OE; ++OI) {
2080 const MachineOperand& OP = *OI;
Rafael Espindolaaeb6da42011-06-15 21:00:28 +00002081 if (OP.isJTI())
2082 return false;
Eli Friedman0fc30152011-06-14 19:30:33 +00002083 if (OP.isMBB() && OP.getMBB() == MBB)
2084 return false;
2085 }
2086 }
2087
2088 return true;
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002089}
2090
2091
2092
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002093GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2094 if (!S->usesMetadata())
2095 return 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002096
2097 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2098 gcp_map_type::iterator GCPI = GCMap.find(S);
2099 if (GCPI != GCMap.end())
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002100 return GCPI->second;
Jim Grosbach83d80832011-03-29 23:20:22 +00002101
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002102 const char *Name = S->getName().c_str();
Jim Grosbach83d80832011-03-29 23:20:22 +00002103
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002104 for (GCMetadataPrinterRegistry::iterator
2105 I = GCMetadataPrinterRegistry::begin(),
2106 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2107 if (strcmp(Name, I->getName()) == 0) {
2108 GCMetadataPrinter *GMP = I->instantiate();
2109 GMP->S = S;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002110 GCMap.insert(std::make_pair(S, GMP));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002111 return GMP;
2112 }
Jim Grosbach83d80832011-03-29 23:20:22 +00002113
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002114 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002115 return 0;
2116}