blob: 3d2f415741399c40528ce6e283df7579d8182029 [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"
David Greene4a37a692009-07-16 22:24:20 +000029#include "llvm/MC/MCInst.h"
Chris Lattnere6ad12f2009-07-31 18:48:30 +000030#include "llvm/MC/MCSection.h"
31#include "llvm/MC/MCStreamer.h"
Chris Lattner08c97082009-09-12 23:02:08 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng42ceb472009-03-25 01:47:28 +000033#include "llvm/Support/CommandLine.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc006e1c2010-01-22 19:52:01 +000035#include "llvm/Support/Format.h"
David Greene63486122009-07-13 20:25:48 +000036#include "llvm/Support/FormattedStream.h"
Chris Lattner621c44d2009-08-22 20:48:53 +000037#include "llvm/MC/MCAsmInfo.h"
Chris Lattner31a54742010-01-16 21:57:06 +000038#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/Target/TargetData.h"
David Greeneca9b04b2009-11-13 21:34:57 +000040#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/Target/TargetLowering.h"
Chris Lattnerc4c40a92009-07-28 03:13:23 +000042#include "llvm/Target/TargetLoweringObjectFile.h"
Evan Cheng0eeed442008-07-01 23:18:29 +000043#include "llvm/Target/TargetOptions.h"
Evan Cheng3c0eda52008-03-15 00:03:38 +000044#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng6fb06762007-11-09 01:32:10 +000045#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner89b36582008-08-17 07:19:36 +000046#include "llvm/ADT/SmallString.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include <cerrno>
48using namespace llvm;
49
Evan Cheng42ceb472009-03-25 01:47:28 +000050static cl::opt<cl::boolOrDefault>
51AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52 cl::init(cl::BOU_UNSET));
53
Chris Lattner1ab24612010-01-22 07:06:15 +000054static bool getVerboseAsm(bool VDef) {
55 switch (AsmVerbose) {
56 default:
57 case cl::BOU_UNSET: return VDef;
58 case cl::BOU_TRUE: return true;
59 case cl::BOU_FALSE: return false;
60 }
61}
62
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063char AsmPrinter::ID = 0;
David Greene302008d2009-07-14 20:18:05 +000064AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
Chris Lattner621c44d2009-08-22 20:48:53 +000065 const MCAsmInfo *T, bool VDef)
Daniel Dunbarb10d2222009-07-01 01:48:54 +000066 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
Chris Lattnera5ef4d32009-08-22 21:43:10 +000067 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
Chris Lattner1eb0ad02009-07-27 21:28:04 +000068
69 OutContext(*new MCContext()),
Chris Lattnera835afd2009-09-14 03:02:37 +000070 // FIXME: Pass instprinter to streamer.
Chris Lattner92c78e82010-01-20 06:39:07 +000071 OutStreamer(*createAsmStreamer(OutContext, O, *T,
Chris Lattner1ab24612010-01-22 07:06:15 +000072 TM.getTargetData()->isLittleEndian(),
73 getVerboseAsm(VDef), 0)),
Chris Lattner1eb0ad02009-07-27 21:28:04 +000074
Devang Patel042945f2010-01-16 06:09:35 +000075 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
Chris Lattner2424eac2009-06-24 19:09:55 +000076 DW = 0; MMI = 0;
Chris Lattner1ab24612010-01-22 07:06:15 +000077 VerboseAsm = getVerboseAsm(VDef);
Evan Cheng42ceb472009-03-25 01:47:28 +000078}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000080AsmPrinter::~AsmPrinter() {
81 for (gcp_iterator I = GCMetadataPrinters.begin(),
82 E = GCMetadataPrinters.end(); I != E; ++I)
83 delete I->second;
Chris Lattner1eb0ad02009-07-27 21:28:04 +000084
85 delete &OutStreamer;
86 delete &OutContext;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000087}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Chris Lattner75bdd292009-08-03 19:12:26 +000089TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Chris Lattnerc4c40a92009-07-28 03:13:23 +000090 return TM.getTargetLowering()->getObjFileLowering();
91}
92
Chris Lattnerd69d8ad2009-08-18 06:15:16 +000093/// getCurrentSection() - Return the current section we are emitting to.
94const MCSection *AsmPrinter::getCurrentSection() const {
95 return OutStreamer.getCurrentSection();
96}
97
98
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000099void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000100 AU.setPreservesAll();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000101 MachineFunctionPass::getAnalysisUsage(AU);
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000102 AU.addRequired<GCModuleInfo>();
David Greene066ed6a2009-08-18 19:22:55 +0000103 if (VerboseAsm)
David Greenee52fd872009-08-10 16:38:07 +0000104 AU.addRequired<MachineLoopInfo>();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000105}
106
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107bool AsmPrinter::doInitialization(Module &M) {
Chris Lattner01316272009-07-31 17:42:42 +0000108 // Initialize TargetLoweringObjectFile.
109 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
110 .Initialize(OutContext, TM);
111
Chris Lattner63ab9bb2010-01-17 18:22:35 +0000112 Mang = new Mangler(*MAI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000114 // Allow the target to emit any magic that it wants at the start of the file.
115 EmitStartOfAsmFile(M);
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000116
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000117 if (MAI->hasSingleParameterDotFile()) {
Chris Lattner77e356c2010-01-23 05:19:23 +0000118 // Very minimal debug info. It is ignored if we emit actual
119 // debug info. If we don't, this at least helps the user find where
120 // a function came from.
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000121 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
122 }
123
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000124 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
125 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000126 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
127 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000128 MP->beginAssembly(O, *this, *MAI);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000129
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 if (!M.getModuleInlineAsm().empty())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000131 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 << M.getModuleInlineAsm()
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000133 << '\n' << MAI->getCommentString()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 << " End of file scope inline assembly\n";
135
Chris Lattnerc73e8eb2009-09-24 05:44:53 +0000136 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137 if (MMI)
138 MMI->AnalyzeModule(M);
139 DW = getAnalysisIfAvailable<DwarfWriter>();
Sanjiv Gupta5461b522009-11-14 07:22:25 +0000140 if (DW)
Chris Lattnerc73e8eb2009-09-24 05:44:53 +0000141 DW->BeginModule(&M, MMI, O, this, MAI);
Devang Patel1a454842009-06-19 21:54:26 +0000142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143 return false;
144}
145
Chris Lattnerd9609472010-01-19 04:39:15 +0000146/// EmitGlobalVariable - Emit the specified global variable to the .s file.
147void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
148 if (!GV->hasInitializer()) // External globals require no code.
149 return;
150
151 // Check to see if this is a special global used by LLVM, if so, emit it.
152 if (EmitSpecialLLVMGlobal(GV))
153 return;
Chris Lattner410c9472010-01-19 05:38:33 +0000154
155 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
156 printVisibility(GVSym, GV->getVisibility());
157
158 if (MAI->hasDotTypeDotSizeDirective()) {
159 O << "\t.type\t" << *GVSym;
160 if (MAI->getCommentString()[0] != '@')
161 O << ",@object\n";
162 else
163 O << ",%object\n";
164 }
Chris Lattnerd9609472010-01-19 04:39:15 +0000165
Chris Lattner410c9472010-01-19 05:38:33 +0000166 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
167
168 const TargetData *TD = TM.getTargetData();
169 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
170 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
171
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000172 // Handle common and BSS local symbols (.lcomm).
173 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner410c9472010-01-19 05:38:33 +0000174 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
175
Chris Lattner410c9472010-01-19 05:38:33 +0000176 if (VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000177 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
178 /*PrintType=*/false, GV->getParent());
179 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000180 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000181
182 // Handle common symbols.
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000183 if (GVKind.isCommon()) {
184 // .comm _foo, 42, 4
Chris Lattnerecf1cdc2010-01-19 06:01:04 +0000185 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000186 return;
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000187 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000188
189 // Handle local BSS symbols.
190 if (MAI->hasMachoZeroFillDirective()) {
191 const MCSection *TheSection =
192 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
193 // .zerofill __DATA, __bss, _foo, 400, 5
194 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
195 return;
196 }
197
198 if (const char *LComm = MAI->getLCOMMDirective()) {
199 // .lcomm _foo, 42
Chris Lattner77e356c2010-01-23 05:19:23 +0000200 O << LComm << *GVSym << ',' << Size << '\n';
Chris Lattnerf26c7792010-01-19 06:25:51 +0000201 return;
202 }
203
204 // .local _foo
Chris Lattner77e356c2010-01-23 05:19:23 +0000205 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Local);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000206 // .comm _foo, 42, 4
207 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattner410c9472010-01-19 05:38:33 +0000208 return;
209 }
210
211 const MCSection *TheSection =
212 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
213
214 // Handle the zerofill directive on darwin, which is a special form of BSS
215 // emission.
216 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
217 // .globl _foo
218 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
219 // .zerofill __DATA, __common, _foo, 400, 5
220 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
221 return;
222 }
223
224 OutStreamer.SwitchSection(TheSection);
225
226 // TODO: Factor into an 'emit linkage' thing that is shared with function
227 // bodies.
228 switch (GV->getLinkage()) {
229 case GlobalValue::CommonLinkage:
230 case GlobalValue::LinkOnceAnyLinkage:
231 case GlobalValue::LinkOnceODRLinkage:
232 case GlobalValue::WeakAnyLinkage:
233 case GlobalValue::WeakODRLinkage:
234 case GlobalValue::LinkerPrivateLinkage:
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000235 if (MAI->getWeakDefDirective() != 0) {
Chris Lattner410c9472010-01-19 05:38:33 +0000236 // .globl _foo
237 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
238 // .weak_definition _foo
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000239 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
Chris Lattner410c9472010-01-19 05:38:33 +0000240 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
241 // .globl _foo
242 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
243 // .linkonce same_size
244 O << LinkOnce;
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000245 } else {
246 // .weak _foo
247 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
248 }
Chris Lattner410c9472010-01-19 05:38:33 +0000249 break;
250 case GlobalValue::DLLExportLinkage:
251 case GlobalValue::AppendingLinkage:
252 // FIXME: appending linkage variables should go into a section of
253 // their name or something. For now, just emit them as external.
254 case GlobalValue::ExternalLinkage:
255 // If external or appending, declare as a global symbol.
256 // .globl _foo
257 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
258 break;
259 case GlobalValue::PrivateLinkage:
260 case GlobalValue::InternalLinkage:
261 break;
262 default:
263 llvm_unreachable("Unknown linkage type!");
264 }
265
266 EmitAlignment(AlignLog, GV);
Chris Lattner410c9472010-01-19 05:38:33 +0000267 if (VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000268 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
269 /*PrintType=*/false, GV->getParent());
270 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000271 }
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000272 OutStreamer.EmitLabel(GVSym);
Chris Lattner410c9472010-01-19 05:38:33 +0000273
274 EmitGlobalConstant(GV->getInitializer());
275
276 if (MAI->hasDotTypeDotSizeDirective())
277 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000278
279 OutStreamer.AddBlankLine();
Chris Lattnerd9609472010-01-19 04:39:15 +0000280}
281
282
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283bool AsmPrinter::doFinalization(Module &M) {
Chris Lattnerae982212009-07-21 18:38:57 +0000284 // Emit global variables.
285 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
286 I != E; ++I)
Chris Lattnerd9609472010-01-19 04:39:15 +0000287 EmitGlobalVariable(I);
Chris Lattnerae982212009-07-21 18:38:57 +0000288
Chris Lattnere1225cc2009-06-24 18:54:37 +0000289 // Emit final debug information.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000290 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
Chris Lattnere1225cc2009-06-24 18:54:37 +0000291 DW->EndModule();
292
Chris Lattnerdb191f02009-06-24 18:52:01 +0000293 // If the target wants to know about weak references, print them all.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000294 if (MAI->getWeakRefDirective()) {
Chris Lattnerdb191f02009-06-24 18:52:01 +0000295 // FIXME: This is not lazy, it would be nice to only print weak references
296 // to stuff that is actually used. Note that doing so would require targets
297 // to notice uses in operands (due to constant exprs etc). This should
298 // happen with the MC stuff eventually.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299
Chris Lattnerdb191f02009-06-24 18:52:01 +0000300 // Print out module-level global variables here.
301 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
302 I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000303 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattner77e356c2010-01-23 05:19:23 +0000304 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
305 MCStreamer::WeakReference);
Chris Lattnerdb191f02009-06-24 18:52:01 +0000306 }
307
Chris Lattner0f98c332009-08-03 23:10:34 +0000308 for (Module::const_iterator I = M.begin(), E = M.end(); 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),
311 MCStreamer::WeakReference);
Chris Lattnerdb191f02009-06-24 18:52:01 +0000312 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 }
314
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000315 if (MAI->getSetDirective()) {
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000316 O << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
Chris Lattnerdb191f02009-06-24 18:52:01 +0000318 I != E; ++I) {
Chris Lattnerc0c8d7d2010-01-16 01:17:26 +0000319 MCSymbol *Name = GetGlobalValueSymbol(I);
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000320
321 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
Chris Lattnerc0c8d7d2010-01-16 01:17:26 +0000322 MCSymbol *Target = GetGlobalValueSymbol(GV);
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000323
Chris Lattnerce409842010-01-17 21:43:43 +0000324 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
Chris Lattner77e356c2010-01-23 05:19:23 +0000325 OutStreamer.EmitSymbolAttribute(Name, MCStreamer::Global);
Chris Lattnerce409842010-01-17 21:43:43 +0000326 else if (I->hasWeakLinkage())
Chris Lattner77e356c2010-01-23 05:19:23 +0000327 OutStreamer.EmitSymbolAttribute(Name, MCStreamer::WeakReference);
Chris Lattnerce409842010-01-17 21:43:43 +0000328 else
Chris Lattner1ff31942010-01-16 01:37:14 +0000329 assert(I->hasLocalLinkage() && "Invalid alias linkage");
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000330
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000331 printVisibility(Name, I->getVisibility());
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000332
Chris Lattnerce409842010-01-17 21:43:43 +0000333 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 }
335 }
336
Duncan Sands4e0d6a72009-01-28 13:14:17 +0000337 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000338 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
339 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
340 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000341 MP->finishAssembly(O, *this, *MAI);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000342
Dan Gohmana65530a2008-05-05 00:28:39 +0000343 // If we don't have any trampolines, then we don't require stack memory
344 // to be executable. Some targets have a directive to declare this.
Chris Lattnerdb191f02009-06-24 18:52:01 +0000345 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
Dan Gohmana65530a2008-05-05 00:28:39 +0000346 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Chris Lattner77e356c2010-01-23 05:19:23 +0000347 // FIXME: This is actually a section switch on linux/x86 and systemz, use
348 // switch section.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000349 if (MAI->getNonexecutableStackDirective())
350 O << MAI->getNonexecutableStackDirective() << '\n';
Dan Gohmana65530a2008-05-05 00:28:39 +0000351
Chris Lattnerb6113072009-09-18 20:17:03 +0000352
353 // Allow the target to emit any magic that it wants at the end of the file,
354 // after everything else has gone out.
355 EmitEndOfAsmFile(M);
356
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 delete Mang; Mang = 0;
Chris Lattner2424eac2009-06-24 19:09:55 +0000358 DW = 0; MMI = 0;
Chris Lattner1eb0ad02009-07-27 21:28:04 +0000359
360 OutStreamer.Finish();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 return false;
362}
363
364void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
Chris Lattnerac5a6ad2010-01-16 01:24:10 +0000365 // Get the function symbol.
Chris Lattner8d656d92010-01-15 23:55:16 +0000366 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
Evan Cheng477013c2007-10-14 05:57:21 +0000367 IncrementFunctionNumber();
David Greenee52fd872009-08-10 16:38:07 +0000368
Chris Lattner57c76b52009-09-16 00:35:39 +0000369 if (VerboseAsm)
David Greenee52fd872009-08-10 16:38:07 +0000370 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371}
372
Evan Cheng68c18682009-03-13 07:51:59 +0000373namespace {
374 // SectionCPs - Keep track the alignment, constpool entries per Section.
375 struct SectionCPs {
Chris Lattnere6ad12f2009-07-31 18:48:30 +0000376 const MCSection *S;
Evan Cheng68c18682009-03-13 07:51:59 +0000377 unsigned Alignment;
378 SmallVector<unsigned, 4> CPEs;
Douglas Gregor8cb41382009-12-19 07:05:23 +0000379 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
Evan Cheng68c18682009-03-13 07:51:59 +0000380 };
381}
382
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383/// EmitConstantPool - Print to the current output stream assembly
384/// representations of the constants in the constant pool MCP. This is
385/// used to print out constants which have been "spilled to memory" by
386/// the code generator.
387///
388void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
389 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
390 if (CP.empty()) return;
391
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000392 // Calculate sections for constant pool entries. We collect entries to go into
393 // the same section together to reduce amount of section switch statements.
Evan Cheng68c18682009-03-13 07:51:59 +0000394 SmallVector<SectionCPs, 4> CPSections;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Chris Lattner680c6f62009-07-22 00:28:43 +0000396 const MachineConstantPoolEntry &CPE = CP[i];
Evan Cheng68c18682009-03-13 07:51:59 +0000397 unsigned Align = CPE.getAlignment();
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000398
399 SectionKind Kind;
400 switch (CPE.getRelocationInfo()) {
401 default: llvm_unreachable("Unknown section kind");
Chris Lattnera9453412009-08-01 23:57:16 +0000402 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000403 case 1:
Chris Lattnera9453412009-08-01 23:57:16 +0000404 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattnered0c6762009-07-26 07:00:12 +0000405 break;
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000406 case 0:
Chris Lattnered0c6762009-07-26 07:00:12 +0000407 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
Chris Lattnera9453412009-08-01 23:57:16 +0000408 case 4: Kind = SectionKind::getMergeableConst4(); break;
409 case 8: Kind = SectionKind::getMergeableConst8(); break;
410 case 16: Kind = SectionKind::getMergeableConst16();break;
411 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000412 }
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000413 }
414
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000415 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Chris Lattner680c6f62009-07-22 00:28:43 +0000416
Evan Cheng68c18682009-03-13 07:51:59 +0000417 // The number of sections are small, just do a linear search from the
418 // last section to the first.
419 bool Found = false;
420 unsigned SecIdx = CPSections.size();
421 while (SecIdx != 0) {
422 if (CPSections[--SecIdx].S == S) {
423 Found = true;
424 break;
425 }
426 }
427 if (!Found) {
428 SecIdx = CPSections.size();
429 CPSections.push_back(SectionCPs(S, Align));
430 }
431
432 if (Align > CPSections[SecIdx].Alignment)
433 CPSections[SecIdx].Alignment = Align;
434 CPSections[SecIdx].CPEs.push_back(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 }
436
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000437 // Now print stuff into the calculated sections.
Evan Cheng68c18682009-03-13 07:51:59 +0000438 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
Chris Lattner73266f92009-08-19 05:49:37 +0000439 OutStreamer.SwitchSection(CPSections[i].S);
Evan Cheng68c18682009-03-13 07:51:59 +0000440 EmitAlignment(Log2_32(CPSections[i].Alignment));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441
Evan Cheng68c18682009-03-13 07:51:59 +0000442 unsigned Offset = 0;
443 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
444 unsigned CPI = CPSections[i].CPEs[j];
445 MachineConstantPoolEntry CPE = CP[CPI];
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000446
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447 // Emit inter-object padding for alignment.
Evan Cheng68c18682009-03-13 07:51:59 +0000448 unsigned AlignMask = CPE.getAlignment() - 1;
449 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
Chris Lattnera71dc602010-01-19 19:46:13 +0000450 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
Evan Cheng68c18682009-03-13 07:51:59 +0000451
452 const Type *Ty = CPE.getType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000453 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
Evan Cheng68c18682009-03-13 07:51:59 +0000454
Chris Lattner77e356c2010-01-23 05:19:23 +0000455 // Emit the label with a comment on it.
Evan Cheng68c18682009-03-13 07:51:59 +0000456 if (VerboseAsm) {
Chris Lattner77e356c2010-01-23 05:19:23 +0000457 OutStreamer.GetCommentOS() << "constant pool ";
458 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
459 MF->getFunction()->getParent());
460 OutStreamer.GetCommentOS() << '\n';
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000461 }
Chris Lattner77e356c2010-01-23 05:19:23 +0000462 OutStreamer.EmitLabel(GetCPISymbol(CPI));
463
Evan Cheng68c18682009-03-13 07:51:59 +0000464 if (CPE.isMachineConstantPoolEntry())
465 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
466 else
467 EmitGlobalConstant(CPE.Val.ConstVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 }
469 }
470}
471
472/// EmitJumpTableInfo - Print assembly representations of the jump tables used
473/// by the current function to the current output stream.
474///
475void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
476 MachineFunction &MF) {
477 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
478 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000479
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
481
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 // Pick the directive to use to print the jump table entries, and switch to
483 // the appropriate section.
484 TargetLowering *LoweringInfo = TM.getTargetLowering();
485
Anton Korobeynikov7f3fa2c2008-07-09 13:27:16 +0000486 const Function *F = MF.getFunction();
Evan Chengccca6f72009-06-18 20:37:15 +0000487 bool JTInDiffSection = false;
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000488 if (F->isWeakForLinker() ||
489 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 // In PIC mode, we need to emit the jump table to the same section as the
491 // function body itself, otherwise the label differences won't make sense.
Anton Korobeynikov7f3fa2c2008-07-09 13:27:16 +0000492 // We should also do if the section name is NULL or function is declared in
493 // discardable section.
Chris Lattner73266f92009-08-19 05:49:37 +0000494 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
495 TM));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 } else {
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000497 // Otherwise, drop it in the readonly section.
498 const MCSection *ReadOnlySection =
Chris Lattnera9453412009-08-01 23:57:16 +0000499 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
Chris Lattner73266f92009-08-19 05:49:37 +0000500 OutStreamer.SwitchSection(ReadOnlySection);
Evan Chengccca6f72009-06-18 20:37:15 +0000501 JTInDiffSection = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 }
503
504 EmitAlignment(Log2_32(MJTI->getAlignment()));
505
506 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
507 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
508
509 // If this jump table was deleted, ignore it.
510 if (JTBBs.empty()) continue;
511
512 // For PIC codegen, if possible we want to use the SetDirective to reduce
513 // the number of relocations the assembler will generate for the jump table.
514 // Set directives are all printed before the jump table itself.
Evan Cheng6fb06762007-11-09 01:32:10 +0000515 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000516 if (MAI->getSetDirective() && IsPic)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Evan Cheng6fb06762007-11-09 01:32:10 +0000518 if (EmittedSets.insert(JTBBs[ii]))
519 printPICJumpTableSetLabel(i, JTBBs[ii]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520
Chris Lattner149495f2009-09-13 19:02:16 +0000521 // On some targets (e.g. Darwin) we want to emit two consequtive labels
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 // before each jump table. The first label is never referenced, but tells
523 // the assembler and linker the extents of the jump table object. The
524 // second label is actually referenced by the code.
Chris Lattner77e356c2010-01-23 05:19:23 +0000525 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
526 OutStreamer.EmitLabel(GetJTISymbol(i, true));
527
528 OutStreamer.EmitLabel(GetJTISymbol(i));
529
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000531 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 O << '\n';
533 }
534 }
535}
536
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000537void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
538 const MachineBasicBlock *MBB,
539 unsigned uid) const {
Chris Lattner3fb451e2009-08-11 20:29:57 +0000540 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000541
542 // Use JumpTableDirective otherwise honor the entry size from the jump table
543 // info.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000544 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000545 bool HadJTEntryDirective = JTEntryDirective != NULL;
546 if (!HadJTEntryDirective) {
547 JTEntryDirective = MJTI->getEntrySize() == 4 ?
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000548 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000549 }
550
551 O << JTEntryDirective << ' ';
552
553 // If we have emitted set directives for the jump table entries, print
554 // them rather than the entries themselves. If we're emitting PIC, then
555 // emit the table entries as differences between two text section labels.
556 // If we're emitting non-PIC code, then emit the entries as direct
557 // references to the target basic blocks.
Chris Lattner3fb451e2009-08-11 20:29:57 +0000558 if (!isPIC) {
Chris Lattnerce409842010-01-17 21:43:43 +0000559 O << *GetMBBSymbol(MBB->getNumber());
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000560 } else if (MAI->getSetDirective()) {
561 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
Chris Lattner3fb451e2009-08-11 20:29:57 +0000562 << '_' << uid << "_set_" << MBB->getNumber();
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000563 } else {
Chris Lattnerce409842010-01-17 21:43:43 +0000564 O << *GetMBBSymbol(MBB->getNumber());
Chris Lattner3fb451e2009-08-11 20:29:57 +0000565 // If the arch uses custom Jump Table directives, don't calc relative to
566 // JT
567 if (!HadJTEntryDirective)
Chris Lattner77e356c2010-01-23 05:19:23 +0000568 O << '-' << *GetJTISymbol(uid);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000569 }
570}
571
572
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
574/// special global used by LLVM. If so, emit it and return true, otherwise
575/// do nothing and return false.
576bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Daniel Dunbare03513b2009-07-25 23:55:21 +0000577 if (GV->getName() == "llvm.used") {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000578 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000579 EmitLLVMUsedList(GV->getInitializer());
580 return true;
581 }
582
Chris Lattner1e0e0d12009-07-20 06:14:25 +0000583 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
Chris Lattner68433442009-04-13 05:44:34 +0000584 if (GV->getSection() == "llvm.metadata" ||
585 GV->hasAvailableExternallyLinkage())
586 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587
588 if (!GV->hasAppendingLinkage()) return false;
589
590 assert(GV->hasInitializer() && "Not a special LLVM global!");
591
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592 const TargetData *TD = TM.getTargetData();
593 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
Chris Lattner0c433e92009-03-09 05:52:15 +0000594 if (GV->getName() == "llvm.global_ctors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000595 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000596 EmitAlignment(Align, 0);
597 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000598
599 if (TM.getRelocationModel() == Reloc::Static &&
600 MAI->hasStaticCtorDtorReferenceInStaticMode())
601 O << ".reference .constructors_used\n";
Chris Lattner1e0e4892009-03-09 08:18:48 +0000602 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 }
604
Chris Lattner0c433e92009-03-09 05:52:15 +0000605 if (GV->getName() == "llvm.global_dtors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000606 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000607 EmitAlignment(Align, 0);
608 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000609
610 if (TM.getRelocationModel() == Reloc::Static &&
611 MAI->hasStaticCtorDtorReferenceInStaticMode())
612 O << ".reference .destructors_used\n";
Chris Lattner1e0e4892009-03-09 08:18:48 +0000613 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 }
615
616 return false;
617}
618
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000619/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
Dale Johannesen60567622008-09-09 22:29:13 +0000620/// global in the specified llvm.used list for which emitUsedDirectiveFor
621/// is true, as being used with this directive.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622void AsmPrinter::EmitLLVMUsedList(Constant *List) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000623 const char *Directive = MAI->getUsedDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624
Dan Gohman9e1657f2009-06-14 23:30:43 +0000625 // Should be an array of 'i8*'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
627 if (InitList == 0) return;
628
629 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner3f621b32009-07-17 22:00:23 +0000630 const GlobalValue *GV =
631 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
Chris Lattner84362ac2009-07-31 20:52:39 +0000632 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
Dale Johannesen4911fb82008-09-03 20:34:58 +0000633 O << Directive;
634 EmitConstantValueOnly(InitList->getOperand(i));
635 O << '\n';
636 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 }
638}
639
640/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
641/// function pointers, ignoring the init priority.
642void AsmPrinter::EmitXXStructorList(Constant *List) {
643 // Should be an array of '{ int, void ()* }' structs. The first value is the
644 // init priority, which we ignore.
645 if (!isa<ConstantArray>(List)) return;
646 ConstantArray *InitList = cast<ConstantArray>(List);
647 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
648 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
649 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
650
651 if (CS->getOperand(1)->isNullValue())
652 return; // Found a null terminator, exit printing.
653 // Emit the function pointer.
654 EmitGlobalConstant(CS->getOperand(1));
655 }
656}
657
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658//===--------------------------------------------------------------------===//
659// Emission and print routines
660//
661
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662/// EmitInt8 - Emit a byte directive and value.
663///
664void AsmPrinter::EmitInt8(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000665 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666}
667
668/// EmitInt16 - Emit a short directive and value.
669///
670void AsmPrinter::EmitInt16(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000671 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672}
673
674/// EmitInt32 - Emit a long directive and value.
675///
676void AsmPrinter::EmitInt32(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000677 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678}
679
680/// EmitInt64 - Emit a long long directive and value.
681///
682void AsmPrinter::EmitInt64(uint64_t Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000683 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684}
685
Chris Lattnera68112c2010-01-23 04:54:10 +0000686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687/// toOctal - Convert the low order bits of X into an octal digit.
688///
689static inline char toOctal(int X) {
690 return (X&7)+'0';
691}
692
693/// printStringChar - Print a char, escaped if necessary.
694///
David Greene302008d2009-07-14 20:18:05 +0000695static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 if (C == '"') {
697 O << "\\\"";
698 } else if (C == '\\') {
699 O << "\\\\";
Chris Lattner07ec1462009-01-22 23:38:45 +0000700 } else if (isprint((unsigned char)C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 O << C;
702 } else {
703 switch(C) {
704 case '\b': O << "\\b"; break;
705 case '\f': O << "\\f"; break;
706 case '\n': O << "\\n"; break;
707 case '\r': O << "\\r"; break;
708 case '\t': O << "\\t"; break;
709 default:
710 O << '\\';
711 O << toOctal(C >> 6);
712 O << toOctal(C >> 3);
713 O << toOctal(C >> 0);
714 break;
715 }
716 }
717}
718
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000719/// EmitFile - Emit a .file directive.
Benjamin Kramer0ad2db92010-01-17 07:46:39 +0000720void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000721 O << "\t.file\t" << Number << " \"";
Chris Lattnere2d4bf72009-04-08 00:28:38 +0000722 for (unsigned i = 0, N = Name.size(); i < N; ++i)
723 printStringChar(O, Name[i]);
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000724 O << '\"';
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000725}
726
727
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728//===----------------------------------------------------------------------===//
729
730// EmitAlignment - Emit an alignment directive to the specified power of
731// two boundary. For example, if you pass in 3 here, you will get an 8
732// byte alignment. If a global value is specified, and if that global has
733// an explicit alignment requested, it will unconditionally override the
734// alignment request. However, if ForcedAlignBits is specified, this value
735// has final say: the ultimate alignment will be the max of ForcedAlignBits
736// and the alignment computed with NumBits and the global.
737//
738// The algorithm is:
739// Align = NumBits;
740// if (GV && GV->hasalignment) Align = GV->getalignment();
741// Align = std::max(Align, ForcedAlignBits);
742//
743void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Cheng7e7d1942008-02-29 19:36:59 +0000744 unsigned ForcedAlignBits,
745 bool UseFillExpr) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 if (GV && GV->getAlignment())
747 NumBits = Log2_32(GV->getAlignment());
748 NumBits = std::max(NumBits, ForcedAlignBits);
749
750 if (NumBits == 0) return; // No need to emit alignment.
Chris Lattner4891d142009-08-19 06:12:02 +0000751
752 unsigned FillValue = 0;
Chris Lattnerd69d8ad2009-08-18 06:15:16 +0000753 if (getCurrentSection()->getKind().isText())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000754 FillValue = MAI->getTextAlignFillValue();
Chris Lattner4891d142009-08-19 06:12:02 +0000755
756 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757}
David Greenecdc2de32009-08-05 21:00:52 +0000758
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759// Print out the specified constant, without a storage class. Only the
760// constants valid in constant expressions can occur here.
761void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
Chris Lattner458c8772010-01-13 04:29:19 +0000762 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000763 O << '0';
Chris Lattner458c8772010-01-13 04:29:19 +0000764 return;
765 }
766
767 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Scott Michel2c1d0552008-06-03 06:18:19 +0000768 O << CI->getZExtValue();
Chris Lattner458c8772010-01-13 04:29:19 +0000769 return;
770 }
771
772 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 // This is a constant address for a global variable or function. Use the
Chris Lattner36d03292009-09-15 23:11:32 +0000774 // name of the variable or function as the address value.
Chris Lattnerce409842010-01-17 21:43:43 +0000775 O << *GetGlobalValueSymbol(GV);
Chris Lattner458c8772010-01-13 04:29:19 +0000776 return;
777 }
778
779 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
Chris Lattnerce409842010-01-17 21:43:43 +0000780 O << *GetBlockAddressSymbol(BA);
Chris Lattner458c8772010-01-13 04:29:19 +0000781 return;
782 }
783
784 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
785 if (CE == 0) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000786 llvm_unreachable("Unknown constant value!");
Chris Lattner458c8772010-01-13 04:29:19 +0000787 O << '0';
788 return;
789 }
790
791 switch (CE->getOpcode()) {
792 case Instruction::ZExt:
793 case Instruction::SExt:
794 case Instruction::FPTrunc:
795 case Instruction::FPExt:
796 case Instruction::UIToFP:
797 case Instruction::SIToFP:
798 case Instruction::FPToUI:
799 case Instruction::FPToSI:
800 default:
801 llvm_unreachable("FIXME: Don't support this constant cast expr");
802 case Instruction::GetElementPtr: {
803 // generate a symbolic expression for the byte address
804 const TargetData *TD = TM.getTargetData();
805 const Constant *ptrVal = CE->getOperand(0);
806 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
807 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
808 idxVec.size());
809 if (Offset == 0)
810 return EmitConstantValueOnly(ptrVal);
811
812 // Truncate/sext the offset to the pointer size.
813 if (TD->getPointerSizeInBits() != 64) {
814 int SExtAmount = 64-TD->getPointerSizeInBits();
815 Offset = (Offset << SExtAmount) >> SExtAmount;
816 }
817
818 if (Offset)
819 O << '(';
820 EmitConstantValueOnly(ptrVal);
821 if (Offset > 0)
822 O << ") + " << Offset;
823 else
824 O << ") - " << -Offset;
825 return;
826 }
827 case Instruction::BitCast:
828 return EmitConstantValueOnly(CE->getOperand(0));
829
830 case Instruction::IntToPtr: {
831 // Handle casts to pointers by changing them into casts to the appropriate
832 // integer type. This promotes constant folding and simplifies this code.
833 const TargetData *TD = TM.getTargetData();
834 Constant *Op = CE->getOperand(0);
835 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
836 false/*ZExt*/);
837 return EmitConstantValueOnly(Op);
838 }
839
840 case Instruction::PtrToInt: {
841 // Support only foldable casts to/from pointers that can be eliminated by
842 // changing the pointer to the appropriately sized integer type.
843 Constant *Op = CE->getOperand(0);
844 const Type *Ty = CE->getType();
845 const TargetData *TD = TM.getTargetData();
846
847 // We can emit the pointer value into this slot if the slot is an
848 // integer slot greater or equal to the size of the pointer.
849 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
850 return EmitConstantValueOnly(Op);
851
852 O << "((";
853 EmitConstantValueOnly(Op);
854 APInt ptrMask =
855 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
856
857 SmallString<40> S;
858 ptrMask.toStringUnsigned(S);
859 O << ") & " << S.str() << ')';
860 return;
861 }
862
863 case Instruction::Trunc:
864 // We emit the value and depend on the assembler to truncate the generated
865 // expression properly. This is important for differences between
866 // blockaddress labels. Since the two labels are in the same function, it
867 // is reasonable to treat their delta as a 32-bit value.
868 return EmitConstantValueOnly(CE->getOperand(0));
869
870 case Instruction::Add:
871 case Instruction::Sub:
872 case Instruction::And:
873 case Instruction::Or:
874 case Instruction::Xor:
875 O << '(';
876 EmitConstantValueOnly(CE->getOperand(0));
877 O << ')';
878 switch (CE->getOpcode()) {
879 case Instruction::Add:
880 O << " + ";
881 break;
882 case Instruction::Sub:
883 O << " - ";
884 break;
885 case Instruction::And:
886 O << " & ";
887 break;
888 case Instruction::Or:
889 O << " | ";
890 break;
891 case Instruction::Xor:
892 O << " ^ ";
893 break;
894 default:
895 break;
896 }
897 O << '(';
898 EmitConstantValueOnly(CE->getOperand(1));
899 O << ')';
900 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 }
902}
903
Chris Lattnere72333d2010-01-19 19:10:44 +0000904static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
905 AsmPrinter &AP) {
Chris Lattnera68112c2010-01-23 04:54:10 +0000906 if (AddrSpace != 0 || !CA->isString()) {
907 // Not a string. Print the values in successive locations
Chris Lattnere72333d2010-01-19 19:10:44 +0000908 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
909 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
Chris Lattnera68112c2010-01-23 04:54:10 +0000910 return;
Dan Gohmane78b0c72008-12-22 21:14:27 +0000911 }
Chris Lattnera68112c2010-01-23 04:54:10 +0000912
913 // Otherwise, it can be emitted as .ascii.
914 SmallVector<char, 128> TmpVec;
915 TmpVec.reserve(CA->getNumOperands());
916 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
917 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
918
919 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000920}
921
Chris Lattnere72333d2010-01-19 19:10:44 +0000922static void EmitGlobalConstantVector(const ConstantVector *CV,
923 unsigned AddrSpace, AsmPrinter &AP) {
Chris Lattnerd3544672010-01-20 07:41:15 +0000924 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Chris Lattnere72333d2010-01-19 19:10:44 +0000925 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000926}
927
Chris Lattnere72333d2010-01-19 19:10:44 +0000928static void EmitGlobalConstantStruct(const ConstantStruct *CS,
929 unsigned AddrSpace, AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +0000930 // Print the fields in successive locations. Pad to align if needed!
Chris Lattnere72333d2010-01-19 19:10:44 +0000931 const TargetData *TD = AP.TM.getTargetData();
932 unsigned Size = TD->getTypeAllocSize(CS->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000933 const StructLayout *Layout = TD->getStructLayout(CS->getType());
Chris Lattnere72333d2010-01-19 19:10:44 +0000934 uint64_t SizeSoFar = 0;
935 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattnerd3544672010-01-20 07:41:15 +0000936 const Constant *Field = CS->getOperand(i);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000937
938 // Check if padding is needed and insert one or more 0s.
Chris Lattnerd3544672010-01-20 07:41:15 +0000939 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000940 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
941 - Layout->getElementOffset(i)) - FieldSize;
942 SizeSoFar += FieldSize + PadSize;
Dan Gohmane78b0c72008-12-22 21:14:27 +0000943
944 // Now print the actual field value.
Chris Lattnerd3544672010-01-20 07:41:15 +0000945 AP.EmitGlobalConstant(Field, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000946
947 // Insert padding - this may include padding to increase the size of the
948 // current field up to the ABI size (if the struct is not packed) as well
949 // as padding to ensure that the next field starts at the right offset.
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000950 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000951 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000952 assert(SizeSoFar == Layout->getSizeInBytes() &&
Dan Gohmane78b0c72008-12-22 21:14:27 +0000953 "Layout of constant struct may be incorrect!");
954}
955
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000956static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
957 AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +0000958 // FP Constants are printed as integer constants to avoid losing
Chris Lattner41fd4b12010-01-20 06:53:37 +0000959 // precision.
Chris Lattner82cdc062009-10-05 05:54:46 +0000960 if (CFP->getType()->isDoubleTy()) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000961 if (AP.VerboseAsm) {
Chris Lattner49d74392010-01-22 19:17:48 +0000962 double Val = CFP->getValueAPF().convertToDouble();
963 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
Chris Lattner4e789282010-01-19 22:16:33 +0000964 }
965
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000966 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
967 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000968 return;
Chris Lattner82cdc062009-10-05 05:54:46 +0000969 }
970
971 if (CFP->getType()->isFloatTy()) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000972 if (AP.VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000973 float Val = CFP->getValueAPF().convertToFloat();
974 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
Dan Gohman87581eb2009-08-12 18:32:22 +0000975 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000976 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
977 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +0000978 return;
Chris Lattner82cdc062009-10-05 05:54:46 +0000979 }
980
981 if (CFP->getType()->isX86_FP80Ty()) {
Dan Gohmane78b0c72008-12-22 21:14:27 +0000982 // all long double variants are printed as hex
983 // api needed to prevent premature destruction
Chris Lattner4e789282010-01-19 22:16:33 +0000984 APInt API = CFP->getValueAPF().bitcastToAPInt();
985 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000986 if (AP.VerboseAsm) {
Chris Lattner84382d22010-01-19 22:11:05 +0000987 // Convert to double so we can print the approximate val as a comment.
988 APFloat DoubleVal = CFP->getValueAPF();
989 bool ignored;
990 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
991 &ignored);
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000992 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
993 << DoubleVal.convertToDouble() << '\n';
Chris Lattner84382d22010-01-19 22:11:05 +0000994 }
995
Chris Lattnerf2fc2762010-01-20 07:11:32 +0000996 if (AP.TM.getTargetData()->isBigEndian()) {
997 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
998 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner84382d22010-01-19 22:11:05 +0000999 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001000 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1001 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001002 }
Chris Lattner41fd4b12010-01-20 06:53:37 +00001003
1004 // Emit the tail padding for the long double.
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001005 const TargetData &TD = *AP.TM.getTargetData();
1006 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1007 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001008 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001009 }
1010
Chris Lattner4e789282010-01-19 22:16:33 +00001011 assert(CFP->getType()->isPPC_FP128Ty() &&
1012 "Floating point constant type not handled");
1013 // All long double variants are printed as hex api needed to prevent
1014 // premature destruction.
1015 APInt API = CFP->getValueAPF().bitcastToAPInt();
1016 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001017 if (AP.TM.getTargetData()->isBigEndian()) {
1018 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1019 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
Chris Lattner41fd4b12010-01-20 06:53:37 +00001020 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001021 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1022 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner4e789282010-01-19 22:16:33 +00001023 }
Dan Gohmane78b0c72008-12-22 21:14:27 +00001024}
1025
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001026static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1027 unsigned AddrSpace, AsmPrinter &AP) {
1028 const TargetData *TD = AP.TM.getTargetData();
Dan Gohmane78b0c72008-12-22 21:14:27 +00001029 unsigned BitWidth = CI->getBitWidth();
Chris Lattner50340312010-01-13 04:39:46 +00001030 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
Dan Gohmane78b0c72008-12-22 21:14:27 +00001031
1032 // We don't expect assemblers to support integer data directives
1033 // for more than 64 bits, so we emit the data in at most 64-bit
1034 // quantities at a time.
1035 const uint64_t *RawData = CI->getValue().getRawData();
1036 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001037 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1038 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001039 }
1040}
1041
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Sanjiv Guptadc2943d2009-01-30 04:25:10 +00001043void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
Chris Lattnere795ca52010-01-20 07:19:19 +00001044 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001045 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
Chris Lattner030176b2010-01-19 21:51:22 +00001046 return OutStreamer.EmitZeros(Size, AddrSpace);
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001047 }
1048
1049 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1050 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1051 switch (Size) {
1052 case 1:
1053 case 2:
1054 case 4:
1055 case 8:
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001056 if (VerboseAsm)
1057 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001058 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1059 return;
1060 default:
1061 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1062 return;
1063 }
1064 }
Chris Lattner9d767d82010-01-13 04:34:19 +00001065
Chris Lattnere72333d2010-01-19 19:10:44 +00001066 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1067 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001068
Chris Lattnere72333d2010-01-19 19:10:44 +00001069 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1070 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001071
Chris Lattnere72333d2010-01-19 19:10:44 +00001072 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001073 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001074
Chris Lattnere72333d2010-01-19 19:10:44 +00001075 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1076 return EmitGlobalConstantVector(V, AddrSpace, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077
Chris Lattner4fb5a132010-01-20 17:57:50 +00001078 if (isa<ConstantPointerNull>(CV)) {
1079 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1080 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1081 return;
1082 }
1083
Chris Lattner939a3142010-01-20 07:33:29 +00001084 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit
1085 // the expression value.
1086 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) {
1087 case 0: return;
1088 case 1: O << MAI->getData8bitsDirective(AddrSpace); break;
1089 case 2: O << MAI->getData16bitsDirective(AddrSpace); break;
1090 case 4: O << MAI->getData32bitsDirective(AddrSpace); break;
1091 case 8:
1092 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) {
1093 O << Dir;
1094 break;
1095 }
1096 // FALL THROUGH.
1097 default:
1098 llvm_unreachable("Target cannot handle given data directive width!");
1099 return;
1100 }
1101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 EmitConstantValueOnly(CV);
Dan Gohman12ebe3f2008-06-30 22:03:41 +00001103 O << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104}
1105
Chris Lattner89b36582008-08-17 07:19:36 +00001106void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 // Target doesn't support this yet!
Edwin Törökbd448e32009-07-14 16:55:14 +00001108 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109}
1110
1111/// PrintSpecial - Print information related to the specified machine instr
1112/// that is independent of the operand, and may be independent of the instr
1113/// itself. This can be useful for portably encoding the comment character
1114/// or other bits of target-specific knowledge into the asmstrings. The
1115/// syntax used is ${:comment}. Targets can override this to add support
1116/// for their own strange codes.
Chris Lattner6af48032009-03-10 05:37:13 +00001117void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 if (!strcmp(Code, "private")) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001119 O << MAI->getPrivateGlobalPrefix();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 } else if (!strcmp(Code, "comment")) {
Evan Cheng11db8142009-03-24 00:17:40 +00001121 if (VerboseAsm)
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001122 O << MAI->getCommentString();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 } else if (!strcmp(Code, "uid")) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 // Comparing the address of MI isn't sufficient, because machineinstrs may
1125 // be allocated to the same address across functions.
1126 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1127
Owen Andersonda3388b2009-06-24 22:28:12 +00001128 // If this is a new LastFn instruction, bump the counter.
1129 if (LastMI != MI || LastFn != ThisF) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 ++Counter;
1131 LastMI = MI;
Owen Andersonda3388b2009-06-24 22:28:12 +00001132 LastFn = ThisF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
1134 O << Counter;
1135 } else {
Edwin Törökced9ff82009-07-11 13:10:19 +00001136 std::string msg;
1137 raw_string_ostream Msg(msg);
1138 Msg << "Unknown special formatter '" << Code
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139 << "' for machine instr: " << *MI;
Edwin Törökced9ff82009-07-11 13:10:19 +00001140 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 }
1142}
1143
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +00001144/// processDebugLoc - Processes the debug information of each machine
1145/// instruction's DebugLoc.
Devang Patel5450fc12009-10-06 02:19:11 +00001146void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1147 bool BeforePrintingInsn) {
Devang Patel90a0fe32009-11-10 23:06:00 +00001148 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1149 || !DW->ShouldEmitDwarfDebug())
Chris Lattner693cfcc2009-08-05 04:09:18 +00001150 return;
Devang Patel86049dc2009-09-30 23:12:50 +00001151 DebugLoc DL = MI->getDebugLoc();
Devang Patel90a0fe32009-11-10 23:06:00 +00001152 if (DL.isUnknown())
1153 return;
Devang Patel042945f2010-01-16 06:09:35 +00001154 DILocation CurDLT = MF->getDILocation(DL);
1155 if (CurDLT.getScope().isNull())
Devang Patel90a0fe32009-11-10 23:06:00 +00001156 return;
1157
Chris Lattnere795ca52010-01-20 07:19:19 +00001158 if (!BeforePrintingInsn) {
Devang Patel90a0fe32009-11-10 23:06:00 +00001159 // After printing instruction
1160 DW->EndScope(MI);
Chris Lattnere795ca52010-01-20 07:19:19 +00001161 } else if (CurDLT.getNode() != PrevDLT) {
1162 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1163 CurDLT.getColumnNumber(),
1164 CurDLT.getScope().getNode());
1165 printLabel(L);
1166 O << '\n';
1167 DW->BeginScope(MI, L);
1168 PrevDLT = CurDLT.getNode();
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +00001169 }
1170}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171
Devang Patel90a0fe32009-11-10 23:06:00 +00001172
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173/// printInlineAsm - This method formats and prints the specified machine
1174/// instruction that is an inline asm.
1175void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1176 unsigned NumOperands = MI->getNumOperands();
1177
1178 // Count the number of register definitions.
1179 unsigned NumDefs = 0;
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001180 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 ++NumDefs)
1182 assert(NumDefs != NumOperands-1 && "No asm string?");
1183
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001184 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185
1186 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1187 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1188
Dan Gohmanbbc43962009-11-06 00:04:54 +00001189 O << '\t';
1190
Dale Johannesene99fc902008-01-29 02:21:21 +00001191 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1192 // These are useful to see where empty asm's wound up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 if (AsmStr[0] == 0) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001194 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1195 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 return;
1197 }
1198
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001199 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200
1201 // The variant of the current asmprinter.
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001202 int AsmPrinterVariant = MAI->getAssemblerDialect();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203
1204 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1205 const char *LastEmitted = AsmStr; // One past the last character emitted.
1206
1207 while (*LastEmitted) {
1208 switch (*LastEmitted) {
1209 default: {
1210 // Not a special case, emit the string section literally.
1211 const char *LiteralEnd = LastEmitted+1;
1212 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1213 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1214 ++LiteralEnd;
1215 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1216 O.write(LastEmitted, LiteralEnd-LastEmitted);
1217 LastEmitted = LiteralEnd;
1218 break;
1219 }
1220 case '\n':
1221 ++LastEmitted; // Consume newline character.
Dan Gohman12ebe3f2008-06-30 22:03:41 +00001222 O << '\n'; // Indent code with newline.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 break;
1224 case '$': {
1225 ++LastEmitted; // Consume '$' character.
1226 bool Done = true;
1227
1228 // Handle escapes.
1229 switch (*LastEmitted) {
1230 default: Done = false; break;
1231 case '$': // $$ -> $
1232 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1233 O << '$';
1234 ++LastEmitted; // Consume second '$' character.
1235 break;
1236 case '(': // $( -> same as GCC's { character.
1237 ++LastEmitted; // Consume '(' character.
1238 if (CurVariant != -1) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001239 llvm_report_error("Nested variants found in inline asm string: '"
1240 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 }
1242 CurVariant = 0; // We're in the first variant now.
1243 break;
1244 case '|':
1245 ++LastEmitted; // consume '|' character.
Dale Johannesen8b0e1172008-10-10 21:04:42 +00001246 if (CurVariant == -1)
1247 O << '|'; // this is gcc's behavior for | outside a variant
1248 else
1249 ++CurVariant; // We're in the next variant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 break;
1251 case ')': // $) -> same as GCC's } char.
1252 ++LastEmitted; // consume ')' character.
Dale Johannesen8b0e1172008-10-10 21:04:42 +00001253 if (CurVariant == -1)
1254 O << '}'; // this is gcc's behavior for } outside a variant
1255 else
1256 CurVariant = -1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 break;
1258 }
1259 if (Done) break;
1260
1261 bool HasCurlyBraces = false;
1262 if (*LastEmitted == '{') { // ${variable}
1263 ++LastEmitted; // Consume '{' character.
1264 HasCurlyBraces = true;
1265 }
1266
Chris Lattner6af48032009-03-10 05:37:13 +00001267 // If we have ${:foo}, then this is not a real operand reference, it is a
1268 // "magic" string reference, just like in .td files. Arrange to call
1269 // PrintSpecial.
1270 if (HasCurlyBraces && *LastEmitted == ':') {
1271 ++LastEmitted;
1272 const char *StrStart = LastEmitted;
1273 const char *StrEnd = strchr(StrStart, '}');
1274 if (StrEnd == 0) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001275 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1276 + std::string(AsmStr) + "'");
Chris Lattner6af48032009-03-10 05:37:13 +00001277 }
1278
1279 std::string Val(StrStart, StrEnd);
1280 PrintSpecial(MI, Val.c_str());
1281 LastEmitted = StrEnd+1;
1282 break;
1283 }
1284
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 const char *IDStart = LastEmitted;
1286 char *IDEnd;
1287 errno = 0;
1288 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1289 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001290 llvm_report_error("Bad $ operand number in inline asm string: '"
1291 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 }
1293 LastEmitted = IDEnd;
1294
1295 char Modifier[2] = { 0, 0 };
1296
1297 if (HasCurlyBraces) {
1298 // If we have curly braces, check for a modifier character. This
1299 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1300 if (*LastEmitted == ':') {
1301 ++LastEmitted; // Consume ':' character.
1302 if (*LastEmitted == 0) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001303 llvm_report_error("Bad ${:} expression in inline asm string: '"
1304 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 }
1306
1307 Modifier[0] = *LastEmitted;
1308 ++LastEmitted; // Consume modifier character.
1309 }
1310
1311 if (*LastEmitted != '}') {
Edwin Törökced9ff82009-07-11 13:10:19 +00001312 llvm_report_error("Bad ${} expression in inline asm string: '"
1313 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
1315 ++LastEmitted; // Consume '}' character.
1316 }
1317
1318 if ((unsigned)Val >= NumOperands-1) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001319 llvm_report_error("Invalid $ operand number in inline asm string: '"
1320 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 }
1322
1323 // Okay, we finally have a value number. Ask the target to print this
1324 // operand!
1325 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1326 unsigned OpNo = 1;
1327
1328 bool Error = false;
1329
1330 // Scan to find the machine operand number for the operand.
1331 for (; Val; --Val) {
1332 if (OpNo >= MI->getNumOperands()) break;
Chris Lattnerda4cff12007-12-30 20:50:28 +00001333 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Evan Cheng92167402009-03-20 18:03:34 +00001334 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 }
1336
1337 if (OpNo >= MI->getNumOperands()) {
1338 Error = true;
1339 } else {
Chris Lattnerda4cff12007-12-30 20:50:28 +00001340 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 ++OpNo; // Skip over the ID number.
1342
Chris Lattnerce409842010-01-17 21:43:43 +00001343 if (Modifier[0] == 'l') // labels are target independent
1344 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
Dale Johannesencfb19e62007-11-05 21:20:28 +00001345 else {
1346 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
Dale Johannesen94464072008-09-24 01:07:17 +00001347 if ((OpFlags & 7) == 4) {
Dale Johannesencfb19e62007-11-05 21:20:28 +00001348 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1349 Modifier[0] ? Modifier : 0);
1350 } else {
1351 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1352 Modifier[0] ? Modifier : 0);
1353 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 }
1355 }
1356 if (Error) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001357 std::string msg;
1358 raw_string_ostream Msg(msg);
Chris Lattnerce409842010-01-17 21:43:43 +00001359 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
Edwin Törökced9ff82009-07-11 13:10:19 +00001360 MI->print(Msg);
1361 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 }
1363 }
1364 break;
1365 }
1366 }
1367 }
Chris Lattner32d4cc72009-09-09 23:14:36 +00001368 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369}
1370
Evan Cheng3c0eda52008-03-15 00:03:38 +00001371/// printImplicitDef - This method prints the specified machine instruction
1372/// that is an implicit def.
1373void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
Chris Lattner32d4cc72009-09-09 23:14:36 +00001374 if (!VerboseAsm) return;
1375 O.PadToColumn(MAI->getCommentColumn());
1376 O << MAI->getCommentString() << " implicit-def: "
Chris Lattner28f7e352009-09-13 19:48:37 +00001377 << TRI->getName(MI->getOperand(0).getReg());
Evan Cheng3c0eda52008-03-15 00:03:38 +00001378}
1379
Jakob Stoklund Olesen7f251672009-11-04 19:24:37 +00001380void AsmPrinter::printKill(const MachineInstr *MI) const {
1381 if (!VerboseAsm) return;
1382 O.PadToColumn(MAI->getCommentColumn());
1383 O << MAI->getCommentString() << " kill:";
1384 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1385 const MachineOperand &op = MI->getOperand(n);
1386 assert(op.isReg() && "KILL instruction must have only register operands");
1387 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1388 }
1389}
1390
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391/// printLabel - This method prints a local label used by debug and
1392/// exception handling tables.
1393void AsmPrinter::printLabel(const MachineInstr *MI) const {
Dan Gohman7d546402008-07-01 00:16:26 +00001394 printLabel(MI->getOperand(0).getImm());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395}
1396
Evan Chenga53c40a2008-02-01 09:10:45 +00001397void AsmPrinter::printLabel(unsigned Id) const {
Chris Lattner32d4cc72009-09-09 23:14:36 +00001398 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
Evan Chenga53c40a2008-02-01 09:10:45 +00001399}
1400
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001401/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1402/// instruction, using the specified assembler variant. Targets should
Dale Johannesenc90c30b2010-01-14 21:50:17 +00001403/// override this to format as appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1405 unsigned AsmVariant, const char *ExtraCode) {
1406 // Target doesn't support this yet!
1407 return true;
1408}
1409
1410bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1411 unsigned AsmVariant,
1412 const char *ExtraCode) {
1413 // Target doesn't support this yet!
1414 return true;
1415}
1416
Dan Gohman885793b2009-11-20 23:18:13 +00001417MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1418 const char *Suffix) const {
1419 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
Dan Gohman91057512009-10-30 01:27:03 +00001420}
1421
1422MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
Dan Gohman885793b2009-11-20 23:18:13 +00001423 const BasicBlock *BB,
1424 const char *Suffix) const {
Dan Gohman91057512009-10-30 01:27:03 +00001425 assert(BB->hasName() &&
1426 "Address of anonymous basic block not supported yet!");
1427
Dan Gohmanff592ec2009-11-05 23:14:35 +00001428 // This code must use the function name itself, and not the function number,
1429 // since it must be possible to generate the label name from within other
1430 // functions.
Chris Lattner6be13f32010-01-13 07:30:49 +00001431 SmallString<60> FnName;
1432 Mang->getNameWithPrefix(FnName, F, false);
Dan Gohman91057512009-10-30 01:27:03 +00001433
Chris Lattner6be13f32010-01-13 07:30:49 +00001434 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
Chris Lattnera38b2872010-01-13 06:38:18 +00001435 SmallString<60> NameResult;
Chris Lattner6be13f32010-01-13 07:30:49 +00001436 Mang->getNameWithPrefix(NameResult,
1437 StringRef("BA") + Twine((unsigned)FnName.size()) +
1438 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1439 Mangler::Private);
Dan Gohmanff592ec2009-11-05 23:14:35 +00001440
Chris Lattnera38b2872010-01-13 06:38:18 +00001441 return OutContext.GetOrCreateSymbol(NameResult.str());
Dan Gohman91057512009-10-30 01:27:03 +00001442}
1443
Chris Lattner08c97082009-09-12 23:02:08 +00001444MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1445 SmallString<60> Name;
1446 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1447 << getFunctionNumber() << '_' << MBBID;
Chris Lattner77e356c2010-01-23 05:19:23 +00001448 return OutContext.GetOrCreateSymbol(Name.str());
1449}
1450
1451/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1452MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1453 SmallString<60> Name;
1454 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1455 << getFunctionNumber() << '_' << CPID;
1456 return OutContext.GetOrCreateSymbol(Name.str());
1457}
1458
1459/// GetJTISymbol - Return the symbol for the specified jump table entry.
1460MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1461 const char *Prefix = isLinkerPrivate ? MAI->getLinkerPrivateGlobalPrefix() :
1462 MAI->getPrivateGlobalPrefix();
1463 SmallString<60> Name;
1464 raw_svector_ostream(Name) << Prefix << "JTI" << getFunctionNumber() << '_'
1465 << JTID;
Chris Lattner08c97082009-09-12 23:02:08 +00001466 return OutContext.GetOrCreateSymbol(Name.str());
1467}
1468
Chris Lattner2eb781d2010-01-15 23:18:17 +00001469/// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1470/// value.
1471MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1472 SmallString<60> NameStr;
1473 Mang->getNameWithPrefix(NameStr, GV, false);
1474 return OutContext.GetOrCreateSymbol(NameStr.str());
1475}
1476
Chris Lattnera6f2a102010-01-16 18:37:32 +00001477/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
Chris Lattnerf7871d12010-01-15 23:25:11 +00001478/// global value name as its base, with the specified suffix, and where the
Chris Lattnera6f2a102010-01-16 18:37:32 +00001479/// symbol is forced to have private linkage if ForcePrivate is true.
1480MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1481 StringRef Suffix,
1482 bool ForcePrivate) const {
Chris Lattnerf7871d12010-01-15 23:25:11 +00001483 SmallString<60> NameStr;
Chris Lattnera6f2a102010-01-16 18:37:32 +00001484 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
Chris Lattnerf7871d12010-01-15 23:25:11 +00001485 NameStr.append(Suffix.begin(), Suffix.end());
1486 return OutContext.GetOrCreateSymbol(NameStr.str());
1487}
1488
Chris Lattner2eb781d2010-01-15 23:18:17 +00001489/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1490/// ExternalSymbol.
1491MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1492 SmallString<60> NameStr;
1493 Mang->getNameWithPrefix(NameStr, Sym);
1494 return OutContext.GetOrCreateSymbol(NameStr.str());
1495}
1496
Chris Lattner08c97082009-09-12 23:02:08 +00001497
Chris Lattner5abc72c2010-01-22 21:50:41 +00001498
1499/// PrintParentLoopComment - Print comments about parent loops of this one.
1500static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1501 unsigned FunctionNumber) {
1502 if (Loop == 0) return;
1503 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1504 OS.indent(Loop->getLoopDepth()*2)
1505 << "Parent Loop BB" << FunctionNumber << "_"
1506 << Loop->getHeader()->getNumber()
1507 << " Depth=" << Loop->getLoopDepth() << '\n';
1508}
1509
1510
1511/// PrintChildLoopComment - Print comments about child loops within
1512/// the loop for this basic block, with nesting.
1513static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1514 unsigned FunctionNumber) {
1515 // Add child loop information
1516 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1517 OS.indent((*CL)->getLoopDepth()*2)
1518 << "Child Loop BB" << FunctionNumber << "_"
1519 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1520 << '\n';
1521 PrintChildLoopComment(OS, *CL, FunctionNumber);
1522 }
1523}
1524
1525/// EmitComments - Pretty-print comments for basic blocks.
1526static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1527 const MachineLoopInfo *LI,
1528 const AsmPrinter &AP) {
1529 // Add loop depth information
1530 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1531 if (Loop == 0) return;
1532
1533 MachineBasicBlock *Header = Loop->getHeader();
1534 assert(Header && "No header for loop");
1535
1536 // If this block is not a loop header, just print out what is the loop header
1537 // and return.
1538 if (Header != &MBB) {
1539 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1540 Twine(AP.getFunctionNumber())+"_" +
1541 Twine(Loop->getHeader()->getNumber())+
1542 " Depth="+Twine(Loop->getLoopDepth()));
1543 return;
1544 }
1545
1546 // Otherwise, it is a loop header. Print out information about child and
1547 // parent loops.
1548 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1549
1550 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1551
1552 OS << "=>";
1553 OS.indent(Loop->getLoopDepth()*2-2);
1554
1555 OS << "This ";
1556 if (Loop->empty())
1557 OS << "Inner ";
1558 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1559
1560 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1561}
1562
1563
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001564/// EmitBasicBlockStart - This method prints the label for the specified
1565/// MachineBasicBlock, an alignment (if present) and a comment describing
1566/// it if appropriate.
Chris Lattnerda5fb6d2009-09-14 03:15:54 +00001567void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001568 // Emit an alignment directive for this block, if needed.
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001569 if (unsigned Align = MBB->getAlignment())
1570 EmitAlignment(Log2_32(Align));
Evan Cheng45c1edb2008-02-28 00:43:03 +00001571
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001572 // If the block has its address taken, emit a special label to satisfy
1573 // references to the block. This is done so that we don't need to
1574 // remember the number of this label, and so that we can make
1575 // forward references to labels without knowing what their numbers
1576 // will be.
Dan Gohman91057512009-10-30 01:27:03 +00001577 if (MBB->hasAddressTaken()) {
Chris Lattner8bae1052010-01-20 07:24:05 +00001578 const BasicBlock *BB = MBB->getBasicBlock();
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001579 if (VerboseAsm)
1580 OutStreamer.AddComment("Address Taken");
Chris Lattner8bae1052010-01-20 07:24:05 +00001581 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
Dan Gohman91057512009-10-30 01:27:03 +00001582 }
1583
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001584 // Print the main label for the block.
Dan Gohman5fda4342009-10-06 17:38:38 +00001585 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001586 if (VerboseAsm) {
Dan Gohman5fda4342009-10-06 17:38:38 +00001587 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001588 if (const BasicBlock *BB = MBB->getBasicBlock())
1589 if (BB->hasName())
1590 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner82be51c2010-01-22 21:00:45 +00001591
Chris Lattner5abc72c2010-01-22 21:50:41 +00001592 PrintBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001593 OutStreamer.AddBlankLine();
1594 }
Dan Gohman5fda4342009-10-06 17:38:38 +00001595 } else {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001596 if (VerboseAsm) {
1597 if (const BasicBlock *BB = MBB->getBasicBlock())
1598 if (BB->hasName())
1599 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner5abc72c2010-01-22 21:50:41 +00001600 PrintBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001601 }
Chris Lattner82be51c2010-01-22 21:00:45 +00001602
Chris Lattner8bae1052010-01-20 07:24:05 +00001603 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
Dan Gohman5fda4342009-10-06 17:38:38 +00001604 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605}
1606
Evan Cheng6fb06762007-11-09 01:32:10 +00001607/// printPICJumpTableSetLabel - This method prints a set label for the
1608/// specified MachineBasicBlock for a jumptable entry.
1609void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1610 const MachineBasicBlock *MBB) const {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001611 if (!MAI->getSetDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612 return;
1613
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001614 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
Chris Lattnerce409842010-01-17 21:43:43 +00001615 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1616 << *GetMBBSymbol(MBB->getNumber())
Chris Lattner77e356c2010-01-23 05:19:23 +00001617 << '-' << *GetJTISymbol(uid) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618}
1619
Evan Cheng6fb06762007-11-09 01:32:10 +00001620void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1621 const MachineBasicBlock *MBB) const {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001622 if (!MAI->getSetDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 return;
1624
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001625 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001626 << getFunctionNumber() << '_' << uid << '_' << uid2
Chris Lattnerce409842010-01-17 21:43:43 +00001627 << "_set_" << MBB->getNumber() << ','
1628 << *GetMBBSymbol(MBB->getNumber())
1629 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
Evan Cheng477013c2007-10-14 05:57:21 +00001630 << '_' << uid << '_' << uid2 << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631}
1632
Chris Lattner67cce682010-01-15 23:38:51 +00001633void AsmPrinter::printVisibility(const MCSymbol *Sym,
1634 unsigned Visibility) const {
1635 if (Visibility == GlobalValue::HiddenVisibility) {
Chris Lattnerce409842010-01-17 21:43:43 +00001636 if (const char *Directive = MAI->getHiddenDirective())
1637 O << Directive << *Sym << '\n';
Chris Lattner67cce682010-01-15 23:38:51 +00001638 } else if (Visibility == GlobalValue::ProtectedVisibility) {
Chris Lattnerce409842010-01-17 21:43:43 +00001639 if (const char *Directive = MAI->getProtectedDirective())
1640 O << Directive << *Sym << '\n';
Chris Lattner67cce682010-01-15 23:38:51 +00001641 }
1642}
1643
Anton Korobeynikov440f23d2008-11-22 16:15:34 +00001644void AsmPrinter::printOffset(int64_t Offset) const {
1645 if (Offset > 0)
1646 O << '+' << Offset;
1647 else if (Offset < 0)
1648 O << Offset;
1649}
1650
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001651GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1652 if (!S->usesMetadata())
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001653 return 0;
1654
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001655 gcp_iterator GCPI = GCMetadataPrinters.find(S);
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001656 if (GCPI != GCMetadataPrinters.end())
1657 return GCPI->second;
1658
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001659 const char *Name = S->getName().c_str();
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001660
1661 for (GCMetadataPrinterRegistry::iterator
1662 I = GCMetadataPrinterRegistry::begin(),
1663 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1664 if (strcmp(Name, I->getName()) == 0) {
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001665 GCMetadataPrinter *GMP = I->instantiate();
1666 GMP->S = S;
1667 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1668 return GMP;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001669 }
1670
Chris Lattnerbf9d76d2009-08-23 07:19:13 +00001671 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +00001672 llvm_unreachable(0);
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001673}
David Greene63486122009-07-13 20:25:48 +00001674
1675/// EmitComments - Pretty-print comments for instructions
Chris Lattnerfdbeb812009-08-07 23:42:01 +00001676void AsmPrinter::EmitComments(const MachineInstr &MI) const {
David Greeneca9b04b2009-11-13 21:34:57 +00001677 if (!VerboseAsm)
1678 return;
David Greene4a37a692009-07-16 22:24:20 +00001679
David Greeneca9b04b2009-11-13 21:34:57 +00001680 bool Newline = false;
1681
1682 if (!MI.getDebugLoc().isUnknown()) {
Devang Patel042945f2010-01-16 06:09:35 +00001683 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
David Greeneca9b04b2009-11-13 21:34:57 +00001684
1685 // Print source line info.
1686 O.PadToColumn(MAI->getCommentColumn());
Dan Gohman4698bab2009-12-05 00:23:29 +00001687 O << MAI->getCommentString() << ' ';
Devang Patel042945f2010-01-16 06:09:35 +00001688 DIScope Scope = DLT.getScope();
Dan Gohman4698bab2009-12-05 00:23:29 +00001689 // Omit the directory, because it's likely to be long and uninteresting.
1690 if (!Scope.isNull())
1691 O << Scope.getFilename();
1692 else
1693 O << "<unknown>";
Devang Patel042945f2010-01-16 06:09:35 +00001694 O << ':' << DLT.getLineNumber();
1695 if (DLT.getColumnNumber() != 0)
1696 O << ':' << DLT.getColumnNumber();
David Greeneca9b04b2009-11-13 21:34:57 +00001697 Newline = true;
David Greene4a37a692009-07-16 22:24:20 +00001698 }
David Greeneca9b04b2009-11-13 21:34:57 +00001699
David Greene2e7b9932009-11-16 15:12:23 +00001700 // Check for spills and reloads
1701 int FI;
1702
1703 const MachineFrameInfo *FrameInfo =
1704 MI.getParent()->getParent()->getFrameInfo();
1705
1706 // We assume a single instruction only has a spill or reload, not
1707 // both.
David Greene11a046f12009-12-04 22:46:04 +00001708 const MachineMemOperand *MMO;
David Greene2e7b9932009-11-16 15:12:23 +00001709 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1710 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
David Greene11a046f12009-12-04 22:46:04 +00001711 MMO = *MI.memoperands_begin();
David Greene2e7b9932009-11-16 15:12:23 +00001712 if (Newline) O << '\n';
1713 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001714 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
David Greene2e7b9932009-11-16 15:12:23 +00001715 Newline = true;
1716 }
1717 }
David Greene11a046f12009-12-04 22:46:04 +00001718 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
David Greene2e7b9932009-11-16 15:12:23 +00001719 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1720 if (Newline) O << '\n';
1721 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001722 O << MAI->getCommentString() << ' '
1723 << MMO->getSize() << "-byte Folded Reload";
David Greene2e7b9932009-11-16 15:12:23 +00001724 Newline = true;
1725 }
1726 }
1727 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1728 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
David Greene11a046f12009-12-04 22:46:04 +00001729 MMO = *MI.memoperands_begin();
David Greene2e7b9932009-11-16 15:12:23 +00001730 if (Newline) O << '\n';
1731 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001732 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
David Greene2e7b9932009-11-16 15:12:23 +00001733 Newline = true;
1734 }
1735 }
David Greene11a046f12009-12-04 22:46:04 +00001736 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
David Greene2e7b9932009-11-16 15:12:23 +00001737 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1738 if (Newline) O << '\n';
1739 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001740 O << MAI->getCommentString() << ' '
1741 << MMO->getSize() << "-byte Folded Spill";
David Greene2e7b9932009-11-16 15:12:23 +00001742 Newline = true;
1743 }
1744 }
1745
1746 // Check for spill-induced copies
1747 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1748 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1749 SrcSubIdx, DstSubIdx)) {
1750 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1751 if (Newline) O << '\n';
1752 O.PadToColumn(MAI->getCommentColumn());
1753 O << MAI->getCommentString() << " Reload Reuse";
David Greene2e7b9932009-11-16 15:12:23 +00001754 }
1755 }
David Greene63486122009-07-13 20:25:48 +00001756}
1757