blob: c9de6d238c09200a60b3f6f6c717400412d6f211 [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
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000625void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
626 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
Rafael Espindolafea8fea2011-04-26 19:26:53 +0000627
Rafael Espindolaf2b04232011-05-06 14:56:22 +0000628 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000629 return;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000630
Rafael Espindolae29887b2011-05-10 18:39:09 +0000631 if (needsCFIMoves() == CFI_M_None)
Rafael Espindolaa4329972011-04-29 14:14:06 +0000632 return;
633
Bill Wendlinge060a5c2011-07-19 00:02:51 +0000634 if (MMI->getCompactUnwindEncoding() != 0)
635 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
636
Rafael Espindolaa4329972011-04-29 14:14:06 +0000637 MachineModuleInfo &MMI = MF->getMMI();
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000638 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000639 bool FoundOne = false;
640 (void)FoundOne;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000641 for (std::vector<MachineMove>::iterator I = Moves.begin(),
642 E = Moves.end(); I != E; ++I) {
643 if (I->getLabel() == Label) {
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000644 EmitCFIFrameMove(*I);
645 FoundOne = true;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000646 }
647 }
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000648 assert(FoundOne);
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000649}
650
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800651/// EmitFunctionBody - This method emits the body and trailer for a
652/// function.
653void AsmPrinter::EmitFunctionBody() {
654 // Emit target-specific gunk before the function body.
655 EmitFunctionBodyStart();
Jim Grosbach83d80832011-03-29 23:20:22 +0000656
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700657 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000658
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800659 // Print out code for the function.
660 bool HasAnyRealCode = false;
Bill Wendling5a1bec12010-07-16 22:51:10 +0000661 const MachineInstr *LastMI = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800662 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
663 I != E; ++I) {
664 // Print a label for the basic block.
665 EmitBasicBlockStart(I);
666 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
667 II != IE; ++II) {
Bill Wendling5a1bec12010-07-16 22:51:10 +0000668 LastMI = II;
669
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800670 // Print the assembly for the instruction.
Dale Johannesen1ffdb1f2010-05-01 16:41:11 +0000671 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
672 !II->isDebugValue()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800673 HasAnyRealCode = true;
674
Evan Cheng53a0cbf2010-04-27 19:38:45 +0000675 ++EmittedInsts;
Shih-wei Liaoa95f5892010-09-11 01:42:09 -0700676 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700677#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700678 if (ShouldPrintDebugScopes) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000679 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Devang Patel2bfdc272010-10-26 17:49:02 +0000680 DD->beginInstruction(II);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700681 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700682#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800683
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700684 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800685 EmitComments(*II, OutStreamer.GetCommentOS());
686
687 switch (II->getOpcode()) {
Bill Wendlinga02effc2010-07-16 22:20:36 +0000688 case TargetOpcode::PROLOG_LABEL:
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000689 emitPrologLabel(*II);
690 break;
691
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800692 case TargetOpcode::EH_LABEL:
693 case TargetOpcode::GC_LABEL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700694 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800695 break;
696 case TargetOpcode::INLINEASM:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700697 EmitInlineAsm(II);
698 break;
699 case TargetOpcode::DBG_VALUE:
700 if (isVerbose()) {
701 if (!EmitDebugValueComment(II, *this))
702 EmitInstruction(II);
703 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800704 break;
705 case TargetOpcode::IMPLICIT_DEF:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700706 if (isVerbose()) EmitImplicitDef(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800707 break;
708 case TargetOpcode::KILL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700709 if (isVerbose()) EmitKill(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800710 break;
711 default:
Devang Patel49a3ff92011-04-29 18:00:54 +0000712 if (!TM.hasMCUseLoc())
713 MCLineEntry::Make(&OutStreamer, getCurrentSection());
714
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800715 EmitInstruction(II);
716 break;
717 }
718
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700719#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700720 if (ShouldPrintDebugScopes) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000721 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Devang Patel2bfdc272010-10-26 17:49:02 +0000722 DD->endInstruction(II);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700723 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700724#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800725 }
726 }
Bill Wendling5a1bec12010-07-16 22:51:10 +0000727
728 // If the last instruction was a prolog label, then we have a situation where
729 // we emitted a prolog but no function body. This results in the ending prolog
730 // label equaling the end of function label and an invalid "row" in the
731 // FDE. We need to emit a noop in this situation so that the FDE's rows are
732 // valid.
Bill Wendlingf7e17752010-07-17 19:18:44 +0000733 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
Bill Wendling5a1bec12010-07-16 22:51:10 +0000734
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800735 // If the function is empty and the object file uses .subsections_via_symbols,
736 // then we need to emit *something* to the function body to prevent the
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700737 // labels from collapsing together. Just emit a noop.
Bill Wendling5a1bec12010-07-16 22:51:10 +0000738 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700739 MCInst Noop;
740 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
741 if (Noop.getOpcode()) {
742 OutStreamer.AddComment("avoids zero-length function");
743 OutStreamer.EmitInstruction(Noop);
744 } else // Target not mc-ized yet.
745 OutStreamer.EmitRawText(StringRef("\tnop\n"));
746 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000747
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800748 // Emit target-specific gunk after the function body.
749 EmitFunctionBodyEnd();
Jim Grosbach83d80832011-03-29 23:20:22 +0000750
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700751 // If the target wants a .size directive for the size of the function, emit
752 // it.
753 if (MAI->hasDotTypeDotSizeDirective()) {
754 // Create a symbol for the end of function, so we can get the size as
755 // difference between the function label and the temp label.
756 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
757 OutStreamer.EmitLabel(FnEndLabel);
Jim Grosbach83d80832011-03-29 23:20:22 +0000758
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700759 const MCExpr *SizeExp =
760 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
761 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
762 OutContext);
763 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
764 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000765
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800766 // Emit post-function debug information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700767#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700768 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000769 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
770 DD->endFunction(MF);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700771 }
772 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000773 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
774 DE->EndFunction();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700775 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700776#endif // ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700777 MMI->EndFunction();
Jim Grosbach83d80832011-03-29 23:20:22 +0000778
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800779 // Print out jump tables referenced by the function.
780 EmitJumpTableInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000781
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800782 OutStreamer.AddBlankLine();
783}
784
Devang Patel7c3efb12010-04-28 01:39:28 +0000785/// getDebugValueLocation - Get location information encoded by DBG_VALUE
786/// operands.
Jim Grosbach83d80832011-03-29 23:20:22 +0000787MachineLocation AsmPrinter::
788getDebugValueLocation(const MachineInstr *MI) const {
Devang Patel7c3efb12010-04-28 01:39:28 +0000789 // Target specific DBG_VALUE instructions are handled by each target.
790 return MachineLocation();
791}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800792
Devang Patelacc381b2011-04-21 21:07:35 +0000793/// EmitDwarfRegOp - Emit dwarf register operation.
Devang Patel0be77df2011-04-27 20:29:27 +0000794void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
Devang Patelc26f5442011-04-28 02:22:40 +0000795 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Rafael Espindola37afca12011-05-27 22:15:01 +0000796 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
797
798 for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
Rafael Espindola7bf114c2011-05-28 00:13:01 +0000799 *SR && Reg < 0; ++SR) {
Rafael Espindola37afca12011-05-27 22:15:01 +0000800 Reg = TRI->getDwarfRegNum(*SR, false);
801 // FIXME: Get the bit range this register uses of the superregister
802 // so that we can produce a DW_OP_bit_piece
803 }
804
805 // FIXME: Handle cases like a super register being encoded as
806 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
807
808 // FIXME: We have no reasonable way of handling errors in here. The
809 // caller might be in the middle of an dwarf expression. We should
810 // probably assert that Reg >= 0 once debug info generation is more mature.
811
Devang Patelacc381b2011-04-21 21:07:35 +0000812 if (int Offset = MLoc.getOffset()) {
Devang Patelc26f5442011-04-28 02:22:40 +0000813 if (Reg < 32) {
814 OutStreamer.AddComment(
815 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
816 EmitInt8(dwarf::DW_OP_breg0 + Reg);
817 } else {
818 OutStreamer.AddComment("DW_OP_bregx");
819 EmitInt8(dwarf::DW_OP_bregx);
820 OutStreamer.AddComment(Twine(Reg));
821 EmitULEB128(Reg);
822 }
Devang Patelacc381b2011-04-21 21:07:35 +0000823 EmitSLEB128(Offset);
824 } else {
825 if (Reg < 32) {
Devang Patelacc381b2011-04-21 21:07:35 +0000826 OutStreamer.AddComment(
827 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
828 EmitInt8(dwarf::DW_OP_reg0 + Reg);
829 } else {
Devang Patelc26f5442011-04-28 02:22:40 +0000830 OutStreamer.AddComment("DW_OP_regx");
Devang Patelacc381b2011-04-21 21:07:35 +0000831 EmitInt8(dwarf::DW_OP_regx);
832 OutStreamer.AddComment(Twine(Reg));
833 EmitULEB128(Reg);
834 }
835 }
Rafael Espindola37afca12011-05-27 22:15:01 +0000836
837 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
Devang Patelacc381b2011-04-21 21:07:35 +0000838}
839
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800840bool AsmPrinter::doFinalization(Module &M) {
841 // Emit global variables.
842 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
843 I != E; ++I)
844 EmitGlobalVariable(I);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000845
846 // Emit visibility info for declarations
847 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
848 const Function &F = *I;
849 if (!F.isDeclaration())
850 continue;
851 GlobalValue::VisibilityTypes V = F.getVisibility();
852 if (V == GlobalValue::DefaultVisibility)
853 continue;
854
855 MCSymbol *Name = Mang->getSymbol(&F);
Stuart Hastings5129bde2011-02-23 02:27:05 +0000856 EmitVisibility(Name, V, false);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000857 }
858
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700859 // Finalize debug and EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700860#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700861 if (DE) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000862 {
863 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700864 DE->EndModule();
865 }
866 delete DE; DE = 0;
867 }
868 if (DD) {
Dan Gohmane2a95082010-06-18 15:56:31 +0000869 {
870 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700871 DD->endModule();
872 }
873 delete DD; DD = 0;
874 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700875#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800876
877 // If the target wants to know about weak references, print them all.
878 if (MAI->getWeakRefDirective()) {
879 // FIXME: This is not lazy, it would be nice to only print weak references
880 // to stuff that is actually used. Note that doing so would require targets
881 // to notice uses in operands (due to constant exprs etc). This should
882 // happen with the MC stuff eventually.
883
884 // Print out module-level global variables here.
885 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
886 I != E; ++I) {
887 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700888 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800889 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000890
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800891 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
892 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700893 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800894 }
895 }
896
897 if (MAI->hasSetDirective()) {
898 OutStreamer.AddBlankLine();
899 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
900 I != E; ++I) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700901 MCSymbol *Name = Mang->getSymbol(I);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800902
Jay Foadb899d952011-08-01 12:27:15 +0000903 const GlobalValue *GV = I->getAliasedGlobal();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700904 MCSymbol *Target = Mang->getSymbol(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800905
906 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
907 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
908 else if (I->hasWeakLinkage())
909 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
910 else
911 assert(I->hasLocalLinkage() && "Invalid alias linkage");
912
913 EmitVisibility(Name, I->getVisibility());
914
915 // Emit the directives as assignments aka .set:
Jim Grosbach83d80832011-03-29 23:20:22 +0000916 OutStreamer.EmitAssignment(Name,
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800917 MCSymbolRefExpr::Create(Target, OutContext));
918 }
919 }
920
921 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
922 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
923 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
924 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700925 MP->finishAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800926
927 // If we don't have any trampolines, then we don't require stack memory
928 // to be executable. Some targets have a directive to declare this.
929 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
930 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700931 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800932 OutStreamer.SwitchSection(S);
Jim Grosbach83d80832011-03-29 23:20:22 +0000933
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800934 // Allow the target to emit any magic that it wants at the end of the file,
935 // after everything else has gone out.
936 EmitEndOfAsmFile(M);
Jim Grosbach83d80832011-03-29 23:20:22 +0000937
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800938 delete Mang; Mang = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700939 MMI = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000940
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800941 OutStreamer.Finish();
942 return false;
943}
944
945void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
946 this->MF = &MF;
947 // Get the function symbol.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700948 CurrentFnSym = Mang->getSymbol(MF.getFunction());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800949
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700950 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800951 LI = &getAnalysis<MachineLoopInfo>();
952}
953
954namespace {
955 // SectionCPs - Keep track the alignment, constpool entries per Section.
956 struct SectionCPs {
957 const MCSection *S;
958 unsigned Alignment;
959 SmallVector<unsigned, 4> CPEs;
960 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
961 };
962}
963
964/// EmitConstantPool - Print to the current output stream assembly
965/// representations of the constants in the constant pool MCP. This is
966/// used to print out constants which have been "spilled to memory" by
967/// the code generator.
968///
969void AsmPrinter::EmitConstantPool() {
970 const MachineConstantPool *MCP = MF->getConstantPool();
971 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
972 if (CP.empty()) return;
973
974 // Calculate sections for constant pool entries. We collect entries to go into
975 // the same section together to reduce amount of section switch statements.
976 SmallVector<SectionCPs, 4> CPSections;
977 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
978 const MachineConstantPoolEntry &CPE = CP[i];
979 unsigned Align = CPE.getAlignment();
Jim Grosbach83d80832011-03-29 23:20:22 +0000980
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800981 SectionKind Kind;
982 switch (CPE.getRelocationInfo()) {
983 default: llvm_unreachable("Unknown section kind");
984 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
985 case 1:
986 Kind = SectionKind::getReadOnlyWithRelLocal();
987 break;
988 case 0:
989 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
990 case 4: Kind = SectionKind::getMergeableConst4(); break;
991 case 8: Kind = SectionKind::getMergeableConst8(); break;
992 case 16: Kind = SectionKind::getMergeableConst16();break;
993 default: Kind = SectionKind::getMergeableConst(); break;
994 }
995 }
996
997 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Jim Grosbach83d80832011-03-29 23:20:22 +0000998
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800999 // The number of sections are small, just do a linear search from the
1000 // last section to the first.
1001 bool Found = false;
1002 unsigned SecIdx = CPSections.size();
1003 while (SecIdx != 0) {
1004 if (CPSections[--SecIdx].S == S) {
1005 Found = true;
1006 break;
1007 }
1008 }
1009 if (!Found) {
1010 SecIdx = CPSections.size();
1011 CPSections.push_back(SectionCPs(S, Align));
1012 }
1013
1014 if (Align > CPSections[SecIdx].Alignment)
1015 CPSections[SecIdx].Alignment = Align;
1016 CPSections[SecIdx].CPEs.push_back(i);
1017 }
1018
1019 // Now print stuff into the calculated sections.
1020 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1021 OutStreamer.SwitchSection(CPSections[i].S);
1022 EmitAlignment(Log2_32(CPSections[i].Alignment));
1023
1024 unsigned Offset = 0;
1025 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1026 unsigned CPI = CPSections[i].CPEs[j];
1027 MachineConstantPoolEntry CPE = CP[CPI];
1028
1029 // Emit inter-object padding for alignment.
1030 unsigned AlignMask = CPE.getAlignment() - 1;
1031 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1032 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1033
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001034 Type *Ty = CPE.getType();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001035 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001036 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1037
1038 if (CPE.isMachineConstantPoolEntry())
1039 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1040 else
1041 EmitGlobalConstant(CPE.Val.ConstVal);
1042 }
1043 }
1044}
1045
1046/// EmitJumpTableInfo - Print assembly representations of the jump tables used
Jim Grosbach83d80832011-03-29 23:20:22 +00001047/// by the current function to the current output stream.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001048///
1049void AsmPrinter::EmitJumpTableInfo() {
1050 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1051 if (MJTI == 0) return;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001052 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001053 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1054 if (JT.empty()) return;
1055
Jim Grosbach83d80832011-03-29 23:20:22 +00001056 // Pick the directive to use to print the jump table entries, and switch to
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001057 // the appropriate section.
1058 const Function *F = MF->getFunction();
1059 bool JTInDiffSection = false;
1060 if (// In PIC mode, we need to emit the jump table to the same section as the
1061 // function body itself, otherwise the label differences won't make sense.
1062 // FIXME: Need a better predicate for this: what about custom entries?
1063 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1064 // We should also do if the section name is NULL or function is declared
1065 // in discardable section
1066 // FIXME: this isn't the right predicate, should be based on the MCSection
1067 // for the function.
1068 F->isWeakForLinker()) {
1069 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1070 } else {
1071 // Otherwise, drop it in the readonly section.
Jim Grosbach83d80832011-03-29 23:20:22 +00001072 const MCSection *ReadOnlySection =
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001073 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1074 OutStreamer.SwitchSection(ReadOnlySection);
1075 JTInDiffSection = true;
1076 }
1077
1078 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
Jim Grosbach83d80832011-03-29 23:20:22 +00001079
Owen Anderson2fec6c52011-10-04 23:26:17 +00001080 // If we know the form of the jump table, go ahead and tag it as such.
1081 if (!JTInDiffSection) {
1082 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32) {
1083 OutStreamer.EmitJumpTable32Region();
1084 } else {
1085 OutStreamer.EmitDataRegion();
1086 }
1087 }
1088
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001089 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1090 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Jim Grosbach83d80832011-03-29 23:20:22 +00001091
1092 // If this jump table was deleted, ignore it.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001093 if (JTBBs.empty()) continue;
1094
1095 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1096 // .set directive for each unique entry. This reduces the number of
1097 // relocations the assembler will generate for the jump table.
1098 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1099 MAI->hasSetDirective()) {
1100 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1101 const TargetLowering *TLI = TM.getTargetLowering();
1102 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1103 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1104 const MachineBasicBlock *MBB = JTBBs[ii];
1105 if (!EmittedSets.insert(MBB)) continue;
Jim Grosbach83d80832011-03-29 23:20:22 +00001106
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001107 // .set LJTSet, LBB32-base
1108 const MCExpr *LHS =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001109 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001110 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1111 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1112 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001113 }
1114
Duncan Sandsab4c3662011-02-15 09:23:02 +00001115 // On some targets (e.g. Darwin) we want to emit two consecutive labels
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001116 // before each jump table. The first label is never referenced, but tells
1117 // the assembler and linker the extents of the jump table object. The
1118 // second label is actually referenced by the code.
1119 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1120 // FIXME: This doesn't have to have any specific name, just any randomly
1121 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1122 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1123
1124 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1125
1126 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1127 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1128 }
1129}
1130
1131/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1132/// current stream.
1133void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1134 const MachineBasicBlock *MBB,
1135 unsigned UID) const {
Jakob Stoklund Olesene5005d02011-02-09 21:52:06 +00001136 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001137 const MCExpr *Value = 0;
1138 switch (MJTI->getEntryKind()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001139 case MachineJumpTableInfo::EK_Inline:
1140 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001141 case MachineJumpTableInfo::EK_Custom32:
1142 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1143 OutContext);
1144 break;
1145 case MachineJumpTableInfo::EK_BlockAddress:
1146 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1147 // .word LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001148 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001149 break;
1150 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1151 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1152 // with a relocation as gp-relative, e.g.:
1153 // .gprel32 LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001154 MCSymbol *MBBSym = MBB->getSymbol();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001155 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1156 return;
1157 }
1158
1159 case MachineJumpTableInfo::EK_LabelDifference32: {
1160 // EK_LabelDifference32 - Each entry is the address of the block minus
1161 // the address of the jump table. This is used for PIC jump tables where
1162 // gprel32 is not supported. e.g.:
1163 // .word LBB123 - LJTI1_2
1164 // If the .set directive is supported, this is emitted as:
1165 // .set L4_5_set_123, LBB123 - LJTI1_2
1166 // .word L4_5_set_123
Jim Grosbach83d80832011-03-29 23:20:22 +00001167
1168 // If we have emitted set directives for the jump table entries, print
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001169 // them rather than the entries themselves. If we're emitting PIC, then
1170 // emit the table entries as differences between two text section labels.
1171 if (MAI->hasSetDirective()) {
1172 // If we used .set, reference the .set's symbol.
1173 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1174 OutContext);
1175 break;
1176 }
1177 // Otherwise, use the difference as the jump table entry.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001178 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001179 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1180 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1181 break;
1182 }
1183 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001184
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001185 assert(Value && "Unknown entry kind!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001186
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001187 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1188 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1189}
1190
1191
1192/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1193/// special global used by LLVM. If so, emit it and return true, otherwise
1194/// do nothing and return false.
1195bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1196 if (GV->getName() == "llvm.used") {
1197 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1198 EmitLLVMUsedList(GV->getInitializer());
1199 return true;
1200 }
1201
1202 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1203 if (GV->getSection() == "llvm.metadata" ||
1204 GV->hasAvailableExternallyLinkage())
1205 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001206
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001207 if (!GV->hasAppendingLinkage()) return false;
1208
1209 assert(GV->hasInitializer() && "Not a special LLVM global!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001210
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001211 const TargetData *TD = TM.getTargetData();
1212 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1213 if (GV->getName() == "llvm.global_ctors") {
1214 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner7516e9e2010-04-28 19:58:07 +00001215 EmitAlignment(Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001216 EmitXXStructorList(GV->getInitializer());
Jim Grosbach83d80832011-03-29 23:20:22 +00001217
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001218 if (TM.getRelocationModel() == Reloc::Static &&
1219 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1220 StringRef Sym(".constructors_used");
1221 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1222 MCSA_Reference);
1223 }
1224 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001225 }
1226
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001227 if (GV->getName() == "llvm.global_dtors") {
1228 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner7516e9e2010-04-28 19:58:07 +00001229 EmitAlignment(Align);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001230 EmitXXStructorList(GV->getInitializer());
1231
1232 if (TM.getRelocationModel() == Reloc::Static &&
1233 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1234 StringRef Sym(".destructors_used");
1235 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1236 MCSA_Reference);
1237 }
1238 return true;
1239 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001240
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001241 return false;
1242}
1243
1244/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1245/// global in the specified llvm.used list for which emitUsedDirectiveFor
1246/// is true, as being used with this directive.
Jay Foad7d715df2011-06-19 18:37:11 +00001247void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001248 // Should be an array of 'i8*'.
Jay Foad7d715df2011-06-19 18:37:11 +00001249 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001250 if (InitList == 0) return;
Jim Grosbach83d80832011-03-29 23:20:22 +00001251
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001252 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1253 const GlobalValue *GV =
1254 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1255 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001256 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001257 }
1258}
1259
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001260typedef std::pair<int, Constant*> Structor;
1261
Duncan Sands9a7d48a2011-09-29 16:01:46 +00001262static bool priority_order(const Structor& lhs, const Structor& rhs) {
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001263 return lhs.first < rhs.first;
1264}
1265
1266/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1267/// priority.
Jay Foad7d715df2011-06-19 18:37:11 +00001268void AsmPrinter::EmitXXStructorList(const Constant *List) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001269 // Should be an array of '{ int, void ()* }' structs. The first value is the
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001270 // init priority.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001271 if (!isa<ConstantArray>(List)) return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001272
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001273 // Sanity check the structors list.
1274 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1275 if (!InitList) return; // Not an array!
1276 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1277 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1278 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1279 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1280
1281 // Gather the structors in a form that's convenient for sorting by priority.
1282 SmallVector<Structor, 8> Structors;
1283 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1284 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1285 if (!CS) continue; // Malformed.
1286 if (CS->getOperand(1)->isNullValue())
1287 break; // Found a null terminator, skip the rest.
1288 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1289 if (!Priority) continue; // Malformed.
1290 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1291 CS->getOperand(1)));
1292 }
1293
1294 // Emit the function pointers in reverse priority order.
Duncan Sands147272b2011-09-02 18:07:19 +00001295 switch (MAI->getStructorOutputOrder()) {
1296 case Structors::None:
1297 break;
1298 case Structors::PriorityOrder:
1299 std::sort(Structors.begin(), Structors.end(), priority_order);
1300 break;
1301 case Structors::ReversePriorityOrder:
1302 std::sort(Structors.rbegin(), Structors.rend(), priority_order);
1303 break;
1304 }
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001305 for (unsigned i = 0, e = Structors.size(); i != e; ++i)
1306 EmitGlobalConstant(Structors[i].second);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001307}
1308
1309//===--------------------------------------------------------------------===//
1310// Emission and print routines
1311//
1312
1313/// EmitInt8 - Emit a byte directive and value.
1314///
1315void AsmPrinter::EmitInt8(int Value) const {
1316 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1317}
1318
1319/// EmitInt16 - Emit a short directive and value.
1320///
1321void AsmPrinter::EmitInt16(int Value) const {
1322 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1323}
1324
1325/// EmitInt32 - Emit a long directive and value.
1326///
1327void AsmPrinter::EmitInt32(int Value) const {
1328 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1329}
1330
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001331/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1332/// in bytes of the directive is specified by Size and Hi/Lo specify the
1333/// labels. This implicitly uses .set if it is available.
1334void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1335 unsigned Size) const {
1336 // Get the Hi-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001337 const MCExpr *Diff =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001338 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1339 MCSymbolRefExpr::Create(Lo, OutContext),
1340 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001341
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001342 if (!MAI->hasSetDirective()) {
1343 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1344 return;
1345 }
1346
1347 // Otherwise, emit with .set (aka assignment).
1348 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1349 OutStreamer.EmitAssignment(SetLabel, Diff);
1350 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001351}
1352
Jim Grosbach83d80832011-03-29 23:20:22 +00001353/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001354/// where the size in bytes of the directive is specified by Size and Hi/Lo
1355/// specify the labels. This implicitly uses .set if it is available.
1356void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
Jim Grosbach83d80832011-03-29 23:20:22 +00001357 const MCSymbol *Lo, unsigned Size)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001358 const {
Jim Grosbach83d80832011-03-29 23:20:22 +00001359
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001360 // Emit Hi+Offset - Lo
1361 // Get the Hi+Offset expression.
1362 const MCExpr *Plus =
Jim Grosbach83d80832011-03-29 23:20:22 +00001363 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001364 MCConstantExpr::Create(Offset, OutContext),
1365 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001366
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001367 // Get the Hi+Offset-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001368 const MCExpr *Diff =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001369 MCBinaryExpr::CreateSub(Plus,
1370 MCSymbolRefExpr::Create(Lo, OutContext),
1371 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001372
1373 if (!MAI->hasSetDirective())
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001374 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1375 else {
1376 // Otherwise, emit with .set (aka assignment).
1377 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1378 OutStreamer.EmitAssignment(SetLabel, Diff);
1379 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1380 }
1381}
Devang Patel17e9a622010-09-02 16:43:44 +00001382
Jim Grosbach83d80832011-03-29 23:20:22 +00001383/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
Devang Patel17e9a622010-09-02 16:43:44 +00001384/// where the size in bytes of the directive is specified by Size and Label
1385/// specifies the label. This implicitly uses .set if it is available.
1386void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
Jim Grosbach83d80832011-03-29 23:20:22 +00001387 unsigned Size)
Devang Patel17e9a622010-09-02 16:43:44 +00001388 const {
Jim Grosbach83d80832011-03-29 23:20:22 +00001389
Devang Patel17e9a622010-09-02 16:43:44 +00001390 // Emit Label+Offset
1391 const MCExpr *Plus =
Jim Grosbach83d80832011-03-29 23:20:22 +00001392 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
Devang Patel17e9a622010-09-02 16:43:44 +00001393 MCConstantExpr::Create(Offset, OutContext),
1394 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001395
Devang Patele5e909f2010-09-02 23:01:10 +00001396 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
Devang Patel17e9a622010-09-02 16:43:44 +00001397}
Jim Grosbach83d80832011-03-29 23:20:22 +00001398
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001399
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001400//===----------------------------------------------------------------------===//
1401
1402// EmitAlignment - Emit an alignment directive to the specified power of
1403// two boundary. For example, if you pass in 3 here, you will get an 8
1404// byte alignment. If a global value is specified, and if that global has
Chris Lattner7516e9e2010-04-28 19:58:07 +00001405// an explicit alignment requested, it will override the alignment request
1406// if required for correctness.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001407//
Chris Lattner027b9362010-04-28 01:08:40 +00001408void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
Chris Lattner7516e9e2010-04-28 19:58:07 +00001409 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
Jim Grosbach83d80832011-03-29 23:20:22 +00001410
Chris Lattner7516e9e2010-04-28 19:58:07 +00001411 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
Jim Grosbach83d80832011-03-29 23:20:22 +00001412
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001413 if (getCurrentSection()->getKind().isText())
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001414 OutStreamer.EmitCodeAlignment(1 << NumBits);
1415 else
1416 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001417}
1418
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001419//===----------------------------------------------------------------------===//
1420// Constant emission.
1421//===----------------------------------------------------------------------===//
1422
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001423/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1424///
1425static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1426 MCContext &Ctx = AP.OutContext;
Jim Grosbach83d80832011-03-29 23:20:22 +00001427
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001428 if (CV->isNullValue() || isa<UndefValue>(CV))
1429 return MCConstantExpr::Create(0, Ctx);
1430
1431 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1432 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001433
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001434 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001435 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
Bill Wendling021fd612010-08-18 18:41:13 +00001436
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001437 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1438 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001439
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001440 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1441 if (CE == 0) {
1442 llvm_unreachable("Unknown constant value to lower!");
1443 return MCConstantExpr::Create(0, Ctx);
1444 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001445
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001446 switch (CE->getOpcode()) {
1447 default:
1448 // If the code isn't optimized, there may be outstanding folding
1449 // opportunities. Attempt to fold the expression using TargetData as a
1450 // last resort before giving up.
1451 if (Constant *C =
1452 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1453 if (C != CE)
1454 return LowerConstant(C, AP);
Dan Gohmana3f4d8f2010-08-04 18:51:09 +00001455
1456 // Otherwise report the problem to the user.
1457 {
1458 std::string S;
1459 raw_string_ostream OS(S);
1460 OS << "Unsupported expression in static initializer: ";
1461 WriteAsOperand(OS, CE, /*PrintType=*/false,
1462 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1463 report_fatal_error(OS.str());
1464 }
1465 return MCConstantExpr::Create(0, Ctx);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001466 case Instruction::GetElementPtr: {
1467 const TargetData &TD = *AP.TM.getTargetData();
1468 // Generate a symbolic expression for the byte address
1469 const Constant *PtrVal = CE->getOperand(0);
1470 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +00001471 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
Jim Grosbach83d80832011-03-29 23:20:22 +00001472
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001473 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1474 if (Offset == 0)
1475 return Base;
Jim Grosbach83d80832011-03-29 23:20:22 +00001476
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001477 // Truncate/sext the offset to the pointer size.
1478 if (TD.getPointerSizeInBits() != 64) {
1479 int SExtAmount = 64-TD.getPointerSizeInBits();
1480 Offset = (Offset << SExtAmount) >> SExtAmount;
1481 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001482
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001483 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1484 Ctx);
1485 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001486
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001487 case Instruction::Trunc:
1488 // We emit the value and depend on the assembler to truncate the generated
1489 // expression properly. This is important for differences between
1490 // blockaddress labels. Since the two labels are in the same function, it
1491 // is reasonable to treat their delta as a 32-bit value.
1492 // FALL THROUGH.
1493 case Instruction::BitCast:
1494 return LowerConstant(CE->getOperand(0), AP);
1495
1496 case Instruction::IntToPtr: {
1497 const TargetData &TD = *AP.TM.getTargetData();
1498 // Handle casts to pointers by changing them into casts to the appropriate
1499 // integer type. This promotes constant folding and simplifies this code.
1500 Constant *Op = CE->getOperand(0);
1501 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1502 false/*ZExt*/);
1503 return LowerConstant(Op, AP);
1504 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001505
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001506 case Instruction::PtrToInt: {
1507 const TargetData &TD = *AP.TM.getTargetData();
1508 // Support only foldable casts to/from pointers that can be eliminated by
1509 // changing the pointer to the appropriately sized integer type.
1510 Constant *Op = CE->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001511 Type *Ty = CE->getType();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001512
1513 const MCExpr *OpExpr = LowerConstant(Op, AP);
1514
1515 // We can emit the pointer value into this slot if the slot is an
1516 // integer slot equal to the size of the pointer.
1517 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1518 return OpExpr;
1519
1520 // Otherwise the pointer is smaller than the resultant integer, mask off
1521 // the high bits so we are sure to get a proper truncation if the input is
1522 // a constant expr.
1523 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1524 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1525 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1526 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001527
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001528 // The MC library also has a right-shift operator, but it isn't consistently
1529 // signed or unsigned between different targets.
1530 case Instruction::Add:
1531 case Instruction::Sub:
1532 case Instruction::Mul:
1533 case Instruction::SDiv:
1534 case Instruction::SRem:
1535 case Instruction::Shl:
1536 case Instruction::And:
1537 case Instruction::Or:
1538 case Instruction::Xor: {
1539 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1540 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1541 switch (CE->getOpcode()) {
1542 default: llvm_unreachable("Unknown binary operator constant cast expr");
1543 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1544 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1545 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1546 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1547 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1548 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1549 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1550 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1551 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1552 }
1553 }
1554 }
1555}
1556
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001557static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1558 AsmPrinter &AP);
1559
David Greened92e2e42011-08-31 17:30:56 +00001560/// isRepeatedByteSequence - Determine whether the given value is
1561/// composed of a repeated sequence of identical bytes and return the
1562/// byte value. If it is not a repeated sequence, return -1.
1563static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1564
1565 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1566 if (CI->getBitWidth() > 64) return -1;
1567
1568 uint64_t Size = TM.getTargetData()->getTypeAllocSize(V->getType());
1569 uint64_t Value = CI->getZExtValue();
1570
1571 // Make sure the constant is at least 8 bits long and has a power
1572 // of 2 bit width. This guarantees the constant bit width is
1573 // always a multiple of 8 bits, avoiding issues with padding out
1574 // to Size and other such corner cases.
1575 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1576
1577 uint8_t Byte = static_cast<uint8_t>(Value);
1578
1579 for (unsigned i = 1; i < Size; ++i) {
1580 Value >>= 8;
1581 if (static_cast<uint8_t>(Value) != Byte) return -1;
1582 }
1583 return Byte;
1584 }
1585 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1586 // Make sure all array elements are sequences of the same repeated
1587 // byte.
1588 if (CA->getNumOperands() == 0) return -1;
1589
1590 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1591 if (Byte == -1) return -1;
1592
1593 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1594 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1595 if (ThisByte == -1) return -1;
1596 if (Byte != ThisByte) return -1;
1597 }
1598 return Byte;
1599 }
1600
1601 return -1;
1602}
1603
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001604static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1605 AsmPrinter &AP) {
1606 if (AddrSpace != 0 || !CA->isString()) {
David Greened92e2e42011-08-31 17:30:56 +00001607 // Not a string. Print the values in successive locations.
1608
1609 // See if we can aggregate some values. Make sure it can be
1610 // represented as a series of bytes of the constant value.
1611 int Value = isRepeatedByteSequence(CA, AP.TM);
1612
1613 if (Value != -1) {
David Greene94fca832011-08-31 21:34:20 +00001614 uint64_t Bytes = AP.TM.getTargetData()->getTypeAllocSize(CA->getType());
David Greened92e2e42011-08-31 17:30:56 +00001615 AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1616 }
1617 else {
1618 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1619 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1620 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001621 return;
1622 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001623
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001624 // Otherwise, it can be emitted as .ascii.
1625 SmallVector<char, 128> TmpVec;
1626 TmpVec.reserve(CA->getNumOperands());
1627 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1628 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1629
1630 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1631}
1632
1633static void EmitGlobalConstantVector(const ConstantVector *CV,
1634 unsigned AddrSpace, AsmPrinter &AP) {
1635 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001636 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
Nick Lewycky5b7ac142011-06-22 18:55:03 +00001637
1638 const TargetData &TD = *AP.TM.getTargetData();
1639 unsigned Size = TD.getTypeAllocSize(CV->getType());
1640 unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1641 CV->getType()->getNumElements();
1642 if (unsigned Padding = Size - EmittedSize)
1643 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001644}
1645
1646static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1647 unsigned AddrSpace, AsmPrinter &AP) {
1648 // Print the fields in successive locations. Pad to align if needed!
1649 const TargetData *TD = AP.TM.getTargetData();
1650 unsigned Size = TD->getTypeAllocSize(CS->getType());
1651 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1652 uint64_t SizeSoFar = 0;
1653 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1654 const Constant *Field = CS->getOperand(i);
1655
1656 // Check if padding is needed and insert one or more 0s.
1657 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1658 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1659 - Layout->getElementOffset(i)) - FieldSize;
1660 SizeSoFar += FieldSize + PadSize;
1661
1662 // Now print the actual field value.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001663 EmitGlobalConstantImpl(Field, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001664
1665 // Insert padding - this may include padding to increase the size of the
1666 // current field up to the ABI size (if the struct is not packed) as well
1667 // as padding to ensure that the next field starts at the right offset.
1668 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1669 }
1670 assert(SizeSoFar == Layout->getSizeInBytes() &&
1671 "Layout of constant struct may be incorrect!");
1672}
1673
1674static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1675 AsmPrinter &AP) {
1676 // FP Constants are printed as integer constants to avoid losing
1677 // precision.
1678 if (CFP->getType()->isDoubleTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001679 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001680 double Val = CFP->getValueAPF().convertToDouble();
1681 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1682 }
1683
1684 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1685 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1686 return;
1687 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001688
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001689 if (CFP->getType()->isFloatTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001690 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001691 float Val = CFP->getValueAPF().convertToFloat();
1692 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1693 }
1694 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1695 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1696 return;
1697 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001698
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001699 if (CFP->getType()->isX86_FP80Ty()) {
1700 // all long double variants are printed as hex
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001701 // API needed to prevent premature destruction
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001702 APInt API = CFP->getValueAPF().bitcastToAPInt();
1703 const uint64_t *p = API.getRawData();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001704 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001705 // Convert to double so we can print the approximate val as a comment.
1706 APFloat DoubleVal = CFP->getValueAPF();
1707 bool ignored;
1708 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1709 &ignored);
1710 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1711 << DoubleVal.convertToDouble() << '\n';
1712 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001713
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001714 if (AP.TM.getTargetData()->isBigEndian()) {
1715 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1716 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1717 } else {
1718 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1719 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1720 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001721
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001722 // Emit the tail padding for the long double.
1723 const TargetData &TD = *AP.TM.getTargetData();
1724 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1725 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1726 return;
1727 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001728
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001729 assert(CFP->getType()->isPPC_FP128Ty() &&
1730 "Floating point constant type not handled");
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001731 // All long double variants are printed as hex
1732 // API needed to prevent premature destruction.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001733 APInt API = CFP->getValueAPF().bitcastToAPInt();
1734 const uint64_t *p = API.getRawData();
1735 if (AP.TM.getTargetData()->isBigEndian()) {
1736 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1737 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1738 } else {
1739 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1740 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1741 }
1742}
1743
1744static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1745 unsigned AddrSpace, AsmPrinter &AP) {
1746 const TargetData *TD = AP.TM.getTargetData();
1747 unsigned BitWidth = CI->getBitWidth();
1748 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1749
1750 // We don't expect assemblers to support integer data directives
1751 // for more than 64 bits, so we emit the data in at most 64-bit
1752 // quantities at a time.
1753 const uint64_t *RawData = CI->getValue().getRawData();
1754 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1755 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1756 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1757 }
1758}
1759
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001760static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1761 AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001762 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001763 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1764 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001765 }
1766
1767 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001768 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001769 switch (Size) {
1770 case 1:
1771 case 2:
1772 case 4:
1773 case 8:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001774 if (AP.isVerbose())
1775 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
Bill Wendling021fd612010-08-18 18:41:13 +00001776 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001777 return;
1778 default:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001779 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001780 return;
1781 }
1782 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001783
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001784 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001785 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
Jim Grosbach83d80832011-03-29 23:20:22 +00001786
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001787 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001788 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001789
1790 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001791 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001792
1793 if (isa<ConstantPointerNull>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001794 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1795 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001796 return;
1797 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001798
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001799 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1800 return EmitGlobalConstantVector(V, AddrSpace, AP);
Jim Grosbach83d80832011-03-29 23:20:22 +00001801
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001802 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1803 // thread the streamer with EmitValue.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001804 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1805 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1806 AddrSpace);
1807}
1808
1809/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1810void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1811 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1812 if (Size)
1813 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1814 else if (MAI->hasSubsectionsViaSymbols()) {
1815 // If the global has zero size, emit a single byte so that two labels don't
1816 // look like they are at the same location.
1817 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1818 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001819}
1820
1821void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1822 // Target doesn't support this yet!
1823 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1824}
1825
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001826void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1827 if (Offset > 0)
1828 OS << '+' << Offset;
1829 else if (Offset < 0)
1830 OS << Offset;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001831}
1832
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001833//===----------------------------------------------------------------------===//
1834// Symbol Lowering Routines.
1835//===----------------------------------------------------------------------===//
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001836
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001837/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1838/// temporary label with the specified stem and unique ID.
1839MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1840 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1841 Name + Twine(ID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001842}
1843
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001844/// GetTempSymbol - Return an assembler temporary label with the specified
1845/// stem.
1846MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1847 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1848 Name);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001849}
1850
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001851
1852MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001853 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001854}
1855
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001856MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1857 return MMI->getAddrLabelSymbol(BB);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001858}
1859
1860/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1861MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001862 return OutContext.GetOrCreateSymbol
1863 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1864 + "_" + Twine(CPID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001865}
1866
1867/// GetJTISymbol - Return the symbol for the specified jump table entry.
1868MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1869 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1870}
1871
1872/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1873/// FIXME: privatize to AsmPrinter.
1874MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001875 return OutContext.GetOrCreateSymbol
1876 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1877 Twine(UID) + "_set_" + Twine(MBBID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001878}
1879
1880/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1881/// global value name as its base, with the specified suffix, and where the
1882/// symbol is forced to have private linkage if ForcePrivate is true.
1883MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1884 StringRef Suffix,
1885 bool ForcePrivate) const {
1886 SmallString<60> NameStr;
1887 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1888 NameStr.append(Suffix.begin(), Suffix.end());
1889 return OutContext.GetOrCreateSymbol(NameStr.str());
1890}
1891
1892/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1893/// ExternalSymbol.
1894MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1895 SmallString<60> NameStr;
1896 Mang->getNameWithPrefix(NameStr, Sym);
1897 return OutContext.GetOrCreateSymbol(NameStr.str());
Jim Grosbach83d80832011-03-29 23:20:22 +00001898}
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001899
1900
1901
1902/// PrintParentLoopComment - Print comments about parent loops of this one.
1903static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1904 unsigned FunctionNumber) {
1905 if (Loop == 0) return;
1906 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1907 OS.indent(Loop->getLoopDepth()*2)
1908 << "Parent Loop BB" << FunctionNumber << "_"
1909 << Loop->getHeader()->getNumber()
1910 << " Depth=" << Loop->getLoopDepth() << '\n';
1911}
1912
1913
1914/// PrintChildLoopComment - Print comments about child loops within
1915/// the loop for this basic block, with nesting.
1916static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1917 unsigned FunctionNumber) {
1918 // Add child loop information
1919 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1920 OS.indent((*CL)->getLoopDepth()*2)
1921 << "Child Loop BB" << FunctionNumber << "_"
1922 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1923 << '\n';
1924 PrintChildLoopComment(OS, *CL, FunctionNumber);
1925 }
1926}
1927
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001928/// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1929static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1930 const MachineLoopInfo *LI,
1931 const AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001932 // Add loop depth information
1933 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1934 if (Loop == 0) return;
Jim Grosbach83d80832011-03-29 23:20:22 +00001935
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001936 MachineBasicBlock *Header = Loop->getHeader();
1937 assert(Header && "No header for loop");
Jim Grosbach83d80832011-03-29 23:20:22 +00001938
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001939 // If this block is not a loop header, just print out what is the loop header
1940 // and return.
1941 if (Header != &MBB) {
1942 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1943 Twine(AP.getFunctionNumber())+"_" +
1944 Twine(Loop->getHeader()->getNumber())+
1945 " Depth="+Twine(Loop->getLoopDepth()));
1946 return;
1947 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001948
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001949 // Otherwise, it is a loop header. Print out information about child and
1950 // parent loops.
1951 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
Jim Grosbach83d80832011-03-29 23:20:22 +00001952
1953 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1954
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001955 OS << "=>";
1956 OS.indent(Loop->getLoopDepth()*2-2);
Jim Grosbach83d80832011-03-29 23:20:22 +00001957
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001958 OS << "This ";
1959 if (Loop->empty())
1960 OS << "Inner ";
1961 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
Jim Grosbach83d80832011-03-29 23:20:22 +00001962
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001963 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1964}
1965
1966
1967/// EmitBasicBlockStart - This method prints the label for the specified
1968/// MachineBasicBlock, an alignment (if present) and a comment describing
1969/// it if appropriate.
1970void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1971 // Emit an alignment directive for this block, if needed.
1972 if (unsigned Align = MBB->getAlignment())
1973 EmitAlignment(Log2_32(Align));
1974
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001975 // If the block has its address taken, emit any labels that were used to
1976 // reference the block. It is possible that there is more than one label
1977 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1978 // the references were generated.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001979 if (MBB->hasAddressTaken()) {
1980 const BasicBlock *BB = MBB->getBasicBlock();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001981 if (isVerbose())
1982 OutStreamer.AddComment("Block address taken");
Jim Grosbach83d80832011-03-29 23:20:22 +00001983
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001984 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1985
1986 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1987 OutStreamer.EmitLabel(Syms[i]);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001988 }
1989
1990 // Print the main label for the block.
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001991 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001992 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001993 if (const BasicBlock *BB = MBB->getBasicBlock())
1994 if (BB->hasName())
1995 OutStreamer.AddComment("%" + BB->getName());
Jim Grosbach83d80832011-03-29 23:20:22 +00001996
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001997 EmitBasicBlockLoopComments(*MBB, LI, *this);
Jim Grosbach83d80832011-03-29 23:20:22 +00001998
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001999 // NOTE: Want this comment at start of line, don't emit with AddComment.
2000 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2001 Twine(MBB->getNumber()) + ":");
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002002 }
2003 } else {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002004 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002005 if (const BasicBlock *BB = MBB->getBasicBlock())
2006 if (BB->hasName())
2007 OutStreamer.AddComment("%" + BB->getName());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002008 EmitBasicBlockLoopComments(*MBB, LI, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002009 }
2010
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002011 OutStreamer.EmitLabel(MBB->getSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002012 }
2013}
2014
Stuart Hastings5129bde2011-02-23 02:27:05 +00002015void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2016 bool IsDefinition) const {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002017 MCSymbolAttr Attr = MCSA_Invalid;
Jim Grosbach83d80832011-03-29 23:20:22 +00002018
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002019 switch (Visibility) {
2020 default: break;
2021 case GlobalValue::HiddenVisibility:
Stuart Hastings5129bde2011-02-23 02:27:05 +00002022 if (IsDefinition)
2023 Attr = MAI->getHiddenVisibilityAttr();
2024 else
2025 Attr = MAI->getHiddenDeclarationVisibilityAttr();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002026 break;
2027 case GlobalValue::ProtectedVisibility:
2028 Attr = MAI->getProtectedVisibilityAttr();
2029 break;
2030 }
2031
2032 if (Attr != MCSA_Invalid)
2033 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2034}
2035
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002036/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2037/// exactly one predecessor and the control transfer mechanism between
2038/// the predecessor and this block is a fall-through.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002039bool AsmPrinter::
2040isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002041 // If this is a landing pad, it isn't a fall through. If it has no preds,
2042 // then nothing falls through to it.
2043 if (MBB->isLandingPad() || MBB->pred_empty())
2044 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002045
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002046 // If there isn't exactly one predecessor, it can't be a fall through.
2047 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2048 ++PI2;
2049 if (PI2 != MBB->pred_end())
2050 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002051
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002052 // The predecessor has to be immediately before this block.
Eli Friedman0fc30152011-06-14 19:30:33 +00002053 MachineBasicBlock *Pred = *PI;
Jim Grosbach83d80832011-03-29 23:20:22 +00002054
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002055 if (!Pred->isLayoutSuccessor(MBB))
2056 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002057
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002058 // If the block is completely empty, then it definitely does fall through.
2059 if (Pred->empty())
2060 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00002061
Eli Friedman0fc30152011-06-14 19:30:33 +00002062 // Check the terminators in the previous blocks
2063 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2064 IE = Pred->end(); II != IE; ++II) {
2065 MachineInstr &MI = *II;
2066
2067 // If it is not a simple branch, we are in a table somewhere.
2068 if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
2069 return false;
2070
2071 // If we are the operands of one of the branches, this is not
2072 // a fall through.
2073 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2074 OE = MI.operands_end(); OI != OE; ++OI) {
2075 const MachineOperand& OP = *OI;
Rafael Espindolaaeb6da42011-06-15 21:00:28 +00002076 if (OP.isJTI())
2077 return false;
Eli Friedman0fc30152011-06-14 19:30:33 +00002078 if (OP.isMBB() && OP.getMBB() == MBB)
2079 return false;
2080 }
2081 }
2082
2083 return true;
Shih-wei Liaoe4454322010-04-07 12:21:42 -07002084}
2085
2086
2087
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002088GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2089 if (!S->usesMetadata())
2090 return 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002091
2092 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2093 gcp_map_type::iterator GCPI = GCMap.find(S);
2094 if (GCPI != GCMap.end())
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002095 return GCPI->second;
Jim Grosbach83d80832011-03-29 23:20:22 +00002096
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002097 const char *Name = S->getName().c_str();
Jim Grosbach83d80832011-03-29 23:20:22 +00002098
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002099 for (GCMetadataPrinterRegistry::iterator
2100 I = GCMetadataPrinterRegistry::begin(),
2101 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2102 if (strcmp(Name, I->getName()) == 0) {
2103 GCMetadataPrinter *GMP = I->instantiate();
2104 GMP->S = S;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002105 GCMap.insert(std::make_pair(S, GMP));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002106 return GMP;
2107 }
Jim Grosbach83d80832011-03-29 23:20:22 +00002108
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002109 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002110 return 0;
2111}
2112