blob: 7de9c6d616c872b57e3d38874f433b7cdcb82a3f [file] [log] [blame]
Chris Lattnerc0561f22010-04-07 18:10:38 +00001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
Chris Lattnera80ba712004-08-16 23:15:22 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera80ba712004-08-16 23:15:22 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
Evan Cheng932f0222006-03-03 02:04:29 +000014#include "llvm/CodeGen/AsmPrinter.h"
Chris Lattner49cd6642010-04-05 05:11:15 +000015#include "DwarfDebug.h"
16#include "DwarfException.h"
Stephen Hines36b56882014-04-23 16:57:46 -070017#include "WinCodeViewLineTables.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/ConstantFolding.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000021#include "llvm/CodeGen/GCMetadataPrinter.h"
Chris Lattner3b4fd322005-11-21 08:25:09 +000022#include "llvm/CodeGen/MachineConstantPool.h"
David Greene1924aab2009-11-13 21:34:57 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
David Greenefe37ab32009-08-18 19:22:55 +000024#include "llvm/CodeGen/MachineFunction.h"
Stephen Hines36b56882014-04-23 16:57:46 -070025#include "llvm/CodeGen/MachineInstrBundle.h"
Nate Begeman37efe672006-04-22 18:53:45 +000026#include "llvm/CodeGen/MachineJumpTableInfo.h"
David Greeneb71d1b22009-08-10 16:38:07 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070030#include "llvm/IR/DebugInfo.h"
31#include "llvm/IR/Mangler.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
33#include "llvm/IR/Operator.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000034#include "llvm/MC/MCAsmInfo.h"
Chris Lattner2b2954f2009-07-27 21:28:04 +000035#include "llvm/MC/MCContext.h"
Chris Lattner52492ac2010-01-23 06:17:14 +000036#include "llvm/MC/MCExpr.h"
David Greene3ac1ab82009-07-16 22:24:20 +000037#include "llvm/MC/MCInst.h"
Chris Lattnera87dea42009-07-31 18:48:30 +000038#include "llvm/MC/MCSection.h"
39#include "llvm/MC/MCStreamer.h"
Chris Lattner7cb384d2009-09-12 23:02:08 +000040#include "llvm/MC/MCSymbol.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000041#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/Format.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Timer.h"
David Blaikie6d9dbd52013-06-16 20:34:15 +000045#include "llvm/Target/TargetFrameLowering.h"
David Greene1924aab2009-11-13 21:34:57 +000046#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner0336fdb2006-10-06 22:50:56 +000047#include "llvm/Target/TargetLowering.h"
Chris Lattnerf0144122009-07-28 03:13:23 +000048#include "llvm/Target/TargetLoweringObjectFile.h"
Rafael Espindolaa4329972011-04-29 14:14:06 +000049#include "llvm/Target/TargetOptions.h"
Evan Chengda47e6e2008-03-15 00:03:38 +000050#include "llvm/Target/TargetRegisterInfo.h"
Stephen Hines36b56882014-04-23 16:57:46 -070051#include "llvm/Target/TargetSubtargetInfo.h"
Rafael Espindola2cc546d2013-10-30 22:08:11 +000052#include "llvm/Transforms/Utils/GlobalStatus.h"
Chris Lattnera80ba712004-08-16 23:15:22 +000053using namespace llvm;
54
Stephen Hinesdce4a402014-05-29 02:49:00 -070055#define DEBUG_TYPE "asm-printer"
56
Craig Topper4172a8a2013-07-16 01:17:10 +000057static const char *const DWARFGroupName = "DWARF Emission";
Stephen Hines36b56882014-04-23 16:57:46 -070058static const char *const DbgTimerName = "Debug Info Emission";
Craig Topper4172a8a2013-07-16 01:17:10 +000059static const char *const EHTimerName = "DWARF Exception Writer";
Stephen Hines36b56882014-04-23 16:57:46 -070060static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
Torok Edwin9c421072010-04-07 10:44:46 +000061
Chris Lattner14c38ec2010-01-28 01:02:27 +000062STATISTIC(EmittedInsts, "Number of machine instrs printed");
63
Devang Patel19974732007-05-03 01:11:54 +000064char AsmPrinter::ID = 0;
Chris Lattner11d53c12010-03-13 20:55:24 +000065
Stephen Hinesdce4a402014-05-29 02:49:00 -070066typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
Chris Lattnere00b59f2010-04-04 17:57:56 +000067static gcp_map_type &getGCMap(void *&P) {
Stephen Hinesdce4a402014-05-29 02:49:00 -070068 if (!P)
Chris Lattnere00b59f2010-04-04 17:57:56 +000069 P = new gcp_map_type();
70 return *(gcp_map_type*)P;
71}
72
73
Chris Lattnere87f7bb2010-04-28 19:58:07 +000074/// getGVAlignmentLog2 - Return the alignment to use for the specified global
75/// value in log2 form. This rounds up to the preferred alignment if possible
76/// and legal.
Micah Villmow3574eca2012-10-08 16:38:25 +000077static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
Chris Lattnere87f7bb2010-04-28 19:58:07 +000078 unsigned InBits = 0) {
79 unsigned NumBits = 0;
80 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
81 NumBits = TD.getPreferredAlignmentLog(GVar);
Jim Grosbach83d80832011-03-29 23:20:22 +000082
Chris Lattnere87f7bb2010-04-28 19:58:07 +000083 // If InBits is specified, round it to it.
84 if (InBits > NumBits)
85 NumBits = InBits;
Jim Grosbach83d80832011-03-29 23:20:22 +000086
Chris Lattnere87f7bb2010-04-28 19:58:07 +000087 // If the GV has a specified alignment, take it into account.
88 if (GV->getAlignment() == 0)
89 return NumBits;
Jim Grosbach83d80832011-03-29 23:20:22 +000090
Chris Lattnere87f7bb2010-04-28 19:58:07 +000091 unsigned GVAlign = Log2_32(GV->getAlignment());
Jim Grosbach83d80832011-03-29 23:20:22 +000092
Chris Lattnere87f7bb2010-04-28 19:58:07 +000093 // If the GVAlign is larger than NumBits, or if we are required to obey
94 // NumBits because the GV has an assigned section, obey it.
95 if (GVAlign > NumBits || GV->hasSection())
96 NumBits = GVAlign;
97 return NumBits;
98}
99
Chris Lattnerb23569a2010-04-04 08:18:47 +0000100AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
Owen Anderson90c579d2010-08-06 18:33:48 +0000101 : MachineFunctionPass(ID),
Joey Gouly715d98d2013-09-12 10:28:05 +0000102 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
Chris Lattner11d53c12010-03-13 20:55:24 +0000103 OutContext(Streamer.getContext()),
104 OutStreamer(Streamer),
Stephen Hinesdce4a402014-05-29 02:49:00 -0700105 LastMI(nullptr), LastFn(0), Counter(~0U), SetCounter(0) {
106 DD = nullptr; MMI = nullptr; LI = nullptr; MF = nullptr;
107 CurrentFnSym = CurrentFnSymForSize = nullptr;
108 GCMetadataPrinters = nullptr;
Chris Lattner56591ab2010-02-02 23:37:42 +0000109 VerboseAsm = Streamer.isVerboseAsm();
Evan Cheng42bf74b2009-03-25 01:47:28 +0000110}
Chris Lattnered138932005-12-13 06:32:10 +0000111
Gordon Henriksenc317a602008-08-17 12:08:44 +0000112AsmPrinter::~AsmPrinter() {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700113 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
Jim Grosbach83d80832011-03-29 23:20:22 +0000114
Stephen Hinesdce4a402014-05-29 02:49:00 -0700115 if (GCMetadataPrinters) {
Chris Lattnere00b59f2010-04-04 17:57:56 +0000116 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
Jim Grosbach83d80832011-03-29 23:20:22 +0000117
Chris Lattnere00b59f2010-04-04 17:57:56 +0000118 delete &GCMap;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700119 GCMetadataPrinters = nullptr;
Chris Lattnere00b59f2010-04-04 17:57:56 +0000120 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000121
Chris Lattner2b2954f2009-07-27 21:28:04 +0000122 delete &OutStreamer;
Gordon Henriksenc317a602008-08-17 12:08:44 +0000123}
Chris Lattnered138932005-12-13 06:32:10 +0000124
Chris Lattnerb84822f2010-01-26 04:35:26 +0000125/// getFunctionNumber - Return a unique ID for the current function.
126///
127unsigned AsmPrinter::getFunctionNumber() const {
128 return MF->getFunctionNumber();
129}
130
Dan Gohman0d805c32010-04-17 16:44:48 +0000131const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Chris Lattnerf0144122009-07-28 03:13:23 +0000132 return TM.getTargetLowering()->getObjFileLowering();
133}
134
Micah Villmow3574eca2012-10-08 16:38:25 +0000135/// getDataLayout - Return information about data layout.
136const DataLayout &AsmPrinter::getDataLayout() const {
137 return *TM.getDataLayout();
Chris Lattnerd38fee82010-04-05 00:13:49 +0000138}
139
Stephen Hines36b56882014-04-23 16:57:46 -0700140const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
141 return TM.getSubtarget<MCSubtargetInfo>();
142}
143
144void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
145 S.EmitInstruction(Inst, getSubtargetInfo());
146}
147
Eric Christopher00297ba2013-04-27 01:07:52 +0000148StringRef AsmPrinter::getTargetTriple() const {
149 return TM.getTargetTriple();
150}
151
Chris Lattnerdabf07c2009-08-18 06:15:16 +0000152/// getCurrentSection() - Return the current section we are emitting to.
153const MCSection *AsmPrinter::getCurrentSection() const {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000154 return OutStreamer.getCurrentSection().first;
Chris Lattnerdabf07c2009-08-18 06:15:16 +0000155}
156
157
Chris Lattnerd38fee82010-04-05 00:13:49 +0000158
Gordon Henriksence224772008-01-07 01:30:38 +0000159void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000160 AU.setPreservesAll();
Gordon Henriksence224772008-01-07 01:30:38 +0000161 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner11d53c12010-03-13 20:55:24 +0000162 AU.addRequired<MachineModuleInfo>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000163 AU.addRequired<GCModuleInfo>();
Chris Lattner3f53c832010-04-04 18:52:31 +0000164 if (isVerbose())
David Greeneb71d1b22009-08-10 16:38:07 +0000165 AU.addRequired<MachineLoopInfo>();
Gordon Henriksence224772008-01-07 01:30:38 +0000166}
167
Chris Lattnera80ba712004-08-16 23:15:22 +0000168bool AsmPrinter::doInitialization(Module &M) {
Chris Lattnerd32c8a52010-04-04 05:09:10 +0000169 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Chris Lattner11d53c12010-03-13 20:55:24 +0000170 MMI->AnalyzeModule(M);
171
Chris Lattnerf26e03b2009-07-31 17:42:42 +0000172 // Initialize TargetLoweringObjectFile.
173 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
174 .Initialize(OutContext, TM);
Jim Grosbach83d80832011-03-29 23:20:22 +0000175
Stephen Hines36b56882014-04-23 16:57:46 -0700176 OutStreamer.InitSections();
Nico Rieck25746dd2013-07-04 21:37:26 +0000177
Stephen Hines36b56882014-04-23 16:57:46 -0700178 Mang = new Mangler(TM.getDataLayout());
179
180 // Emit the version-min deplyment target directive if needed.
181 //
182 // FIXME: If we end up with a collection of these sorts of Darwin-specific
183 // or ELF-specific things, it may make sense to have a platform helper class
184 // that will work with the target helper class. For now keep it here, as the
185 // alternative is duplicated code in each of the target asm printers that
186 // use the directive, where it would need the same conditionalization
187 // anyway.
188 Triple TT(getTargetTriple());
189 if (TT.isOSDarwin()) {
190 unsigned Major, Minor, Update;
191 TT.getOSVersion(Major, Minor, Update);
192 // If there is a version specified, Major will be non-zero.
193 if (Major)
194 OutStreamer.EmitVersionMin((TT.isMacOSX() ?
195 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
196 Major, Minor, Update);
197 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000198
Bob Wilson812209a2009-09-30 22:06:26 +0000199 // Allow the target to emit any magic that it wants at the start of the file.
200 EmitStartOfAsmFile(M);
Rafael Espindola952b8392008-12-03 11:01:37 +0000201
Chris Lattnera6594fc2010-01-25 18:58:59 +0000202 // Very minimal debug info. It is ignored if we emit actual debug info. If we
203 // don't, this at least helps the user find where a global came from.
Chris Lattner33adcfb2009-08-22 21:43:10 +0000204 if (MAI->hasSingleParameterDotFile()) {
Chris Lattnera6594fc2010-01-25 18:58:59 +0000205 // .file "foo.c"
206 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
Rafael Espindola952b8392008-12-03 11:01:37 +0000207 }
208
Bob Wilson812209a2009-09-30 22:06:26 +0000209 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
210 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
Stephen Hinesdce4a402014-05-29 02:49:00 -0700211 for (auto &I : *MI)
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000212 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Chris Lattner7d73c7f2010-04-04 07:39:04 +0000213 MP->beginAssembly(*this);
Chris Lattner91bead72010-04-03 21:35:55 +0000214
215 // Emit module-level inline asm if it exists.
Chris Lattner47b7e5d2010-04-03 21:13:18 +0000216 if (!M.getModuleInlineAsm().empty()) {
217 OutStreamer.AddComment("Start of file scope inline assembly");
218 OutStreamer.AddBlankLine();
Chris Lattnera38941d2010-11-17 07:53:40 +0000219 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
Chris Lattner47b7e5d2010-04-03 21:13:18 +0000220 OutStreamer.AddComment("End of file scope inline assembly");
221 OutStreamer.AddBlankLine();
222 }
Chris Lattner2c1b1592006-01-23 23:47:53 +0000223
Stephen Hines36b56882014-04-23 16:57:46 -0700224 if (MAI->doesSupportDebugInformation()) {
225 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
226 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
227 DbgTimerName,
228 CodeViewLineTablesGroupName));
229 } else {
230 DD = new DwarfDebug(this, &M);
231 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
232 }
233 }
Anton Korobeynikovd7e8ddc2011-01-14 21:57:45 +0000234
Stephen Hinesdce4a402014-05-29 02:49:00 -0700235 DwarfException *DE = nullptr;
Rafael Espindola2d57a642011-05-05 19:48:34 +0000236 switch (MAI->getExceptionHandlingType()) {
237 case ExceptionHandling::None:
Stephen Hines36b56882014-04-23 16:57:46 -0700238 break;
Rafael Espindola2d57a642011-05-05 19:48:34 +0000239 case ExceptionHandling::SjLj:
Rafael Espindola2d57a642011-05-05 19:48:34 +0000240 case ExceptionHandling::DwarfCFI:
241 DE = new DwarfCFIException(this);
Stephen Hines36b56882014-04-23 16:57:46 -0700242 break;
Rafael Espindola2d57a642011-05-05 19:48:34 +0000243 case ExceptionHandling::ARM:
244 DE = new ARMException(this);
Stephen Hines36b56882014-04-23 16:57:46 -0700245 break;
Charles Davisd652b132011-05-27 23:47:32 +0000246 case ExceptionHandling::Win64:
247 DE = new Win64Exception(this);
Stephen Hines36b56882014-04-23 16:57:46 -0700248 break;
249 }
250 if (DE)
251 Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
252 return false;
253}
254
255static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
256 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
257 if (Linkage != GlobalValue::LinkOnceODRLinkage)
Charles Davisd652b132011-05-27 23:47:32 +0000258 return false;
Stephen Hines36b56882014-04-23 16:57:46 -0700259
260 if (!MAI.hasWeakDefCanBeHiddenDirective())
261 return false;
262
263 if (GV->hasUnnamedAddr())
264 return true;
265
266 // This is only used for MachO, so right now it doesn't really matter how
267 // we handle alias. Revisit this once the MachO linker implements aliases.
268 if (isa<GlobalAlias>(GV))
269 return false;
270
271 // If it is a non constant variable, it needs to be uniqued across shared
272 // objects.
273 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
274 if (!Var->isConstant())
275 return false;
Rafael Espindola2d57a642011-05-05 19:48:34 +0000276 }
Devang Patel14a55d92009-06-19 21:54:26 +0000277
Stephen Hines36b56882014-04-23 16:57:46 -0700278 GlobalStatus GS;
279 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
280 return true;
281
282 return false;
Chris Lattnera80ba712004-08-16 23:15:22 +0000283}
284
Rafael Espindola2cc546d2013-10-30 22:08:11 +0000285void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
286 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
Rafael Espindola38733612013-10-23 21:24:34 +0000287 switch (Linkage) {
Chris Lattnera3e88832010-01-26 23:47:12 +0000288 case GlobalValue::CommonLinkage:
289 case GlobalValue::LinkOnceAnyLinkage:
290 case GlobalValue::LinkOnceODRLinkage:
291 case GlobalValue::WeakAnyLinkage:
292 case GlobalValue::WeakODRLinkage:
Stephen Hines36b56882014-04-23 16:57:46 -0700293 if (MAI->hasWeakDefDirective()) {
Chris Lattnera3e88832010-01-26 23:47:12 +0000294 // .globl _foo
295 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Bill Wendling55ae5152010-08-20 22:05:50 +0000296
Stephen Hines36b56882014-04-23 16:57:46 -0700297 if (!canBeHidden(GV, *MAI))
Bill Wendling55ae5152010-08-20 22:05:50 +0000298 // .weak_definition _foo
299 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
300 else
301 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
Stephen Hines36b56882014-04-23 16:57:46 -0700302 } else if (MAI->hasLinkOnceDirective()) {
Chris Lattnera3e88832010-01-26 23:47:12 +0000303 // .globl _foo
304 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Duncan Sands5b1b3b72010-05-12 07:11:33 +0000305 //NOTE: linkonce is handled by the section the symbol was assigned to.
Chris Lattnera3e88832010-01-26 23:47:12 +0000306 } else {
307 // .weak _foo
308 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
309 }
Rafael Espindola38733612013-10-23 21:24:34 +0000310 return;
Chris Lattnera3e88832010-01-26 23:47:12 +0000311 case GlobalValue::AppendingLinkage:
312 // FIXME: appending linkage variables should go into a section of
313 // their name or something. For now, just emit them as external.
314 case GlobalValue::ExternalLinkage:
315 // If external or appending, declare as a global symbol.
316 // .globl _foo
317 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Rafael Espindola38733612013-10-23 21:24:34 +0000318 return;
Chris Lattnera3e88832010-01-26 23:47:12 +0000319 case GlobalValue::PrivateLinkage:
320 case GlobalValue::InternalLinkage:
Rafael Espindola38733612013-10-23 21:24:34 +0000321 return;
322 case GlobalValue::AvailableExternallyLinkage:
323 llvm_unreachable("Should never emit this");
Rafael Espindola38733612013-10-23 21:24:34 +0000324 case GlobalValue::ExternalWeakLinkage:
325 llvm_unreachable("Don't know how to emit these");
Chris Lattnera3e88832010-01-26 23:47:12 +0000326 }
Rafael Espindola38733612013-10-23 21:24:34 +0000327 llvm_unreachable("Unknown linkage type!");
Chris Lattnera3e88832010-01-26 23:47:12 +0000328}
329
Stephen Hines36b56882014-04-23 16:57:46 -0700330void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
331 const GlobalValue *GV) const {
332 TM.getNameWithPrefix(Name, GV, *Mang);
333}
334
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000335MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
Stephen Hines36b56882014-04-23 16:57:46 -0700336 return TM.getSymbol(GV, *Mang);
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000337}
Chris Lattnera3e88832010-01-26 23:47:12 +0000338
Chris Lattner48d64ba2010-01-19 04:39:15 +0000339/// EmitGlobalVariable - Emit the specified global variable to the .s file.
340void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
Rafael Espindola84397472011-04-05 15:51:32 +0000341 if (GV->hasInitializer()) {
342 // Check to see if this is a special global used by LLVM, if so, emit it.
343 if (EmitSpecialLLVMGlobal(GV))
344 return;
Jim Grosbach83d80832011-03-29 23:20:22 +0000345
Rafael Espindola84397472011-04-05 15:51:32 +0000346 if (isVerbose()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700347 GV->printAsOperand(OutStreamer.GetCommentOS(),
Rafael Espindola84397472011-04-05 15:51:32 +0000348 /*PrintType=*/false, GV->getParent());
349 OutStreamer.GetCommentOS() << '\n';
350 }
Eric Christopher04386ca2010-05-25 21:49:43 +0000351 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000352
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000353 MCSymbol *GVSym = getSymbol(GV);
Chad Rosier348d5422011-06-10 00:53:15 +0000354 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
Chris Lattner74bfe212010-01-19 05:38:33 +0000355
Rafael Espindola84397472011-04-05 15:51:32 +0000356 if (!GV->hasInitializer()) // External globals require no extra code.
357 return;
358
Chris Lattnera800f7c2010-01-25 18:33:40 +0000359 if (MAI->hasDotTypeDotSizeDirective())
360 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
Jim Grosbach83d80832011-03-29 23:20:22 +0000361
Chris Lattner74bfe212010-01-19 05:38:33 +0000362 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
363
Matt Arsenaultcee51c42013-10-03 19:50:01 +0000364 const DataLayout *DL = TM.getDataLayout();
365 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
Jim Grosbach83d80832011-03-29 23:20:22 +0000366
Chris Lattner567dd1f2010-04-26 18:46:46 +0000367 // If the alignment is specified, we *must* obey it. Overaligning a global
368 // with a specified alignment is a prompt way to break globals emitted to
369 // sections and expected to be contiguous (e.g. ObjC metadata).
Matt Arsenaultcee51c42013-10-03 19:50:01 +0000370 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
Jim Grosbach83d80832011-03-29 23:20:22 +0000371
Stephen Hinesdce4a402014-05-29 02:49:00 -0700372 for (const HandlerInfo &HI : Handlers) {
373 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
374 HI.Handler->setSymbolSize(GVSym, Size);
Stephen Hines36b56882014-04-23 16:57:46 -0700375 }
Richard Mittoneb46def2013-09-23 17:56:20 +0000376
Chris Lattner9744d612010-01-19 05:51:42 +0000377 // Handle common and BSS local symbols (.lcomm).
378 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner74bfe212010-01-19 05:38:33 +0000379 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
Benjamin Kramer36a16012011-09-01 23:04:27 +0000380 unsigned Align = 1 << AlignLog;
Jim Grosbach83d80832011-03-29 23:20:22 +0000381
Chris Lattner814819f2010-01-19 06:25:51 +0000382 // Handle common symbols.
Chris Lattner9744d612010-01-19 05:51:42 +0000383 if (GVKind.isCommon()) {
Chris Lattner8048ebe2010-09-27 06:44:54 +0000384 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
385 Align = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000386
Chris Lattner9744d612010-01-19 05:51:42 +0000387 // .comm _foo, 42, 4
Chris Lattner8048ebe2010-09-27 06:44:54 +0000388 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
Chris Lattner814819f2010-01-19 06:25:51 +0000389 return;
Chris Lattner9744d612010-01-19 05:51:42 +0000390 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000391
Chris Lattner814819f2010-01-19 06:25:51 +0000392 // Handle local BSS symbols.
393 if (MAI->hasMachoZeroFillDirective()) {
394 const MCSection *TheSection =
Stephen Hines36b56882014-04-23 16:57:46 -0700395 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
Chris Lattner814819f2010-01-19 06:25:51 +0000396 // .zerofill __DATA, __bss, _foo, 400, 5
Benjamin Kramer36a16012011-09-01 23:04:27 +0000397 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
Chris Lattner814819f2010-01-19 06:25:51 +0000398 return;
399 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000400
Ulrich Weiganddba37a32012-11-27 16:11:16 +0000401 // Use .lcomm only if it supports user-specified alignment.
402 // Otherwise, while it would still be correct to use .lcomm in some
403 // cases (e.g. when Align == 1), the external assembler might enfore
404 // some -unknown- default alignment behavior, which could cause
405 // spurious differences between external and integrated assembler.
406 // Prefer to simply fall back to .local / .comm in this case.
407 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
Chris Lattner814819f2010-01-19 06:25:51 +0000408 // .lcomm _foo, 42
Benjamin Kramer36a16012011-09-01 23:04:27 +0000409 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
Chris Lattner814819f2010-01-19 06:25:51 +0000410 return;
411 }
Chris Lattner8048ebe2010-09-27 06:44:54 +0000412
Chris Lattner8048ebe2010-09-27 06:44:54 +0000413 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
414 Align = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000415
Chris Lattner814819f2010-01-19 06:25:51 +0000416 // .local _foo
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000417 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
Chris Lattner814819f2010-01-19 06:25:51 +0000418 // .comm _foo, 42, 4
Chris Lattner8048ebe2010-09-27 06:44:54 +0000419 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
Chris Lattner74bfe212010-01-19 05:38:33 +0000420 return;
421 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000422
Chris Lattner74bfe212010-01-19 05:38:33 +0000423 const MCSection *TheSection =
Stephen Hines36b56882014-04-23 16:57:46 -0700424 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
Chris Lattner74bfe212010-01-19 05:38:33 +0000425
426 // Handle the zerofill directive on darwin, which is a special form of BSS
427 // emission.
428 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
Chris Lattner4c4d0c02010-04-27 07:41:44 +0000429 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
Jim Grosbach83d80832011-03-29 23:20:22 +0000430
Chris Lattner74bfe212010-01-19 05:38:33 +0000431 // .globl _foo
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000432 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner74bfe212010-01-19 05:38:33 +0000433 // .zerofill __DATA, __common, _foo, 400, 5
434 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
435 return;
436 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000437
Eric Christopher02b46bc2010-05-25 21:28:50 +0000438 // Handle thread local data for mach-o which requires us to output an
439 // additional structure of data and mangle the original symbol so that we
440 // can reference it later.
Chris Lattnerdfe254b2010-09-05 20:33:40 +0000441 //
442 // TODO: This should become an "emit thread local global" method on TLOF.
443 // All of this macho specific stuff should be sunk down into TLOFMachO and
444 // stuff like "TLSExtraDataSection" should no longer be part of the parent
445 // TLOF class. This will also make it more obvious that stuff like
446 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
447 // specific code.
Eric Christopher02b46bc2010-05-25 21:28:50 +0000448 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
Eric Christopher8116ca52010-05-22 00:10:22 +0000449 // Emit the .tbss symbol
Jim Grosbach83d80832011-03-29 23:20:22 +0000450 MCSymbol *MangSym =
Eric Christopher8116ca52010-05-22 00:10:22 +0000451 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
Jim Grosbach83d80832011-03-29 23:20:22 +0000452
Eric Christopher10251752013-08-07 21:13:06 +0000453 if (GVKind.isThreadBSS()) {
454 TheSection = getObjFileLowering().getTLSBSSSection();
Eric Christopher02b46bc2010-05-25 21:28:50 +0000455 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
Eric Christopher10251752013-08-07 21:13:06 +0000456 } else if (GVKind.isThreadData()) {
Eric Christopher02b46bc2010-05-25 21:28:50 +0000457 OutStreamer.SwitchSection(TheSection);
458
Jim Grosbach83d80832011-03-29 23:20:22 +0000459 EmitAlignment(AlignLog, GV);
Eric Christopher02b46bc2010-05-25 21:28:50 +0000460 OutStreamer.EmitLabel(MangSym);
Jim Grosbach83d80832011-03-29 23:20:22 +0000461
Eric Christopher02b46bc2010-05-25 21:28:50 +0000462 EmitGlobalConstant(GV->getInitializer());
463 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000464
Eric Christopher8116ca52010-05-22 00:10:22 +0000465 OutStreamer.AddBlankLine();
Jim Grosbach83d80832011-03-29 23:20:22 +0000466
Eric Christopher8116ca52010-05-22 00:10:22 +0000467 // Emit the variable struct for the runtime.
Jim Grosbach83d80832011-03-29 23:20:22 +0000468 const MCSection *TLVSect
Eric Christopher8116ca52010-05-22 00:10:22 +0000469 = getObjFileLowering().getTLSExtraDataSection();
Jim Grosbach83d80832011-03-29 23:20:22 +0000470
Eric Christopher8116ca52010-05-22 00:10:22 +0000471 OutStreamer.SwitchSection(TLVSect);
472 // Emit the linkage here.
Rafael Espindola2cc546d2013-10-30 22:08:11 +0000473 EmitLinkage(GV, GVSym);
Eric Christopher8116ca52010-05-22 00:10:22 +0000474 OutStreamer.EmitLabel(GVSym);
Jim Grosbach83d80832011-03-29 23:20:22 +0000475
Eric Christopher8116ca52010-05-22 00:10:22 +0000476 // Three pointers in size:
477 // - __tlv_bootstrap - used to make sure support exists
478 // - spare pointer, used when mapped by the runtime
479 // - pointer to mangled symbol above with initializer
Matt Arsenault6d9e0132013-11-10 04:46:57 +0000480 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
Eric Christopher73100642010-06-03 04:02:59 +0000481 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
Eric Christopherfdfc81f2013-06-24 23:20:02 +0000482 PtrSize);
Eric Christopher68ca5622013-01-09 01:57:54 +0000483 OutStreamer.EmitIntValue(0, PtrSize);
484 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
Jim Grosbach83d80832011-03-29 23:20:22 +0000485
Eric Christopher8116ca52010-05-22 00:10:22 +0000486 OutStreamer.AddBlankLine();
Eric Christopherc1a887d2010-05-20 00:49:07 +0000487 return;
488 }
Chris Lattner74bfe212010-01-19 05:38:33 +0000489
490 OutStreamer.SwitchSection(TheSection);
491
Rafael Espindola2cc546d2013-10-30 22:08:11 +0000492 EmitLinkage(GV, GVSym);
Chris Lattnerf74e25f2010-04-26 18:30:45 +0000493 EmitAlignment(AlignLog, GV);
Chris Lattnera3e88832010-01-26 23:47:12 +0000494
Chris Lattner4c8c6682010-01-19 06:41:24 +0000495 OutStreamer.EmitLabel(GVSym);
Chris Lattner74bfe212010-01-19 05:38:33 +0000496
497 EmitGlobalConstant(GV->getInitializer());
498
499 if (MAI->hasDotTypeDotSizeDirective())
Chris Lattner1947f242010-01-25 07:53:05 +0000500 // .size foo, 42
Chris Lattner99328ad2010-01-25 07:52:13 +0000501 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
Jim Grosbach83d80832011-03-29 23:20:22 +0000502
Chris Lattner0fd90fd2010-01-22 19:52:01 +0000503 OutStreamer.AddBlankLine();
Chris Lattner48d64ba2010-01-19 04:39:15 +0000504}
505
Chris Lattnerb11caed2010-01-26 23:18:44 +0000506/// EmitFunctionHeader - This method emits the header for the current
507/// function.
508void AsmPrinter::EmitFunctionHeader() {
509 // Print out constants referenced by the function
Chris Lattnera2406192010-01-28 00:19:24 +0000510 EmitConstantPool();
Jim Grosbach83d80832011-03-29 23:20:22 +0000511
Chris Lattnerb11caed2010-01-26 23:18:44 +0000512 // Print the 'header' of function.
Chris Lattnerb11caed2010-01-26 23:18:44 +0000513 const Function *F = MF->getFunction();
514
Stephen Hines36b56882014-04-23 16:57:46 -0700515 OutStreamer.SwitchSection(
516 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
Chris Lattnerbe9dfce2010-01-28 00:05:10 +0000517 EmitVisibility(CurrentFnSym, F->getVisibility());
Chris Lattnerb11caed2010-01-26 23:18:44 +0000518
Rafael Espindola2cc546d2013-10-30 22:08:11 +0000519 EmitLinkage(F, CurrentFnSym);
Chris Lattnerb406a812010-01-26 23:41:48 +0000520 EmitAlignment(MF->getAlignment(), F);
521
Chris Lattnerb11caed2010-01-26 23:18:44 +0000522 if (MAI->hasDotTypeDotSizeDirective())
523 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
524
Chris Lattner3f53c832010-04-04 18:52:31 +0000525 if (isVerbose()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700526 F->printAsOperand(OutStreamer.GetCommentOS(),
Chris Lattner9bc20ab2010-01-26 23:53:39 +0000527 /*PrintType=*/false, F->getParent());
528 OutStreamer.GetCommentOS() << '\n';
Chris Lattnerb11caed2010-01-26 23:18:44 +0000529 }
Chris Lattnerb11caed2010-01-26 23:18:44 +0000530
Dan Gohmanf451cb82010-02-10 16:03:48 +0000531 // Emit the CurrentFnSym. This is a virtual function to allow targets to
Chris Lattner2cf72512010-01-27 07:21:55 +0000532 // do their wild and crazy things as required.
533 EmitFunctionEntryLabel();
Jim Grosbach83d80832011-03-29 23:20:22 +0000534
Chris Lattner9cc0da92010-03-15 20:39:00 +0000535 // If the function had address-taken blocks that got deleted, then we have
536 // references to the dangling symbols. Emit them at the start of the function
537 // so that we don't get references to undefined symbols.
538 std::vector<MCSymbol*> DeadBlockSyms;
539 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
540 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
541 OutStreamer.AddComment("Address taken block that was later removed");
542 OutStreamer.EmitLabel(DeadBlockSyms[i]);
543 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000544
Chris Lattnerb11caed2010-01-26 23:18:44 +0000545 // Emit pre-function debug and/or EH information.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700546 for (const HandlerInfo &HI : Handlers) {
547 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
548 HI.Handler->beginFunction(MF);
Torok Edwin9c421072010-04-07 10:44:46 +0000549 }
Peter Collingbourne0abc3622013-10-20 02:16:21 +0000550
551 // Emit the prefix data.
552 if (F->hasPrefixData())
553 EmitGlobalConstant(F->getPrefixData());
Chris Lattnerb11caed2010-01-26 23:18:44 +0000554}
555
Chris Lattner2cf72512010-01-27 07:21:55 +0000556/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
557/// function. This can be overridden by targets as required to do custom stuff.
558void AsmPrinter::EmitFunctionEntryLabel() {
Chris Lattnerb4202db2010-05-06 00:05:37 +0000559 // The function label could have already been emitted if two symbols end up
560 // conflicting due to asm renaming. Detect this and emit an error.
Jim Grosbach3e965312012-05-18 19:12:01 +0000561 if (CurrentFnSym->isUndefined())
Chris Lattnerb4202db2010-05-06 00:05:37 +0000562 return OutStreamer.EmitLabel(CurrentFnSym);
563
564 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
565 "' label emitted multiple times to assembly file");
Chris Lattner2cf72512010-01-27 07:21:55 +0000566}
Chris Lattnerb11caed2010-01-26 23:18:44 +0000567
Chad Rosierc53ade22012-09-07 18:16:38 +0000568/// emitComments - Pretty-print comments for instructions.
569static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
Devang Patele025e962010-06-29 22:29:15 +0000570 const MachineFunction *MF = MI.getParent()->getParent();
571 const TargetMachine &TM = MF->getTarget();
Jim Grosbach83d80832011-03-29 23:20:22 +0000572
Chris Lattner47529c92010-02-10 00:47:53 +0000573 // Check for spills and reloads
574 int FI;
Jim Grosbach83d80832011-03-29 23:20:22 +0000575
Chris Lattner47529c92010-02-10 00:47:53 +0000576 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000577
Chris Lattner47529c92010-02-10 00:47:53 +0000578 // We assume a single instruction only has a spill or reload, not
579 // both.
580 const MachineMemOperand *MMO;
581 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
582 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
583 MMO = *MI.memoperands_begin();
584 CommentOS << MMO->getSize() << "-byte Reload\n";
585 }
586 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
587 if (FrameInfo->isSpillSlotObjectIndex(FI))
588 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
589 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
590 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
591 MMO = *MI.memoperands_begin();
592 CommentOS << MMO->getSize() << "-byte Spill\n";
593 }
594 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
595 if (FrameInfo->isSpillSlotObjectIndex(FI))
596 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
597 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000598
Chris Lattner47529c92010-02-10 00:47:53 +0000599 // Check for spill-induced copies
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000600 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
601 CommentOS << " Reload Reuse\n";
Chris Lattner47529c92010-02-10 00:47:53 +0000602}
603
Chad Rosierc53ade22012-09-07 18:16:38 +0000604/// emitImplicitDef - This method emits the specified machine instruction
Chris Lattner17fedf22010-04-04 18:58:53 +0000605/// that is an implicit def.
Justin Holewinski43777c32013-10-11 12:39:36 +0000606void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
Chris Lattner17fedf22010-04-04 18:58:53 +0000607 unsigned RegNo = MI->getOperand(0).getReg();
Justin Holewinski43777c32013-10-11 12:39:36 +0000608 OutStreamer.AddComment(Twine("implicit-def: ") +
609 TM.getRegisterInfo()->getName(RegNo));
610 OutStreamer.AddBlankLine();
Chris Lattner17fedf22010-04-04 18:58:53 +0000611}
612
Chad Rosierc53ade22012-09-07 18:16:38 +0000613static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
Chris Lattner17fedf22010-04-04 18:58:53 +0000614 std::string Str = "kill:";
615 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
616 const MachineOperand &Op = MI->getOperand(i);
617 assert(Op.isReg() && "KILL instruction must have only register operands");
618 Str += ' ';
619 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
620 Str += (Op.isDef() ? "<def>" : "<kill>");
621 }
622 AP.OutStreamer.AddComment(Str);
623 AP.OutStreamer.AddBlankLine();
624}
625
Chad Rosierc53ade22012-09-07 18:16:38 +0000626/// emitDebugValueComment - This method handles the target-independent form
Dale Johannesen343b42e2010-04-07 01:15:14 +0000627/// of DBG_VALUE, returning true if it was able to do so. A false return
628/// means the target will need to handle MI in EmitInstruction.
Chad Rosierc53ade22012-09-07 18:16:38 +0000629static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
Dale Johannesen343b42e2010-04-07 01:15:14 +0000630 // This code handles only the 3-operand target-independent form.
631 if (MI->getNumOperands() != 3)
632 return false;
Chris Lattner47529c92010-02-10 00:47:53 +0000633
Benjamin Kramera592e672010-04-07 09:26:51 +0000634 SmallString<128> Str;
635 raw_svector_ostream OS(Str);
Stephen Hines36b56882014-04-23 16:57:46 -0700636 OS << "DEBUG_VALUE: ";
Benjamin Kramera592e672010-04-07 09:26:51 +0000637
Stephen Hines36b56882014-04-23 16:57:46 -0700638 DIVariable V(MI->getOperand(2).getMetadata());
David Blaikie702ff962013-06-15 00:33:47 +0000639 if (V.getContext().isSubprogram()) {
640 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
641 if (!Name.empty())
642 OS << Name << ":";
643 }
Benjamin Kramera592e672010-04-07 09:26:51 +0000644 OS << V.getName() << " <- ";
Dale Johannesen343b42e2010-04-07 01:15:14 +0000645
Adrian Prantl35176402013-07-09 20:28:37 +0000646 // The second operand is only an offset if it's an immediate.
647 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
648 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
649
Dale Johannesen343b42e2010-04-07 01:15:14 +0000650 // Register or immediate value. Register 0 means undef.
651 if (MI->getOperand(0).isFPImm()) {
652 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
653 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
Benjamin Kramera592e672010-04-07 09:26:51 +0000654 OS << (double)APF.convertToFloat();
Dale Johannesen343b42e2010-04-07 01:15:14 +0000655 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
Benjamin Kramera592e672010-04-07 09:26:51 +0000656 OS << APF.convertToDouble();
Dale Johannesen343b42e2010-04-07 01:15:14 +0000657 } else {
658 // There is no good way to print long double. Convert a copy to
659 // double. Ah well, it's only a comment.
660 bool ignored;
661 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
662 &ignored);
Benjamin Kramera592e672010-04-07 09:26:51 +0000663 OS << "(long double) " << APF.convertToDouble();
Dale Johannesen343b42e2010-04-07 01:15:14 +0000664 }
665 } else if (MI->getOperand(0).isImm()) {
Benjamin Kramera592e672010-04-07 09:26:51 +0000666 OS << MI->getOperand(0).getImm();
Devang Patel8594d422011-06-24 20:46:11 +0000667 } else if (MI->getOperand(0).isCImm()) {
668 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
Chris Lattner00d13902010-04-07 22:29:10 +0000669 } else {
David Blaikie6d9dbd52013-06-16 20:34:15 +0000670 unsigned Reg;
671 if (MI->getOperand(0).isReg()) {
672 Reg = MI->getOperand(0).getReg();
David Blaikie6d9dbd52013-06-16 20:34:15 +0000673 } else {
674 assert(MI->getOperand(0).isFI() && "Unknown operand type");
675 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
Eric Christopherfdfc81f2013-06-24 23:20:02 +0000676 Offset += TFI->getFrameIndexReference(*AP.MF,
677 MI->getOperand(0).getIndex(), Reg);
David Blaikie6d9dbd52013-06-16 20:34:15 +0000678 Deref = true;
679 }
David Blaikief14b44c2013-06-15 15:52:58 +0000680 if (Reg == 0) {
Dale Johannesen343b42e2010-04-07 01:15:14 +0000681 // Suppress offset, it is not meaningful here.
Benjamin Kramera592e672010-04-07 09:26:51 +0000682 OS << "undef";
Dale Johannesen343b42e2010-04-07 01:15:14 +0000683 // NOTE: Want this comment at start of line, don't emit with AddComment.
Stephen Hines36b56882014-04-23 16:57:46 -0700684 AP.OutStreamer.emitRawComment(OS.str());
Dale Johannesen343b42e2010-04-07 01:15:14 +0000685 return true;
686 }
David Blaikief14b44c2013-06-15 15:52:58 +0000687 if (Deref)
688 OS << '[';
689 OS << AP.TM.getRegisterInfo()->getName(Reg);
Chris Lattner00d13902010-04-07 22:29:10 +0000690 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000691
David Blaikief14b44c2013-06-15 15:52:58 +0000692 if (Deref)
Adrian Prantl35176402013-07-09 20:28:37 +0000693 OS << '+' << Offset << ']';
694
Dale Johannesen343b42e2010-04-07 01:15:14 +0000695 // NOTE: Want this comment at start of line, don't emit with AddComment.
Stephen Hines36b56882014-04-23 16:57:46 -0700696 AP.OutStreamer.emitRawComment(OS.str());
Dale Johannesen343b42e2010-04-07 01:15:14 +0000697 return true;
698}
Chris Lattner47529c92010-02-10 00:47:53 +0000699
Rafael Espindolae29887b2011-05-10 18:39:09 +0000700AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000701 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
702 MF->getFunction()->needsUnwindTableEntry())
703 return CFI_M_EH;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000704
Rafael Espindolaf2b04232011-05-06 14:56:22 +0000705 if (MMI->hasDebugInfo())
Rafael Espindolae29887b2011-05-10 18:39:09 +0000706 return CFI_M_Debug;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000707
Rafael Espindolae29887b2011-05-10 18:39:09 +0000708 return CFI_M_None;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000709}
710
Charles Davisf4633702011-05-28 04:21:04 +0000711bool AsmPrinter::needsSEHMoves() {
712 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
713 MF->getFunction()->needsUnwindTableEntry();
714}
715
Stephen Hines36b56882014-04-23 16:57:46 -0700716void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
717 ExceptionHandling::ExceptionsType ExceptionHandlingType =
718 MAI->getExceptionHandlingType();
719 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
720 ExceptionHandlingType != ExceptionHandling::ARM)
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000721 return;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000722
Rafael Espindolae29887b2011-05-10 18:39:09 +0000723 if (needsCFIMoves() == CFI_M_None)
Rafael Espindolaa4329972011-04-29 14:14:06 +0000724 return;
725
Bill Wendlinge060a5c2011-07-19 00:02:51 +0000726 if (MMI->getCompactUnwindEncoding() != 0)
727 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
728
Bill Wendling873e3922013-08-15 20:25:44 +0000729 const MachineModuleInfo &MMI = MF->getMMI();
Bill Wendling7d938ad2013-08-15 20:21:49 +0000730 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
Stephen Hines36b56882014-04-23 16:57:46 -0700731 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
732 const MCCFIInstruction &CFI = Instrs[CFIIndex];
733 emitCFIInstruction(CFI);
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000734}
735
Chris Lattner14c38ec2010-01-28 01:02:27 +0000736/// EmitFunctionBody - This method emits the body and trailer for a
737/// function.
738void AsmPrinter::EmitFunctionBody() {
Chris Lattneredfe7762010-01-28 01:58:58 +0000739 // Emit target-specific gunk before the function body.
740 EmitFunctionBodyStart();
Jim Grosbach83d80832011-03-29 23:20:22 +0000741
Stephen Hines36b56882014-04-23 16:57:46 -0700742 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000743
Chris Lattner14c38ec2010-01-28 01:02:27 +0000744 // Print out code for the function.
745 bool HasAnyRealCode = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700746 const MachineInstr *LastMI = nullptr;
747 for (auto &MBB : *MF) {
Chris Lattner14c38ec2010-01-28 01:02:27 +0000748 // Print a label for the basic block.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700749 EmitBasicBlockStart(MBB);
750 for (auto &MI : MBB) {
751 LastMI = &MI;
Bill Wendlingdc867042010-07-16 22:51:10 +0000752
Chris Lattner14c38ec2010-01-28 01:02:27 +0000753 // Print the assembly for the instruction.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700754 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
755 !MI.isDebugValue()) {
Chris Lattner14c38ec2010-01-28 01:02:27 +0000756 HasAnyRealCode = true;
Evan Chenged33b132010-04-27 19:38:45 +0000757 ++EmittedInsts;
758 }
759
Torok Edwin9c421072010-04-07 10:44:46 +0000760 if (ShouldPrintDebugScopes) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700761 for (const HandlerInfo &HI : Handlers) {
762 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
Stephen Hines36b56882014-04-23 16:57:46 -0700763 TimePassesIsEnabled);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700764 HI.Handler->beginInstruction(&MI);
Stephen Hines36b56882014-04-23 16:57:46 -0700765 }
Torok Edwin9c421072010-04-07 10:44:46 +0000766 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000767
Chris Lattner3f53c832010-04-04 18:52:31 +0000768 if (isVerbose())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700769 emitComments(MI, OutStreamer.GetCommentOS());
Chris Lattner47529c92010-02-10 00:47:53 +0000770
Stephen Hinesdce4a402014-05-29 02:49:00 -0700771 switch (MI.getOpcode()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700772 case TargetOpcode::CFI_INSTRUCTION:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700773 emitCFIInstruction(MI);
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000774 break;
775
Chris Lattner518bb532010-02-09 19:54:29 +0000776 case TargetOpcode::EH_LABEL:
777 case TargetOpcode::GC_LABEL:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700778 OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
Chris Lattner0d883e32010-02-03 01:00:52 +0000779 break;
Chris Lattner518bb532010-02-09 19:54:29 +0000780 case TargetOpcode::INLINEASM:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700781 EmitInlineAsm(&MI);
Chris Lattner0d883e32010-02-03 01:00:52 +0000782 break;
Dale Johannesen343b42e2010-04-07 01:15:14 +0000783 case TargetOpcode::DBG_VALUE:
784 if (isVerbose()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700785 if (!emitDebugValueComment(&MI, *this))
786 EmitInstruction(&MI);
Dale Johannesen343b42e2010-04-07 01:15:14 +0000787 }
788 break;
Chris Lattner518bb532010-02-09 19:54:29 +0000789 case TargetOpcode::IMPLICIT_DEF:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700790 if (isVerbose()) emitImplicitDef(&MI);
Chris Lattner0d883e32010-02-03 01:00:52 +0000791 break;
Chris Lattner518bb532010-02-09 19:54:29 +0000792 case TargetOpcode::KILL:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700793 if (isVerbose()) emitKill(&MI, *this);
Chris Lattner0d883e32010-02-03 01:00:52 +0000794 break;
795 default:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700796 EmitInstruction(&MI);
Chris Lattner0d883e32010-02-03 01:00:52 +0000797 break;
798 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000799
Torok Edwin9c421072010-04-07 10:44:46 +0000800 if (ShouldPrintDebugScopes) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700801 for (const HandlerInfo &HI : Handlers) {
802 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
Stephen Hines36b56882014-04-23 16:57:46 -0700803 TimePassesIsEnabled);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700804 HI.Handler->endInstruction();
Stephen Hines36b56882014-04-23 16:57:46 -0700805 }
Torok Edwin9c421072010-04-07 10:44:46 +0000806 }
Chris Lattner14c38ec2010-01-28 01:02:27 +0000807 }
808 }
Bill Wendlingdc867042010-07-16 22:51:10 +0000809
810 // If the last instruction was a prolog label, then we have a situation where
811 // we emitted a prolog but no function body. This results in the ending prolog
812 // label equaling the end of function label and an invalid "row" in the
813 // FDE. We need to emit a noop in this situation so that the FDE's rows are
814 // valid.
Stephen Hines36b56882014-04-23 16:57:46 -0700815 bool RequiresNoop = LastMI && LastMI->isCFIInstruction();
Bill Wendlingdc867042010-07-16 22:51:10 +0000816
Chris Lattner14c38ec2010-01-28 01:02:27 +0000817 // If the function is empty and the object file uses .subsections_via_symbols,
Chris Lattnerd49fe1b2010-01-28 01:28:58 +0000818 // then we need to emit *something* to the function body to prevent the
Chris Lattneree9eb412010-04-26 23:37:21 +0000819 // labels from collapsing together. Just emit a noop.
Bill Wendlingdc867042010-07-16 22:51:10 +0000820 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
Chris Lattneree9eb412010-04-26 23:37:21 +0000821 MCInst Noop;
822 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
Chris Lattnerd61647d2010-04-26 23:41:43 +0000823 if (Noop.getOpcode()) {
824 OutStreamer.AddComment("avoids zero-length function");
Stephen Hines36b56882014-04-23 16:57:46 -0700825 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
Chris Lattnerd61647d2010-04-26 23:41:43 +0000826 } else // Target not mc-ized yet.
Chris Lattneree9eb412010-04-26 23:37:21 +0000827 OutStreamer.EmitRawText(StringRef("\tnop\n"));
828 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000829
Rafael Espindola6c5b2dc2011-11-15 19:08:46 +0000830 const Function *F = MF->getFunction();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700831 for (const auto &BB : *F) {
832 if (!BB.hasAddressTaken())
Rafael Espindola6c5b2dc2011-11-15 19:08:46 +0000833 continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700834 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
Rafael Espindola6c5b2dc2011-11-15 19:08:46 +0000835 if (Sym->isDefined())
836 continue;
837 OutStreamer.AddComment("Address of block that was removed by CodeGen");
838 OutStreamer.EmitLabel(Sym);
839 }
840
Chris Lattneredfe7762010-01-28 01:58:58 +0000841 // Emit target-specific gunk after the function body.
842 EmitFunctionBodyEnd();
Jim Grosbach83d80832011-03-29 23:20:22 +0000843
Chris Lattnerfd60b8b2010-04-03 22:19:41 +0000844 // If the target wants a .size directive for the size of the function, emit
845 // it.
846 if (MAI->hasDotTypeDotSizeDirective()) {
Chris Lattner0c08d092010-04-03 22:28:33 +0000847 // Create a symbol for the end of function, so we can get the size as
848 // difference between the function label and the temp label.
849 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
850 OutStreamer.EmitLabel(FnEndLabel);
Jim Grosbach83d80832011-03-29 23:20:22 +0000851
Chris Lattner0c08d092010-04-03 22:28:33 +0000852 const MCExpr *SizeExp =
853 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
Hal Finkeld55a2662012-02-22 21:11:47 +0000854 MCSymbolRefExpr::Create(CurrentFnSymForSize,
855 OutContext),
Chris Lattner0c08d092010-04-03 22:28:33 +0000856 OutContext);
857 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
Chris Lattnerfd60b8b2010-04-03 22:19:41 +0000858 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000859
Stephen Hines36b56882014-04-23 16:57:46 -0700860 // Emit post-function debug and/or EH information.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700861 for (const HandlerInfo &HI : Handlers) {
862 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
863 HI.Handler->endFunction(MF);
Torok Edwin9c421072010-04-07 10:44:46 +0000864 }
Chris Lattner49cd6642010-04-05 05:11:15 +0000865 MMI->EndFunction();
Jim Grosbach83d80832011-03-29 23:20:22 +0000866
Chris Lattner14c38ec2010-01-28 01:02:27 +0000867 // Print out jump tables referenced by the function.
868 EmitJumpTableInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000869
Chris Lattnerd26a80f2010-02-03 01:49:49 +0000870 OutStreamer.AddBlankLine();
Chris Lattner14c38ec2010-01-28 01:02:27 +0000871}
872
Chris Lattnera80ba712004-08-16 23:15:22 +0000873bool AsmPrinter::doFinalization(Module &M) {
Chris Lattner40bbebd2009-07-21 18:38:57 +0000874 // Emit global variables.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700875 for (const auto &G : M.globals())
876 EmitGlobalVariable(&G);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000877
878 // Emit visibility info for declarations
Stephen Hinesdce4a402014-05-29 02:49:00 -0700879 for (const Function &F : M) {
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000880 if (!F.isDeclaration())
881 continue;
882 GlobalValue::VisibilityTypes V = F.getVisibility();
883 if (V == GlobalValue::DefaultVisibility)
884 continue;
885
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000886 MCSymbol *Name = getSymbol(&F);
Stuart Hastings5129bde2011-02-23 02:27:05 +0000887 EmitVisibility(Name, V, false);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000888 }
889
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000890 // Emit module flags.
Bill Wendling057d5212012-02-15 22:36:15 +0000891 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
892 M.getModuleFlagsMetadata(ModuleFlags);
893 if (!ModuleFlags.empty())
Stephen Hines36b56882014-04-23 16:57:46 -0700894 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000895
Richard Mitton5cc319a2013-09-19 23:21:01 +0000896 // Make sure we wrote out everything we need.
897 OutStreamer.Flush();
898
Chris Lattner49cd6642010-04-05 05:11:15 +0000899 // Finalize debug and EH information.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700900 for (const HandlerInfo &HI : Handlers) {
901 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
Stephen Hines36b56882014-04-23 16:57:46 -0700902 TimePassesIsEnabled);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700903 HI.Handler->endModule();
904 delete HI.Handler;
Chris Lattner49cd6642010-04-05 05:11:15 +0000905 }
Stephen Hines36b56882014-04-23 16:57:46 -0700906 Handlers.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700907 DD = nullptr;
Jim Grosbach83d80832011-03-29 23:20:22 +0000908
Chris Lattner0a7befa2009-06-24 18:52:01 +0000909 // If the target wants to know about weak references, print them all.
Chris Lattner33adcfb2009-08-22 21:43:10 +0000910 if (MAI->getWeakRefDirective()) {
Chris Lattner0a7befa2009-06-24 18:52:01 +0000911 // FIXME: This is not lazy, it would be nice to only print weak references
912 // to stuff that is actually used. Note that doing so would require targets
913 // to notice uses in operands (due to constant exprs etc). This should
914 // happen with the MC stuff eventually.
Rafael Espindola15404d02006-12-18 03:37:18 +0000915
Chris Lattner0a7befa2009-06-24 18:52:01 +0000916 // Print out module-level global variables here.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700917 for (const auto &G : M.globals()) {
918 if (!G.hasExternalWeakLinkage())
919 continue;
920 OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
Chris Lattner0a7befa2009-06-24 18:52:01 +0000921 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000922
Stephen Hinesdce4a402014-05-29 02:49:00 -0700923 for (const auto &F : M) {
924 if (!F.hasExternalWeakLinkage())
925 continue;
926 OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
Chris Lattner0a7befa2009-06-24 18:52:01 +0000927 }
Rafael Espindola15404d02006-12-18 03:37:18 +0000928 }
929
Chris Lattnercee63322010-01-26 20:40:54 +0000930 if (MAI->hasSetDirective()) {
Chris Lattner3a9be0e2010-01-23 05:51:36 +0000931 OutStreamer.AddBlankLine();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700932 for (const auto &Alias : M.aliases()) {
933 MCSymbol *Name = getSymbol(&Alias);
Anton Korobeynikov325be7c2007-09-06 17:21:48 +0000934
Stephen Hinesdce4a402014-05-29 02:49:00 -0700935 const GlobalValue *GV = Alias.getAliasee();
Stephen Hines36b56882014-04-23 16:57:46 -0700936 assert(!GV->isDeclaration());
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000937 MCSymbol *Target = getSymbol(GV);
Anton Korobeynikov541af7f2008-09-24 22:21:04 +0000938
Stephen Hinesdce4a402014-05-29 02:49:00 -0700939 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000940 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700941 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000942 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
Chris Lattner10b318b2010-01-17 21:43:43 +0000943 else
Stephen Hinesdce4a402014-05-29 02:49:00 -0700944 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
Anton Korobeynikov22c9e652008-03-11 21:41:14 +0000945
Stephen Hinesdce4a402014-05-29 02:49:00 -0700946 EmitVisibility(Name, Alias.getVisibility());
Anton Korobeynikov22c9e652008-03-11 21:41:14 +0000947
Chris Lattnerc618c8a2010-01-26 21:53:08 +0000948 // Emit the directives as assignments aka .set:
Jim Grosbach83d80832011-03-29 23:20:22 +0000949 OutStreamer.EmitAssignment(Name,
Chris Lattnerc618c8a2010-01-26 21:53:08 +0000950 MCSymbolRefExpr::Create(Target, OutContext));
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +0000951 }
952 }
953
Duncan Sands1465d612009-01-28 13:14:17 +0000954 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000955 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
956 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
Stephen Hinesdce4a402014-05-29 02:49:00 -0700957 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
Chris Lattner7d73c7f2010-04-04 07:39:04 +0000958 MP->finishAssembly(*this);
Gordon Henriksence224772008-01-07 01:30:38 +0000959
Rafael Espindola3aa342b2013-10-16 01:49:05 +0000960 // Emit llvm.ident metadata in an '.ident' directive.
961 EmitModuleIdents(M);
962
Dan Gohmana779a982008-05-05 00:28:39 +0000963 // If we don't have any trampolines, then we don't require stack memory
964 // to be executable. Some targets have a directive to declare this.
Chris Lattner0a7befa2009-06-24 18:52:01 +0000965 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
Dan Gohmana779a982008-05-05 00:28:39 +0000966 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Chris Lattner74aae472010-04-08 21:26:26 +0000967 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
Chris Lattnerf9f93e42010-01-23 07:21:06 +0000968 OutStreamer.SwitchSection(S);
Jim Grosbach83d80832011-03-29 23:20:22 +0000969
Chris Lattnerbd23d5f2009-09-18 20:17:03 +0000970 // Allow the target to emit any magic that it wants at the end of the file,
971 // after everything else has gone out.
972 EmitEndOfAsmFile(M);
Jim Grosbach83d80832011-03-29 23:20:22 +0000973
Stephen Hinesdce4a402014-05-29 02:49:00 -0700974 delete Mang; Mang = nullptr;
975 MMI = nullptr;
Jim Grosbach83d80832011-03-29 23:20:22 +0000976
Chris Lattner2b2954f2009-07-27 21:28:04 +0000977 OutStreamer.Finish();
Pedro Artigas5399d252012-12-12 22:59:46 +0000978 OutStreamer.reset();
979
Chris Lattnera80ba712004-08-16 23:15:22 +0000980 return false;
981}
982
Chris Lattner25045bd2005-11-21 07:51:36 +0000983void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
Chris Lattnerb84822f2010-01-26 04:35:26 +0000984 this->MF = &MF;
Chris Lattner412c3a52010-01-16 01:24:10 +0000985 // Get the function symbol.
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000986 CurrentFnSym = getSymbol(MF.getFunction());
Hal Finkeld55a2662012-02-22 21:11:47 +0000987 CurrentFnSymForSize = CurrentFnSym;
David Greeneb71d1b22009-08-10 16:38:07 +0000988
Chris Lattner3f53c832010-04-04 18:52:31 +0000989 if (isVerbose())
David Greeneb71d1b22009-08-10 16:38:07 +0000990 LI = &getAnalysis<MachineLoopInfo>();
Chris Lattnera80ba712004-08-16 23:15:22 +0000991}
992
Evan Cheng1606e8e2009-03-13 07:51:59 +0000993namespace {
994 // SectionCPs - Keep track the alignment, constpool entries per Section.
995 struct SectionCPs {
Chris Lattnera87dea42009-07-31 18:48:30 +0000996 const MCSection *S;
Evan Cheng1606e8e2009-03-13 07:51:59 +0000997 unsigned Alignment;
998 SmallVector<unsigned, 4> CPEs;
Douglas Gregorcabdd742009-12-19 07:05:23 +0000999 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
Evan Cheng1606e8e2009-03-13 07:51:59 +00001000 };
1001}
1002
Chris Lattner3b4fd322005-11-21 08:25:09 +00001003/// EmitConstantPool - Print to the current output stream assembly
1004/// representations of the constants in the constant pool MCP. This is
1005/// used to print out constants which have been "spilled to memory" by
1006/// the code generator.
1007///
Chris Lattnera2406192010-01-28 00:19:24 +00001008void AsmPrinter::EmitConstantPool() {
1009 const MachineConstantPool *MCP = MF->getConstantPool();
Chris Lattnerfa77d432006-02-09 04:22:52 +00001010 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
Chris Lattner3b4fd322005-11-21 08:25:09 +00001011 if (CP.empty()) return;
Evan Cheng2d2cec12006-06-29 00:26:09 +00001012
Anton Korobeynikov088ae832008-09-24 22:17:59 +00001013 // Calculate sections for constant pool entries. We collect entries to go into
1014 // the same section together to reduce amount of section switch statements.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001015 SmallVector<SectionCPs, 4> CPSections;
Chris Lattner3b4fd322005-11-21 08:25:09 +00001016 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Chris Lattner298414e2009-07-22 00:28:43 +00001017 const MachineConstantPoolEntry &CPE = CP[i];
Evan Cheng1606e8e2009-03-13 07:51:59 +00001018 unsigned Align = CPE.getAlignment();
Jim Grosbach83d80832011-03-29 23:20:22 +00001019
Chris Lattner5c2f7892009-07-26 06:26:55 +00001020 SectionKind Kind;
1021 switch (CPE.getRelocationInfo()) {
1022 default: llvm_unreachable("Unknown section kind");
Chris Lattner27981192009-08-01 23:57:16 +00001023 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattner4c509222009-07-26 07:00:12 +00001024 case 1:
Chris Lattner27981192009-08-01 23:57:16 +00001025 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattner4c509222009-07-26 07:00:12 +00001026 break;
Chris Lattner5c2f7892009-07-26 06:26:55 +00001027 case 0:
Micah Villmow3574eca2012-10-08 16:38:25 +00001028 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
Chris Lattner27981192009-08-01 23:57:16 +00001029 case 4: Kind = SectionKind::getMergeableConst4(); break;
1030 case 8: Kind = SectionKind::getMergeableConst8(); break;
1031 case 16: Kind = SectionKind::getMergeableConst16();break;
1032 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattner4c509222009-07-26 07:00:12 +00001033 }
Chris Lattner5c2f7892009-07-26 06:26:55 +00001034 }
1035
Chris Lattner83d77fa2009-08-01 23:46:12 +00001036 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Jim Grosbach83d80832011-03-29 23:20:22 +00001037
Evan Cheng1606e8e2009-03-13 07:51:59 +00001038 // The number of sections are small, just do a linear search from the
1039 // last section to the first.
1040 bool Found = false;
1041 unsigned SecIdx = CPSections.size();
1042 while (SecIdx != 0) {
1043 if (CPSections[--SecIdx].S == S) {
1044 Found = true;
1045 break;
1046 }
1047 }
1048 if (!Found) {
1049 SecIdx = CPSections.size();
1050 CPSections.push_back(SectionCPs(S, Align));
1051 }
1052
1053 if (Align > CPSections[SecIdx].Alignment)
1054 CPSections[SecIdx].Alignment = Align;
1055 CPSections[SecIdx].CPEs.push_back(i);
Evan Cheng2d2cec12006-06-29 00:26:09 +00001056 }
1057
Anton Korobeynikov088ae832008-09-24 22:17:59 +00001058 // Now print stuff into the calculated sections.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001059 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001060 OutStreamer.SwitchSection(CPSections[i].S);
Evan Cheng1606e8e2009-03-13 07:51:59 +00001061 EmitAlignment(Log2_32(CPSections[i].Alignment));
Evan Cheng2d2cec12006-06-29 00:26:09 +00001062
Evan Cheng1606e8e2009-03-13 07:51:59 +00001063 unsigned Offset = 0;
1064 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1065 unsigned CPI = CPSections[i].CPEs[j];
1066 MachineConstantPoolEntry CPE = CP[CPI];
Anton Korobeynikov088ae832008-09-24 22:17:59 +00001067
Chris Lattner3029f922006-02-09 04:46:04 +00001068 // Emit inter-object padding for alignment.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001069 unsigned AlignMask = CPE.getAlignment() - 1;
1070 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
Eric Christopherca1dd052013-01-09 01:35:34 +00001071 OutStreamer.EmitZeros(NewOffset - Offset);
Evan Cheng1606e8e2009-03-13 07:51:59 +00001072
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001073 Type *Ty = CPE.getType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001074 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
Chris Lattner39248682010-01-23 05:19:23 +00001075 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1076
Evan Cheng1606e8e2009-03-13 07:51:59 +00001077 if (CPE.isMachineConstantPoolEntry())
1078 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1079 else
1080 EmitGlobalConstant(CPE.Val.ConstVal);
Chris Lattner3029f922006-02-09 04:46:04 +00001081 }
Chris Lattner3b4fd322005-11-21 08:25:09 +00001082 }
1083}
1084
Nate Begeman37efe672006-04-22 18:53:45 +00001085/// EmitJumpTableInfo - Print assembly representations of the jump tables used
Jim Grosbach83d80832011-03-29 23:20:22 +00001086/// by the current function to the current output stream.
Nate Begeman37efe672006-04-22 18:53:45 +00001087///
Chris Lattner14c38ec2010-01-28 01:02:27 +00001088void AsmPrinter::EmitJumpTableInfo() {
Stephen Hines36b56882014-04-23 16:57:46 -07001089 const DataLayout *DL = MF->getTarget().getDataLayout();
Chris Lattner14c38ec2010-01-28 01:02:27 +00001090 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001091 if (!MJTI) return;
Richard Osborne95da6052010-03-11 14:58:16 +00001092 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001093 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1094 if (JT.empty()) return;
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001095
Jim Grosbach83d80832011-03-29 23:20:22 +00001096 // Pick the directive to use to print the jump table entries, and switch to
Nate Begeman2f1ae882006-07-27 01:13:04 +00001097 // the appropriate section.
Chris Lattner14c38ec2010-01-28 01:02:27 +00001098 const Function *F = MF->getFunction();
Evan Chengb13bafe2009-06-18 20:37:15 +00001099 bool JTInDiffSection = false;
Chris Lattnerf1214cb2010-01-26 06:53:37 +00001100 if (// In PIC mode, we need to emit the jump table to the same section as the
1101 // function body itself, otherwise the label differences won't make sense.
1102 // FIXME: Need a better predicate for this: what about custom entries?
1103 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1104 // We should also do if the section name is NULL or function is declared
1105 // in discardable section
1106 // FIXME: this isn't the right predicate, should be based on the MCSection
1107 // for the function.
1108 F->isWeakForLinker()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001109 OutStreamer.SwitchSection(
1110 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
Nate Begeman2f1ae882006-07-27 01:13:04 +00001111 } else {
Chris Lattner83d77fa2009-08-01 23:46:12 +00001112 // Otherwise, drop it in the readonly section.
Jim Grosbach83d80832011-03-29 23:20:22 +00001113 const MCSection *ReadOnlySection =
Chris Lattner27981192009-08-01 23:57:16 +00001114 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001115 OutStreamer.SwitchSection(ReadOnlySection);
Evan Chengb13bafe2009-06-18 20:37:15 +00001116 JTInDiffSection = true;
Nate Begeman2f1ae882006-07-27 01:13:04 +00001117 }
Chris Lattner071c62f2010-01-25 23:26:13 +00001118
Micah Villmow3574eca2012-10-08 16:38:25 +00001119 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
Jim Grosbach83d80832011-03-29 23:20:22 +00001120
Jim Grosbache9525d82012-09-24 23:06:27 +00001121 // Jump tables in code sections are marked with a data_region directive
1122 // where that's supported.
1123 if (!JTInDiffSection)
1124 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1125
Chris Lattner3b131d72010-01-26 06:42:44 +00001126 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1127 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Jim Grosbach83d80832011-03-29 23:20:22 +00001128
1129 // If this jump table was deleted, ignore it.
Chris Lattner07371882006-10-28 18:10:06 +00001130 if (JTBBs.empty()) continue;
Nate Begeman52a51e382006-08-12 21:29:52 +00001131
Chris Lattnere35df922010-01-26 05:15:20 +00001132 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1133 // .set directive for each unique entry. This reduces the number of
1134 // relocations the assembler will generate for the jump table.
1135 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
Chris Lattnercee63322010-01-26 20:40:54 +00001136 MAI->hasSetDirective()) {
Chris Lattner3b131d72010-01-26 06:42:44 +00001137 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1138 const TargetLowering *TLI = TM.getTargetLowering();
Chris Lattner14c38ec2010-01-28 01:02:27 +00001139 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
Chris Lattner3b131d72010-01-26 06:42:44 +00001140 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1141 const MachineBasicBlock *MBB = JTBBs[ii];
1142 if (!EmittedSets.insert(MBB)) continue;
Jim Grosbach83d80832011-03-29 23:20:22 +00001143
Chris Lattnerc618c8a2010-01-26 21:53:08 +00001144 // .set LJTSet, LBB32-base
1145 const MCExpr *LHS =
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001146 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattnerc618c8a2010-01-26 21:53:08 +00001147 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1148 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
Chris Lattner3b131d72010-01-26 06:42:44 +00001149 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001150 }
1151
Duncan Sandsab4c3662011-02-15 09:23:02 +00001152 // On some targets (e.g. Darwin) we want to emit two consecutive labels
Chris Lattner393a8ee2007-01-18 01:12:56 +00001153 // before each jump table. The first label is never referenced, but tells
1154 // the assembler and linker the extents of the jump table object. The
1155 // second label is actually referenced by the code.
Stephen Hines36b56882014-04-23 16:57:46 -07001156 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
Chris Lattnerbeeb93e2010-01-26 05:58:28 +00001157 // FIXME: This doesn't have to have any specific name, just any randomly
1158 // named and numbered 'l' label would work. Simplify GetJTISymbol.
Chris Lattner3b131d72010-01-26 06:42:44 +00001159 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
Chris Lattner39248682010-01-23 05:19:23 +00001160
Chris Lattner3b131d72010-01-26 06:42:44 +00001161 OutStreamer.EmitLabel(GetJTISymbol(JTI));
Chris Lattner39248682010-01-23 05:19:23 +00001162
Chris Lattner6bf1def2010-01-26 05:10:10 +00001163 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Chris Lattner3b131d72010-01-26 06:42:44 +00001164 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
Nate Begeman37efe672006-04-22 18:53:45 +00001165 }
Jim Grosbache9525d82012-09-24 23:06:27 +00001166 if (!JTInDiffSection)
1167 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
Nate Begeman37efe672006-04-22 18:53:45 +00001168}
1169
Chris Lattner6bf1def2010-01-26 05:10:10 +00001170/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1171/// current stream.
1172void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1173 const MachineBasicBlock *MBB,
1174 unsigned UID) const {
Jakob Stoklund Olesene5005d02011-02-09 21:52:06 +00001175 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
Stephen Hinesdce4a402014-05-29 02:49:00 -07001176 const MCExpr *Value = nullptr;
Chris Lattnerff537ce2010-01-26 03:43:22 +00001177 switch (MJTI->getEntryKind()) {
Richard Osborne95da6052010-03-11 14:58:16 +00001178 case MachineJumpTableInfo::EK_Inline:
David Blaikie4d6ccb52012-01-20 21:51:11 +00001179 llvm_unreachable("Cannot emit EK_Inline jump table entry");
Chris Lattner85fe0782010-01-26 04:05:28 +00001180 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner6bf1def2010-01-26 05:10:10 +00001181 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
Chris Lattner85fe0782010-01-26 04:05:28 +00001182 OutContext);
1183 break;
Chris Lattnerff537ce2010-01-26 03:43:22 +00001184 case MachineJumpTableInfo::EK_BlockAddress:
1185 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1186 // .word LBB123
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001187 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattnerff537ce2010-01-26 03:43:22 +00001188 break;
Chris Lattnerff537ce2010-01-26 03:43:22 +00001189 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1190 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1191 // with a relocation as gp-relative, e.g.:
1192 // .gprel32 LBB123
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001193 MCSymbol *MBBSym = MBB->getSymbol();
Chris Lattner718fb592010-01-25 21:28:50 +00001194 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
Chris Lattner78f485a2010-01-25 21:10:10 +00001195 return;
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001196 }
Chris Lattner85fe0782010-01-26 04:05:28 +00001197
Akira Hatanaka6c2cf8b2012-02-03 04:33:00 +00001198 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1199 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1200 // with a relocation as gp-relative, e.g.:
1201 // .gpdword LBB123
1202 MCSymbol *MBBSym = MBB->getSymbol();
1203 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1204 return;
1205 }
1206
Chris Lattnerff537ce2010-01-26 03:43:22 +00001207 case MachineJumpTableInfo::EK_LabelDifference32: {
1208 // EK_LabelDifference32 - Each entry is the address of the block minus
1209 // the address of the jump table. This is used for PIC jump tables where
1210 // gprel32 is not supported. e.g.:
1211 // .word LBB123 - LJTI1_2
1212 // If the .set directive is supported, this is emitted as:
1213 // .set L4_5_set_123, LBB123 - LJTI1_2
1214 // .word L4_5_set_123
Jim Grosbach83d80832011-03-29 23:20:22 +00001215
1216 // If we have emitted set directives for the jump table entries, print
Chris Lattnerff537ce2010-01-26 03:43:22 +00001217 // them rather than the entries themselves. If we're emitting PIC, then
1218 // emit the table entries as differences between two text section labels.
Chris Lattnercee63322010-01-26 20:40:54 +00001219 if (MAI->hasSetDirective()) {
Chris Lattnerff537ce2010-01-26 03:43:22 +00001220 // If we used .set, reference the .set's symbol.
Chris Lattner6bf1def2010-01-26 05:10:10 +00001221 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
Chris Lattnerff537ce2010-01-26 03:43:22 +00001222 OutContext);
1223 break;
1224 }
Chris Lattner1aca2492010-01-25 21:22:22 +00001225 // Otherwise, use the difference as the jump table entry.
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001226 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattner6bf1def2010-01-26 05:10:10 +00001227 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
Chris Lattnerff537ce2010-01-26 03:43:22 +00001228 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1229 break;
1230 }
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001231 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001232
Chris Lattnerff537ce2010-01-26 03:43:22 +00001233 assert(Value && "Unknown entry kind!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001234
Micah Villmow3574eca2012-10-08 16:38:25 +00001235 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
Eric Christopherca1dd052013-01-09 01:35:34 +00001236 OutStreamer.EmitValue(Value, EntrySize);
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001237}
1238
1239
Chris Lattnered138932005-12-13 06:32:10 +00001240/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1241/// special global used by LLVM. If so, emit it and return true, otherwise
1242/// do nothing and return false.
1243bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Daniel Dunbar03d76512009-07-25 23:55:21 +00001244 if (GV->getName() == "llvm.used") {
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001245 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
Rafael Espindolacde25b42013-04-22 14:58:02 +00001246 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
Andrew Lenharthb753a9b2007-08-22 19:33:11 +00001247 return true;
1248 }
1249
Chris Lattner401e10c2009-07-20 06:14:25 +00001250 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
Chris Lattner266c7bb2009-04-13 05:44:34 +00001251 if (GV->getSection() == "llvm.metadata" ||
1252 GV->hasAvailableExternallyLinkage())
1253 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001254
Jim Laskey78098112006-03-07 22:00:35 +00001255 if (!GV->hasAppendingLinkage()) return false;
1256
1257 assert(GV->hasInitializer() && "Not a special LLVM global!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001258
Chris Lattnerf231c072009-03-09 05:52:15 +00001259 if (GV->getName() == "llvm.global_ctors") {
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001260 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
Jim Grosbach83d80832011-03-29 23:20:22 +00001261
Chris Lattner71eae712010-01-19 04:34:02 +00001262 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001263 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1264 StringRef Sym(".constructors_used");
1265 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001266 MCSA_Reference);
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001267 }
Chris Lattnerea3a9ff2009-03-09 08:18:48 +00001268 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001269 }
1270
Chris Lattnerf231c072009-03-09 05:52:15 +00001271 if (GV->getName() == "llvm.global_dtors") {
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001272 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
Chris Lattner71eae712010-01-19 04:34:02 +00001273
1274 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001275 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1276 StringRef Sym(".destructors_used");
1277 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001278 MCSA_Reference);
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001279 }
Chris Lattnerea3a9ff2009-03-09 08:18:48 +00001280 return true;
Chris Lattnered138932005-12-13 06:32:10 +00001281 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001282
Chris Lattnered138932005-12-13 06:32:10 +00001283 return false;
1284}
1285
Chris Lattner33adcfb2009-08-22 21:43:10 +00001286/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
Dale Johannesend2e51af2008-09-09 22:29:13 +00001287/// global in the specified llvm.used list for which emitUsedDirectiveFor
1288/// is true, as being used with this directive.
Rafael Espindolacde25b42013-04-22 14:58:02 +00001289void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
Dan Gohmana119de82009-06-14 23:30:43 +00001290 // Should be an array of 'i8*'.
Chris Lattnercb05af82006-09-26 03:38:18 +00001291 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner16fe9902009-07-17 22:00:23 +00001292 const GlobalValue *GV =
1293 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
Stephen Hines36b56882014-04-23 16:57:46 -07001294 if (GV)
Rafael Espindolaffc7dca2013-10-29 17:07:16 +00001295 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
Chris Lattnercb05af82006-09-26 03:38:18 +00001296 }
1297}
1298
Stephen Hinesdce4a402014-05-29 02:49:00 -07001299namespace {
1300struct Structor {
1301 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1302 int Priority;
1303 llvm::Constant *Func;
1304 llvm::GlobalValue *ComdatKey;
1305};
1306} // end namespace
1307
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001308/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1309/// priority.
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001310void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
Chris Lattnered138932005-12-13 06:32:10 +00001311 // Should be an array of '{ int, void ()* }' structs. The first value is the
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001312 // init priority.
Chris Lattnered138932005-12-13 06:32:10 +00001313 if (!isa<ConstantArray>(List)) return;
Chris Lattner8de324b2005-12-21 01:17:37 +00001314
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001315 // Sanity check the structors list.
1316 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1317 if (!InitList) return; // Not an array!
1318 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
Stephen Hinesdce4a402014-05-29 02:49:00 -07001319 // FIXME: Only allow the 3-field form in LLVM 4.0.
1320 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1321 return; // Not an array of two or three elements!
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001322 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1323 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
Stephen Hinesdce4a402014-05-29 02:49:00 -07001324 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1325 return; // Not (int, ptr, ptr).
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001326
1327 // Gather the structors in a form that's convenient for sorting by priority.
1328 SmallVector<Structor, 8> Structors;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001329 for (Value *O : InitList->operands()) {
1330 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001331 if (!CS) continue; // Malformed.
1332 if (CS->getOperand(1)->isNullValue())
1333 break; // Found a null terminator, skip the rest.
1334 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1335 if (!Priority) continue; // Malformed.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001336 Structors.push_back(Structor());
1337 Structor &S = Structors.back();
1338 S.Priority = Priority->getLimitedValue(65535);
1339 S.Func = CS->getOperand(1);
1340 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1341 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001342 }
1343
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001344 // Emit the function pointers in the target-specific order
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001345 const DataLayout *DL = TM.getDataLayout();
1346 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
Stephen Hinesdce4a402014-05-29 02:49:00 -07001347 std::stable_sort(Structors.begin(), Structors.end(),
1348 [](const Structor &L,
1349 const Structor &R) { return L.Priority < R.Priority; });
1350 for (Structor &S : Structors) {
1351 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1352 const MCSymbol *KeySym = nullptr;
1353 const MCSection *KeySec = nullptr;
1354 if (S.ComdatKey) {
1355 KeySym = getSymbol(S.ComdatKey);
1356 KeySec = getObjFileLowering().SectionForGlobal(S.ComdatKey, *Mang, TM);
1357 }
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001358 const MCSection *OutputSection =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001359 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym, KeySec)
1360 : Obj.getStaticDtorSection(S.Priority, KeySym, KeySec));
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001361 OutStreamer.SwitchSection(OutputSection);
1362 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1363 EmitAlignment(Align);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001364 EmitXXStructor(S.Func);
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001365 }
Chris Lattnered138932005-12-13 06:32:10 +00001366}
Chris Lattner3b4fd322005-11-21 08:25:09 +00001367
Rafael Espindola3aa342b2013-10-16 01:49:05 +00001368void AsmPrinter::EmitModuleIdents(Module &M) {
1369 if (!MAI->hasIdentDirective())
1370 return;
1371
1372 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1373 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1374 const MDNode *N = NMD->getOperand(i);
Stephen Hines36b56882014-04-23 16:57:46 -07001375 assert(N->getNumOperands() == 1 &&
Rafael Espindola3aa342b2013-10-16 01:49:05 +00001376 "llvm.ident metadata entry can have only one operand");
1377 const MDString *S = cast<MDString>(N->getOperand(0));
1378 OutStreamer.EmitIdent(S->getString());
1379 }
1380 }
1381}
1382
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001383//===--------------------------------------------------------------------===//
1384// Emission and print routines
1385//
1386
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001387/// EmitInt8 - Emit a byte directive and value.
1388///
1389void AsmPrinter::EmitInt8(int Value) const {
Eric Christopherca1dd052013-01-09 01:35:34 +00001390 OutStreamer.EmitIntValue(Value, 1);
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001391}
1392
1393/// EmitInt16 - Emit a short directive and value.
1394///
1395void AsmPrinter::EmitInt16(int Value) const {
Eric Christopherca1dd052013-01-09 01:35:34 +00001396 OutStreamer.EmitIntValue(Value, 2);
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001397}
1398
1399/// EmitInt32 - Emit a long directive and value.
1400///
1401void AsmPrinter::EmitInt32(int Value) const {
Eric Christopherca1dd052013-01-09 01:35:34 +00001402 OutStreamer.EmitIntValue(Value, 4);
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001403}
1404
Chris Lattner0d50c762010-03-08 23:58:37 +00001405/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1406/// in bytes of the directive is specified by Size and Hi/Lo specify the
1407/// labels. This implicitly uses .set if it is available.
1408void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1409 unsigned Size) const {
1410 // Get the Hi-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001411 const MCExpr *Diff =
Chris Lattner0d50c762010-03-08 23:58:37 +00001412 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1413 MCSymbolRefExpr::Create(Lo, OutContext),
1414 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001415
Chris Lattner0d50c762010-03-08 23:58:37 +00001416 if (!MAI->hasSetDirective()) {
Eric Christopherca1dd052013-01-09 01:35:34 +00001417 OutStreamer.EmitValue(Diff, Size);
Chris Lattner0d50c762010-03-08 23:58:37 +00001418 return;
1419 }
1420
1421 // Otherwise, emit with .set (aka assignment).
Chris Lattnerc0215722010-04-04 19:25:43 +00001422 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
Chris Lattner0d50c762010-03-08 23:58:37 +00001423 OutStreamer.EmitAssignment(SetLabel, Diff);
Eric Christopherca1dd052013-01-09 01:35:34 +00001424 OutStreamer.EmitSymbolValue(SetLabel, Size);
Chris Lattner0d50c762010-03-08 23:58:37 +00001425}
1426
Jim Grosbach83d80832011-03-29 23:20:22 +00001427/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
Devang Patelf2548ca2010-04-16 23:33:45 +00001428/// where the size in bytes of the directive is specified by Size and Hi/Lo
1429/// specify the labels. This implicitly uses .set if it is available.
1430void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
Stephen Hines36b56882014-04-23 16:57:46 -07001431 const MCSymbol *Lo,
1432 unsigned Size) const {
Jim Grosbach83d80832011-03-29 23:20:22 +00001433
Devang Patelf2548ca2010-04-16 23:33:45 +00001434 // Emit Hi+Offset - Lo
1435 // Get the Hi+Offset expression.
1436 const MCExpr *Plus =
Jim Grosbach83d80832011-03-29 23:20:22 +00001437 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
Devang Patelf2548ca2010-04-16 23:33:45 +00001438 MCConstantExpr::Create(Offset, OutContext),
1439 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001440
Devang Patelf2548ca2010-04-16 23:33:45 +00001441 // Get the Hi+Offset-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001442 const MCExpr *Diff =
Devang Patelf2548ca2010-04-16 23:33:45 +00001443 MCBinaryExpr::CreateSub(Plus,
1444 MCSymbolRefExpr::Create(Lo, OutContext),
1445 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001446
1447 if (!MAI->hasSetDirective())
Manman Ren38856f82013-10-29 23:14:15 +00001448 OutStreamer.EmitValue(Diff, Size);
Devang Patelf2548ca2010-04-16 23:33:45 +00001449 else {
1450 // Otherwise, emit with .set (aka assignment).
1451 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1452 OutStreamer.EmitAssignment(SetLabel, Diff);
Manman Ren38856f82013-10-29 23:14:15 +00001453 OutStreamer.EmitSymbolValue(SetLabel, Size);
Devang Patelf2548ca2010-04-16 23:33:45 +00001454 }
1455}
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001456
Jim Grosbach83d80832011-03-29 23:20:22 +00001457/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001458/// where the size in bytes of the directive is specified by Size and Label
1459/// specifies the label. This implicitly uses .set if it is available.
1460void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
Stephen Hines36b56882014-04-23 16:57:46 -07001461 unsigned Size,
1462 bool IsSectionRelative) const {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001463 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
Carlo Kokfdabd9f2013-08-02 16:14:15 +00001464 OutStreamer.EmitCOFFSecRel32(Label);
1465 return;
1466 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001467
Nick Lewyckyffccd922012-06-22 01:25:12 +00001468 // Emit Label+Offset (or just Label if Offset is zero)
1469 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1470 if (Offset)
Stephen Hines36b56882014-04-23 16:57:46 -07001471 Expr = MCBinaryExpr::CreateAdd(
1472 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001473
Eric Christopherca1dd052013-01-09 01:35:34 +00001474 OutStreamer.EmitValue(Expr, Size);
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001475}
Jim Grosbach83d80832011-03-29 23:20:22 +00001476
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001477//===----------------------------------------------------------------------===//
1478
Chris Lattner3a420532007-05-31 18:57:45 +00001479// EmitAlignment - Emit an alignment directive to the specified power of
1480// two boundary. For example, if you pass in 3 here, you will get an 8
1481// byte alignment. If a global value is specified, and if that global has
Chris Lattnere87f7bb2010-04-28 19:58:07 +00001482// an explicit alignment requested, it will override the alignment request
1483// if required for correctness.
Chris Lattner3a420532007-05-31 18:57:45 +00001484//
Stephen Hinesdce4a402014-05-29 02:49:00 -07001485void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
Micah Villmow3574eca2012-10-08 16:38:25 +00001486 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
Jim Grosbach83d80832011-03-29 23:20:22 +00001487
Chris Lattnere87f7bb2010-04-28 19:58:07 +00001488 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
Jim Grosbach83d80832011-03-29 23:20:22 +00001489
Chris Lattnerdabf07c2009-08-18 06:15:16 +00001490 if (getCurrentSection()->getKind().isText())
Chris Lattner2cce3712010-02-23 18:46:22 +00001491 OutStreamer.EmitCodeAlignment(1 << NumBits);
1492 else
Stephen Hines36b56882014-04-23 16:57:46 -07001493 OutStreamer.EmitValueToAlignment(1 << NumBits);
Chris Lattnerbfddc202004-08-17 19:14:29 +00001494}
David Greenea5bb59f2009-08-05 21:00:52 +00001495
Chris Lattner44e05082010-04-20 06:20:21 +00001496//===----------------------------------------------------------------------===//
1497// Constant emission.
1498//===----------------------------------------------------------------------===//
1499
Chad Rosierc53ade22012-09-07 18:16:38 +00001500/// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
Chris Lattner52492ac2010-01-23 06:17:14 +00001501///
Chad Rosierc53ade22012-09-07 18:16:38 +00001502static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
Chris Lattner52492ac2010-01-23 06:17:14 +00001503 MCContext &Ctx = AP.OutContext;
Jim Grosbach83d80832011-03-29 23:20:22 +00001504
Chris Lattner52492ac2010-01-23 06:17:14 +00001505 if (CV->isNullValue() || isa<UndefValue>(CV))
1506 return MCConstantExpr::Create(0, Ctx);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001507
Chris Lattner52492ac2010-01-23 06:17:14 +00001508 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1509 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001510
Chris Lattner52492ac2010-01-23 06:17:14 +00001511 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Rafael Espindolaffc7dca2013-10-29 17:07:16 +00001512 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
Bill Wendling3d7ff082010-08-18 18:41:13 +00001513
Chris Lattner52492ac2010-01-23 06:17:14 +00001514 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1515 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001516
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001517 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001518 if (!CE) {
Chris Lattner52492ac2010-01-23 06:17:14 +00001519 llvm_unreachable("Unknown constant value to lower!");
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001520 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001521
Stephen Hines36b56882014-04-23 16:57:46 -07001522 if (const MCExpr *RelocExpr =
1523 AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
1524 AP.TM))
1525 return RelocExpr;
1526
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001527 switch (CE->getOpcode()) {
Dan Gohman618f1772010-02-08 22:02:38 +00001528 default:
1529 // If the code isn't optimized, there may be outstanding folding
Micah Villmow3574eca2012-10-08 16:38:25 +00001530 // opportunities. Attempt to fold the expression using DataLayout as a
Dan Gohman618f1772010-02-08 22:02:38 +00001531 // last resort before giving up.
Dan Gohman54e72ec2010-02-08 22:19:11 +00001532 if (Constant *C =
Micah Villmow3574eca2012-10-08 16:38:25 +00001533 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Dan Gohman54e72ec2010-02-08 22:19:11 +00001534 if (C != CE)
Chad Rosierc53ade22012-09-07 18:16:38 +00001535 return lowerConstant(C, AP);
Dan Gohman9f6a68622010-08-04 18:51:09 +00001536
1537 // Otherwise report the problem to the user.
1538 {
1539 std::string S;
1540 raw_string_ostream OS(S);
1541 OS << "Unsupported expression in static initializer: ";
Stephen Hines36b56882014-04-23 16:57:46 -07001542 CE->printAsOperand(OS, /*PrintType=*/false,
Stephen Hinesdce4a402014-05-29 02:49:00 -07001543 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
Dan Gohman9f6a68622010-08-04 18:51:09 +00001544 report_fatal_error(OS.str());
1545 }
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001546 case Instruction::GetElementPtr: {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001547 const DataLayout &DL = *AP.TM.getDataLayout();
Chris Lattner52492ac2010-01-23 06:17:14 +00001548 // Generate a symbolic expression for the byte address
Matt Arsenaultff718122013-10-21 20:03:54 +00001549 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001550 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
Jim Grosbach83d80832011-03-29 23:20:22 +00001551
Chad Rosierc53ade22012-09-07 18:16:38 +00001552 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
Nuno Lopes98281a22012-12-30 16:25:48 +00001553 if (!OffsetAI)
Chris Lattner52492ac2010-01-23 06:17:14 +00001554 return Base;
Jim Grosbach83d80832011-03-29 23:20:22 +00001555
Nuno Lopes98281a22012-12-30 16:25:48 +00001556 int64_t Offset = OffsetAI.getSExtValue();
Chris Lattner52492ac2010-01-23 06:17:14 +00001557 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1558 Ctx);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001559 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001560
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001561 case Instruction::Trunc:
1562 // We emit the value and depend on the assembler to truncate the generated
1563 // expression properly. This is important for differences between
1564 // blockaddress labels. Since the two labels are in the same function, it
1565 // is reasonable to treat their delta as a 32-bit value.
Chris Lattner52492ac2010-01-23 06:17:14 +00001566 // FALL THROUGH.
1567 case Instruction::BitCast:
Chad Rosierc53ade22012-09-07 18:16:38 +00001568 return lowerConstant(CE->getOperand(0), AP);
Chris Lattner52492ac2010-01-23 06:17:14 +00001569
1570 case Instruction::IntToPtr: {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001571 const DataLayout &DL = *AP.TM.getDataLayout();
Chris Lattner52492ac2010-01-23 06:17:14 +00001572 // Handle casts to pointers by changing them into casts to the appropriate
1573 // integer type. This promotes constant folding and simplifies this code.
1574 Constant *Op = CE->getOperand(0);
Matt Arsenaultff718122013-10-21 20:03:54 +00001575 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
Chris Lattner52492ac2010-01-23 06:17:14 +00001576 false/*ZExt*/);
Chad Rosierc53ade22012-09-07 18:16:38 +00001577 return lowerConstant(Op, AP);
Chris Lattner52492ac2010-01-23 06:17:14 +00001578 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001579
Chris Lattner52492ac2010-01-23 06:17:14 +00001580 case Instruction::PtrToInt: {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001581 const DataLayout &DL = *AP.TM.getDataLayout();
Chris Lattner52492ac2010-01-23 06:17:14 +00001582 // Support only foldable casts to/from pointers that can be eliminated by
1583 // changing the pointer to the appropriately sized integer type.
1584 Constant *Op = CE->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001585 Type *Ty = CE->getType();
Chris Lattner52492ac2010-01-23 06:17:14 +00001586
Chad Rosierc53ade22012-09-07 18:16:38 +00001587 const MCExpr *OpExpr = lowerConstant(Op, AP);
Chris Lattner52492ac2010-01-23 06:17:14 +00001588
1589 // We can emit the pointer value into this slot if the slot is an
1590 // integer slot equal to the size of the pointer.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001591 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
Chris Lattner52492ac2010-01-23 06:17:14 +00001592 return OpExpr;
1593
1594 // Otherwise the pointer is smaller than the resultant integer, mask off
1595 // the high bits so we are sure to get a proper truncation if the input is
1596 // a constant expr.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001597 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Chris Lattner52492ac2010-01-23 06:17:14 +00001598 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1599 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1600 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001601
Dan Gohman5938a3e2010-02-09 00:02:37 +00001602 // The MC library also has a right-shift operator, but it isn't consistently
1603 // signed or unsigned between different targets.
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001604 case Instruction::Add:
1605 case Instruction::Sub:
Dan Gohman5938a3e2010-02-09 00:02:37 +00001606 case Instruction::Mul:
1607 case Instruction::SDiv:
1608 case Instruction::SRem:
1609 case Instruction::Shl:
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001610 case Instruction::And:
1611 case Instruction::Or:
Chris Lattner52492ac2010-01-23 06:17:14 +00001612 case Instruction::Xor: {
Chad Rosierc53ade22012-09-07 18:16:38 +00001613 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1614 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001615 switch (CE->getOpcode()) {
Chris Lattner52492ac2010-01-23 06:17:14 +00001616 default: llvm_unreachable("Unknown binary operator constant cast expr");
1617 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1618 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
Dan Gohman5938a3e2010-02-09 00:02:37 +00001619 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1620 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1621 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1622 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
Chris Lattner52492ac2010-01-23 06:17:14 +00001623 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1624 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1625 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001626 }
Chris Lattner52492ac2010-01-23 06:17:14 +00001627 }
Chris Lattnera80ba712004-08-16 23:15:22 +00001628 }
1629}
Chris Lattner1b7e2352004-08-17 06:36:49 +00001630
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001631static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
Chris Lattner44e05082010-04-20 06:20:21 +00001632
David Greened92e2e42011-08-31 17:30:56 +00001633/// isRepeatedByteSequence - Determine whether the given value is
1634/// composed of a repeated sequence of identical bytes and return the
1635/// byte value. If it is not a repeated sequence, return -1.
Chris Lattner9e631da2012-01-24 09:31:43 +00001636static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1637 StringRef Data = V->getRawDataValues();
1638 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1639 char C = Data[0];
1640 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1641 if (Data[i] != C) return -1;
Chandler Carruthbeb05952012-01-30 23:47:44 +00001642 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
Chris Lattner9e631da2012-01-24 09:31:43 +00001643}
1644
1645
1646/// isRepeatedByteSequence - Determine whether the given value is
1647/// composed of a repeated sequence of identical bytes and return the
1648/// byte value. If it is not a repeated sequence, return -1.
David Greened92e2e42011-08-31 17:30:56 +00001649static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1650
1651 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1652 if (CI->getBitWidth() > 64) return -1;
1653
Micah Villmow3574eca2012-10-08 16:38:25 +00001654 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
David Greened92e2e42011-08-31 17:30:56 +00001655 uint64_t Value = CI->getZExtValue();
1656
1657 // Make sure the constant is at least 8 bits long and has a power
1658 // of 2 bit width. This guarantees the constant bit width is
1659 // always a multiple of 8 bits, avoiding issues with padding out
1660 // to Size and other such corner cases.
1661 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1662
1663 uint8_t Byte = static_cast<uint8_t>(Value);
1664
1665 for (unsigned i = 1; i < Size; ++i) {
1666 Value >>= 8;
1667 if (static_cast<uint8_t>(Value) != Byte) return -1;
1668 }
1669 return Byte;
1670 }
1671 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1672 // Make sure all array elements are sequences of the same repeated
1673 // byte.
Chris Lattner9e631da2012-01-24 09:31:43 +00001674 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
David Greened92e2e42011-08-31 17:30:56 +00001675 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1676 if (Byte == -1) return -1;
1677
1678 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1679 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1680 if (ThisByte == -1) return -1;
1681 if (Byte != ThisByte) return -1;
1682 }
1683 return Byte;
1684 }
Eric Christopherdcc675a2012-11-20 20:34:44 +00001685
Chris Lattner9e631da2012-01-24 09:31:43 +00001686 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1687 return isRepeatedByteSequence(CDS);
David Greened92e2e42011-08-31 17:30:56 +00001688
1689 return -1;
1690}
1691
Chad Rosierc53ade22012-09-07 18:16:38 +00001692static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001693 AsmPrinter &AP){
Eric Christopherdcc675a2012-11-20 20:34:44 +00001694
Chris Lattner9e631da2012-01-24 09:31:43 +00001695 // See if we can aggregate this into a .fill, if so, emit it as such.
1696 int Value = isRepeatedByteSequence(CDS, AP.TM);
1697 if (Value != -1) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001698 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
Chris Lattnerc63352f2012-01-31 03:39:24 +00001699 // Don't emit a 1-byte object as a .fill.
1700 if (Bytes > 1)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001701 return AP.OutStreamer.EmitFill(Bytes, Value);
Chris Lattner9e631da2012-01-24 09:31:43 +00001702 }
Eric Christopherdcc675a2012-11-20 20:34:44 +00001703
Chris Lattner9e631da2012-01-24 09:31:43 +00001704 // If this can be emitted with .ascii/.asciz, emit it as such.
1705 if (CDS->isString())
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001706 return AP.OutStreamer.EmitBytes(CDS->getAsString());
Chris Lattner9e631da2012-01-24 09:31:43 +00001707
1708 // Otherwise, emit the values in successive locations.
1709 unsigned ElementByteSize = CDS->getElementByteSize();
1710 if (isa<IntegerType>(CDS->getElementType())) {
Chris Lattner0f193b82012-01-25 01:27:20 +00001711 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerb66fb5a2012-01-30 05:55:11 +00001712 if (AP.isVerbose())
1713 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1714 CDS->getElementAsInteger(i));
Chris Lattner9e631da2012-01-24 09:31:43 +00001715 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001716 ElementByteSize);
Chris Lattner9e631da2012-01-24 09:31:43 +00001717 }
Chris Lattner6e64c382012-01-30 05:49:43 +00001718 } else if (ElementByteSize == 4) {
1719 // FP Constants are printed as integer constants to avoid losing
1720 // precision.
1721 assert(CDS->getElementType()->isFloatTy());
Chris Lattner0f193b82012-01-25 01:27:20 +00001722 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner9e631da2012-01-24 09:31:43 +00001723 union {
1724 float F;
1725 uint32_t I;
1726 };
Eric Christopherdcc675a2012-11-20 20:34:44 +00001727
Chris Lattner9e631da2012-01-24 09:31:43 +00001728 F = CDS->getElementAsFloat(i);
1729 if (AP.isVerbose())
1730 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001731 AP.OutStreamer.EmitIntValue(I, 4);
Chris Lattner9e631da2012-01-24 09:31:43 +00001732 }
Chris Lattner6e64c382012-01-30 05:49:43 +00001733 } else {
1734 assert(CDS->getElementType()->isDoubleTy());
1735 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1736 union {
1737 double F;
1738 uint64_t I;
1739 };
Eric Christopherdcc675a2012-11-20 20:34:44 +00001740
Chris Lattner6e64c382012-01-30 05:49:43 +00001741 F = CDS->getElementAsDouble(i);
1742 if (AP.isVerbose())
1743 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001744 AP.OutStreamer.EmitIntValue(I, 8);
Chris Lattner6e64c382012-01-30 05:49:43 +00001745 }
Chris Lattner9e631da2012-01-24 09:31:43 +00001746 }
1747
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001748 const DataLayout &DL = *AP.TM.getDataLayout();
1749 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1750 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
Chris Lattner6e64c382012-01-30 05:49:43 +00001751 CDS->getNumElements();
1752 if (unsigned Padding = Size - EmittedSize)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001753 AP.OutStreamer.EmitZeros(Padding);
Chris Lattner6e64c382012-01-30 05:49:43 +00001754
Chris Lattner9e631da2012-01-24 09:31:43 +00001755}
1756
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001757static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
Chris Lattner18c7f802012-02-05 02:29:43 +00001758 // See if we can aggregate some values. Make sure it can be
1759 // represented as a series of bytes of the constant value.
1760 int Value = isRepeatedByteSequence(CA, AP.TM);
David Greened92e2e42011-08-31 17:30:56 +00001761
Chris Lattner18c7f802012-02-05 02:29:43 +00001762 if (Value != -1) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001763 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001764 AP.OutStreamer.EmitFill(Bytes, Value);
Dan Gohman00d448a2008-12-22 21:14:27 +00001765 }
Chris Lattner18c7f802012-02-05 02:29:43 +00001766 else {
1767 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001768 emitGlobalConstantImpl(CA->getOperand(i), AP);
Chris Lattner18c7f802012-02-05 02:29:43 +00001769 }
Dan Gohman00d448a2008-12-22 21:14:27 +00001770}
1771
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001772static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
Chris Lattnerbcb83e52010-01-20 07:41:15 +00001773 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001774 emitGlobalConstantImpl(CV->getOperand(i), AP);
Nick Lewycky5b7ac142011-06-22 18:55:03 +00001775
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001776 const DataLayout &DL = *AP.TM.getDataLayout();
1777 unsigned Size = DL.getTypeAllocSize(CV->getType());
1778 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
Nick Lewycky5b7ac142011-06-22 18:55:03 +00001779 CV->getType()->getNumElements();
1780 if (unsigned Padding = Size - EmittedSize)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001781 AP.OutStreamer.EmitZeros(Padding);
Dan Gohman00d448a2008-12-22 21:14:27 +00001782}
1783
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001784static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
Dan Gohman00d448a2008-12-22 21:14:27 +00001785 // Print the fields in successive locations. Pad to align if needed!
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001786 const DataLayout *DL = AP.TM.getDataLayout();
1787 unsigned Size = DL->getTypeAllocSize(CS->getType());
1788 const StructLayout *Layout = DL->getStructLayout(CS->getType());
Chris Lattner91093ec2010-01-19 19:10:44 +00001789 uint64_t SizeSoFar = 0;
1790 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattnerbcb83e52010-01-20 07:41:15 +00001791 const Constant *Field = CS->getOperand(i);
Dan Gohman00d448a2008-12-22 21:14:27 +00001792
1793 // Check if padding is needed and insert one or more 0s.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001794 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
Chris Lattner2dd245c2010-01-20 07:11:32 +00001795 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1796 - Layout->getElementOffset(i)) - FieldSize;
1797 SizeSoFar += FieldSize + PadSize;
Dan Gohman00d448a2008-12-22 21:14:27 +00001798
1799 // Now print the actual field value.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001800 emitGlobalConstantImpl(Field, AP);
Dan Gohman00d448a2008-12-22 21:14:27 +00001801
1802 // Insert padding - this may include padding to increase the size of the
1803 // current field up to the ABI size (if the struct is not packed) as well
1804 // as padding to ensure that the next field starts at the right offset.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001805 AP.OutStreamer.EmitZeros(PadSize);
Dan Gohman00d448a2008-12-22 21:14:27 +00001806 }
Chris Lattner2dd245c2010-01-20 07:11:32 +00001807 assert(SizeSoFar == Layout->getSizeInBytes() &&
Dan Gohman00d448a2008-12-22 21:14:27 +00001808 "Layout of constant struct may be incorrect!");
1809}
1810
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001811static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
Chris Lattner09ce6742010-01-19 22:16:33 +00001812 APInt API = CFP->getValueAPF().bitcastToAPInt();
Tim Northover5f2801b2013-01-11 10:36:13 +00001813
1814 // First print a comment with what we think the original floating-point value
1815 // should have been.
1816 if (AP.isVerbose()) {
1817 SmallString<8> StrVal;
1818 CFP->getValueAPF().toString(StrVal);
1819
1820 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1821 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
Chris Lattner09ce6742010-01-19 22:16:33 +00001822 }
Tim Northover5f2801b2013-01-11 10:36:13 +00001823
1824 // Now iterate through the APInt chunks, emitting them in endian-correct
1825 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1826 // floats).
1827 unsigned NumBytes = API.getBitWidth() / 8;
1828 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1829 const uint64_t *p = API.getRawData();
1830
1831 // PPC's long double has odd notions of endianness compared to how LLVM
1832 // handles it: p[0] goes first for *big* endian on PPC.
1833 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1834 int Chunk = API.getNumWords() - 1;
1835
1836 if (TrailingBytes)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001837 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
Tim Northover5f2801b2013-01-11 10:36:13 +00001838
1839 for (; Chunk >= 0; --Chunk)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001840 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
Tim Northover5f2801b2013-01-11 10:36:13 +00001841 } else {
1842 unsigned Chunk;
1843 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001844 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
Tim Northover5f2801b2013-01-11 10:36:13 +00001845
1846 if (TrailingBytes)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001847 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
Tim Northover5f2801b2013-01-11 10:36:13 +00001848 }
1849
1850 // Emit the tail padding for the long double.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001851 const DataLayout &DL = *AP.TM.getDataLayout();
1852 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1853 DL.getTypeStoreSize(CFP->getType()));
Dan Gohman00d448a2008-12-22 21:14:27 +00001854}
1855
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001856static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001857 const DataLayout *DL = AP.TM.getDataLayout();
Dan Gohman00d448a2008-12-22 21:14:27 +00001858 unsigned BitWidth = CI->getBitWidth();
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001859
1860 // Copy the value as we may massage the layout for constants whose bit width
1861 // is not a multiple of 64-bits.
1862 APInt Realigned(CI->getValue());
1863 uint64_t ExtraBits = 0;
1864 unsigned ExtraBitsSize = BitWidth & 63;
1865
1866 if (ExtraBitsSize) {
1867 // The bit width of the data is not a multiple of 64-bits.
1868 // The extra bits are expected to be at the end of the chunk of the memory.
1869 // Little endian:
1870 // * Nothing to be done, just record the extra bits to emit.
1871 // Big endian:
1872 // * Record the extra bits to emit.
1873 // * Realign the raw data to emit the chunks of 64-bits.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001874 if (DL->isBigEndian()) {
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001875 // Basically the structure of the raw data is a chunk of 64-bits cells:
1876 // 0 1 BitWidth / 64
1877 // [chunk1][chunk2] ... [chunkN].
1878 // The most significant chunk is chunkN and it should be emitted first.
1879 // However, due to the alignment issue chunkN contains useless bits.
1880 // Realign the chunks so that they contain only useless information:
1881 // ExtraBits 0 1 (BitWidth / 64) - 1
1882 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1883 ExtraBits = Realigned.getRawData()[0] &
1884 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1885 Realigned = Realigned.lshr(ExtraBitsSize);
1886 } else
1887 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1888 }
Dan Gohman00d448a2008-12-22 21:14:27 +00001889
1890 // We don't expect assemblers to support integer data directives
1891 // for more than 64 bits, so we emit the data in at most 64-bit
1892 // quantities at a time.
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001893 const uint64_t *RawData = Realigned.getRawData();
Dan Gohman00d448a2008-12-22 21:14:27 +00001894 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001895 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001896 AP.OutStreamer.EmitIntValue(Val, 8);
Dan Gohman00d448a2008-12-22 21:14:27 +00001897 }
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001898
1899 if (ExtraBitsSize) {
1900 // Emit the extra bits after the 64-bits chunks.
1901
1902 // Emit a directive that fills the expected size.
1903 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1904 Size -= (BitWidth / 64) * 8;
1905 assert(Size && Size * 8 >= ExtraBitsSize &&
1906 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1907 == ExtraBits && "Directive too small for extra bits.");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001908 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001909 }
Dan Gohman00d448a2008-12-22 21:14:27 +00001910}
1911
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001912static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001913 const DataLayout *DL = AP.TM.getDataLayout();
1914 uint64_t Size = DL->getTypeAllocSize(CV->getType());
Bill Wendling21e42d02012-03-20 08:56:43 +00001915 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001916 return AP.OutStreamer.EmitZeros(Size);
Chris Lattner2dd245c2010-01-20 07:11:32 +00001917
1918 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Chris Lattner2dd245c2010-01-20 07:11:32 +00001919 switch (Size) {
1920 case 1:
1921 case 2:
1922 case 4:
1923 case 8:
Chris Lattner44e05082010-04-20 06:20:21 +00001924 if (AP.isVerbose())
Benjamin Kramer41a96492011-11-05 08:57:40 +00001925 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1926 CI->getZExtValue());
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001927 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
Chris Lattner2dd245c2010-01-20 07:11:32 +00001928 return;
1929 default:
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001930 emitGlobalConstantLargeInt(CI, AP);
Chris Lattner2dd245c2010-01-20 07:11:32 +00001931 return;
1932 }
1933 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001934
Chris Lattner91093ec2010-01-19 19:10:44 +00001935 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001936 return emitGlobalConstantFP(CFP, AP);
Chris Lattner1b7e2352004-08-17 06:36:49 +00001937
Chris Lattnerb0bedd62010-01-20 17:57:50 +00001938 if (isa<ConstantPointerNull>(CV)) {
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001939 AP.OutStreamer.EmitIntValue(0, Size);
Chris Lattnerb0bedd62010-01-20 17:57:50 +00001940 return;
1941 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001942
Chris Lattner9e631da2012-01-24 09:31:43 +00001943 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001944 return emitGlobalConstantDataSequential(CDS, AP);
Eric Christopherdcc675a2012-11-20 20:34:44 +00001945
Chris Lattner9e631da2012-01-24 09:31:43 +00001946 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001947 return emitGlobalConstantArray(CVA, AP);
Jim Grosbach83d80832011-03-29 23:20:22 +00001948
Chris Lattner9e631da2012-01-24 09:31:43 +00001949 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001950 return emitGlobalConstantStruct(CVS, AP);
Chris Lattner9e631da2012-01-24 09:31:43 +00001951
Bill Wendling21e42d02012-03-20 08:56:43 +00001952 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1953 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1954 // vectors).
Chris Lattner9e631da2012-01-24 09:31:43 +00001955 if (CE->getOpcode() == Instruction::BitCast)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001956 return emitGlobalConstantImpl(CE->getOperand(0), AP);
Bill Wendling21e42d02012-03-20 08:56:43 +00001957
1958 if (Size > 8) {
1959 // If the constant expression's size is greater than 64-bits, then we have
1960 // to emit the value in chunks. Try to constant fold the value and emit it
1961 // that way.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001962 Constant *New = ConstantFoldConstantExpression(CE, DL);
Bill Wendling21e42d02012-03-20 08:56:43 +00001963 if (New && New != CE)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001964 return emitGlobalConstantImpl(New, AP);
Bill Wendling21e42d02012-03-20 08:56:43 +00001965 }
1966 }
Eric Christopherdcc675a2012-11-20 20:34:44 +00001967
Chris Lattner9e631da2012-01-24 09:31:43 +00001968 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001969 return emitGlobalConstantVector(V, AP);
Eric Christopherdcc675a2012-11-20 20:34:44 +00001970
Chris Lattner52492ac2010-01-23 06:17:14 +00001971 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1972 // thread the streamer with EmitValue.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001973 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
Chris Lattner44e05082010-04-20 06:20:21 +00001974}
1975
1976/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001977void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001978 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
Chris Lattner44e05082010-04-20 06:20:21 +00001979 if (Size)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001980 emitGlobalConstantImpl(CV, *this);
Chris Lattner44e05082010-04-20 06:20:21 +00001981 else if (MAI->hasSubsectionsViaSymbols()) {
1982 // If the global has zero size, emit a single byte so that two labels don't
1983 // look like they are at the same location.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001984 OutStreamer.EmitIntValue(0, 1);
Chris Lattner44e05082010-04-20 06:20:21 +00001985 }
Chris Lattner1b7e2352004-08-17 06:36:49 +00001986}
Chris Lattner0264d1a2006-01-27 02:10:10 +00001987
Chris Lattnerfad86b02008-08-17 07:19:36 +00001988void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
Evan Chengd6594ae2006-09-12 21:00:35 +00001989 // Target doesn't support this yet!
Torok Edwinc23197a2009-07-14 16:55:14 +00001990 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
Evan Chengd6594ae2006-09-12 21:00:35 +00001991}
1992
Chris Lattnerdfa107e2010-04-04 18:16:38 +00001993void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1994 if (Offset > 0)
1995 OS << '+' << Offset;
1996 else if (Offset < 0)
1997 OS << Offset;
1998}
1999
Chris Lattnerc0215722010-04-04 19:25:43 +00002000//===----------------------------------------------------------------------===//
2001// Symbol Lowering Routines.
2002//===----------------------------------------------------------------------===//
2003
2004/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2005/// temporary label with the specified stem and unique ID.
Stephen Hines36b56882014-04-23 16:57:46 -07002006MCSymbol *AsmPrinter::GetTempSymbol(Twine Name, unsigned ID) const {
2007 const DataLayout *DL = TM.getDataLayout();
2008 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
Chris Lattnerc0215722010-04-04 19:25:43 +00002009 Name + Twine(ID));
2010}
2011
2012/// GetTempSymbol - Return an assembler temporary label with the specified
2013/// stem.
Stephen Hines36b56882014-04-23 16:57:46 -07002014MCSymbol *AsmPrinter::GetTempSymbol(Twine Name) const {
2015 const DataLayout *DL = TM.getDataLayout();
2016 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
Chris Lattnerc0215722010-04-04 19:25:43 +00002017 Name);
2018}
2019
Chris Lattner66099132006-02-01 22:41:11 +00002020
Chris Lattner95175542010-02-08 23:10:08 +00002021MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Chris Lattner3b9d6212010-03-14 17:53:23 +00002022 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Dan Gohman8c2b5252009-10-30 01:27:03 +00002023}
2024
Chris Lattner3b9d6212010-03-14 17:53:23 +00002025MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2026 return MMI->getAddrLabelSymbol(BB);
Dan Gohman8c2b5252009-10-30 01:27:03 +00002027}
2028
Chris Lattner39248682010-01-23 05:19:23 +00002029/// GetCPISymbol - Return the symbol for the specified constant pool entry.
2030MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Stephen Hines36b56882014-04-23 16:57:46 -07002031 const DataLayout *DL = TM.getDataLayout();
Chris Lattner9b97a732010-03-30 18:10:53 +00002032 return OutContext.GetOrCreateSymbol
Stephen Hines36b56882014-04-23 16:57:46 -07002033 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
Chris Lattner98cdab52010-03-10 02:25:11 +00002034 + "_" + Twine(CPID));
Chris Lattner39248682010-01-23 05:19:23 +00002035}
2036
2037/// GetJTISymbol - Return the symbol for the specified jump table entry.
Bill Wendling07d31772010-06-29 22:34:52 +00002038MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2039 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
Chris Lattner7cb384d2009-09-12 23:02:08 +00002040}
2041
Chris Lattner798d1252010-01-25 21:17:10 +00002042/// GetJTSetSymbol - Return the symbol for the specified jump table .set
2043/// FIXME: privatize to AsmPrinter.
2044MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Stephen Hines36b56882014-04-23 16:57:46 -07002045 const DataLayout *DL = TM.getDataLayout();
Chris Lattner9b97a732010-03-30 18:10:53 +00002046 return OutContext.GetOrCreateSymbol
Stephen Hines36b56882014-04-23 16:57:46 -07002047 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
Chris Lattner98cdab52010-03-10 02:25:11 +00002048 Twine(UID) + "_set_" + Twine(MBBID));
Chris Lattner798d1252010-01-25 21:17:10 +00002049}
2050
Stephen Hines36b56882014-04-23 16:57:46 -07002051MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2052 StringRef Suffix) const {
2053 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2054 TM);
Chris Lattnerd588b972010-01-15 23:25:11 +00002055}
2056
Chris Lattner6b04ede2010-01-15 23:18:17 +00002057/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2058/// ExternalSymbol.
2059MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2060 SmallString<60> NameStr;
2061 Mang->getNameWithPrefix(NameStr, Sym);
2062 return OutContext.GetOrCreateSymbol(NameStr.str());
Jim Grosbach83d80832011-03-29 23:20:22 +00002063}
Chris Lattner6b04ede2010-01-15 23:18:17 +00002064
Chris Lattner7cb384d2009-09-12 23:02:08 +00002065
Chris Lattner523a5082010-01-22 21:50:41 +00002066
2067/// PrintParentLoopComment - Print comments about parent loops of this one.
2068static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2069 unsigned FunctionNumber) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07002070 if (!Loop) return;
Chris Lattner523a5082010-01-22 21:50:41 +00002071 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2072 OS.indent(Loop->getLoopDepth()*2)
2073 << "Parent Loop BB" << FunctionNumber << "_"
2074 << Loop->getHeader()->getNumber()
2075 << " Depth=" << Loop->getLoopDepth() << '\n';
2076}
2077
2078
2079/// PrintChildLoopComment - Print comments about child loops within
2080/// the loop for this basic block, with nesting.
2081static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2082 unsigned FunctionNumber) {
2083 // Add child loop information
Stephen Hinesdce4a402014-05-29 02:49:00 -07002084 for (const MachineLoop *CL : *Loop) {
2085 OS.indent(CL->getLoopDepth()*2)
Chris Lattner523a5082010-01-22 21:50:41 +00002086 << "Child Loop BB" << FunctionNumber << "_"
Stephen Hinesdce4a402014-05-29 02:49:00 -07002087 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
Chris Lattner523a5082010-01-22 21:50:41 +00002088 << '\n';
Stephen Hinesdce4a402014-05-29 02:49:00 -07002089 PrintChildLoopComment(OS, CL, FunctionNumber);
Chris Lattner523a5082010-01-22 21:50:41 +00002090 }
2091}
2092
Chad Rosierc53ade22012-09-07 18:16:38 +00002093/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2094static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
Chris Lattnerdfa107e2010-04-04 18:16:38 +00002095 const MachineLoopInfo *LI,
2096 const AsmPrinter &AP) {
Chris Lattner523a5082010-01-22 21:50:41 +00002097 // Add loop depth information
2098 const MachineLoop *Loop = LI->getLoopFor(&MBB);
Stephen Hinesdce4a402014-05-29 02:49:00 -07002099 if (!Loop) return;
Jim Grosbach83d80832011-03-29 23:20:22 +00002100
Chris Lattner523a5082010-01-22 21:50:41 +00002101 MachineBasicBlock *Header = Loop->getHeader();
2102 assert(Header && "No header for loop");
Jim Grosbach83d80832011-03-29 23:20:22 +00002103
Chris Lattner523a5082010-01-22 21:50:41 +00002104 // If this block is not a loop header, just print out what is the loop header
2105 // and return.
2106 if (Header != &MBB) {
2107 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2108 Twine(AP.getFunctionNumber())+"_" +
2109 Twine(Loop->getHeader()->getNumber())+
2110 " Depth="+Twine(Loop->getLoopDepth()));
2111 return;
2112 }
Jim Grosbach83d80832011-03-29 23:20:22 +00002113
Chris Lattner523a5082010-01-22 21:50:41 +00002114 // Otherwise, it is a loop header. Print out information about child and
2115 // parent loops.
2116 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
Jim Grosbach83d80832011-03-29 23:20:22 +00002117
2118 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2119
Chris Lattner523a5082010-01-22 21:50:41 +00002120 OS << "=>";
2121 OS.indent(Loop->getLoopDepth()*2-2);
Jim Grosbach83d80832011-03-29 23:20:22 +00002122
Chris Lattner523a5082010-01-22 21:50:41 +00002123 OS << "This ";
2124 if (Loop->empty())
2125 OS << "Inner ";
2126 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
Jim Grosbach83d80832011-03-29 23:20:22 +00002127
Chris Lattner523a5082010-01-22 21:50:41 +00002128 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2129}
2130
2131
Chris Lattner70a54c02009-09-13 18:25:37 +00002132/// EmitBasicBlockStart - This method prints the label for the specified
2133/// MachineBasicBlock, an alignment (if present) and a comment describing
2134/// it if appropriate.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002135void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
Dan Gohmanb1cac332009-10-30 01:34:35 +00002136 // Emit an alignment directive for this block, if needed.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002137 if (unsigned Align = MBB.getAlignment())
Jakob Stoklund Olesen8c741b82011-12-06 01:26:19 +00002138 EmitAlignment(Align);
Evan Chengfb8075d2008-02-28 00:43:03 +00002139
Chris Lattner999aee22010-03-16 00:29:39 +00002140 // If the block has its address taken, emit any labels that were used to
2141 // reference the block. It is possible that there is more than one label
2142 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2143 // the references were generated.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002144 if (MBB.hasAddressTaken()) {
2145 const BasicBlock *BB = MBB.getBasicBlock();
Chris Lattner3f53c832010-04-04 18:52:31 +00002146 if (isVerbose())
Chris Lattner999aee22010-03-16 00:29:39 +00002147 OutStreamer.AddComment("Block address taken");
Jim Grosbach83d80832011-03-29 23:20:22 +00002148
Stephen Hinesdce4a402014-05-29 02:49:00 -07002149 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2150 for (auto *Sym : Symbols)
2151 OutStreamer.EmitLabel(Sym);
Dan Gohman8c2b5252009-10-30 01:27:03 +00002152 }
2153
Jakob Stoklund Olesenc511c282012-03-06 22:27:13 +00002154 // Print some verbose block comments.
2155 if (isVerbose()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07002156 if (const BasicBlock *BB = MBB.getBasicBlock())
Jakob Stoklund Olesenc511c282012-03-06 22:27:13 +00002157 if (BB->hasName())
2158 OutStreamer.AddComment("%" + BB->getName());
Stephen Hinesdce4a402014-05-29 02:49:00 -07002159 emitBasicBlockLoopComments(MBB, LI, *this);
Jakob Stoklund Olesenc511c282012-03-06 22:27:13 +00002160 }
2161
Dan Gohmanb1cac332009-10-30 01:34:35 +00002162 // Print the main label for the block.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002163 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
Stephen Hines36b56882014-04-23 16:57:46 -07002164 if (isVerbose()) {
Chris Lattner58bc4dd2010-04-03 22:12:35 +00002165 // NOTE: Want this comment at start of line, don't emit with AddComment.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002166 OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
Chris Lattner0fd90fd2010-01-22 19:52:01 +00002167 }
Dan Gohmane3cc3f32009-10-06 17:38:38 +00002168 } else {
Stephen Hinesdce4a402014-05-29 02:49:00 -07002169 OutStreamer.EmitLabel(MBB.getSymbol());
Dan Gohmane3cc3f32009-10-06 17:38:38 +00002170 }
Nate Begeman37efe672006-04-22 18:53:45 +00002171}
Nate Begeman52a51e382006-08-12 21:29:52 +00002172
Stuart Hastings5129bde2011-02-23 02:27:05 +00002173void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2174 bool IsDefinition) const {
Chris Lattner152a29b2010-01-23 06:53:23 +00002175 MCSymbolAttr Attr = MCSA_Invalid;
Jim Grosbach83d80832011-03-29 23:20:22 +00002176
Chris Lattner152a29b2010-01-23 06:53:23 +00002177 switch (Visibility) {
2178 default: break;
2179 case GlobalValue::HiddenVisibility:
Stuart Hastings5129bde2011-02-23 02:27:05 +00002180 if (IsDefinition)
2181 Attr = MAI->getHiddenVisibilityAttr();
2182 else
2183 Attr = MAI->getHiddenDeclarationVisibilityAttr();
Chris Lattner152a29b2010-01-23 06:53:23 +00002184 break;
2185 case GlobalValue::ProtectedVisibility:
2186 Attr = MAI->getProtectedVisibilityAttr();
2187 break;
Chris Lattner53d4d782010-01-15 23:38:51 +00002188 }
Chris Lattner152a29b2010-01-23 06:53:23 +00002189
2190 if (Attr != MCSA_Invalid)
2191 OutStreamer.EmitSymbolAttribute(Sym, Attr);
Chris Lattner53d4d782010-01-15 23:38:51 +00002192}
2193
Chris Lattner0a3f3992010-02-17 18:52:56 +00002194/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2195/// exactly one predecessor and the control transfer mechanism between
2196/// the predecessor and this block is a fall-through.
Chris Lattnere00b59f2010-04-04 17:57:56 +00002197bool AsmPrinter::
2198isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Chris Lattner0a3f3992010-02-17 18:52:56 +00002199 // If this is a landing pad, it isn't a fall through. If it has no preds,
2200 // then nothing falls through to it.
2201 if (MBB->isLandingPad() || MBB->pred_empty())
2202 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002203
Chris Lattner0a3f3992010-02-17 18:52:56 +00002204 // If there isn't exactly one predecessor, it can't be a fall through.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002205 if (MBB->pred_size() > 1)
Chris Lattner0a3f3992010-02-17 18:52:56 +00002206 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002207
Chris Lattner0a3f3992010-02-17 18:52:56 +00002208 // The predecessor has to be immediately before this block.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002209 MachineBasicBlock *Pred = *MBB->pred_begin();
Chris Lattner0a3f3992010-02-17 18:52:56 +00002210 if (!Pred->isLayoutSuccessor(MBB))
2211 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002212
Chris Lattner0a3f3992010-02-17 18:52:56 +00002213 // If the block is completely empty, then it definitely does fall through.
2214 if (Pred->empty())
2215 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00002216
Eli Friedman0fc30152011-06-14 19:30:33 +00002217 // Check the terminators in the previous blocks
Stephen Hinesdce4a402014-05-29 02:49:00 -07002218 for (const auto &MI : Pred->terminators()) {
Eli Friedman0fc30152011-06-14 19:30:33 +00002219 // If it is not a simple branch, we are in a table somewhere.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00002220 if (!MI.isBranch() || MI.isIndirectBranch())
Eli Friedman0fc30152011-06-14 19:30:33 +00002221 return false;
2222
Stephen Hines36b56882014-04-23 16:57:46 -07002223 // If we are the operands of one of the branches, this is not a fall
2224 // through. Note that targets with delay slots will usually bundle
2225 // terminators with the delay slot instruction.
2226 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2227 if (OP->isJTI())
Rafael Espindolaaeb6da42011-06-15 21:00:28 +00002228 return false;
Stephen Hines36b56882014-04-23 16:57:46 -07002229 if (OP->isMBB() && OP->getMBB() == MBB)
Eli Friedman0fc30152011-06-14 19:30:33 +00002230 return false;
2231 }
2232 }
2233
2234 return true;
Chris Lattner0a3f3992010-02-17 18:52:56 +00002235}
2236
2237
2238
Stephen Hinesdce4a402014-05-29 02:49:00 -07002239GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2240 if (!S.usesMetadata())
2241 return nullptr;
Chris Lattnere00b59f2010-04-04 17:57:56 +00002242
2243 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
Stephen Hinesdce4a402014-05-29 02:49:00 -07002244 gcp_map_type::iterator GCPI = GCMap.find(&S);
Chris Lattnere00b59f2010-04-04 17:57:56 +00002245 if (GCPI != GCMap.end())
Stephen Hinesdce4a402014-05-29 02:49:00 -07002246 return GCPI->second.get();
Jim Grosbach83d80832011-03-29 23:20:22 +00002247
Stephen Hinesdce4a402014-05-29 02:49:00 -07002248 const char *Name = S.getName().c_str();
Jim Grosbach83d80832011-03-29 23:20:22 +00002249
Gordon Henriksenc317a602008-08-17 12:08:44 +00002250 for (GCMetadataPrinterRegistry::iterator
2251 I = GCMetadataPrinterRegistry::begin(),
2252 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2253 if (strcmp(Name, I->getName()) == 0) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07002254 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2255 GMP->S = &S;
2256 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2257 return IterBool.first->second.get();
Gordon Henriksenc317a602008-08-17 12:08:44 +00002258 }
Jim Grosbach83d80832011-03-29 23:20:22 +00002259
Chris Lattner75361b62010-04-07 22:58:41 +00002260 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
Gordon Henriksenc317a602008-08-17 12:08:44 +00002261}
Stephen Hines36b56882014-04-23 16:57:46 -07002262
2263/// Pin vtable to this file.
2264AsmPrinterHandler::~AsmPrinterHandler() {}