blob: a91ab22ce1b03f476ccbd77f318191ab3257f302 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/AsmPrinter.h"
15#include "llvm/Assembly/Writer.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Constants.h"
18#include "llvm/Module.h"
Chris Lattner31a54742010-01-16 21:57:06 +000019#include "llvm/CodeGen/DwarfWriter.h"
Gordon Henriksen1aed5992008-08-17 18:44:35 +000020#include "llvm/CodeGen/GCMetadataPrinter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineConstantPool.h"
David Greeneca9b04b2009-11-13 21:34:57 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
David Greene066ed6a2009-08-18 19:22:55 +000023#include "llvm/CodeGen/MachineFunction.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
David Greenee52fd872009-08-10 16:38:07 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +000027#include "llvm/Analysis/DebugInfo.h"
Chris Lattner1eb0ad02009-07-27 21:28:04 +000028#include "llvm/MC/MCContext.h"
Chris Lattner54bfda72010-01-23 06:17:14 +000029#include "llvm/MC/MCExpr.h"
David Greene4a37a692009-07-16 22:24:20 +000030#include "llvm/MC/MCInst.h"
Chris Lattnere6ad12f2009-07-31 18:48:30 +000031#include "llvm/MC/MCSection.h"
32#include "llvm/MC/MCStreamer.h"
Chris Lattner08c97082009-09-12 23:02:08 +000033#include "llvm/MC/MCSymbol.h"
Evan Cheng42ceb472009-03-25 01:47:28 +000034#include "llvm/Support/CommandLine.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000035#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc006e1c2010-01-22 19:52:01 +000036#include "llvm/Support/Format.h"
David Greene63486122009-07-13 20:25:48 +000037#include "llvm/Support/FormattedStream.h"
Chris Lattner621c44d2009-08-22 20:48:53 +000038#include "llvm/MC/MCAsmInfo.h"
Chris Lattner31a54742010-01-16 21:57:06 +000039#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Target/TargetData.h"
David Greeneca9b04b2009-11-13 21:34:57 +000041#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/Target/TargetLowering.h"
Chris Lattnerc4c40a92009-07-28 03:13:23 +000043#include "llvm/Target/TargetLoweringObjectFile.h"
Evan Cheng0eeed442008-07-01 23:18:29 +000044#include "llvm/Target/TargetOptions.h"
Evan Cheng3c0eda52008-03-15 00:03:38 +000045#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng6fb06762007-11-09 01:32:10 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner89b36582008-08-17 07:19:36 +000047#include "llvm/ADT/SmallString.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include <cerrno>
49using namespace llvm;
50
Evan Cheng42ceb472009-03-25 01:47:28 +000051static cl::opt<cl::boolOrDefault>
52AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
53 cl::init(cl::BOU_UNSET));
54
Chris Lattner1ab24612010-01-22 07:06:15 +000055static bool getVerboseAsm(bool VDef) {
56 switch (AsmVerbose) {
57 default:
58 case cl::BOU_UNSET: return VDef;
59 case cl::BOU_TRUE: return true;
60 case cl::BOU_FALSE: return false;
61 }
62}
63
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064char AsmPrinter::ID = 0;
David Greene302008d2009-07-14 20:18:05 +000065AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
Chris Lattner621c44d2009-08-22 20:48:53 +000066 const MCAsmInfo *T, bool VDef)
Chris Lattner01462ba2010-01-26 04:35:26 +000067 : MachineFunctionPass(&ID), O(o),
Chris Lattnera5ef4d32009-08-22 21:43:10 +000068 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
Chris Lattner1eb0ad02009-07-27 21:28:04 +000069
70 OutContext(*new MCContext()),
Chris Lattnera835afd2009-09-14 03:02:37 +000071 // FIXME: Pass instprinter to streamer.
Chris Lattner92c78e82010-01-20 06:39:07 +000072 OutStreamer(*createAsmStreamer(OutContext, O, *T,
Chris Lattner1ab24612010-01-22 07:06:15 +000073 TM.getTargetData()->isLittleEndian(),
74 getVerboseAsm(VDef), 0)),
Chris Lattner1eb0ad02009-07-27 21:28:04 +000075
Devang Patel042945f2010-01-16 06:09:35 +000076 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
Chris Lattner2424eac2009-06-24 19:09:55 +000077 DW = 0; MMI = 0;
Chris Lattner1ab24612010-01-22 07:06:15 +000078 VerboseAsm = getVerboseAsm(VDef);
Evan Cheng42ceb472009-03-25 01:47:28 +000079}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000081AsmPrinter::~AsmPrinter() {
82 for (gcp_iterator I = GCMetadataPrinters.begin(),
83 E = GCMetadataPrinters.end(); I != E; ++I)
84 delete I->second;
Chris Lattner1eb0ad02009-07-27 21:28:04 +000085
86 delete &OutStreamer;
87 delete &OutContext;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000088}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089
Chris Lattner01462ba2010-01-26 04:35:26 +000090/// getFunctionNumber - Return a unique ID for the current function.
91///
92unsigned AsmPrinter::getFunctionNumber() const {
93 return MF->getFunctionNumber();
94}
95
Chris Lattner75bdd292009-08-03 19:12:26 +000096TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Chris Lattnerc4c40a92009-07-28 03:13:23 +000097 return TM.getTargetLowering()->getObjFileLowering();
98}
99
Chris Lattnerd69d8ad2009-08-18 06:15:16 +0000100/// getCurrentSection() - Return the current section we are emitting to.
101const MCSection *AsmPrinter::getCurrentSection() const {
102 return OutStreamer.getCurrentSection();
103}
104
105
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000106void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000107 AU.setPreservesAll();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000108 MachineFunctionPass::getAnalysisUsage(AU);
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000109 AU.addRequired<GCModuleInfo>();
David Greene066ed6a2009-08-18 19:22:55 +0000110 if (VerboseAsm)
David Greenee52fd872009-08-10 16:38:07 +0000111 AU.addRequired<MachineLoopInfo>();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000112}
113
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114bool AsmPrinter::doInitialization(Module &M) {
Chris Lattner01316272009-07-31 17:42:42 +0000115 // Initialize TargetLoweringObjectFile.
116 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
117 .Initialize(OutContext, TM);
118
Chris Lattner63ab9bb2010-01-17 18:22:35 +0000119 Mang = new Mangler(*MAI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000121 // Allow the target to emit any magic that it wants at the start of the file.
122 EmitStartOfAsmFile(M);
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000123
Chris Lattner59be4ea2010-01-25 18:58:59 +0000124 // Very minimal debug info. It is ignored if we emit actual debug info. If we
125 // don't, this at least helps the user find where a global came from.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000126 if (MAI->hasSingleParameterDotFile()) {
Chris Lattner59be4ea2010-01-25 18:58:59 +0000127 // .file "foo.c"
128 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000129 }
130
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000131 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
132 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000133 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
134 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000135 MP->beginAssembly(O, *this, *MAI);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000136
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137 if (!M.getModuleInlineAsm().empty())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000138 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 << M.getModuleInlineAsm()
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000140 << '\n' << MAI->getCommentString()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 << " End of file scope inline assembly\n";
142
Chris Lattnerc73e8eb2009-09-24 05:44:53 +0000143 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
144 if (MMI)
145 MMI->AnalyzeModule(M);
146 DW = getAnalysisIfAvailable<DwarfWriter>();
Sanjiv Gupta5461b522009-11-14 07:22:25 +0000147 if (DW)
Chris Lattnerc73e8eb2009-09-24 05:44:53 +0000148 DW->BeginModule(&M, MMI, O, this, MAI);
Devang Patel1a454842009-06-19 21:54:26 +0000149
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 return false;
151}
152
Chris Lattnerd9609472010-01-19 04:39:15 +0000153/// EmitGlobalVariable - Emit the specified global variable to the .s file.
154void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
155 if (!GV->hasInitializer()) // External globals require no code.
156 return;
157
158 // Check to see if this is a special global used by LLVM, if so, emit it.
159 if (EmitSpecialLLVMGlobal(GV))
160 return;
Chris Lattner410c9472010-01-19 05:38:33 +0000161
162 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
163 printVisibility(GVSym, GV->getVisibility());
164
Chris Lattner9f8ef902010-01-25 18:33:40 +0000165 if (MAI->hasDotTypeDotSizeDirective())
166 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
Chris Lattnerd9609472010-01-19 04:39:15 +0000167
Chris Lattner410c9472010-01-19 05:38:33 +0000168 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
169
170 const TargetData *TD = TM.getTargetData();
171 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
172 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
173
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000174 // Handle common and BSS local symbols (.lcomm).
175 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner410c9472010-01-19 05:38:33 +0000176 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
177
Chris Lattner410c9472010-01-19 05:38:33 +0000178 if (VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000179 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
180 /*PrintType=*/false, GV->getParent());
181 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000182 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000183
184 // Handle common symbols.
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000185 if (GVKind.isCommon()) {
186 // .comm _foo, 42, 4
Chris Lattnerecf1cdc2010-01-19 06:01:04 +0000187 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000188 return;
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000189 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000190
191 // Handle local BSS symbols.
192 if (MAI->hasMachoZeroFillDirective()) {
193 const MCSection *TheSection =
194 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
195 // .zerofill __DATA, __bss, _foo, 400, 5
196 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
197 return;
198 }
199
Chris Lattnerd70deeb2010-01-23 07:47:02 +0000200 if (MAI->hasLCOMMDirective()) {
Chris Lattnerf26c7792010-01-19 06:25:51 +0000201 // .lcomm _foo, 42
Chris Lattnerd70deeb2010-01-23 07:47:02 +0000202 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000203 return;
204 }
205
206 // .local _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000207 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000208 // .comm _foo, 42, 4
209 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattner410c9472010-01-19 05:38:33 +0000210 return;
211 }
212
213 const MCSection *TheSection =
214 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
215
216 // Handle the zerofill directive on darwin, which is a special form of BSS
217 // emission.
218 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
219 // .globl _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000220 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner410c9472010-01-19 05:38:33 +0000221 // .zerofill __DATA, __common, _foo, 400, 5
222 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
223 return;
224 }
225
226 OutStreamer.SwitchSection(TheSection);
227
228 // TODO: Factor into an 'emit linkage' thing that is shared with function
229 // bodies.
230 switch (GV->getLinkage()) {
231 case GlobalValue::CommonLinkage:
232 case GlobalValue::LinkOnceAnyLinkage:
233 case GlobalValue::LinkOnceODRLinkage:
234 case GlobalValue::WeakAnyLinkage:
235 case GlobalValue::WeakODRLinkage:
236 case GlobalValue::LinkerPrivateLinkage:
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000237 if (MAI->getWeakDefDirective() != 0) {
Chris Lattner410c9472010-01-19 05:38:33 +0000238 // .globl _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000239 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner410c9472010-01-19 05:38:33 +0000240 // .weak_definition _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000241 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
Chris Lattner410c9472010-01-19 05:38:33 +0000242 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
243 // .globl _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000244 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner59be4ea2010-01-25 18:58:59 +0000245 // FIXME: linkonce should be a section attribute, handled by COFF Section
246 // assignment.
247 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
Chris Lattner410c9472010-01-19 05:38:33 +0000248 // .linkonce same_size
249 O << LinkOnce;
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000250 } else {
251 // .weak _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000253 }
Chris Lattner410c9472010-01-19 05:38:33 +0000254 break;
255 case GlobalValue::DLLExportLinkage:
256 case GlobalValue::AppendingLinkage:
257 // FIXME: appending linkage variables should go into a section of
258 // their name or something. For now, just emit them as external.
259 case GlobalValue::ExternalLinkage:
260 // If external or appending, declare as a global symbol.
261 // .globl _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner410c9472010-01-19 05:38:33 +0000263 break;
264 case GlobalValue::PrivateLinkage:
265 case GlobalValue::InternalLinkage:
266 break;
267 default:
268 llvm_unreachable("Unknown linkage type!");
269 }
270
271 EmitAlignment(AlignLog, GV);
Chris Lattner410c9472010-01-19 05:38:33 +0000272 if (VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000273 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
274 /*PrintType=*/false, GV->getParent());
275 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000276 }
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000277 OutStreamer.EmitLabel(GVSym);
Chris Lattner410c9472010-01-19 05:38:33 +0000278
279 EmitGlobalConstant(GV->getInitializer());
280
281 if (MAI->hasDotTypeDotSizeDirective())
Chris Lattner53ee5d82010-01-25 07:53:05 +0000282 // .size foo, 42
Chris Lattnere13c8ac2010-01-25 07:52:13 +0000283 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000284
285 OutStreamer.AddBlankLine();
Chris Lattnerd9609472010-01-19 04:39:15 +0000286}
287
288
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289bool AsmPrinter::doFinalization(Module &M) {
Chris Lattnerae982212009-07-21 18:38:57 +0000290 // Emit global variables.
291 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
292 I != E; ++I)
Chris Lattnerd9609472010-01-19 04:39:15 +0000293 EmitGlobalVariable(I);
Chris Lattnerae982212009-07-21 18:38:57 +0000294
Chris Lattnere1225cc2009-06-24 18:54:37 +0000295 // Emit final debug information.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000296 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
Chris Lattnere1225cc2009-06-24 18:54:37 +0000297 DW->EndModule();
298
Chris Lattnerdb191f02009-06-24 18:52:01 +0000299 // If the target wants to know about weak references, print them all.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000300 if (MAI->getWeakRefDirective()) {
Chris Lattnerdb191f02009-06-24 18:52:01 +0000301 // FIXME: This is not lazy, it would be nice to only print weak references
302 // to stuff that is actually used. Note that doing so would require targets
303 // to notice uses in operands (due to constant exprs etc). This should
304 // happen with the MC stuff eventually.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305
Chris Lattnerdb191f02009-06-24 18:52:01 +0000306 // Print out module-level global variables here.
307 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
308 I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000309 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattner77e356c2010-01-23 05:19:23 +0000310 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000311 MCSA_WeakReference);
Chris Lattnerdb191f02009-06-24 18:52:01 +0000312 }
313
Chris Lattner0f98c332009-08-03 23:10:34 +0000314 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000315 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattner77e356c2010-01-23 05:19:23 +0000316 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000317 MCSA_WeakReference);
Chris Lattnerdb191f02009-06-24 18:52:01 +0000318 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 }
320
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000321 if (MAI->getSetDirective()) {
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000322 OutStreamer.AddBlankLine();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
Chris Lattnerdb191f02009-06-24 18:52:01 +0000324 I != E; ++I) {
Chris Lattnerc0c8d7d2010-01-16 01:17:26 +0000325 MCSymbol *Name = GetGlobalValueSymbol(I);
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000326
327 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
Chris Lattnerc0c8d7d2010-01-16 01:17:26 +0000328 MCSymbol *Target = GetGlobalValueSymbol(GV);
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000329
Chris Lattnerce409842010-01-17 21:43:43 +0000330 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
Chris Lattner2d7c8142010-01-23 06:39:22 +0000331 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
Chris Lattnerce409842010-01-17 21:43:43 +0000332 else if (I->hasWeakLinkage())
Chris Lattner2d7c8142010-01-23 06:39:22 +0000333 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
Chris Lattnerce409842010-01-17 21:43:43 +0000334 else
Chris Lattner1ff31942010-01-16 01:37:14 +0000335 assert(I->hasLocalLinkage() && "Invalid alias linkage");
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000336
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000337 printVisibility(Name, I->getVisibility());
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000338
Chris Lattnerce409842010-01-17 21:43:43 +0000339 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 }
341 }
342
Duncan Sands4e0d6a72009-01-28 13:14:17 +0000343 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000344 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
345 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
346 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000347 MP->finishAssembly(O, *this, *MAI);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000348
Dan Gohmana65530a2008-05-05 00:28:39 +0000349 // If we don't have any trampolines, then we don't require stack memory
350 // to be executable. Some targets have a directive to declare this.
Chris Lattnerdb191f02009-06-24 18:52:01 +0000351 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
Dan Gohmana65530a2008-05-05 00:28:39 +0000352 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Chris Lattner2dc6ddd2010-01-23 07:21:06 +0000353 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
354 OutStreamer.SwitchSection(S);
Chris Lattnerb6113072009-09-18 20:17:03 +0000355
356 // Allow the target to emit any magic that it wants at the end of the file,
357 // after everything else has gone out.
358 EmitEndOfAsmFile(M);
359
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 delete Mang; Mang = 0;
Chris Lattner2424eac2009-06-24 19:09:55 +0000361 DW = 0; MMI = 0;
Chris Lattner1eb0ad02009-07-27 21:28:04 +0000362
363 OutStreamer.Finish();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 return false;
365}
366
367void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
Chris Lattner01462ba2010-01-26 04:35:26 +0000368 this->MF = &MF;
Chris Lattnerac5a6ad2010-01-16 01:24:10 +0000369 // Get the function symbol.
Chris Lattner8d656d92010-01-15 23:55:16 +0000370 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
David Greenee52fd872009-08-10 16:38:07 +0000371
Chris Lattner57c76b52009-09-16 00:35:39 +0000372 if (VerboseAsm)
David Greenee52fd872009-08-10 16:38:07 +0000373 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374}
375
Evan Cheng68c18682009-03-13 07:51:59 +0000376namespace {
377 // SectionCPs - Keep track the alignment, constpool entries per Section.
378 struct SectionCPs {
Chris Lattnere6ad12f2009-07-31 18:48:30 +0000379 const MCSection *S;
Evan Cheng68c18682009-03-13 07:51:59 +0000380 unsigned Alignment;
381 SmallVector<unsigned, 4> CPEs;
Douglas Gregor8cb41382009-12-19 07:05:23 +0000382 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
Evan Cheng68c18682009-03-13 07:51:59 +0000383 };
384}
385
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386/// EmitConstantPool - Print to the current output stream assembly
387/// representations of the constants in the constant pool MCP. This is
388/// used to print out constants which have been "spilled to memory" by
389/// the code generator.
390///
391void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
392 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
393 if (CP.empty()) return;
394
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000395 // Calculate sections for constant pool entries. We collect entries to go into
396 // the same section together to reduce amount of section switch statements.
Evan Cheng68c18682009-03-13 07:51:59 +0000397 SmallVector<SectionCPs, 4> CPSections;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Chris Lattner680c6f62009-07-22 00:28:43 +0000399 const MachineConstantPoolEntry &CPE = CP[i];
Evan Cheng68c18682009-03-13 07:51:59 +0000400 unsigned Align = CPE.getAlignment();
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000401
402 SectionKind Kind;
403 switch (CPE.getRelocationInfo()) {
404 default: llvm_unreachable("Unknown section kind");
Chris Lattnera9453412009-08-01 23:57:16 +0000405 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000406 case 1:
Chris Lattnera9453412009-08-01 23:57:16 +0000407 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattnered0c6762009-07-26 07:00:12 +0000408 break;
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000409 case 0:
Chris Lattnered0c6762009-07-26 07:00:12 +0000410 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
Chris Lattnera9453412009-08-01 23:57:16 +0000411 case 4: Kind = SectionKind::getMergeableConst4(); break;
412 case 8: Kind = SectionKind::getMergeableConst8(); break;
413 case 16: Kind = SectionKind::getMergeableConst16();break;
414 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000415 }
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000416 }
417
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000418 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Chris Lattner680c6f62009-07-22 00:28:43 +0000419
Evan Cheng68c18682009-03-13 07:51:59 +0000420 // The number of sections are small, just do a linear search from the
421 // last section to the first.
422 bool Found = false;
423 unsigned SecIdx = CPSections.size();
424 while (SecIdx != 0) {
425 if (CPSections[--SecIdx].S == S) {
426 Found = true;
427 break;
428 }
429 }
430 if (!Found) {
431 SecIdx = CPSections.size();
432 CPSections.push_back(SectionCPs(S, Align));
433 }
434
435 if (Align > CPSections[SecIdx].Alignment)
436 CPSections[SecIdx].Alignment = Align;
437 CPSections[SecIdx].CPEs.push_back(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 }
439
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000440 // Now print stuff into the calculated sections.
Evan Cheng68c18682009-03-13 07:51:59 +0000441 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
Chris Lattner73266f92009-08-19 05:49:37 +0000442 OutStreamer.SwitchSection(CPSections[i].S);
Evan Cheng68c18682009-03-13 07:51:59 +0000443 EmitAlignment(Log2_32(CPSections[i].Alignment));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444
Evan Cheng68c18682009-03-13 07:51:59 +0000445 unsigned Offset = 0;
446 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
447 unsigned CPI = CPSections[i].CPEs[j];
448 MachineConstantPoolEntry CPE = CP[CPI];
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 // Emit inter-object padding for alignment.
Evan Cheng68c18682009-03-13 07:51:59 +0000451 unsigned AlignMask = CPE.getAlignment() - 1;
452 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
Chris Lattnera71dc602010-01-19 19:46:13 +0000453 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
Evan Cheng68c18682009-03-13 07:51:59 +0000454
455 const Type *Ty = CPE.getType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000456 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
Evan Cheng68c18682009-03-13 07:51:59 +0000457
Chris Lattner77e356c2010-01-23 05:19:23 +0000458 // Emit the label with a comment on it.
Evan Cheng68c18682009-03-13 07:51:59 +0000459 if (VerboseAsm) {
Chris Lattner77e356c2010-01-23 05:19:23 +0000460 OutStreamer.GetCommentOS() << "constant pool ";
461 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
462 MF->getFunction()->getParent());
463 OutStreamer.GetCommentOS() << '\n';
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000464 }
Chris Lattner77e356c2010-01-23 05:19:23 +0000465 OutStreamer.EmitLabel(GetCPISymbol(CPI));
466
Evan Cheng68c18682009-03-13 07:51:59 +0000467 if (CPE.isMachineConstantPoolEntry())
468 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
469 else
470 EmitGlobalConstant(CPE.Val.ConstVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 }
472 }
473}
474
475/// EmitJumpTableInfo - Print assembly representations of the jump tables used
476/// by the current function to the current output stream.
477///
Chris Lattner1f8c8922010-01-25 22:41:33 +0000478void AsmPrinter::EmitJumpTableInfo(MachineFunction &MF) {
479 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
480 if (MJTI == 0) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
482 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000483
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
485
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 // Pick the directive to use to print the jump table entries, and switch to
487 // the appropriate section.
Anton Korobeynikov7f3fa2c2008-07-09 13:27:16 +0000488 const Function *F = MF.getFunction();
Evan Chengccca6f72009-06-18 20:37:15 +0000489 bool JTInDiffSection = false;
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000490 if (F->isWeakForLinker() ||
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000491 (IsPic && !TM.getTargetLowering()->usesGlobalOffsetTable())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492 // In PIC mode, we need to emit the jump table to the same section as the
493 // function body itself, otherwise the label differences won't make sense.
Anton Korobeynikov7f3fa2c2008-07-09 13:27:16 +0000494 // We should also do if the section name is NULL or function is declared in
495 // discardable section.
Chris Lattner73266f92009-08-19 05:49:37 +0000496 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
497 TM));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 } else {
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000499 // Otherwise, drop it in the readonly section.
500 const MCSection *ReadOnlySection =
Chris Lattnera9453412009-08-01 23:57:16 +0000501 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
Chris Lattner73266f92009-08-19 05:49:37 +0000502 OutStreamer.SwitchSection(ReadOnlySection);
Evan Chengccca6f72009-06-18 20:37:15 +0000503 JTInDiffSection = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 }
Chris Lattner1d196bc2010-01-25 23:26:13 +0000505
Chris Lattner1d196bc2010-01-25 23:26:13 +0000506 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507
Chris Lattnerc077d722010-01-26 06:42:44 +0000508 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
509 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
511 // If this jump table was deleted, ignore it.
512 if (JTBBs.empty()) continue;
513
Chris Lattnerb494ccd2010-01-26 05:15:20 +0000514 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
515 // .set directive for each unique entry. This reduces the number of
516 // relocations the assembler will generate for the jump table.
517 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
518 MAI->getSetDirective()) {
Chris Lattnerc077d722010-01-26 06:42:44 +0000519 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
520 const TargetLowering *TLI = TM.getTargetLowering();
521 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(&MF, JTI,
522 OutContext);
523 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
524 const MachineBasicBlock *MBB = JTBBs[ii];
525 if (!EmittedSets.insert(MBB)) continue;
526
527 O << MAI->getSetDirective() << ' '
528 << *GetJTSetSymbol(JTI, MBB->getNumber()) << ','
529 << *MBB->getSymbol(OutContext) << '-' << *Base << '\n';
530 }
531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532
Chris Lattner149495f2009-09-13 19:02:16 +0000533 // On some targets (e.g. Darwin) we want to emit two consequtive labels
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 // before each jump table. The first label is never referenced, but tells
535 // the assembler and linker the extents of the jump table object. The
536 // second label is actually referenced by the code.
Chris Lattner77e356c2010-01-23 05:19:23 +0000537 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
Chris Lattner978b9772010-01-26 05:58:28 +0000538 // FIXME: This doesn't have to have any specific name, just any randomly
539 // named and numbered 'l' label would work. Simplify GetJTISymbol.
Chris Lattnerc077d722010-01-26 06:42:44 +0000540 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
Chris Lattner77e356c2010-01-23 05:19:23 +0000541
Chris Lattnerc077d722010-01-26 06:42:44 +0000542 OutStreamer.EmitLabel(GetJTISymbol(JTI));
Chris Lattner77e356c2010-01-23 05:19:23 +0000543
Chris Lattner3d680c02010-01-26 05:10:10 +0000544 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Chris Lattnerc077d722010-01-26 06:42:44 +0000545 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 }
547}
548
Chris Lattner3d680c02010-01-26 05:10:10 +0000549/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
550/// current stream.
551void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
552 const MachineBasicBlock *MBB,
553 unsigned UID) const {
Chris Lattner06b01dd2010-01-26 03:43:22 +0000554 const MCExpr *Value = 0;
555 switch (MJTI->getEntryKind()) {
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000556 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner3d680c02010-01-26 05:10:10 +0000557 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000558 OutContext);
559 break;
Chris Lattner06b01dd2010-01-26 03:43:22 +0000560 case MachineJumpTableInfo::EK_BlockAddress:
561 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
562 // .word LBB123
Chris Lattner84d5ca92010-01-26 04:55:51 +0000563 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
Chris Lattner06b01dd2010-01-26 03:43:22 +0000564 break;
Chris Lattner06b01dd2010-01-26 03:43:22 +0000565 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
566 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
567 // with a relocation as gp-relative, e.g.:
568 // .gprel32 LBB123
Chris Lattner84d5ca92010-01-26 04:55:51 +0000569 MCSymbol *MBBSym = MBB->getSymbol(OutContext);
Chris Lattner3dac3412010-01-25 21:28:50 +0000570 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
Chris Lattner48b139f2010-01-25 21:10:10 +0000571 return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000572 }
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000573
Chris Lattner06b01dd2010-01-26 03:43:22 +0000574 case MachineJumpTableInfo::EK_LabelDifference32: {
575 // EK_LabelDifference32 - Each entry is the address of the block minus
576 // the address of the jump table. This is used for PIC jump tables where
577 // gprel32 is not supported. e.g.:
578 // .word LBB123 - LJTI1_2
579 // If the .set directive is supported, this is emitted as:
580 // .set L4_5_set_123, LBB123 - LJTI1_2
581 // .word L4_5_set_123
582
583 // If we have emitted set directives for the jump table entries, print
584 // them rather than the entries themselves. If we're emitting PIC, then
585 // emit the table entries as differences between two text section labels.
586 if (MAI->getSetDirective()) {
587 // If we used .set, reference the .set's symbol.
Chris Lattner3d680c02010-01-26 05:10:10 +0000588 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
Chris Lattner06b01dd2010-01-26 03:43:22 +0000589 OutContext);
590 break;
591 }
Chris Lattner7eba6722010-01-25 21:22:22 +0000592 // Otherwise, use the difference as the jump table entry.
Chris Lattner84d5ca92010-01-26 04:55:51 +0000593 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
Chris Lattner3d680c02010-01-26 05:10:10 +0000594 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
Chris Lattner06b01dd2010-01-26 03:43:22 +0000595 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
596 break;
597 }
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000598 }
Chris Lattner7eba6722010-01-25 21:22:22 +0000599
Chris Lattner06b01dd2010-01-26 03:43:22 +0000600 assert(Value && "Unknown entry kind!");
601
Chris Lattner1d196bc2010-01-25 23:26:13 +0000602 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
Chris Lattner06b01dd2010-01-26 03:43:22 +0000603 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000604}
605
606
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
608/// special global used by LLVM. If so, emit it and return true, otherwise
609/// do nothing and return false.
610bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Daniel Dunbare03513b2009-07-25 23:55:21 +0000611 if (GV->getName() == "llvm.used") {
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000612 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000613 EmitLLVMUsedList(GV->getInitializer());
614 return true;
615 }
616
Chris Lattner1e0e0d12009-07-20 06:14:25 +0000617 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
Chris Lattner68433442009-04-13 05:44:34 +0000618 if (GV->getSection() == "llvm.metadata" ||
619 GV->hasAvailableExternallyLinkage())
620 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621
622 if (!GV->hasAppendingLinkage()) return false;
623
624 assert(GV->hasInitializer() && "Not a special LLVM global!");
625
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 const TargetData *TD = TM.getTargetData();
627 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
Chris Lattner0c433e92009-03-09 05:52:15 +0000628 if (GV->getName() == "llvm.global_ctors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000629 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000630 EmitAlignment(Align, 0);
631 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000632
633 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000634 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
635 StringRef Sym(".constructors_used");
636 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000637 MCSA_Reference);
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000638 }
Chris Lattner1e0e4892009-03-09 08:18:48 +0000639 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 }
641
Chris Lattner0c433e92009-03-09 05:52:15 +0000642 if (GV->getName() == "llvm.global_dtors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000643 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000644 EmitAlignment(Align, 0);
645 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000646
647 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000648 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
649 StringRef Sym(".destructors_used");
650 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000651 MCSA_Reference);
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000652 }
Chris Lattner1e0e4892009-03-09 08:18:48 +0000653 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 }
655
656 return false;
657}
658
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000659/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
Dale Johannesen60567622008-09-09 22:29:13 +0000660/// global in the specified llvm.used list for which emitUsedDirectiveFor
661/// is true, as being used with this directive.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662void AsmPrinter::EmitLLVMUsedList(Constant *List) {
Dan Gohman9e1657f2009-06-14 23:30:43 +0000663 // Should be an array of 'i8*'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
665 if (InitList == 0) return;
666
667 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner3f621b32009-07-17 22:00:23 +0000668 const GlobalValue *GV =
669 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000670 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
671 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000672 MCSA_NoDeadStrip);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 }
674}
675
676/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
677/// function pointers, ignoring the init priority.
678void AsmPrinter::EmitXXStructorList(Constant *List) {
679 // Should be an array of '{ int, void ()* }' structs. The first value is the
680 // init priority, which we ignore.
681 if (!isa<ConstantArray>(List)) return;
682 ConstantArray *InitList = cast<ConstantArray>(List);
683 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
684 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
685 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
686
687 if (CS->getOperand(1)->isNullValue())
688 return; // Found a null terminator, exit printing.
689 // Emit the function pointer.
690 EmitGlobalConstant(CS->getOperand(1));
691 }
692}
693
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694//===--------------------------------------------------------------------===//
695// Emission and print routines
696//
697
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698/// EmitInt8 - Emit a byte directive and value.
699///
700void AsmPrinter::EmitInt8(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000701 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702}
703
704/// EmitInt16 - Emit a short directive and value.
705///
706void AsmPrinter::EmitInt16(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000707 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708}
709
710/// EmitInt32 - Emit a long directive and value.
711///
712void AsmPrinter::EmitInt32(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000713 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714}
715
716/// EmitInt64 - Emit a long long directive and value.
717///
718void AsmPrinter::EmitInt64(uint64_t Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000719 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720}
721
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722//===----------------------------------------------------------------------===//
723
724// EmitAlignment - Emit an alignment directive to the specified power of
725// two boundary. For example, if you pass in 3 here, you will get an 8
726// byte alignment. If a global value is specified, and if that global has
727// an explicit alignment requested, it will unconditionally override the
728// alignment request. However, if ForcedAlignBits is specified, this value
729// has final say: the ultimate alignment will be the max of ForcedAlignBits
730// and the alignment computed with NumBits and the global.
731//
732// The algorithm is:
733// Align = NumBits;
734// if (GV && GV->hasalignment) Align = GV->getalignment();
735// Align = std::max(Align, ForcedAlignBits);
736//
737void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Cheng7e7d1942008-02-29 19:36:59 +0000738 unsigned ForcedAlignBits,
739 bool UseFillExpr) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 if (GV && GV->getAlignment())
741 NumBits = Log2_32(GV->getAlignment());
742 NumBits = std::max(NumBits, ForcedAlignBits);
743
744 if (NumBits == 0) return; // No need to emit alignment.
Chris Lattner4891d142009-08-19 06:12:02 +0000745
746 unsigned FillValue = 0;
Chris Lattnerd69d8ad2009-08-18 06:15:16 +0000747 if (getCurrentSection()->getKind().isText())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000748 FillValue = MAI->getTextAlignFillValue();
Chris Lattner4891d142009-08-19 06:12:02 +0000749
750 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751}
David Greenecdc2de32009-08-05 21:00:52 +0000752
Chris Lattner54bfda72010-01-23 06:17:14 +0000753/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
754///
755static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
756 MCContext &Ctx = AP.OutContext;
757
758 if (CV->isNullValue() || isa<UndefValue>(CV))
759 return MCConstantExpr::Create(0, Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +0000760
Chris Lattner54bfda72010-01-23 06:17:14 +0000761 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
762 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +0000763
Chris Lattner54bfda72010-01-23 06:17:14 +0000764 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
765 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
766 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
767 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +0000768
769 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
770 if (CE == 0) {
Chris Lattner54bfda72010-01-23 06:17:14 +0000771 llvm_unreachable("Unknown constant value to lower!");
772 return MCConstantExpr::Create(0, Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +0000773 }
774
775 switch (CE->getOpcode()) {
776 case Instruction::ZExt:
777 case Instruction::SExt:
778 case Instruction::FPTrunc:
779 case Instruction::FPExt:
780 case Instruction::UIToFP:
781 case Instruction::SIToFP:
782 case Instruction::FPToUI:
783 case Instruction::FPToSI:
Chris Lattner54bfda72010-01-23 06:17:14 +0000784 default: llvm_unreachable("FIXME: Don't support this constant cast expr");
Chris Lattner458c8772010-01-13 04:29:19 +0000785 case Instruction::GetElementPtr: {
Chris Lattner54bfda72010-01-23 06:17:14 +0000786 const TargetData &TD = *AP.TM.getTargetData();
787 // Generate a symbolic expression for the byte address
788 const Constant *PtrVal = CE->getOperand(0);
789 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
790 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
791 IdxVec.size());
792
793 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
Chris Lattner458c8772010-01-13 04:29:19 +0000794 if (Offset == 0)
Chris Lattner54bfda72010-01-23 06:17:14 +0000795 return Base;
Chris Lattner458c8772010-01-13 04:29:19 +0000796
797 // Truncate/sext the offset to the pointer size.
Chris Lattner54bfda72010-01-23 06:17:14 +0000798 if (TD.getPointerSizeInBits() != 64) {
799 int SExtAmount = 64-TD.getPointerSizeInBits();
Chris Lattner458c8772010-01-13 04:29:19 +0000800 Offset = (Offset << SExtAmount) >> SExtAmount;
801 }
802
Chris Lattner54bfda72010-01-23 06:17:14 +0000803 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
804 Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +0000805 }
806
807 case Instruction::Trunc:
808 // We emit the value and depend on the assembler to truncate the generated
809 // expression properly. This is important for differences between
810 // blockaddress labels. Since the two labels are in the same function, it
811 // is reasonable to treat their delta as a 32-bit value.
Chris Lattner54bfda72010-01-23 06:17:14 +0000812 // FALL THROUGH.
813 case Instruction::BitCast:
814 return LowerConstant(CE->getOperand(0), AP);
815
816 case Instruction::IntToPtr: {
817 const TargetData &TD = *AP.TM.getTargetData();
818 // Handle casts to pointers by changing them into casts to the appropriate
819 // integer type. This promotes constant folding and simplifies this code.
820 Constant *Op = CE->getOperand(0);
821 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
822 false/*ZExt*/);
823 return LowerConstant(Op, AP);
824 }
825
826 case Instruction::PtrToInt: {
827 const TargetData &TD = *AP.TM.getTargetData();
828 // Support only foldable casts to/from pointers that can be eliminated by
829 // changing the pointer to the appropriately sized integer type.
830 Constant *Op = CE->getOperand(0);
831 const Type *Ty = CE->getType();
832
833 const MCExpr *OpExpr = LowerConstant(Op, AP);
834
835 // We can emit the pointer value into this slot if the slot is an
836 // integer slot equal to the size of the pointer.
837 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
838 return OpExpr;
839
840 // Otherwise the pointer is smaller than the resultant integer, mask off
841 // the high bits so we are sure to get a proper truncation if the input is
842 // a constant expr.
843 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
844 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
845 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
846 }
Chris Lattner458c8772010-01-13 04:29:19 +0000847
848 case Instruction::Add:
849 case Instruction::Sub:
850 case Instruction::And:
851 case Instruction::Or:
Chris Lattner54bfda72010-01-23 06:17:14 +0000852 case Instruction::Xor: {
853 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
854 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
Chris Lattner458c8772010-01-13 04:29:19 +0000855 switch (CE->getOpcode()) {
Chris Lattner54bfda72010-01-23 06:17:14 +0000856 default: llvm_unreachable("Unknown binary operator constant cast expr");
857 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
858 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
859 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
860 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
861 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +0000862 }
Chris Lattner54bfda72010-01-23 06:17:14 +0000863 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 }
865}
866
Chris Lattnere72333d2010-01-19 19:10:44 +0000867static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
868 AsmPrinter &AP) {
Chris Lattnera68112c2010-01-23 04:54:10 +0000869 if (AddrSpace != 0 || !CA->isString()) {
870 // Not a string. Print the values in successive locations
Chris Lattnere72333d2010-01-19 19:10:44 +0000871 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
872 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
Chris Lattnera68112c2010-01-23 04:54:10 +0000873 return;
Dan Gohmane78b0c72008-12-22 21:14:27 +0000874 }
Chris Lattnera68112c2010-01-23 04:54:10 +0000875
876 // Otherwise, it can be emitted as .ascii.
877 SmallVector<char, 128> TmpVec;
878 TmpVec.reserve(CA->getNumOperands());
879 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
880 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
881
882 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000883}
884
Chris Lattnere72333d2010-01-19 19:10:44 +0000885static void EmitGlobalConstantVector(const ConstantVector *CV,
886 unsigned AddrSpace, AsmPrinter &AP) {
Chris Lattnerd3544672010-01-20 07:41:15 +0000887 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Chris Lattnere72333d2010-01-19 19:10:44 +0000888 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000889}
890
Chris Lattnere72333d2010-01-19 19:10:44 +0000891static void EmitGlobalConstantStruct(const ConstantStruct *CS,
892 unsigned AddrSpace, AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +0000893 // Print the fields in successive locations. Pad to align if needed!
Chris Lattnere72333d2010-01-19 19:10:44 +0000894 const TargetData *TD = AP.TM.getTargetData();
895 unsigned Size = TD->getTypeAllocSize(CS->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000896 const StructLayout *Layout = TD->getStructLayout(CS->getType());
Chris Lattnere72333d2010-01-19 19:10:44 +0000897 uint64_t SizeSoFar = 0;
898 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattnerd3544672010-01-20 07:41:15 +0000899 const Constant *Field = CS->getOperand(i);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000900
901 // Check if padding is needed and insert one or more 0s.
Chris Lattnerd3544672010-01-20 07:41:15 +0000902 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000903 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
904 - Layout->getElementOffset(i)) - FieldSize;
905 SizeSoFar += FieldSize + PadSize;
Dan Gohmane78b0c72008-12-22 21:14:27 +0000906
907 // Now print the actual field value.
Chris Lattnerd3544672010-01-20 07:41:15 +0000908 AP.EmitGlobalConstant(Field, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000909
910 // Insert padding - this may include padding to increase the size of the
911 // current field up to the ABI size (if the struct is not packed) as well
912 // as padding to ensure that the next field starts at the right offset.
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000913 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000914 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000915 assert(SizeSoFar == Layout->getSizeInBytes() &&
Dan Gohmane78b0c72008-12-22 21:14:27 +0000916 "Layout of constant struct may be incorrect!");
917}
918
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000919static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
920 AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +0000921 // FP Constants are printed as integer constants to avoid losing
Chris Lattner41fd4b12010-01-20 06:53:37 +0000922 // precision.
Chris Lattner82cdc062009-10-05 05:54:46 +0000923 if (CFP->getType()->isDoubleTy()) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000924 if (AP.VerboseAsm) {
Chris Lattner49d74392010-01-22 19:17:48 +0000925 double Val = CFP->getValueAPF().convertToDouble();
926 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
Chris Lattner4e789282010-01-19 22:16:33 +0000927 }
928
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000929 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
930 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000931 return;
Chris Lattner82cdc062009-10-05 05:54:46 +0000932 }
933
934 if (CFP->getType()->isFloatTy()) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000935 if (AP.VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000936 float Val = CFP->getValueAPF().convertToFloat();
937 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
Dan Gohman87581eb2009-08-12 18:32:22 +0000938 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000939 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
940 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000941 return;
Chris Lattner82cdc062009-10-05 05:54:46 +0000942 }
943
944 if (CFP->getType()->isX86_FP80Ty()) {
Dan Gohmane78b0c72008-12-22 21:14:27 +0000945 // all long double variants are printed as hex
946 // api needed to prevent premature destruction
Chris Lattner4e789282010-01-19 22:16:33 +0000947 APInt API = CFP->getValueAPF().bitcastToAPInt();
948 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000949 if (AP.VerboseAsm) {
Chris Lattner84382d22010-01-19 22:11:05 +0000950 // Convert to double so we can print the approximate val as a comment.
951 APFloat DoubleVal = CFP->getValueAPF();
952 bool ignored;
953 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
954 &ignored);
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000955 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
956 << DoubleVal.convertToDouble() << '\n';
Chris Lattner84382d22010-01-19 22:11:05 +0000957 }
958
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000959 if (AP.TM.getTargetData()->isBigEndian()) {
960 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
961 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner84382d22010-01-19 22:11:05 +0000962 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000963 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
964 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000965 }
Chris Lattner41fd4b12010-01-20 06:53:37 +0000966
967 // Emit the tail padding for the long double.
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000968 const TargetData &TD = *AP.TM.getTargetData();
969 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
970 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000971 return;
Chris Lattner82cdc062009-10-05 05:54:46 +0000972 }
973
Chris Lattner4e789282010-01-19 22:16:33 +0000974 assert(CFP->getType()->isPPC_FP128Ty() &&
975 "Floating point constant type not handled");
976 // All long double variants are printed as hex api needed to prevent
977 // premature destruction.
978 APInt API = CFP->getValueAPF().bitcastToAPInt();
979 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000980 if (AP.TM.getTargetData()->isBigEndian()) {
981 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
982 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
Chris Lattner41fd4b12010-01-20 06:53:37 +0000983 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000984 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
985 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner4e789282010-01-19 22:16:33 +0000986 }
Dan Gohmane78b0c72008-12-22 21:14:27 +0000987}
988
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000989static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
990 unsigned AddrSpace, AsmPrinter &AP) {
991 const TargetData *TD = AP.TM.getTargetData();
Dan Gohmane78b0c72008-12-22 21:14:27 +0000992 unsigned BitWidth = CI->getBitWidth();
Chris Lattner50340312010-01-13 04:39:46 +0000993 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
Dan Gohmane78b0c72008-12-22 21:14:27 +0000994
995 // We don't expect assemblers to support integer data directives
996 // for more than 64 bits, so we emit the data in at most 64-bit
997 // quantities at a time.
998 const uint64_t *RawData = CI->getValue().getRawData();
999 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001000 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1001 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001002 }
1003}
1004
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Sanjiv Guptadc2943d2009-01-30 04:25:10 +00001006void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
Chris Lattnere795ca52010-01-20 07:19:19 +00001007 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001008 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
Chris Lattner030176b2010-01-19 21:51:22 +00001009 return OutStreamer.EmitZeros(Size, AddrSpace);
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001010 }
1011
1012 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1013 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1014 switch (Size) {
1015 case 1:
1016 case 2:
1017 case 4:
1018 case 8:
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001019 if (VerboseAsm)
1020 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001021 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1022 return;
1023 default:
1024 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1025 return;
1026 }
1027 }
Chris Lattner9d767d82010-01-13 04:34:19 +00001028
Chris Lattnere72333d2010-01-19 19:10:44 +00001029 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1030 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001031
Chris Lattnere72333d2010-01-19 19:10:44 +00001032 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1033 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001034
Chris Lattnere72333d2010-01-19 19:10:44 +00001035 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001036 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001037
Chris Lattnere72333d2010-01-19 19:10:44 +00001038 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1039 return EmitGlobalConstantVector(V, AddrSpace, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040
Chris Lattner4fb5a132010-01-20 17:57:50 +00001041 if (isa<ConstantPointerNull>(CV)) {
1042 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1043 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1044 return;
1045 }
1046
Chris Lattner54bfda72010-01-23 06:17:14 +00001047 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1048 // thread the streamer with EmitValue.
1049 OutStreamer.EmitValue(LowerConstant(CV, *this),
1050 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1051 AddrSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052}
1053
Chris Lattner89b36582008-08-17 07:19:36 +00001054void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 // Target doesn't support this yet!
Edwin Törökbd448e32009-07-14 16:55:14 +00001056 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057}
1058
1059/// PrintSpecial - Print information related to the specified machine instr
1060/// that is independent of the operand, and may be independent of the instr
1061/// itself. This can be useful for portably encoding the comment character
1062/// or other bits of target-specific knowledge into the asmstrings. The
1063/// syntax used is ${:comment}. Targets can override this to add support
1064/// for their own strange codes.
Chris Lattner6af48032009-03-10 05:37:13 +00001065void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 if (!strcmp(Code, "private")) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001067 O << MAI->getPrivateGlobalPrefix();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 } else if (!strcmp(Code, "comment")) {
Evan Cheng11db8142009-03-24 00:17:40 +00001069 if (VerboseAsm)
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001070 O << MAI->getCommentString();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 } else if (!strcmp(Code, "uid")) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 // Comparing the address of MI isn't sufficient, because machineinstrs may
1073 // be allocated to the same address across functions.
1074 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1075
Owen Andersonda3388b2009-06-24 22:28:12 +00001076 // If this is a new LastFn instruction, bump the counter.
1077 if (LastMI != MI || LastFn != ThisF) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 ++Counter;
1079 LastMI = MI;
Owen Andersonda3388b2009-06-24 22:28:12 +00001080 LastFn = ThisF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 }
1082 O << Counter;
1083 } else {
Edwin Törökced9ff82009-07-11 13:10:19 +00001084 std::string msg;
1085 raw_string_ostream Msg(msg);
1086 Msg << "Unknown special formatter '" << Code
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 << "' for machine instr: " << *MI;
Edwin Törökced9ff82009-07-11 13:10:19 +00001088 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 }
1090}
1091
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +00001092/// processDebugLoc - Processes the debug information of each machine
1093/// instruction's DebugLoc.
Devang Patel5450fc12009-10-06 02:19:11 +00001094void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1095 bool BeforePrintingInsn) {
Devang Patel90a0fe32009-11-10 23:06:00 +00001096 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1097 || !DW->ShouldEmitDwarfDebug())
Chris Lattner693cfcc2009-08-05 04:09:18 +00001098 return;
Devang Patel86049dc2009-09-30 23:12:50 +00001099 DebugLoc DL = MI->getDebugLoc();
Devang Patel90a0fe32009-11-10 23:06:00 +00001100 if (DL.isUnknown())
1101 return;
Devang Patel042945f2010-01-16 06:09:35 +00001102 DILocation CurDLT = MF->getDILocation(DL);
1103 if (CurDLT.getScope().isNull())
Devang Patel90a0fe32009-11-10 23:06:00 +00001104 return;
1105
Chris Lattnere795ca52010-01-20 07:19:19 +00001106 if (!BeforePrintingInsn) {
Devang Patel90a0fe32009-11-10 23:06:00 +00001107 // After printing instruction
1108 DW->EndScope(MI);
Chris Lattnere795ca52010-01-20 07:19:19 +00001109 } else if (CurDLT.getNode() != PrevDLT) {
1110 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1111 CurDLT.getColumnNumber(),
1112 CurDLT.getScope().getNode());
1113 printLabel(L);
1114 O << '\n';
1115 DW->BeginScope(MI, L);
1116 PrevDLT = CurDLT.getNode();
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +00001117 }
1118}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119
Devang Patel90a0fe32009-11-10 23:06:00 +00001120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121/// printInlineAsm - This method formats and prints the specified machine
1122/// instruction that is an inline asm.
1123void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1124 unsigned NumOperands = MI->getNumOperands();
1125
1126 // Count the number of register definitions.
1127 unsigned NumDefs = 0;
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001128 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129 ++NumDefs)
1130 assert(NumDefs != NumOperands-1 && "No asm string?");
1131
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001132 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133
1134 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1135 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1136
Dan Gohmanbbc43962009-11-06 00:04:54 +00001137 O << '\t';
1138
Dale Johannesene99fc902008-01-29 02:21:21 +00001139 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1140 // These are useful to see where empty asm's wound up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 if (AsmStr[0] == 0) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001142 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1143 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 return;
1145 }
1146
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001147 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148
1149 // The variant of the current asmprinter.
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001150 int AsmPrinterVariant = MAI->getAssemblerDialect();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151
1152 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1153 const char *LastEmitted = AsmStr; // One past the last character emitted.
1154
1155 while (*LastEmitted) {
1156 switch (*LastEmitted) {
1157 default: {
1158 // Not a special case, emit the string section literally.
1159 const char *LiteralEnd = LastEmitted+1;
1160 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1161 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1162 ++LiteralEnd;
1163 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1164 O.write(LastEmitted, LiteralEnd-LastEmitted);
1165 LastEmitted = LiteralEnd;
1166 break;
1167 }
1168 case '\n':
1169 ++LastEmitted; // Consume newline character.
Dan Gohman12ebe3f2008-06-30 22:03:41 +00001170 O << '\n'; // Indent code with newline.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 break;
1172 case '$': {
1173 ++LastEmitted; // Consume '$' character.
1174 bool Done = true;
1175
1176 // Handle escapes.
1177 switch (*LastEmitted) {
1178 default: Done = false; break;
1179 case '$': // $$ -> $
1180 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1181 O << '$';
1182 ++LastEmitted; // Consume second '$' character.
1183 break;
1184 case '(': // $( -> same as GCC's { character.
1185 ++LastEmitted; // Consume '(' character.
1186 if (CurVariant != -1) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001187 llvm_report_error("Nested variants found in inline asm string: '"
1188 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 }
1190 CurVariant = 0; // We're in the first variant now.
1191 break;
1192 case '|':
1193 ++LastEmitted; // consume '|' character.
Dale Johannesen8b0e1172008-10-10 21:04:42 +00001194 if (CurVariant == -1)
1195 O << '|'; // this is gcc's behavior for | outside a variant
1196 else
1197 ++CurVariant; // We're in the next variant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 break;
1199 case ')': // $) -> same as GCC's } char.
1200 ++LastEmitted; // consume ')' character.
Dale Johannesen8b0e1172008-10-10 21:04:42 +00001201 if (CurVariant == -1)
1202 O << '}'; // this is gcc's behavior for } outside a variant
1203 else
1204 CurVariant = -1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205 break;
1206 }
1207 if (Done) break;
1208
1209 bool HasCurlyBraces = false;
1210 if (*LastEmitted == '{') { // ${variable}
1211 ++LastEmitted; // Consume '{' character.
1212 HasCurlyBraces = true;
1213 }
1214
Chris Lattner6af48032009-03-10 05:37:13 +00001215 // If we have ${:foo}, then this is not a real operand reference, it is a
1216 // "magic" string reference, just like in .td files. Arrange to call
1217 // PrintSpecial.
1218 if (HasCurlyBraces && *LastEmitted == ':') {
1219 ++LastEmitted;
1220 const char *StrStart = LastEmitted;
1221 const char *StrEnd = strchr(StrStart, '}');
1222 if (StrEnd == 0) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001223 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1224 + std::string(AsmStr) + "'");
Chris Lattner6af48032009-03-10 05:37:13 +00001225 }
1226
1227 std::string Val(StrStart, StrEnd);
1228 PrintSpecial(MI, Val.c_str());
1229 LastEmitted = StrEnd+1;
1230 break;
1231 }
1232
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 const char *IDStart = LastEmitted;
1234 char *IDEnd;
1235 errno = 0;
1236 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1237 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001238 llvm_report_error("Bad $ operand number in inline asm string: '"
1239 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 }
1241 LastEmitted = IDEnd;
1242
1243 char Modifier[2] = { 0, 0 };
1244
1245 if (HasCurlyBraces) {
1246 // If we have curly braces, check for a modifier character. This
1247 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1248 if (*LastEmitted == ':') {
1249 ++LastEmitted; // Consume ':' character.
1250 if (*LastEmitted == 0) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001251 llvm_report_error("Bad ${:} expression in inline asm string: '"
1252 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 }
1254
1255 Modifier[0] = *LastEmitted;
1256 ++LastEmitted; // Consume modifier character.
1257 }
1258
1259 if (*LastEmitted != '}') {
Edwin Törökced9ff82009-07-11 13:10:19 +00001260 llvm_report_error("Bad ${} expression in inline asm string: '"
1261 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 }
1263 ++LastEmitted; // Consume '}' character.
1264 }
1265
1266 if ((unsigned)Val >= NumOperands-1) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001267 llvm_report_error("Invalid $ operand number in inline asm string: '"
1268 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 }
1270
1271 // Okay, we finally have a value number. Ask the target to print this
1272 // operand!
1273 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1274 unsigned OpNo = 1;
1275
1276 bool Error = false;
1277
1278 // Scan to find the machine operand number for the operand.
1279 for (; Val; --Val) {
1280 if (OpNo >= MI->getNumOperands()) break;
Chris Lattnerda4cff12007-12-30 20:50:28 +00001281 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Evan Cheng92167402009-03-20 18:03:34 +00001282 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 }
1284
1285 if (OpNo >= MI->getNumOperands()) {
1286 Error = true;
1287 } else {
Chris Lattnerda4cff12007-12-30 20:50:28 +00001288 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 ++OpNo; // Skip over the ID number.
1290
Chris Lattnerce409842010-01-17 21:43:43 +00001291 if (Modifier[0] == 'l') // labels are target independent
Chris Lattner84d5ca92010-01-26 04:55:51 +00001292 O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
Dale Johannesencfb19e62007-11-05 21:20:28 +00001293 else {
1294 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
Dale Johannesen94464072008-09-24 01:07:17 +00001295 if ((OpFlags & 7) == 4) {
Dale Johannesencfb19e62007-11-05 21:20:28 +00001296 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1297 Modifier[0] ? Modifier : 0);
1298 } else {
1299 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1300 Modifier[0] ? Modifier : 0);
1301 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 }
1303 }
1304 if (Error) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001305 std::string msg;
1306 raw_string_ostream Msg(msg);
Chris Lattnerce409842010-01-17 21:43:43 +00001307 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
Edwin Törökced9ff82009-07-11 13:10:19 +00001308 MI->print(Msg);
1309 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 }
1311 }
1312 break;
1313 }
1314 }
1315 }
Chris Lattner32d4cc72009-09-09 23:14:36 +00001316 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317}
1318
Evan Cheng3c0eda52008-03-15 00:03:38 +00001319/// printImplicitDef - This method prints the specified machine instruction
1320/// that is an implicit def.
1321void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
Chris Lattner32d4cc72009-09-09 23:14:36 +00001322 if (!VerboseAsm) return;
1323 O.PadToColumn(MAI->getCommentColumn());
1324 O << MAI->getCommentString() << " implicit-def: "
Chris Lattner28f7e352009-09-13 19:48:37 +00001325 << TRI->getName(MI->getOperand(0).getReg());
Evan Cheng3c0eda52008-03-15 00:03:38 +00001326}
1327
Jakob Stoklund Olesen7f251672009-11-04 19:24:37 +00001328void AsmPrinter::printKill(const MachineInstr *MI) const {
1329 if (!VerboseAsm) return;
1330 O.PadToColumn(MAI->getCommentColumn());
1331 O << MAI->getCommentString() << " kill:";
1332 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1333 const MachineOperand &op = MI->getOperand(n);
1334 assert(op.isReg() && "KILL instruction must have only register operands");
1335 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1336 }
1337}
1338
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339/// printLabel - This method prints a local label used by debug and
1340/// exception handling tables.
1341void AsmPrinter::printLabel(const MachineInstr *MI) const {
Dan Gohman7d546402008-07-01 00:16:26 +00001342 printLabel(MI->getOperand(0).getImm());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343}
1344
Evan Chenga53c40a2008-02-01 09:10:45 +00001345void AsmPrinter::printLabel(unsigned Id) const {
Chris Lattner32d4cc72009-09-09 23:14:36 +00001346 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
Evan Chenga53c40a2008-02-01 09:10:45 +00001347}
1348
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1350/// instruction, using the specified assembler variant. Targets should
Dale Johannesenc90c30b2010-01-14 21:50:17 +00001351/// override this to format as appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1353 unsigned AsmVariant, const char *ExtraCode) {
1354 // Target doesn't support this yet!
1355 return true;
1356}
1357
1358bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1359 unsigned AsmVariant,
1360 const char *ExtraCode) {
1361 // Target doesn't support this yet!
1362 return true;
1363}
1364
Dan Gohman885793b2009-11-20 23:18:13 +00001365MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1366 const char *Suffix) const {
1367 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
Dan Gohman91057512009-10-30 01:27:03 +00001368}
1369
1370MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
Dan Gohman885793b2009-11-20 23:18:13 +00001371 const BasicBlock *BB,
1372 const char *Suffix) const {
Dan Gohman91057512009-10-30 01:27:03 +00001373 assert(BB->hasName() &&
1374 "Address of anonymous basic block not supported yet!");
1375
Dan Gohmanff592ec2009-11-05 23:14:35 +00001376 // This code must use the function name itself, and not the function number,
1377 // since it must be possible to generate the label name from within other
1378 // functions.
Chris Lattner6be13f32010-01-13 07:30:49 +00001379 SmallString<60> FnName;
1380 Mang->getNameWithPrefix(FnName, F, false);
Dan Gohman91057512009-10-30 01:27:03 +00001381
Chris Lattner6be13f32010-01-13 07:30:49 +00001382 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
Chris Lattnera38b2872010-01-13 06:38:18 +00001383 SmallString<60> NameResult;
Chris Lattner6be13f32010-01-13 07:30:49 +00001384 Mang->getNameWithPrefix(NameResult,
1385 StringRef("BA") + Twine((unsigned)FnName.size()) +
1386 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1387 Mangler::Private);
Dan Gohmanff592ec2009-11-05 23:14:35 +00001388
Chris Lattnera38b2872010-01-13 06:38:18 +00001389 return OutContext.GetOrCreateSymbol(NameResult.str());
Dan Gohman91057512009-10-30 01:27:03 +00001390}
1391
Chris Lattner77e356c2010-01-23 05:19:23 +00001392/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1393MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1394 SmallString<60> Name;
1395 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1396 << getFunctionNumber() << '_' << CPID;
1397 return OutContext.GetOrCreateSymbol(Name.str());
1398}
1399
1400/// GetJTISymbol - Return the symbol for the specified jump table entry.
1401MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
Chris Lattner541d8902010-01-26 06:28:43 +00001402 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
Chris Lattner08c97082009-09-12 23:02:08 +00001403}
1404
Chris Lattnerda1416d2010-01-25 21:17:10 +00001405/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1406/// FIXME: privatize to AsmPrinter.
1407MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1408 SmallString<60> Name;
1409 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1410 << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1411 return OutContext.GetOrCreateSymbol(Name.str());
1412}
1413
Chris Lattner2eb781d2010-01-15 23:18:17 +00001414/// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1415/// value.
1416MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1417 SmallString<60> NameStr;
1418 Mang->getNameWithPrefix(NameStr, GV, false);
1419 return OutContext.GetOrCreateSymbol(NameStr.str());
1420}
1421
Chris Lattnera6f2a102010-01-16 18:37:32 +00001422/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
Chris Lattnerf7871d12010-01-15 23:25:11 +00001423/// global value name as its base, with the specified suffix, and where the
Chris Lattnera6f2a102010-01-16 18:37:32 +00001424/// symbol is forced to have private linkage if ForcePrivate is true.
1425MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1426 StringRef Suffix,
1427 bool ForcePrivate) const {
Chris Lattnerf7871d12010-01-15 23:25:11 +00001428 SmallString<60> NameStr;
Chris Lattnera6f2a102010-01-16 18:37:32 +00001429 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
Chris Lattnerf7871d12010-01-15 23:25:11 +00001430 NameStr.append(Suffix.begin(), Suffix.end());
1431 return OutContext.GetOrCreateSymbol(NameStr.str());
1432}
1433
Chris Lattner2eb781d2010-01-15 23:18:17 +00001434/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1435/// ExternalSymbol.
1436MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1437 SmallString<60> NameStr;
1438 Mang->getNameWithPrefix(NameStr, Sym);
1439 return OutContext.GetOrCreateSymbol(NameStr.str());
1440}
1441
Chris Lattner08c97082009-09-12 23:02:08 +00001442
Chris Lattner5abc72c2010-01-22 21:50:41 +00001443
1444/// PrintParentLoopComment - Print comments about parent loops of this one.
1445static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1446 unsigned FunctionNumber) {
1447 if (Loop == 0) return;
1448 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1449 OS.indent(Loop->getLoopDepth()*2)
1450 << "Parent Loop BB" << FunctionNumber << "_"
1451 << Loop->getHeader()->getNumber()
1452 << " Depth=" << Loop->getLoopDepth() << '\n';
1453}
1454
1455
1456/// PrintChildLoopComment - Print comments about child loops within
1457/// the loop for this basic block, with nesting.
1458static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1459 unsigned FunctionNumber) {
1460 // Add child loop information
1461 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1462 OS.indent((*CL)->getLoopDepth()*2)
1463 << "Child Loop BB" << FunctionNumber << "_"
1464 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1465 << '\n';
1466 PrintChildLoopComment(OS, *CL, FunctionNumber);
1467 }
1468}
1469
1470/// EmitComments - Pretty-print comments for basic blocks.
1471static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1472 const MachineLoopInfo *LI,
1473 const AsmPrinter &AP) {
1474 // Add loop depth information
1475 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1476 if (Loop == 0) return;
1477
1478 MachineBasicBlock *Header = Loop->getHeader();
1479 assert(Header && "No header for loop");
1480
1481 // If this block is not a loop header, just print out what is the loop header
1482 // and return.
1483 if (Header != &MBB) {
1484 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1485 Twine(AP.getFunctionNumber())+"_" +
1486 Twine(Loop->getHeader()->getNumber())+
1487 " Depth="+Twine(Loop->getLoopDepth()));
1488 return;
1489 }
1490
1491 // Otherwise, it is a loop header. Print out information about child and
1492 // parent loops.
1493 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1494
1495 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1496
1497 OS << "=>";
1498 OS.indent(Loop->getLoopDepth()*2-2);
1499
1500 OS << "This ";
1501 if (Loop->empty())
1502 OS << "Inner ";
1503 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1504
1505 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1506}
1507
1508
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001509/// EmitBasicBlockStart - This method prints the label for the specified
1510/// MachineBasicBlock, an alignment (if present) and a comment describing
1511/// it if appropriate.
Chris Lattnerda5fb6d2009-09-14 03:15:54 +00001512void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001513 // Emit an alignment directive for this block, if needed.
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001514 if (unsigned Align = MBB->getAlignment())
1515 EmitAlignment(Log2_32(Align));
Evan Cheng45c1edb2008-02-28 00:43:03 +00001516
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001517 // If the block has its address taken, emit a special label to satisfy
1518 // references to the block. This is done so that we don't need to
1519 // remember the number of this label, and so that we can make
1520 // forward references to labels without knowing what their numbers
1521 // will be.
Dan Gohman91057512009-10-30 01:27:03 +00001522 if (MBB->hasAddressTaken()) {
Chris Lattner8bae1052010-01-20 07:24:05 +00001523 const BasicBlock *BB = MBB->getBasicBlock();
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001524 if (VerboseAsm)
1525 OutStreamer.AddComment("Address Taken");
Chris Lattner8bae1052010-01-20 07:24:05 +00001526 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
Dan Gohman91057512009-10-30 01:27:03 +00001527 }
1528
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001529 // Print the main label for the block.
Dan Gohman5fda4342009-10-06 17:38:38 +00001530 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001531 if (VerboseAsm) {
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +00001532 // NOTE: Want this comment at start of line.
Dan Gohman5fda4342009-10-06 17:38:38 +00001533 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001534 if (const BasicBlock *BB = MBB->getBasicBlock())
1535 if (BB->hasName())
1536 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner82be51c2010-01-22 21:00:45 +00001537
Chris Lattner5abc72c2010-01-22 21:50:41 +00001538 PrintBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001539 OutStreamer.AddBlankLine();
1540 }
Dan Gohman5fda4342009-10-06 17:38:38 +00001541 } else {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001542 if (VerboseAsm) {
1543 if (const BasicBlock *BB = MBB->getBasicBlock())
1544 if (BB->hasName())
1545 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner5abc72c2010-01-22 21:50:41 +00001546 PrintBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001547 }
Chris Lattner82be51c2010-01-22 21:00:45 +00001548
Chris Lattner84d5ca92010-01-26 04:55:51 +00001549 OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
Dan Gohman5fda4342009-10-06 17:38:38 +00001550 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551}
1552
Chris Lattner10bcc6b2010-01-23 06:53:23 +00001553void AsmPrinter::printVisibility(MCSymbol *Sym, unsigned Visibility) const {
1554 MCSymbolAttr Attr = MCSA_Invalid;
1555
1556 switch (Visibility) {
1557 default: break;
1558 case GlobalValue::HiddenVisibility:
1559 Attr = MAI->getHiddenVisibilityAttr();
1560 break;
1561 case GlobalValue::ProtectedVisibility:
1562 Attr = MAI->getProtectedVisibilityAttr();
1563 break;
Chris Lattner67cce682010-01-15 23:38:51 +00001564 }
Chris Lattner10bcc6b2010-01-23 06:53:23 +00001565
1566 if (Attr != MCSA_Invalid)
1567 OutStreamer.EmitSymbolAttribute(Sym, Attr);
Chris Lattner67cce682010-01-15 23:38:51 +00001568}
1569
Anton Korobeynikov440f23d2008-11-22 16:15:34 +00001570void AsmPrinter::printOffset(int64_t Offset) const {
1571 if (Offset > 0)
1572 O << '+' << Offset;
1573 else if (Offset < 0)
1574 O << Offset;
1575}
1576
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001577GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1578 if (!S->usesMetadata())
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001579 return 0;
1580
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001581 gcp_iterator GCPI = GCMetadataPrinters.find(S);
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001582 if (GCPI != GCMetadataPrinters.end())
1583 return GCPI->second;
1584
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001585 const char *Name = S->getName().c_str();
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001586
1587 for (GCMetadataPrinterRegistry::iterator
1588 I = GCMetadataPrinterRegistry::begin(),
1589 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1590 if (strcmp(Name, I->getName()) == 0) {
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001591 GCMetadataPrinter *GMP = I->instantiate();
1592 GMP->S = S;
1593 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1594 return GMP;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001595 }
1596
Chris Lattner54bfda72010-01-23 06:17:14 +00001597 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1598 return 0;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001599}
David Greene63486122009-07-13 20:25:48 +00001600
1601/// EmitComments - Pretty-print comments for instructions
Chris Lattnerfdbeb812009-08-07 23:42:01 +00001602void AsmPrinter::EmitComments(const MachineInstr &MI) const {
David Greeneca9b04b2009-11-13 21:34:57 +00001603 if (!VerboseAsm)
1604 return;
David Greene4a37a692009-07-16 22:24:20 +00001605
David Greeneca9b04b2009-11-13 21:34:57 +00001606 bool Newline = false;
1607
1608 if (!MI.getDebugLoc().isUnknown()) {
Devang Patel042945f2010-01-16 06:09:35 +00001609 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
David Greeneca9b04b2009-11-13 21:34:57 +00001610
1611 // Print source line info.
1612 O.PadToColumn(MAI->getCommentColumn());
Dan Gohman4698bab2009-12-05 00:23:29 +00001613 O << MAI->getCommentString() << ' ';
Devang Patel042945f2010-01-16 06:09:35 +00001614 DIScope Scope = DLT.getScope();
Dan Gohman4698bab2009-12-05 00:23:29 +00001615 // Omit the directory, because it's likely to be long and uninteresting.
1616 if (!Scope.isNull())
1617 O << Scope.getFilename();
1618 else
1619 O << "<unknown>";
Devang Patel042945f2010-01-16 06:09:35 +00001620 O << ':' << DLT.getLineNumber();
1621 if (DLT.getColumnNumber() != 0)
1622 O << ':' << DLT.getColumnNumber();
David Greeneca9b04b2009-11-13 21:34:57 +00001623 Newline = true;
David Greene4a37a692009-07-16 22:24:20 +00001624 }
David Greeneca9b04b2009-11-13 21:34:57 +00001625
David Greene2e7b9932009-11-16 15:12:23 +00001626 // Check for spills and reloads
1627 int FI;
1628
1629 const MachineFrameInfo *FrameInfo =
1630 MI.getParent()->getParent()->getFrameInfo();
1631
1632 // We assume a single instruction only has a spill or reload, not
1633 // both.
David Greene11a046f12009-12-04 22:46:04 +00001634 const MachineMemOperand *MMO;
David Greene2e7b9932009-11-16 15:12:23 +00001635 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1636 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
David Greene11a046f12009-12-04 22:46:04 +00001637 MMO = *MI.memoperands_begin();
David Greene2e7b9932009-11-16 15:12:23 +00001638 if (Newline) O << '\n';
1639 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001640 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
David Greene2e7b9932009-11-16 15:12:23 +00001641 Newline = true;
1642 }
1643 }
David Greene11a046f12009-12-04 22:46:04 +00001644 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
David Greene2e7b9932009-11-16 15:12:23 +00001645 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1646 if (Newline) O << '\n';
1647 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001648 O << MAI->getCommentString() << ' '
1649 << MMO->getSize() << "-byte Folded Reload";
David Greene2e7b9932009-11-16 15:12:23 +00001650 Newline = true;
1651 }
1652 }
1653 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1654 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
David Greene11a046f12009-12-04 22:46:04 +00001655 MMO = *MI.memoperands_begin();
David Greene2e7b9932009-11-16 15:12:23 +00001656 if (Newline) O << '\n';
1657 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001658 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
David Greene2e7b9932009-11-16 15:12:23 +00001659 Newline = true;
1660 }
1661 }
David Greene11a046f12009-12-04 22:46:04 +00001662 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
David Greene2e7b9932009-11-16 15:12:23 +00001663 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1664 if (Newline) O << '\n';
1665 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001666 O << MAI->getCommentString() << ' '
1667 << MMO->getSize() << "-byte Folded Spill";
David Greene2e7b9932009-11-16 15:12:23 +00001668 Newline = true;
1669 }
1670 }
1671
1672 // Check for spill-induced copies
1673 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1674 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1675 SrcSubIdx, DstSubIdx)) {
1676 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1677 if (Newline) O << '\n';
1678 O.PadToColumn(MAI->getCommentColumn());
1679 O << MAI->getCommentString() << " Reload Reuse";
David Greene2e7b9932009-11-16 15:12:23 +00001680 }
1681 }
David Greene63486122009-07-13 20:25:48 +00001682}
1683