blob: 9cdae3483382c3400e3eccda0dde588fcf08ee30 [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"
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000019#include "llvm/CodeGen/Collector.h"
20#include "llvm/CodeGen/CollectorMetadata.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Mangler.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
28#include "llvm/Target/TargetAsmInfo.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetLowering.h"
31#include "llvm/Target/TargetMachine.h"
Evan Cheng6fb06762007-11-09 01:32:10 +000032#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include <cerrno>
34using namespace llvm;
35
36static cl::opt<bool>
37AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
38
39char AsmPrinter::ID = 0;
40AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
41 const TargetAsmInfo *T)
Evan Cheng45c1edb2008-02-28 00:43:03 +000042 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T),
43 IsInTextSection(false)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044{}
45
46std::string AsmPrinter::getSectionForFunction(const Function &F) const {
47 return TAI->getTextSection();
48}
49
50
51/// SwitchToTextSection - Switch to the specified text section of the executable
52/// if we are not already in it!
53///
54void AsmPrinter::SwitchToTextSection(const char *NewSection,
55 const GlobalValue *GV) {
56 std::string NS;
57 if (GV && GV->hasSection())
58 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
59 else
60 NS = NewSection;
61
62 // If we're already in this section, we're done.
63 if (CurrentSection == NS) return;
64
65 // Close the current section, if applicable.
66 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
67 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
68
69 CurrentSection = NS;
70
71 if (!CurrentSection.empty())
72 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
Evan Cheng45c1edb2008-02-28 00:43:03 +000073
74 IsInTextSection = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075}
76
77/// SwitchToDataSection - Switch to the specified data section of the executable
78/// if we are not already in it!
79///
80void AsmPrinter::SwitchToDataSection(const char *NewSection,
81 const GlobalValue *GV) {
82 std::string NS;
83 if (GV && GV->hasSection())
84 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
85 else
86 NS = NewSection;
87
88 // If we're already in this section, we're done.
89 if (CurrentSection == NS) return;
90
91 // Close the current section, if applicable.
92 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
93 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
94
95 CurrentSection = NS;
96
97 if (!CurrentSection.empty())
98 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
Evan Cheng45c1edb2008-02-28 00:43:03 +000099
100 IsInTextSection = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101}
102
103
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000104void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
105 MachineFunctionPass::getAnalysisUsage(AU);
106 AU.addRequired<CollectorModuleMetadata>();
107}
108
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109bool AsmPrinter::doInitialization(Module &M) {
110 Mang = new Mangler(M, TAI->getGlobalPrefix());
111
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000112 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
113 assert(CMM && "AsmPrinter didn't require CollectorModuleMetadata?");
114 for (CollectorModuleMetadata::iterator I = CMM->begin(),
115 E = CMM->end(); I != E; ++I)
116 (*I)->beginAssembly(O, *this, *TAI);
117
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 if (!M.getModuleInlineAsm().empty())
119 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
120 << M.getModuleInlineAsm()
121 << "\n" << TAI->getCommentString()
122 << " End of file scope inline assembly\n";
123
124 SwitchToDataSection(""); // Reset back to no section.
125
Evan Chengc439a852008-02-04 23:06:48 +0000126 MMI = getAnalysisToUpdate<MachineModuleInfo>();
127 if (MMI) MMI->AnalyzeModule(M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128
129 return false;
130}
131
132bool AsmPrinter::doFinalization(Module &M) {
133 if (TAI->getWeakRefDirective()) {
134 if (!ExtWeakSymbols.empty())
135 SwitchToDataSection("");
136
137 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
138 e = ExtWeakSymbols.end(); i != e; ++i) {
139 const GlobalValue *GV = *i;
140 std::string Name = Mang->getValueName(GV);
141 O << TAI->getWeakRefDirective() << Name << "\n";
142 }
143 }
144
145 if (TAI->getSetDirective()) {
146 if (!M.alias_empty())
147 SwitchToTextSection(TAI->getTextSection());
148
149 O << "\n";
150 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
151 I!=E; ++I) {
152 std::string Name = Mang->getValueName(I);
153 std::string Target;
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000154
155 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
156 Target = Mang->getValueName(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000158 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 O << "\t.globl\t" << Name << "\n";
160 else if (I->hasWeakLinkage())
161 O << TAI->getWeakRefDirective() << Name << "\n";
162 else if (!I->hasInternalLinkage())
163 assert(0 && "Invalid alias linkage");
164
Nick Lewyckyf3df2392008-02-07 06:36:26 +0000165 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << "\n";
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000166
167 // If the aliasee has external weak linkage it can be referenced only by
168 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
169 // weak reference in such case.
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000170 if (GV->hasExternalWeakLinkage()) {
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000171 if (TAI->getWeakRefDirective())
172 O << TAI->getWeakRefDirective() << Target << "\n";
173 else
174 O << "\t.globl\t" << Target << "\n";
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000175 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 }
177 }
178
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000179 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
180 assert(CMM && "AsmPrinter didn't require CollectorModuleMetadata?");
181 for (CollectorModuleMetadata::iterator I = CMM->end(),
182 E = CMM->begin(); I != E; )
183 (*--I)->finishAssembly(O, *this, *TAI);
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 delete Mang; Mang = 0;
186 return false;
187}
188
Bill Wendlinge9ecdcf2007-09-18 09:10:16 +0000189std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
Bill Wendlingef9211a2007-09-18 01:47:22 +0000190 assert(MF && "No machine function?");
Bill Wendlingd2144aa2007-09-18 05:03:44 +0000191 return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
192 TAI->getGlobalPrefix());
Bill Wendlingef9211a2007-09-18 01:47:22 +0000193}
194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
196 // What's my mangled name?
197 CurrentFnName = Mang->getValueName(MF.getFunction());
Evan Cheng477013c2007-10-14 05:57:21 +0000198 IncrementFunctionNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199}
200
201/// EmitConstantPool - Print to the current output stream assembly
202/// representations of the constants in the constant pool MCP. This is
203/// used to print out constants which have been "spilled to memory" by
204/// the code generator.
205///
206void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
207 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
208 if (CP.empty()) return;
209
210 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
211 // in special sections.
212 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
213 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
214 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
215 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
216 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
217 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
218 MachineConstantPoolEntry CPE = CP[i];
219 const Type *Ty = CPE.getType();
220 if (TAI->getFourByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000221 TM.getTargetData()->getABITypeSize(Ty) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 FourByteCPs.push_back(std::make_pair(CPE, i));
223 else if (TAI->getEightByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000224 TM.getTargetData()->getABITypeSize(Ty) == 8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 EightByteCPs.push_back(std::make_pair(CPE, i));
226 else if (TAI->getSixteenByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000227 TM.getTargetData()->getABITypeSize(Ty) == 16)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 SixteenByteCPs.push_back(std::make_pair(CPE, i));
229 else
230 OtherCPs.push_back(std::make_pair(CPE, i));
231 }
232
233 unsigned Alignment = MCP->getConstantPoolAlignment();
234 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
235 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
236 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
237 SixteenByteCPs);
238 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
239}
240
241void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
242 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
243 if (CP.empty()) return;
244
245 SwitchToDataSection(Section);
246 EmitAlignment(Alignment);
247 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Evan Cheng477013c2007-10-14 05:57:21 +0000248 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
249 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
251 if (CP[i].first.isMachineConstantPoolEntry())
252 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
253 else
254 EmitGlobalConstant(CP[i].first.Val.ConstVal);
255 if (i != e-1) {
256 const Type *Ty = CP[i].first.getType();
257 unsigned EntSize =
Duncan Sands8157ef42007-11-05 00:04:43 +0000258 TM.getTargetData()->getABITypeSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
260 // Emit inter-object padding for alignment.
261 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
262 }
263 }
264}
265
266/// EmitJumpTableInfo - Print assembly representations of the jump tables used
267/// by the current function to the current output stream.
268///
269void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
270 MachineFunction &MF) {
271 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
272 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000273
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
275
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 // Pick the directive to use to print the jump table entries, and switch to
277 // the appropriate section.
278 TargetLowering *LoweringInfo = TM.getTargetLowering();
279
280 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
281 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
282 !JumpTableDataSection) {
283 // In PIC mode, we need to emit the jump table to the same section as the
284 // function body itself, otherwise the label differences won't make sense.
285 // We should also do if the section name is NULL.
286 const Function *F = MF.getFunction();
287 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
288 } else {
289 SwitchToDataSection(JumpTableDataSection);
290 }
291
292 EmitAlignment(Log2_32(MJTI->getAlignment()));
293
294 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
295 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
296
297 // If this jump table was deleted, ignore it.
298 if (JTBBs.empty()) continue;
299
300 // For PIC codegen, if possible we want to use the SetDirective to reduce
301 // the number of relocations the assembler will generate for the jump table.
302 // Set directives are all printed before the jump table itself.
Evan Cheng6fb06762007-11-09 01:32:10 +0000303 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 if (TAI->getSetDirective() && IsPic)
305 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Evan Cheng6fb06762007-11-09 01:32:10 +0000306 if (EmittedSets.insert(JTBBs[ii]))
307 printPICJumpTableSetLabel(i, JTBBs[ii]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308
309 // On some targets (e.g. darwin) we want to emit two consequtive labels
310 // before each jump table. The first label is never referenced, but tells
311 // the assembler and linker the extents of the jump table object. The
312 // second label is actually referenced by the code.
313 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
Evan Cheng477013c2007-10-14 05:57:21 +0000314 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315
Evan Cheng477013c2007-10-14 05:57:21 +0000316 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
317 << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318
319 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000320 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 O << '\n';
322 }
323 }
324}
325
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000326void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
327 const MachineBasicBlock *MBB,
328 unsigned uid) const {
329 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
330
331 // Use JumpTableDirective otherwise honor the entry size from the jump table
332 // info.
333 const char *JTEntryDirective = TAI->getJumpTableDirective();
334 bool HadJTEntryDirective = JTEntryDirective != NULL;
335 if (!HadJTEntryDirective) {
336 JTEntryDirective = MJTI->getEntrySize() == 4 ?
337 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
338 }
339
340 O << JTEntryDirective << ' ';
341
342 // If we have emitted set directives for the jump table entries, print
343 // them rather than the entries themselves. If we're emitting PIC, then
344 // emit the table entries as differences between two text section labels.
345 // If we're emitting non-PIC code, then emit the entries as direct
346 // references to the target basic blocks.
347 if (IsPic) {
348 if (TAI->getSetDirective()) {
349 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
350 << '_' << uid << "_set_" << MBB->getNumber();
351 } else {
Evan Cheng45c1edb2008-02-28 00:43:03 +0000352 printBasicBlockLabel(MBB, false, false, false);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000353 // If the arch uses custom Jump Table directives, don't calc relative to
354 // JT
355 if (!HadJTEntryDirective)
356 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
357 << getFunctionNumber() << '_' << uid;
358 }
359 } else {
Evan Cheng45c1edb2008-02-28 00:43:03 +0000360 printBasicBlockLabel(MBB, false, false, false);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000361 }
362}
363
364
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
366/// special global used by LLVM. If so, emit it and return true, otherwise
367/// do nothing and return false.
368bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000369 if (GV->getName() == "llvm.used") {
370 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
371 EmitLLVMUsedList(GV->getInitializer());
372 return true;
373 }
374
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 // Ignore debug and non-emitted data.
376 if (GV->getSection() == "llvm.metadata") return true;
377
378 if (!GV->hasAppendingLinkage()) return false;
379
380 assert(GV->hasInitializer() && "Not a special LLVM global!");
381
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 const TargetData *TD = TM.getTargetData();
383 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
384 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
385 SwitchToDataSection(TAI->getStaticCtorsSection());
386 EmitAlignment(Align, 0);
387 EmitXXStructorList(GV->getInitializer());
388 return true;
389 }
390
391 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
392 SwitchToDataSection(TAI->getStaticDtorsSection());
393 EmitAlignment(Align, 0);
394 EmitXXStructorList(GV->getInitializer());
395 return true;
396 }
397
398 return false;
399}
400
401/// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
402/// global in the specified llvm.used list as being used with this directive.
403void AsmPrinter::EmitLLVMUsedList(Constant *List) {
404 const char *Directive = TAI->getUsedDirective();
405
406 // Should be an array of 'sbyte*'.
407 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
408 if (InitList == 0) return;
409
410 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
411 O << Directive;
412 EmitConstantValueOnly(InitList->getOperand(i));
413 O << "\n";
414 }
415}
416
417/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
418/// function pointers, ignoring the init priority.
419void AsmPrinter::EmitXXStructorList(Constant *List) {
420 // Should be an array of '{ int, void ()* }' structs. The first value is the
421 // init priority, which we ignore.
422 if (!isa<ConstantArray>(List)) return;
423 ConstantArray *InitList = cast<ConstantArray>(List);
424 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
425 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
426 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
427
428 if (CS->getOperand(1)->isNullValue())
429 return; // Found a null terminator, exit printing.
430 // Emit the function pointer.
431 EmitGlobalConstant(CS->getOperand(1));
432 }
433}
434
435/// getGlobalLinkName - Returns the asm/link name of of the specified
436/// global variable. Should be overridden by each target asm printer to
437/// generate the appropriate value.
438const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
439 std::string LinkName;
440
441 if (isa<Function>(GV)) {
442 LinkName += TAI->getFunctionAddrPrefix();
443 LinkName += Mang->getValueName(GV);
444 LinkName += TAI->getFunctionAddrSuffix();
445 } else {
446 LinkName += TAI->getGlobalVarAddrPrefix();
447 LinkName += Mang->getValueName(GV);
448 LinkName += TAI->getGlobalVarAddrSuffix();
449 }
450
451 return LinkName;
452}
453
454/// EmitExternalGlobal - Emit the external reference to a global variable.
455/// Should be overridden if an indirect reference should be used.
456void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
457 O << getGlobalLinkName(GV);
458}
459
460
461
462//===----------------------------------------------------------------------===//
463/// LEB 128 number encoding.
464
465/// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
466/// representing an unsigned leb128 value.
467void AsmPrinter::PrintULEB128(unsigned Value) const {
468 do {
469 unsigned Byte = Value & 0x7f;
470 Value >>= 7;
471 if (Value) Byte |= 0x80;
472 O << "0x" << std::hex << Byte << std::dec;
473 if (Value) O << ", ";
474 } while (Value);
475}
476
477/// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
478/// value.
479unsigned AsmPrinter::SizeULEB128(unsigned Value) {
480 unsigned Size = 0;
481 do {
482 Value >>= 7;
483 Size += sizeof(int8_t);
484 } while (Value);
485 return Size;
486}
487
488/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
489/// representing a signed leb128 value.
490void AsmPrinter::PrintSLEB128(int Value) const {
491 int Sign = Value >> (8 * sizeof(Value) - 1);
492 bool IsMore;
493
494 do {
495 unsigned Byte = Value & 0x7f;
496 Value >>= 7;
497 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
498 if (IsMore) Byte |= 0x80;
499 O << "0x" << std::hex << Byte << std::dec;
500 if (IsMore) O << ", ";
501 } while (IsMore);
502}
503
504/// SizeSLEB128 - Compute the number of bytes required for a signed leb128
505/// value.
506unsigned AsmPrinter::SizeSLEB128(int Value) {
507 unsigned Size = 0;
508 int Sign = Value >> (8 * sizeof(Value) - 1);
509 bool IsMore;
510
511 do {
512 unsigned Byte = Value & 0x7f;
513 Value >>= 7;
514 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
515 Size += sizeof(int8_t);
516 } while (IsMore);
517 return Size;
518}
519
520//===--------------------------------------------------------------------===//
521// Emission and print routines
522//
523
524/// PrintHex - Print a value as a hexidecimal value.
525///
526void AsmPrinter::PrintHex(int Value) const {
527 O << "0x" << std::hex << Value << std::dec;
528}
529
530/// EOL - Print a newline character to asm stream. If a comment is present
531/// then it will be printed first. Comments should not contain '\n'.
532void AsmPrinter::EOL() const {
533 O << "\n";
534}
535void AsmPrinter::EOL(const std::string &Comment) const {
536 if (AsmVerbose && !Comment.empty()) {
537 O << "\t"
538 << TAI->getCommentString()
539 << " "
540 << Comment;
541 }
542 O << "\n";
543}
544
545/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
546/// unsigned leb128 value.
547void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
548 if (TAI->hasLEB128()) {
549 O << "\t.uleb128\t"
550 << Value;
551 } else {
552 O << TAI->getData8bitsDirective();
553 PrintULEB128(Value);
554 }
555}
556
557/// EmitSLEB128Bytes - print an assembler byte data directive to compose a
558/// signed leb128 value.
559void AsmPrinter::EmitSLEB128Bytes(int Value) const {
560 if (TAI->hasLEB128()) {
561 O << "\t.sleb128\t"
562 << Value;
563 } else {
564 O << TAI->getData8bitsDirective();
565 PrintSLEB128(Value);
566 }
567}
568
569/// EmitInt8 - Emit a byte directive and value.
570///
571void AsmPrinter::EmitInt8(int Value) const {
572 O << TAI->getData8bitsDirective();
573 PrintHex(Value & 0xFF);
574}
575
576/// EmitInt16 - Emit a short directive and value.
577///
578void AsmPrinter::EmitInt16(int Value) const {
579 O << TAI->getData16bitsDirective();
580 PrintHex(Value & 0xFFFF);
581}
582
583/// EmitInt32 - Emit a long directive and value.
584///
585void AsmPrinter::EmitInt32(int Value) const {
586 O << TAI->getData32bitsDirective();
587 PrintHex(Value);
588}
589
590/// EmitInt64 - Emit a long long directive and value.
591///
592void AsmPrinter::EmitInt64(uint64_t Value) const {
593 if (TAI->getData64bitsDirective()) {
594 O << TAI->getData64bitsDirective();
595 PrintHex(Value);
596 } else {
597 if (TM.getTargetData()->isBigEndian()) {
598 EmitInt32(unsigned(Value >> 32)); O << "\n";
599 EmitInt32(unsigned(Value));
600 } else {
601 EmitInt32(unsigned(Value)); O << "\n";
602 EmitInt32(unsigned(Value >> 32));
603 }
604 }
605}
606
607/// toOctal - Convert the low order bits of X into an octal digit.
608///
609static inline char toOctal(int X) {
610 return (X&7)+'0';
611}
612
613/// printStringChar - Print a char, escaped if necessary.
614///
615static void printStringChar(std::ostream &O, unsigned char C) {
616 if (C == '"') {
617 O << "\\\"";
618 } else if (C == '\\') {
619 O << "\\\\";
620 } else if (isprint(C)) {
621 O << C;
622 } else {
623 switch(C) {
624 case '\b': O << "\\b"; break;
625 case '\f': O << "\\f"; break;
626 case '\n': O << "\\n"; break;
627 case '\r': O << "\\r"; break;
628 case '\t': O << "\\t"; break;
629 default:
630 O << '\\';
631 O << toOctal(C >> 6);
632 O << toOctal(C >> 3);
633 O << toOctal(C >> 0);
634 break;
635 }
636 }
637}
638
639/// EmitString - Emit a string with quotes and a null terminator.
640/// Special characters are emitted properly.
641/// \literal (Eg. '\t') \endliteral
642void AsmPrinter::EmitString(const std::string &String) const {
643 const char* AscizDirective = TAI->getAscizDirective();
644 if (AscizDirective)
645 O << AscizDirective;
646 else
647 O << TAI->getAsciiDirective();
648 O << "\"";
649 for (unsigned i = 0, N = String.size(); i < N; ++i) {
650 unsigned char C = String[i];
651 printStringChar(O, C);
652 }
653 if (AscizDirective)
654 O << "\"";
655 else
656 O << "\\0\"";
657}
658
659
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000660/// EmitFile - Emit a .file directive.
661void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
662 O << "\t.file\t" << Number << " \"";
663 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
664 unsigned char C = Name[i];
665 printStringChar(O, C);
666 }
667 O << "\"";
668}
669
670
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671//===----------------------------------------------------------------------===//
672
673// EmitAlignment - Emit an alignment directive to the specified power of
674// two boundary. For example, if you pass in 3 here, you will get an 8
675// byte alignment. If a global value is specified, and if that global has
676// an explicit alignment requested, it will unconditionally override the
677// alignment request. However, if ForcedAlignBits is specified, this value
678// has final say: the ultimate alignment will be the max of ForcedAlignBits
679// and the alignment computed with NumBits and the global.
680//
681// The algorithm is:
682// Align = NumBits;
683// if (GV && GV->hasalignment) Align = GV->getalignment();
684// Align = std::max(Align, ForcedAlignBits);
685//
686void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Cheng45c1edb2008-02-28 00:43:03 +0000687 unsigned ForcedAlignBits) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 if (GV && GV->getAlignment())
689 NumBits = Log2_32(GV->getAlignment());
690 NumBits = std::max(NumBits, ForcedAlignBits);
691
692 if (NumBits == 0) return; // No need to emit alignment.
693 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
Evan Chengc1f41aa2007-07-25 23:35:07 +0000694 O << TAI->getAlignDirective() << NumBits;
Evan Cheng45c1edb2008-02-28 00:43:03 +0000695
696 unsigned FillValue = TAI->getTextAlignFillValue();
697 bool UseFillExpr = IsInTextSection && FillValue;
Evan Chengc1f41aa2007-07-25 23:35:07 +0000698 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
699 O << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700}
701
702
703/// EmitZeros - Emit a block of zeros.
704///
705void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
706 if (NumZeros) {
707 if (TAI->getZeroDirective()) {
708 O << TAI->getZeroDirective() << NumZeros;
709 if (TAI->getZeroDirectiveSuffix())
710 O << TAI->getZeroDirectiveSuffix();
711 O << "\n";
712 } else {
713 for (; NumZeros; --NumZeros)
714 O << TAI->getData8bitsDirective() << "0\n";
715 }
716 }
717}
718
719// Print out the specified constant, without a storage class. Only the
720// constants valid in constant expressions can occur here.
721void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
722 if (CV->isNullValue() || isa<UndefValue>(CV))
723 O << "0";
724 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
725 O << CI->getZExtValue();
726 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
727 // This is a constant address for a global variable or function. Use the
728 // name of the variable or function as the address value, possibly
729 // decorating it with GlobalVarAddrPrefix/Suffix or
730 // FunctionAddrPrefix/Suffix (these all default to "" )
731 if (isa<Function>(GV)) {
732 O << TAI->getFunctionAddrPrefix()
733 << Mang->getValueName(GV)
734 << TAI->getFunctionAddrSuffix();
735 } else {
736 O << TAI->getGlobalVarAddrPrefix()
737 << Mang->getValueName(GV)
738 << TAI->getGlobalVarAddrSuffix();
739 }
740 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
741 const TargetData *TD = TM.getTargetData();
742 unsigned Opcode = CE->getOpcode();
743 switch (Opcode) {
744 case Instruction::GetElementPtr: {
745 // generate a symbolic expression for the byte address
746 const Constant *ptrVal = CE->getOperand(0);
747 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
748 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
749 idxVec.size())) {
750 if (Offset)
751 O << "(";
752 EmitConstantValueOnly(ptrVal);
753 if (Offset > 0)
754 O << ") + " << Offset;
755 else if (Offset < 0)
756 O << ") - " << -Offset;
757 } else {
758 EmitConstantValueOnly(ptrVal);
759 }
760 break;
761 }
762 case Instruction::Trunc:
763 case Instruction::ZExt:
764 case Instruction::SExt:
765 case Instruction::FPTrunc:
766 case Instruction::FPExt:
767 case Instruction::UIToFP:
768 case Instruction::SIToFP:
769 case Instruction::FPToUI:
770 case Instruction::FPToSI:
771 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
772 break;
773 case Instruction::BitCast:
774 return EmitConstantValueOnly(CE->getOperand(0));
775
776 case Instruction::IntToPtr: {
777 // Handle casts to pointers by changing them into casts to the appropriate
778 // integer type. This promotes constant folding and simplifies this code.
779 Constant *Op = CE->getOperand(0);
780 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
781 return EmitConstantValueOnly(Op);
782 }
783
784
785 case Instruction::PtrToInt: {
786 // Support only foldable casts to/from pointers that can be eliminated by
787 // changing the pointer to the appropriately sized integer type.
788 Constant *Op = CE->getOperand(0);
789 const Type *Ty = CE->getType();
790
791 // We can emit the pointer value into this slot if the slot is an
792 // integer slot greater or equal to the size of the pointer.
793 if (Ty->isInteger() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000794 TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 return EmitConstantValueOnly(Op);
796
797 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
798 EmitConstantValueOnly(Op);
799 break;
800 }
801 case Instruction::Add:
802 case Instruction::Sub:
Anton Korobeynikovd3b58742007-12-18 20:53:41 +0000803 case Instruction::And:
804 case Instruction::Or:
805 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 O << "(";
807 EmitConstantValueOnly(CE->getOperand(0));
Anton Korobeynikovd3b58742007-12-18 20:53:41 +0000808 O << ")";
809 switch (Opcode) {
810 case Instruction::Add:
811 O << " + ";
812 break;
813 case Instruction::Sub:
814 O << " - ";
815 break;
816 case Instruction::And:
817 O << " & ";
818 break;
819 case Instruction::Or:
820 O << " | ";
821 break;
822 case Instruction::Xor:
823 O << " ^ ";
824 break;
825 default:
826 break;
827 }
828 O << "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 EmitConstantValueOnly(CE->getOperand(1));
830 O << ")";
831 break;
832 default:
833 assert(0 && "Unsupported operator!");
834 }
835 } else {
836 assert(0 && "Unknown constant value!");
837 }
838}
839
840/// printAsCString - Print the specified array as a C compatible string, only if
841/// the predicate isString is true.
842///
843static void printAsCString(std::ostream &O, const ConstantArray *CVA,
844 unsigned LastElt) {
845 assert(CVA->isString() && "Array is not string compatible!");
846
847 O << "\"";
848 for (unsigned i = 0; i != LastElt; ++i) {
849 unsigned char C =
850 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
851 printStringChar(O, C);
852 }
853 O << "\"";
854}
855
856/// EmitString - Emit a zero-byte-terminated string constant.
857///
858void AsmPrinter::EmitString(const ConstantArray *CVA) const {
859 unsigned NumElts = CVA->getNumOperands();
860 if (TAI->getAscizDirective() && NumElts &&
861 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
862 O << TAI->getAscizDirective();
863 printAsCString(O, CVA, NumElts-1);
864 } else {
865 O << TAI->getAsciiDirective();
866 printAsCString(O, CVA, NumElts);
867 }
868 O << "\n";
869}
870
871/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Duncan Sands8157ef42007-11-05 00:04:43 +0000872/// If Packed is false, pad to the ABI size.
873void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874 const TargetData *TD = TM.getTargetData();
Duncan Sands8157ef42007-11-05 00:04:43 +0000875 unsigned Size = Packed ?
876 TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877
878 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Duncan Sands8157ef42007-11-05 00:04:43 +0000879 EmitZeros(Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 return;
881 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
882 if (CVA->isString()) {
883 EmitString(CVA);
884 } else { // Not a string. Print the values in successive locations
Duncan Sands8157ef42007-11-05 00:04:43 +0000885 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
886 EmitGlobalConstant(CVA->getOperand(i), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 }
888 return;
889 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
890 // Print the fields in successive locations. Pad to align if needed!
891 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
892 uint64_t sizeSoFar = 0;
893 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
894 const Constant* field = CVS->getOperand(i);
895
896 // Check if padding is needed and insert one or more 0s.
Duncan Sands8157ef42007-11-05 00:04:43 +0000897 uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000898 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 - cvsLayout->getElementOffset(i)) - fieldSize;
900 sizeSoFar += fieldSize + padSize;
901
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000902 // Now print the actual field value without ABI size padding.
903 EmitGlobalConstant(field, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000905 // Insert padding - this may include padding to increase the size of the
906 // current field up to the ABI size (if the struct is not packed) as well
907 // as padding to ensure that the next field starts at the right offset.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 EmitZeros(padSize);
909 }
910 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
911 "Layout of constant struct may be incorrect!");
912 return;
913 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
914 // FP Constants are printed as integer constants to avoid losing
915 // precision...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 if (CFP->getType() == Type::DoubleTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000917 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000918 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 if (TAI->getData64bitsDirective())
Dale Johannesen1616e902007-09-11 18:32:33 +0000920 O << TAI->getData64bitsDirective() << i << "\t"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 << TAI->getCommentString() << " double value: " << Val << "\n";
922 else if (TD->isBigEndian()) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000923 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 << "\t" << TAI->getCommentString()
925 << " double most significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000926 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 << "\t" << TAI->getCommentString()
928 << " double least significant word " << Val << "\n";
929 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +0000930 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 << "\t" << TAI->getCommentString()
932 << " double least significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000933 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 << "\t" << TAI->getCommentString()
935 << " double most significant word " << Val << "\n";
936 }
937 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000938 } else if (CFP->getType() == Type::FloatTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000939 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
940 O << TAI->getData32bitsDirective()
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000941 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
943 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000944 } else if (CFP->getType() == Type::X86_FP80Ty) {
945 // all long double variants are printed as hex
Dale Johannesen693aa822007-09-26 23:20:33 +0000946 // api needed to prevent premature destruction
947 APInt api = CFP->getValueAPF().convertToAPInt();
948 const uint64_t *p = api.getRawData();
Chris Lattner00d63062008-01-27 06:09:28 +0000949 APFloat DoubleVal = CFP->getValueAPF();
950 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000951 if (TD->isBigEndian()) {
952 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
953 << "\t" << TAI->getCommentString()
Chris Lattner00d63062008-01-27 06:09:28 +0000954 << " long double most significant halfword of ~"
955 << DoubleVal.convertToDouble() << "\n";
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000956 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
957 << "\t" << TAI->getCommentString()
958 << " long double next halfword\n";
959 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
960 << "\t" << TAI->getCommentString()
961 << " long double next halfword\n";
962 O << TAI->getData16bitsDirective() << uint16_t(p[0])
963 << "\t" << TAI->getCommentString()
964 << " long double next halfword\n";
965 O << TAI->getData16bitsDirective() << uint16_t(p[1])
966 << "\t" << TAI->getCommentString()
967 << " long double least significant halfword\n";
968 } else {
969 O << TAI->getData16bitsDirective() << uint16_t(p[1])
970 << "\t" << TAI->getCommentString()
Chris Lattner00d63062008-01-27 06:09:28 +0000971 << " long double least significant halfword of ~"
972 << DoubleVal.convertToDouble() << "\n";
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000973 O << TAI->getData16bitsDirective() << uint16_t(p[0])
974 << "\t" << TAI->getCommentString()
975 << " long double next halfword\n";
976 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
977 << "\t" << TAI->getCommentString()
978 << " long double next halfword\n";
979 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
980 << "\t" << TAI->getCommentString()
981 << " long double next halfword\n";
982 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
983 << "\t" << TAI->getCommentString()
984 << " long double most significant halfword\n";
985 }
Duncan Sands8157ef42007-11-05 00:04:43 +0000986 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000987 return;
Dale Johannesend3b6af32007-10-11 23:32:15 +0000988 } else if (CFP->getType() == Type::PPC_FP128Ty) {
989 // all long double variants are printed as hex
990 // api needed to prevent premature destruction
991 APInt api = CFP->getValueAPF().convertToAPInt();
992 const uint64_t *p = api.getRawData();
993 if (TD->isBigEndian()) {
994 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
995 << "\t" << TAI->getCommentString()
996 << " long double most significant word\n";
997 O << TAI->getData32bitsDirective() << uint32_t(p[0])
998 << "\t" << TAI->getCommentString()
999 << " long double next word\n";
1000 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
1001 << "\t" << TAI->getCommentString()
1002 << " long double next word\n";
1003 O << TAI->getData32bitsDirective() << uint32_t(p[1])
1004 << "\t" << TAI->getCommentString()
1005 << " long double least significant word\n";
1006 } else {
1007 O << TAI->getData32bitsDirective() << uint32_t(p[1])
1008 << "\t" << TAI->getCommentString()
1009 << " long double least significant word\n";
1010 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
1011 << "\t" << TAI->getCommentString()
1012 << " long double next word\n";
1013 O << TAI->getData32bitsDirective() << uint32_t(p[0])
1014 << "\t" << TAI->getCommentString()
1015 << " long double next word\n";
1016 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
1017 << "\t" << TAI->getCommentString()
1018 << " long double most significant word\n";
1019 }
1020 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00001021 } else assert(0 && "Floating point constant type not handled");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 } else if (CV->getType() == Type::Int64Ty) {
1023 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1024 uint64_t Val = CI->getZExtValue();
1025
1026 if (TAI->getData64bitsDirective())
1027 O << TAI->getData64bitsDirective() << Val << "\n";
1028 else if (TD->isBigEndian()) {
1029 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1030 << "\t" << TAI->getCommentString()
1031 << " Double-word most significant word " << Val << "\n";
1032 O << TAI->getData32bitsDirective() << unsigned(Val)
1033 << "\t" << TAI->getCommentString()
1034 << " Double-word least significant word " << Val << "\n";
1035 } else {
1036 O << TAI->getData32bitsDirective() << unsigned(Val)
1037 << "\t" << TAI->getCommentString()
1038 << " Double-word least significant word " << Val << "\n";
1039 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1040 << "\t" << TAI->getCommentString()
1041 << " Double-word most significant word " << Val << "\n";
1042 }
1043 return;
1044 }
1045 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1046 const VectorType *PTy = CP->getType();
1047
1048 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
Duncan Sands8157ef42007-11-05 00:04:43 +00001049 EmitGlobalConstant(CP->getOperand(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 return;
1052 }
1053
1054 const Type *type = CV->getType();
1055 printDataDirective(type);
1056 EmitConstantValueOnly(CV);
1057 O << "\n";
1058}
1059
1060void
1061AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1062 // Target doesn't support this yet!
1063 abort();
1064}
1065
1066/// PrintSpecial - Print information related to the specified machine instr
1067/// that is independent of the operand, and may be independent of the instr
1068/// itself. This can be useful for portably encoding the comment character
1069/// or other bits of target-specific knowledge into the asmstrings. The
1070/// syntax used is ${:comment}. Targets can override this to add support
1071/// for their own strange codes.
1072void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1073 if (!strcmp(Code, "private")) {
1074 O << TAI->getPrivateGlobalPrefix();
1075 } else if (!strcmp(Code, "comment")) {
1076 O << TAI->getCommentString();
1077 } else if (!strcmp(Code, "uid")) {
1078 // Assign a unique ID to this machine instruction.
1079 static const MachineInstr *LastMI = 0;
1080 static const Function *F = 0;
1081 static unsigned Counter = 0U-1;
1082
1083 // Comparing the address of MI isn't sufficient, because machineinstrs may
1084 // be allocated to the same address across functions.
1085 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1086
1087 // If this is a new machine instruction, bump the counter.
1088 if (LastMI != MI || F != ThisF) {
1089 ++Counter;
1090 LastMI = MI;
1091 F = ThisF;
1092 }
1093 O << Counter;
1094 } else {
1095 cerr << "Unknown special formatter '" << Code
1096 << "' for machine instr: " << *MI;
1097 exit(1);
1098 }
1099}
1100
1101
1102/// printInlineAsm - This method formats and prints the specified machine
1103/// instruction that is an inline asm.
1104void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1105 unsigned NumOperands = MI->getNumOperands();
1106
1107 // Count the number of register definitions.
1108 unsigned NumDefs = 0;
Dan Gohman38a9a9f2007-09-14 20:33:02 +00001109 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 ++NumDefs)
1111 assert(NumDefs != NumOperands-1 && "No asm string?");
1112
1113 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1114
1115 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1116 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1117
Dale Johannesene99fc902008-01-29 02:21:21 +00001118 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1119 // These are useful to see where empty asm's wound up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 if (AsmStr[0] == 0) {
Dale Johannesene99fc902008-01-29 02:21:21 +00001121 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 return;
1123 }
1124
1125 O << TAI->getInlineAsmStart() << "\n\t";
1126
1127 // The variant of the current asmprinter.
1128 int AsmPrinterVariant = TAI->getAssemblerDialect();
1129
1130 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1131 const char *LastEmitted = AsmStr; // One past the last character emitted.
1132
1133 while (*LastEmitted) {
1134 switch (*LastEmitted) {
1135 default: {
1136 // Not a special case, emit the string section literally.
1137 const char *LiteralEnd = LastEmitted+1;
1138 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1139 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1140 ++LiteralEnd;
1141 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1142 O.write(LastEmitted, LiteralEnd-LastEmitted);
1143 LastEmitted = LiteralEnd;
1144 break;
1145 }
1146 case '\n':
1147 ++LastEmitted; // Consume newline character.
1148 O << "\n"; // Indent code with newline.
1149 break;
1150 case '$': {
1151 ++LastEmitted; // Consume '$' character.
1152 bool Done = true;
1153
1154 // Handle escapes.
1155 switch (*LastEmitted) {
1156 default: Done = false; break;
1157 case '$': // $$ -> $
1158 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1159 O << '$';
1160 ++LastEmitted; // Consume second '$' character.
1161 break;
1162 case '(': // $( -> same as GCC's { character.
1163 ++LastEmitted; // Consume '(' character.
1164 if (CurVariant != -1) {
1165 cerr << "Nested variants found in inline asm string: '"
1166 << AsmStr << "'\n";
1167 exit(1);
1168 }
1169 CurVariant = 0; // We're in the first variant now.
1170 break;
1171 case '|':
1172 ++LastEmitted; // consume '|' character.
1173 if (CurVariant == -1) {
1174 cerr << "Found '|' character outside of variant in inline asm "
1175 << "string: '" << AsmStr << "'\n";
1176 exit(1);
1177 }
1178 ++CurVariant; // We're in the next variant.
1179 break;
1180 case ')': // $) -> same as GCC's } char.
1181 ++LastEmitted; // consume ')' character.
1182 if (CurVariant == -1) {
1183 cerr << "Found '}' character outside of variant in inline asm "
1184 << "string: '" << AsmStr << "'\n";
1185 exit(1);
1186 }
1187 CurVariant = -1;
1188 break;
1189 }
1190 if (Done) break;
1191
1192 bool HasCurlyBraces = false;
1193 if (*LastEmitted == '{') { // ${variable}
1194 ++LastEmitted; // Consume '{' character.
1195 HasCurlyBraces = true;
1196 }
1197
1198 const char *IDStart = LastEmitted;
1199 char *IDEnd;
1200 errno = 0;
1201 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1202 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1203 cerr << "Bad $ operand number in inline asm string: '"
1204 << AsmStr << "'\n";
1205 exit(1);
1206 }
1207 LastEmitted = IDEnd;
1208
1209 char Modifier[2] = { 0, 0 };
1210
1211 if (HasCurlyBraces) {
1212 // If we have curly braces, check for a modifier character. This
1213 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1214 if (*LastEmitted == ':') {
1215 ++LastEmitted; // Consume ':' character.
1216 if (*LastEmitted == 0) {
1217 cerr << "Bad ${:} expression in inline asm string: '"
1218 << AsmStr << "'\n";
1219 exit(1);
1220 }
1221
1222 Modifier[0] = *LastEmitted;
1223 ++LastEmitted; // Consume modifier character.
1224 }
1225
1226 if (*LastEmitted != '}') {
1227 cerr << "Bad ${} expression in inline asm string: '"
1228 << AsmStr << "'\n";
1229 exit(1);
1230 }
1231 ++LastEmitted; // Consume '}' character.
1232 }
1233
1234 if ((unsigned)Val >= NumOperands-1) {
1235 cerr << "Invalid $ operand number in inline asm string: '"
1236 << AsmStr << "'\n";
1237 exit(1);
1238 }
1239
1240 // Okay, we finally have a value number. Ask the target to print this
1241 // operand!
1242 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1243 unsigned OpNo = 1;
1244
1245 bool Error = false;
1246
1247 // Scan to find the machine operand number for the operand.
1248 for (; Val; --Val) {
1249 if (OpNo >= MI->getNumOperands()) break;
Chris Lattnerda4cff12007-12-30 20:50:28 +00001250 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 OpNo += (OpFlags >> 3) + 1;
1252 }
1253
1254 if (OpNo >= MI->getNumOperands()) {
1255 Error = true;
1256 } else {
Chris Lattnerda4cff12007-12-30 20:50:28 +00001257 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 ++OpNo; // Skip over the ID number.
1259
Dale Johannesencfb19e62007-11-05 21:20:28 +00001260 if (Modifier[0]=='l') // labels are target independent
Chris Lattner6017d482007-12-30 23:10:15 +00001261 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
Evan Cheng45c1edb2008-02-28 00:43:03 +00001262 false, false, false);
Dale Johannesencfb19e62007-11-05 21:20:28 +00001263 else {
1264 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1265 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1266 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1267 Modifier[0] ? Modifier : 0);
1268 } else {
1269 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1270 Modifier[0] ? Modifier : 0);
1271 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 }
1273 }
1274 if (Error) {
1275 cerr << "Invalid operand found in inline asm: '"
1276 << AsmStr << "'\n";
1277 MI->dump();
1278 exit(1);
1279 }
1280 }
1281 break;
1282 }
1283 }
1284 }
1285 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1286}
1287
1288/// printLabel - This method prints a local label used by debug and
1289/// exception handling tables.
1290void AsmPrinter::printLabel(const MachineInstr *MI) const {
Evan Cheng8b988692008-02-02 08:39:46 +00001291 O << TAI->getPrivateGlobalPrefix()
Chris Lattnerda4cff12007-12-30 20:50:28 +00001292 << "label" << MI->getOperand(0).getImm() << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293}
1294
Evan Chenga53c40a2008-02-01 09:10:45 +00001295void AsmPrinter::printLabel(unsigned Id) const {
Evan Cheng8b988692008-02-02 08:39:46 +00001296 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
Evan Chenga53c40a2008-02-01 09:10:45 +00001297}
1298
Evan Cheng2e28d622008-02-02 04:07:54 +00001299/// printDeclare - This method prints a local variable declaration used by
1300/// debug tables.
Evan Chengc439a852008-02-04 23:06:48 +00001301/// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1302/// entry into dwarf table.
Evan Cheng2e28d622008-02-02 04:07:54 +00001303void AsmPrinter::printDeclare(const MachineInstr *MI) const {
Evan Chengc439a852008-02-04 23:06:48 +00001304 int FI = MI->getOperand(0).getIndex();
1305 GlobalValue *GV = MI->getOperand(1).getGlobal();
1306 MMI->RecordVariable(GV, FI);
Evan Cheng2e28d622008-02-02 04:07:54 +00001307}
1308
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1310/// instruction, using the specified assembler variant. Targets should
1311/// overried this to format as appropriate.
1312bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1313 unsigned AsmVariant, const char *ExtraCode) {
1314 // Target doesn't support this yet!
1315 return true;
1316}
1317
1318bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1319 unsigned AsmVariant,
1320 const char *ExtraCode) {
1321 // Target doesn't support this yet!
1322 return true;
1323}
1324
1325/// printBasicBlockLabel - This method prints the label for the specified
1326/// MachineBasicBlock
1327void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
Evan Cheng45c1edb2008-02-28 00:43:03 +00001328 bool printAlign,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 bool printColon,
1330 bool printComment) const {
Evan Cheng45c1edb2008-02-28 00:43:03 +00001331 if (printAlign) {
1332 unsigned Align = MBB->getAlignment();
1333 if (Align)
1334 EmitAlignment(Log2_32(Align));
1335 }
1336
Evan Cheng477013c2007-10-14 05:57:21 +00001337 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1338 << MBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 if (printColon)
1340 O << ':';
1341 if (printComment && MBB->getBasicBlock())
Dan Gohman0912cda2007-07-30 15:06:25 +00001342 O << '\t' << TAI->getCommentString() << ' '
1343 << MBB->getBasicBlock()->getName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344}
1345
Evan Cheng6fb06762007-11-09 01:32:10 +00001346/// printPICJumpTableSetLabel - This method prints a set label for the
1347/// specified MachineBasicBlock for a jumptable entry.
1348void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1349 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 if (!TAI->getSetDirective())
1351 return;
1352
1353 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001354 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
Evan Cheng45c1edb2008-02-28 00:43:03 +00001355 printBasicBlockLabel(MBB, false, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001356 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1357 << '_' << uid << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358}
1359
Evan Cheng6fb06762007-11-09 01:32:10 +00001360void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1361 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 if (!TAI->getSetDirective())
1363 return;
1364
1365 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001366 << getFunctionNumber() << '_' << uid << '_' << uid2
1367 << "_set_" << MBB->getNumber() << ',';
Evan Cheng45c1edb2008-02-28 00:43:03 +00001368 printBasicBlockLabel(MBB, false, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001369 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1370 << '_' << uid << '_' << uid2 << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371}
1372
1373/// printDataDirective - This method prints the asm directive for the
1374/// specified type.
1375void AsmPrinter::printDataDirective(const Type *type) {
1376 const TargetData *TD = TM.getTargetData();
1377 switch (type->getTypeID()) {
1378 case Type::IntegerTyID: {
1379 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1380 if (BitWidth <= 8)
1381 O << TAI->getData8bitsDirective();
1382 else if (BitWidth <= 16)
1383 O << TAI->getData16bitsDirective();
1384 else if (BitWidth <= 32)
1385 O << TAI->getData32bitsDirective();
1386 else if (BitWidth <= 64) {
1387 assert(TAI->getData64bitsDirective() &&
1388 "Target cannot handle 64-bit constant exprs!");
1389 O << TAI->getData64bitsDirective();
1390 }
1391 break;
1392 }
1393 case Type::PointerTyID:
1394 if (TD->getPointerSize() == 8) {
1395 assert(TAI->getData64bitsDirective() &&
1396 "Target cannot handle 64-bit pointer exprs!");
1397 O << TAI->getData64bitsDirective();
1398 } else {
1399 O << TAI->getData32bitsDirective();
1400 }
1401 break;
1402 case Type::FloatTyID: case Type::DoubleTyID:
Dale Johannesen3b5303b2007-09-28 18:06:58 +00001403 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404 assert (0 && "Should have already output floating point constant.");
1405 default:
1406 assert (0 && "Can't handle printing this type of thing");
1407 break;
1408 }
1409}
1410