blob: 2acf287988bd19359458a1bb5f92450c92eceddd [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 Cheng477013c2007-10-14 05:57:21 +000042 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043{}
44
45std::string AsmPrinter::getSectionForFunction(const Function &F) const {
46 return TAI->getTextSection();
47}
48
49
50/// SwitchToTextSection - Switch to the specified text section of the executable
51/// if we are not already in it!
52///
53void AsmPrinter::SwitchToTextSection(const char *NewSection,
54 const GlobalValue *GV) {
55 std::string NS;
56 if (GV && GV->hasSection())
57 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
58 else
59 NS = NewSection;
60
61 // If we're already in this section, we're done.
62 if (CurrentSection == NS) return;
63
64 // Close the current section, if applicable.
65 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
66 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
67
68 CurrentSection = NS;
69
70 if (!CurrentSection.empty())
71 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
72}
73
74/// SwitchToDataSection - Switch to the specified data section of the executable
75/// if we are not already in it!
76///
77void AsmPrinter::SwitchToDataSection(const char *NewSection,
78 const GlobalValue *GV) {
79 std::string NS;
80 if (GV && GV->hasSection())
81 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
82 else
83 NS = NewSection;
84
85 // If we're already in this section, we're done.
86 if (CurrentSection == NS) return;
87
88 // Close the current section, if applicable.
89 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
90 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
91
92 CurrentSection = NS;
93
94 if (!CurrentSection.empty())
95 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
96}
97
98
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000099void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
100 MachineFunctionPass::getAnalysisUsage(AU);
101 AU.addRequired<CollectorModuleMetadata>();
102}
103
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104bool AsmPrinter::doInitialization(Module &M) {
105 Mang = new Mangler(M, TAI->getGlobalPrefix());
106
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000107 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
108 assert(CMM && "AsmPrinter didn't require CollectorModuleMetadata?");
109 for (CollectorModuleMetadata::iterator I = CMM->begin(),
110 E = CMM->end(); I != E; ++I)
111 (*I)->beginAssembly(O, *this, *TAI);
112
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 if (!M.getModuleInlineAsm().empty())
114 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
115 << M.getModuleInlineAsm()
116 << "\n" << TAI->getCommentString()
117 << " End of file scope inline assembly\n";
118
119 SwitchToDataSection(""); // Reset back to no section.
120
121 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
122 MMI->AnalyzeModule(M);
123 }
124
125 return false;
126}
127
128bool AsmPrinter::doFinalization(Module &M) {
129 if (TAI->getWeakRefDirective()) {
130 if (!ExtWeakSymbols.empty())
131 SwitchToDataSection("");
132
133 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
134 e = ExtWeakSymbols.end(); i != e; ++i) {
135 const GlobalValue *GV = *i;
136 std::string Name = Mang->getValueName(GV);
137 O << TAI->getWeakRefDirective() << Name << "\n";
138 }
139 }
140
141 if (TAI->getSetDirective()) {
142 if (!M.alias_empty())
143 SwitchToTextSection(TAI->getTextSection());
144
145 O << "\n";
146 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
147 I!=E; ++I) {
148 std::string Name = Mang->getValueName(I);
149 std::string Target;
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000150
151 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
152 Target = Mang->getValueName(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000154 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 O << "\t.globl\t" << Name << "\n";
156 else if (I->hasWeakLinkage())
157 O << TAI->getWeakRefDirective() << Name << "\n";
158 else if (!I->hasInternalLinkage())
159 assert(0 && "Invalid alias linkage");
160
161 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000162
163 // If the aliasee has external weak linkage it can be referenced only by
164 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
165 // weak reference in such case.
166 if (GV->hasExternalWeakLinkage())
167 if (TAI->getWeakRefDirective())
168 O << TAI->getWeakRefDirective() << Target << "\n";
169 else
170 O << "\t.globl\t" << Target << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 }
172 }
173
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000174 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
175 assert(CMM && "AsmPrinter didn't require CollectorModuleMetadata?");
176 for (CollectorModuleMetadata::iterator I = CMM->end(),
177 E = CMM->begin(); I != E; )
178 (*--I)->finishAssembly(O, *this, *TAI);
179
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 delete Mang; Mang = 0;
181 return false;
182}
183
Bill Wendlinge9ecdcf2007-09-18 09:10:16 +0000184std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
Bill Wendlingef9211a2007-09-18 01:47:22 +0000185 assert(MF && "No machine function?");
Bill Wendlingd2144aa2007-09-18 05:03:44 +0000186 return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
187 TAI->getGlobalPrefix());
Bill Wendlingef9211a2007-09-18 01:47:22 +0000188}
189
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
191 // What's my mangled name?
192 CurrentFnName = Mang->getValueName(MF.getFunction());
Evan Cheng477013c2007-10-14 05:57:21 +0000193 IncrementFunctionNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194}
195
196/// EmitConstantPool - Print to the current output stream assembly
197/// representations of the constants in the constant pool MCP. This is
198/// used to print out constants which have been "spilled to memory" by
199/// the code generator.
200///
201void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
202 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
203 if (CP.empty()) return;
204
205 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
206 // in special sections.
207 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
208 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
209 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
210 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
211 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
212 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
213 MachineConstantPoolEntry CPE = CP[i];
214 const Type *Ty = CPE.getType();
215 if (TAI->getFourByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000216 TM.getTargetData()->getABITypeSize(Ty) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 FourByteCPs.push_back(std::make_pair(CPE, i));
218 else if (TAI->getEightByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000219 TM.getTargetData()->getABITypeSize(Ty) == 8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 EightByteCPs.push_back(std::make_pair(CPE, i));
221 else if (TAI->getSixteenByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000222 TM.getTargetData()->getABITypeSize(Ty) == 16)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 SixteenByteCPs.push_back(std::make_pair(CPE, i));
224 else
225 OtherCPs.push_back(std::make_pair(CPE, i));
226 }
227
228 unsigned Alignment = MCP->getConstantPoolAlignment();
229 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
230 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
231 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
232 SixteenByteCPs);
233 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
234}
235
236void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
237 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
238 if (CP.empty()) return;
239
240 SwitchToDataSection(Section);
241 EmitAlignment(Alignment);
242 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Evan Cheng477013c2007-10-14 05:57:21 +0000243 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
244 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
246 if (CP[i].first.isMachineConstantPoolEntry())
247 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
248 else
249 EmitGlobalConstant(CP[i].first.Val.ConstVal);
250 if (i != e-1) {
251 const Type *Ty = CP[i].first.getType();
252 unsigned EntSize =
Duncan Sands8157ef42007-11-05 00:04:43 +0000253 TM.getTargetData()->getABITypeSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
255 // Emit inter-object padding for alignment.
256 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
257 }
258 }
259}
260
261/// EmitJumpTableInfo - Print assembly representations of the jump tables used
262/// by the current function to the current output stream.
263///
264void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
265 MachineFunction &MF) {
266 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
267 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000268
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
270
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 // Pick the directive to use to print the jump table entries, and switch to
272 // the appropriate section.
273 TargetLowering *LoweringInfo = TM.getTargetLowering();
274
275 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
276 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
277 !JumpTableDataSection) {
278 // In PIC mode, we need to emit the jump table to the same section as the
279 // function body itself, otherwise the label differences won't make sense.
280 // We should also do if the section name is NULL.
281 const Function *F = MF.getFunction();
282 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
283 } else {
284 SwitchToDataSection(JumpTableDataSection);
285 }
286
287 EmitAlignment(Log2_32(MJTI->getAlignment()));
288
289 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
290 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
291
292 // If this jump table was deleted, ignore it.
293 if (JTBBs.empty()) continue;
294
295 // For PIC codegen, if possible we want to use the SetDirective to reduce
296 // the number of relocations the assembler will generate for the jump table.
297 // Set directives are all printed before the jump table itself.
Evan Cheng6fb06762007-11-09 01:32:10 +0000298 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 if (TAI->getSetDirective() && IsPic)
300 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Evan Cheng6fb06762007-11-09 01:32:10 +0000301 if (EmittedSets.insert(JTBBs[ii]))
302 printPICJumpTableSetLabel(i, JTBBs[ii]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303
304 // On some targets (e.g. darwin) we want to emit two consequtive labels
305 // before each jump table. The first label is never referenced, but tells
306 // the assembler and linker the extents of the jump table object. The
307 // second label is actually referenced by the code.
308 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
Evan Cheng477013c2007-10-14 05:57:21 +0000309 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310
Evan Cheng477013c2007-10-14 05:57:21 +0000311 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
312 << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313
314 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000315 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 O << '\n';
317 }
318 }
319}
320
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000321void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
322 const MachineBasicBlock *MBB,
323 unsigned uid) const {
324 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
325
326 // Use JumpTableDirective otherwise honor the entry size from the jump table
327 // info.
328 const char *JTEntryDirective = TAI->getJumpTableDirective();
329 bool HadJTEntryDirective = JTEntryDirective != NULL;
330 if (!HadJTEntryDirective) {
331 JTEntryDirective = MJTI->getEntrySize() == 4 ?
332 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
333 }
334
335 O << JTEntryDirective << ' ';
336
337 // If we have emitted set directives for the jump table entries, print
338 // them rather than the entries themselves. If we're emitting PIC, then
339 // emit the table entries as differences between two text section labels.
340 // If we're emitting non-PIC code, then emit the entries as direct
341 // references to the target basic blocks.
342 if (IsPic) {
343 if (TAI->getSetDirective()) {
344 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
345 << '_' << uid << "_set_" << MBB->getNumber();
346 } else {
347 printBasicBlockLabel(MBB, false, false);
348 // If the arch uses custom Jump Table directives, don't calc relative to
349 // JT
350 if (!HadJTEntryDirective)
351 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
352 << getFunctionNumber() << '_' << uid;
353 }
354 } else {
355 printBasicBlockLabel(MBB, false, false);
356 }
357}
358
359
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
361/// special global used by LLVM. If so, emit it and return true, otherwise
362/// do nothing and return false.
363bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000364 if (GV->getName() == "llvm.used") {
365 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
366 EmitLLVMUsedList(GV->getInitializer());
367 return true;
368 }
369
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 // Ignore debug and non-emitted data.
371 if (GV->getSection() == "llvm.metadata") return true;
372
373 if (!GV->hasAppendingLinkage()) return false;
374
375 assert(GV->hasInitializer() && "Not a special LLVM global!");
376
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 const TargetData *TD = TM.getTargetData();
378 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
379 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
380 SwitchToDataSection(TAI->getStaticCtorsSection());
381 EmitAlignment(Align, 0);
382 EmitXXStructorList(GV->getInitializer());
383 return true;
384 }
385
386 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
387 SwitchToDataSection(TAI->getStaticDtorsSection());
388 EmitAlignment(Align, 0);
389 EmitXXStructorList(GV->getInitializer());
390 return true;
391 }
392
393 return false;
394}
395
396/// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
397/// global in the specified llvm.used list as being used with this directive.
398void AsmPrinter::EmitLLVMUsedList(Constant *List) {
399 const char *Directive = TAI->getUsedDirective();
400
401 // Should be an array of 'sbyte*'.
402 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
403 if (InitList == 0) return;
404
405 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
406 O << Directive;
407 EmitConstantValueOnly(InitList->getOperand(i));
408 O << "\n";
409 }
410}
411
412/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
413/// function pointers, ignoring the init priority.
414void AsmPrinter::EmitXXStructorList(Constant *List) {
415 // Should be an array of '{ int, void ()* }' structs. The first value is the
416 // init priority, which we ignore.
417 if (!isa<ConstantArray>(List)) return;
418 ConstantArray *InitList = cast<ConstantArray>(List);
419 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
420 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
421 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
422
423 if (CS->getOperand(1)->isNullValue())
424 return; // Found a null terminator, exit printing.
425 // Emit the function pointer.
426 EmitGlobalConstant(CS->getOperand(1));
427 }
428}
429
430/// getGlobalLinkName - Returns the asm/link name of of the specified
431/// global variable. Should be overridden by each target asm printer to
432/// generate the appropriate value.
433const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
434 std::string LinkName;
435
436 if (isa<Function>(GV)) {
437 LinkName += TAI->getFunctionAddrPrefix();
438 LinkName += Mang->getValueName(GV);
439 LinkName += TAI->getFunctionAddrSuffix();
440 } else {
441 LinkName += TAI->getGlobalVarAddrPrefix();
442 LinkName += Mang->getValueName(GV);
443 LinkName += TAI->getGlobalVarAddrSuffix();
444 }
445
446 return LinkName;
447}
448
449/// EmitExternalGlobal - Emit the external reference to a global variable.
450/// Should be overridden if an indirect reference should be used.
451void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
452 O << getGlobalLinkName(GV);
453}
454
455
456
457//===----------------------------------------------------------------------===//
458/// LEB 128 number encoding.
459
460/// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
461/// representing an unsigned leb128 value.
462void AsmPrinter::PrintULEB128(unsigned Value) const {
463 do {
464 unsigned Byte = Value & 0x7f;
465 Value >>= 7;
466 if (Value) Byte |= 0x80;
467 O << "0x" << std::hex << Byte << std::dec;
468 if (Value) O << ", ";
469 } while (Value);
470}
471
472/// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
473/// value.
474unsigned AsmPrinter::SizeULEB128(unsigned Value) {
475 unsigned Size = 0;
476 do {
477 Value >>= 7;
478 Size += sizeof(int8_t);
479 } while (Value);
480 return Size;
481}
482
483/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
484/// representing a signed leb128 value.
485void AsmPrinter::PrintSLEB128(int Value) const {
486 int Sign = Value >> (8 * sizeof(Value) - 1);
487 bool IsMore;
488
489 do {
490 unsigned Byte = Value & 0x7f;
491 Value >>= 7;
492 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
493 if (IsMore) Byte |= 0x80;
494 O << "0x" << std::hex << Byte << std::dec;
495 if (IsMore) O << ", ";
496 } while (IsMore);
497}
498
499/// SizeSLEB128 - Compute the number of bytes required for a signed leb128
500/// value.
501unsigned AsmPrinter::SizeSLEB128(int Value) {
502 unsigned Size = 0;
503 int Sign = Value >> (8 * sizeof(Value) - 1);
504 bool IsMore;
505
506 do {
507 unsigned Byte = Value & 0x7f;
508 Value >>= 7;
509 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
510 Size += sizeof(int8_t);
511 } while (IsMore);
512 return Size;
513}
514
515//===--------------------------------------------------------------------===//
516// Emission and print routines
517//
518
519/// PrintHex - Print a value as a hexidecimal value.
520///
521void AsmPrinter::PrintHex(int Value) const {
522 O << "0x" << std::hex << Value << std::dec;
523}
524
525/// EOL - Print a newline character to asm stream. If a comment is present
526/// then it will be printed first. Comments should not contain '\n'.
527void AsmPrinter::EOL() const {
528 O << "\n";
529}
530void AsmPrinter::EOL(const std::string &Comment) const {
531 if (AsmVerbose && !Comment.empty()) {
532 O << "\t"
533 << TAI->getCommentString()
534 << " "
535 << Comment;
536 }
537 O << "\n";
538}
539
540/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
541/// unsigned leb128 value.
542void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
543 if (TAI->hasLEB128()) {
544 O << "\t.uleb128\t"
545 << Value;
546 } else {
547 O << TAI->getData8bitsDirective();
548 PrintULEB128(Value);
549 }
550}
551
552/// EmitSLEB128Bytes - print an assembler byte data directive to compose a
553/// signed leb128 value.
554void AsmPrinter::EmitSLEB128Bytes(int Value) const {
555 if (TAI->hasLEB128()) {
556 O << "\t.sleb128\t"
557 << Value;
558 } else {
559 O << TAI->getData8bitsDirective();
560 PrintSLEB128(Value);
561 }
562}
563
564/// EmitInt8 - Emit a byte directive and value.
565///
566void AsmPrinter::EmitInt8(int Value) const {
567 O << TAI->getData8bitsDirective();
568 PrintHex(Value & 0xFF);
569}
570
571/// EmitInt16 - Emit a short directive and value.
572///
573void AsmPrinter::EmitInt16(int Value) const {
574 O << TAI->getData16bitsDirective();
575 PrintHex(Value & 0xFFFF);
576}
577
578/// EmitInt32 - Emit a long directive and value.
579///
580void AsmPrinter::EmitInt32(int Value) const {
581 O << TAI->getData32bitsDirective();
582 PrintHex(Value);
583}
584
585/// EmitInt64 - Emit a long long directive and value.
586///
587void AsmPrinter::EmitInt64(uint64_t Value) const {
588 if (TAI->getData64bitsDirective()) {
589 O << TAI->getData64bitsDirective();
590 PrintHex(Value);
591 } else {
592 if (TM.getTargetData()->isBigEndian()) {
593 EmitInt32(unsigned(Value >> 32)); O << "\n";
594 EmitInt32(unsigned(Value));
595 } else {
596 EmitInt32(unsigned(Value)); O << "\n";
597 EmitInt32(unsigned(Value >> 32));
598 }
599 }
600}
601
602/// toOctal - Convert the low order bits of X into an octal digit.
603///
604static inline char toOctal(int X) {
605 return (X&7)+'0';
606}
607
608/// printStringChar - Print a char, escaped if necessary.
609///
610static void printStringChar(std::ostream &O, unsigned char C) {
611 if (C == '"') {
612 O << "\\\"";
613 } else if (C == '\\') {
614 O << "\\\\";
615 } else if (isprint(C)) {
616 O << C;
617 } else {
618 switch(C) {
619 case '\b': O << "\\b"; break;
620 case '\f': O << "\\f"; break;
621 case '\n': O << "\\n"; break;
622 case '\r': O << "\\r"; break;
623 case '\t': O << "\\t"; break;
624 default:
625 O << '\\';
626 O << toOctal(C >> 6);
627 O << toOctal(C >> 3);
628 O << toOctal(C >> 0);
629 break;
630 }
631 }
632}
633
634/// EmitString - Emit a string with quotes and a null terminator.
635/// Special characters are emitted properly.
636/// \literal (Eg. '\t') \endliteral
637void AsmPrinter::EmitString(const std::string &String) const {
638 const char* AscizDirective = TAI->getAscizDirective();
639 if (AscizDirective)
640 O << AscizDirective;
641 else
642 O << TAI->getAsciiDirective();
643 O << "\"";
644 for (unsigned i = 0, N = String.size(); i < N; ++i) {
645 unsigned char C = String[i];
646 printStringChar(O, C);
647 }
648 if (AscizDirective)
649 O << "\"";
650 else
651 O << "\\0\"";
652}
653
654
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000655/// EmitFile - Emit a .file directive.
656void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
657 O << "\t.file\t" << Number << " \"";
658 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
659 unsigned char C = Name[i];
660 printStringChar(O, C);
661 }
662 O << "\"";
663}
664
665
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666//===----------------------------------------------------------------------===//
667
668// EmitAlignment - Emit an alignment directive to the specified power of
669// two boundary. For example, if you pass in 3 here, you will get an 8
670// byte alignment. If a global value is specified, and if that global has
671// an explicit alignment requested, it will unconditionally override the
672// alignment request. However, if ForcedAlignBits is specified, this value
673// has final say: the ultimate alignment will be the max of ForcedAlignBits
674// and the alignment computed with NumBits and the global.
675//
676// The algorithm is:
677// Align = NumBits;
678// if (GV && GV->hasalignment) Align = GV->getalignment();
679// Align = std::max(Align, ForcedAlignBits);
680//
681void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Chengc1f41aa2007-07-25 23:35:07 +0000682 unsigned ForcedAlignBits, bool UseFillExpr,
683 unsigned FillValue) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 if (GV && GV->getAlignment())
685 NumBits = Log2_32(GV->getAlignment());
686 NumBits = std::max(NumBits, ForcedAlignBits);
687
688 if (NumBits == 0) return; // No need to emit alignment.
689 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
Evan Chengc1f41aa2007-07-25 23:35:07 +0000690 O << TAI->getAlignDirective() << NumBits;
691 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
692 O << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693}
694
695
696/// EmitZeros - Emit a block of zeros.
697///
698void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
699 if (NumZeros) {
700 if (TAI->getZeroDirective()) {
701 O << TAI->getZeroDirective() << NumZeros;
702 if (TAI->getZeroDirectiveSuffix())
703 O << TAI->getZeroDirectiveSuffix();
704 O << "\n";
705 } else {
706 for (; NumZeros; --NumZeros)
707 O << TAI->getData8bitsDirective() << "0\n";
708 }
709 }
710}
711
712// Print out the specified constant, without a storage class. Only the
713// constants valid in constant expressions can occur here.
714void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
715 if (CV->isNullValue() || isa<UndefValue>(CV))
716 O << "0";
717 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
718 O << CI->getZExtValue();
719 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
720 // This is a constant address for a global variable or function. Use the
721 // name of the variable or function as the address value, possibly
722 // decorating it with GlobalVarAddrPrefix/Suffix or
723 // FunctionAddrPrefix/Suffix (these all default to "" )
724 if (isa<Function>(GV)) {
725 O << TAI->getFunctionAddrPrefix()
726 << Mang->getValueName(GV)
727 << TAI->getFunctionAddrSuffix();
728 } else {
729 O << TAI->getGlobalVarAddrPrefix()
730 << Mang->getValueName(GV)
731 << TAI->getGlobalVarAddrSuffix();
732 }
733 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
734 const TargetData *TD = TM.getTargetData();
735 unsigned Opcode = CE->getOpcode();
736 switch (Opcode) {
737 case Instruction::GetElementPtr: {
738 // generate a symbolic expression for the byte address
739 const Constant *ptrVal = CE->getOperand(0);
740 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
741 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
742 idxVec.size())) {
743 if (Offset)
744 O << "(";
745 EmitConstantValueOnly(ptrVal);
746 if (Offset > 0)
747 O << ") + " << Offset;
748 else if (Offset < 0)
749 O << ") - " << -Offset;
750 } else {
751 EmitConstantValueOnly(ptrVal);
752 }
753 break;
754 }
755 case Instruction::Trunc:
756 case Instruction::ZExt:
757 case Instruction::SExt:
758 case Instruction::FPTrunc:
759 case Instruction::FPExt:
760 case Instruction::UIToFP:
761 case Instruction::SIToFP:
762 case Instruction::FPToUI:
763 case Instruction::FPToSI:
764 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
765 break;
766 case Instruction::BitCast:
767 return EmitConstantValueOnly(CE->getOperand(0));
768
769 case Instruction::IntToPtr: {
770 // Handle casts to pointers by changing them into casts to the appropriate
771 // integer type. This promotes constant folding and simplifies this code.
772 Constant *Op = CE->getOperand(0);
773 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
774 return EmitConstantValueOnly(Op);
775 }
776
777
778 case Instruction::PtrToInt: {
779 // Support only foldable casts to/from pointers that can be eliminated by
780 // changing the pointer to the appropriately sized integer type.
781 Constant *Op = CE->getOperand(0);
782 const Type *Ty = CE->getType();
783
784 // We can emit the pointer value into this slot if the slot is an
785 // integer slot greater or equal to the size of the pointer.
786 if (Ty->isInteger() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000787 TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 return EmitConstantValueOnly(Op);
789
790 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
791 EmitConstantValueOnly(Op);
792 break;
793 }
794 case Instruction::Add:
795 case Instruction::Sub:
Anton Korobeynikovd3b58742007-12-18 20:53:41 +0000796 case Instruction::And:
797 case Instruction::Or:
798 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 O << "(";
800 EmitConstantValueOnly(CE->getOperand(0));
Anton Korobeynikovd3b58742007-12-18 20:53:41 +0000801 O << ")";
802 switch (Opcode) {
803 case Instruction::Add:
804 O << " + ";
805 break;
806 case Instruction::Sub:
807 O << " - ";
808 break;
809 case Instruction::And:
810 O << " & ";
811 break;
812 case Instruction::Or:
813 O << " | ";
814 break;
815 case Instruction::Xor:
816 O << " ^ ";
817 break;
818 default:
819 break;
820 }
821 O << "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 EmitConstantValueOnly(CE->getOperand(1));
823 O << ")";
824 break;
825 default:
826 assert(0 && "Unsupported operator!");
827 }
828 } else {
829 assert(0 && "Unknown constant value!");
830 }
831}
832
833/// printAsCString - Print the specified array as a C compatible string, only if
834/// the predicate isString is true.
835///
836static void printAsCString(std::ostream &O, const ConstantArray *CVA,
837 unsigned LastElt) {
838 assert(CVA->isString() && "Array is not string compatible!");
839
840 O << "\"";
841 for (unsigned i = 0; i != LastElt; ++i) {
842 unsigned char C =
843 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
844 printStringChar(O, C);
845 }
846 O << "\"";
847}
848
849/// EmitString - Emit a zero-byte-terminated string constant.
850///
851void AsmPrinter::EmitString(const ConstantArray *CVA) const {
852 unsigned NumElts = CVA->getNumOperands();
853 if (TAI->getAscizDirective() && NumElts &&
854 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
855 O << TAI->getAscizDirective();
856 printAsCString(O, CVA, NumElts-1);
857 } else {
858 O << TAI->getAsciiDirective();
859 printAsCString(O, CVA, NumElts);
860 }
861 O << "\n";
862}
863
864/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Duncan Sands8157ef42007-11-05 00:04:43 +0000865/// If Packed is false, pad to the ABI size.
866void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 const TargetData *TD = TM.getTargetData();
Duncan Sands8157ef42007-11-05 00:04:43 +0000868 unsigned Size = Packed ?
869 TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870
871 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Duncan Sands8157ef42007-11-05 00:04:43 +0000872 EmitZeros(Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 return;
874 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
875 if (CVA->isString()) {
876 EmitString(CVA);
877 } else { // Not a string. Print the values in successive locations
Duncan Sands8157ef42007-11-05 00:04:43 +0000878 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
879 EmitGlobalConstant(CVA->getOperand(i), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 }
881 return;
882 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
883 // Print the fields in successive locations. Pad to align if needed!
884 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
885 uint64_t sizeSoFar = 0;
886 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
887 const Constant* field = CVS->getOperand(i);
888
889 // Check if padding is needed and insert one or more 0s.
Duncan Sands8157ef42007-11-05 00:04:43 +0000890 uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000891 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 - cvsLayout->getElementOffset(i)) - fieldSize;
893 sizeSoFar += fieldSize + padSize;
894
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000895 // Now print the actual field value without ABI size padding.
896 EmitGlobalConstant(field, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000898 // Insert padding - this may include padding to increase the size of the
899 // current field up to the ABI size (if the struct is not packed) as well
900 // as padding to ensure that the next field starts at the right offset.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 EmitZeros(padSize);
902 }
903 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
904 "Layout of constant struct may be incorrect!");
905 return;
906 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
907 // FP Constants are printed as integer constants to avoid losing
908 // precision...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909 if (CFP->getType() == Type::DoubleTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000910 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000911 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 if (TAI->getData64bitsDirective())
Dale Johannesen1616e902007-09-11 18:32:33 +0000913 O << TAI->getData64bitsDirective() << i << "\t"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 << TAI->getCommentString() << " double value: " << Val << "\n";
915 else if (TD->isBigEndian()) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000916 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 << "\t" << TAI->getCommentString()
918 << " double most significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000919 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 << "\t" << TAI->getCommentString()
921 << " double least significant word " << Val << "\n";
922 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +0000923 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 << "\t" << TAI->getCommentString()
925 << " double least significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000926 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 << "\t" << TAI->getCommentString()
928 << " double most significant word " << Val << "\n";
929 }
930 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000931 } else if (CFP->getType() == Type::FloatTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000932 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
933 O << TAI->getData32bitsDirective()
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000934 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
936 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000937 } else if (CFP->getType() == Type::X86_FP80Ty) {
938 // all long double variants are printed as hex
Dale Johannesen693aa822007-09-26 23:20:33 +0000939 // api needed to prevent premature destruction
940 APInt api = CFP->getValueAPF().convertToAPInt();
941 const uint64_t *p = api.getRawData();
Chris Lattner00d63062008-01-27 06:09:28 +0000942 APFloat DoubleVal = CFP->getValueAPF();
943 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000944 if (TD->isBigEndian()) {
945 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
946 << "\t" << TAI->getCommentString()
Chris Lattner00d63062008-01-27 06:09:28 +0000947 << " long double most significant halfword of ~"
948 << DoubleVal.convertToDouble() << "\n";
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000949 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
950 << "\t" << TAI->getCommentString()
951 << " long double next halfword\n";
952 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
953 << "\t" << TAI->getCommentString()
954 << " long double next halfword\n";
955 O << TAI->getData16bitsDirective() << uint16_t(p[0])
956 << "\t" << TAI->getCommentString()
957 << " long double next halfword\n";
958 O << TAI->getData16bitsDirective() << uint16_t(p[1])
959 << "\t" << TAI->getCommentString()
960 << " long double least significant halfword\n";
961 } else {
962 O << TAI->getData16bitsDirective() << uint16_t(p[1])
963 << "\t" << TAI->getCommentString()
Chris Lattner00d63062008-01-27 06:09:28 +0000964 << " long double least significant halfword of ~"
965 << DoubleVal.convertToDouble() << "\n";
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000966 O << TAI->getData16bitsDirective() << uint16_t(p[0])
967 << "\t" << TAI->getCommentString()
968 << " long double next halfword\n";
969 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
970 << "\t" << TAI->getCommentString()
971 << " long double next halfword\n";
972 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
973 << "\t" << TAI->getCommentString()
974 << " long double next halfword\n";
975 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
976 << "\t" << TAI->getCommentString()
977 << " long double most significant halfword\n";
978 }
Duncan Sands8157ef42007-11-05 00:04:43 +0000979 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000980 return;
Dale Johannesend3b6af32007-10-11 23:32:15 +0000981 } else if (CFP->getType() == Type::PPC_FP128Ty) {
982 // all long double variants are printed as hex
983 // api needed to prevent premature destruction
984 APInt api = CFP->getValueAPF().convertToAPInt();
985 const uint64_t *p = api.getRawData();
986 if (TD->isBigEndian()) {
987 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
988 << "\t" << TAI->getCommentString()
989 << " long double most significant word\n";
990 O << TAI->getData32bitsDirective() << uint32_t(p[0])
991 << "\t" << TAI->getCommentString()
992 << " long double next word\n";
993 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
994 << "\t" << TAI->getCommentString()
995 << " long double next word\n";
996 O << TAI->getData32bitsDirective() << uint32_t(p[1])
997 << "\t" << TAI->getCommentString()
998 << " long double least significant word\n";
999 } else {
1000 O << TAI->getData32bitsDirective() << uint32_t(p[1])
1001 << "\t" << TAI->getCommentString()
1002 << " long double least significant word\n";
1003 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
1004 << "\t" << TAI->getCommentString()
1005 << " long double next word\n";
1006 O << TAI->getData32bitsDirective() << uint32_t(p[0])
1007 << "\t" << TAI->getCommentString()
1008 << " long double next word\n";
1009 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
1010 << "\t" << TAI->getCommentString()
1011 << " long double most significant word\n";
1012 }
1013 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00001014 } else assert(0 && "Floating point constant type not handled");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 } else if (CV->getType() == Type::Int64Ty) {
1016 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1017 uint64_t Val = CI->getZExtValue();
1018
1019 if (TAI->getData64bitsDirective())
1020 O << TAI->getData64bitsDirective() << Val << "\n";
1021 else if (TD->isBigEndian()) {
1022 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1023 << "\t" << TAI->getCommentString()
1024 << " Double-word most significant word " << Val << "\n";
1025 O << TAI->getData32bitsDirective() << unsigned(Val)
1026 << "\t" << TAI->getCommentString()
1027 << " Double-word least significant word " << Val << "\n";
1028 } else {
1029 O << TAI->getData32bitsDirective() << unsigned(Val)
1030 << "\t" << TAI->getCommentString()
1031 << " Double-word least significant word " << Val << "\n";
1032 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1033 << "\t" << TAI->getCommentString()
1034 << " Double-word most significant word " << Val << "\n";
1035 }
1036 return;
1037 }
1038 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1039 const VectorType *PTy = CP->getType();
1040
1041 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
Duncan Sands8157ef42007-11-05 00:04:43 +00001042 EmitGlobalConstant(CP->getOperand(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043
1044 return;
1045 }
1046
1047 const Type *type = CV->getType();
1048 printDataDirective(type);
1049 EmitConstantValueOnly(CV);
1050 O << "\n";
1051}
1052
1053void
1054AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1055 // Target doesn't support this yet!
1056 abort();
1057}
1058
1059/// PrintSpecial - Print information related to the specified machine instr
1060/// that is independent of the operand, and may be independent of the instr
1061/// itself. This can be useful for portably encoding the comment character
1062/// or other bits of target-specific knowledge into the asmstrings. The
1063/// syntax used is ${:comment}. Targets can override this to add support
1064/// for their own strange codes.
1065void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1066 if (!strcmp(Code, "private")) {
1067 O << TAI->getPrivateGlobalPrefix();
1068 } else if (!strcmp(Code, "comment")) {
1069 O << TAI->getCommentString();
1070 } else if (!strcmp(Code, "uid")) {
1071 // Assign a unique ID to this machine instruction.
1072 static const MachineInstr *LastMI = 0;
1073 static const Function *F = 0;
1074 static unsigned Counter = 0U-1;
1075
1076 // Comparing the address of MI isn't sufficient, because machineinstrs may
1077 // be allocated to the same address across functions.
1078 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1079
1080 // If this is a new machine instruction, bump the counter.
1081 if (LastMI != MI || F != ThisF) {
1082 ++Counter;
1083 LastMI = MI;
1084 F = ThisF;
1085 }
1086 O << Counter;
1087 } else {
1088 cerr << "Unknown special formatter '" << Code
1089 << "' for machine instr: " << *MI;
1090 exit(1);
1091 }
1092}
1093
1094
1095/// printInlineAsm - This method formats and prints the specified machine
1096/// instruction that is an inline asm.
1097void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1098 unsigned NumOperands = MI->getNumOperands();
1099
1100 // Count the number of register definitions.
1101 unsigned NumDefs = 0;
Dan Gohman38a9a9f2007-09-14 20:33:02 +00001102 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 ++NumDefs)
1104 assert(NumDefs != NumOperands-1 && "No asm string?");
1105
1106 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1107
1108 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1109 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1110
Dale Johannesene99fc902008-01-29 02:21:21 +00001111 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1112 // These are useful to see where empty asm's wound up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 if (AsmStr[0] == 0) {
Dale Johannesene99fc902008-01-29 02:21:21 +00001114 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 return;
1116 }
1117
1118 O << TAI->getInlineAsmStart() << "\n\t";
1119
1120 // The variant of the current asmprinter.
1121 int AsmPrinterVariant = TAI->getAssemblerDialect();
1122
1123 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1124 const char *LastEmitted = AsmStr; // One past the last character emitted.
1125
1126 while (*LastEmitted) {
1127 switch (*LastEmitted) {
1128 default: {
1129 // Not a special case, emit the string section literally.
1130 const char *LiteralEnd = LastEmitted+1;
1131 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1132 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1133 ++LiteralEnd;
1134 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1135 O.write(LastEmitted, LiteralEnd-LastEmitted);
1136 LastEmitted = LiteralEnd;
1137 break;
1138 }
1139 case '\n':
1140 ++LastEmitted; // Consume newline character.
1141 O << "\n"; // Indent code with newline.
1142 break;
1143 case '$': {
1144 ++LastEmitted; // Consume '$' character.
1145 bool Done = true;
1146
1147 // Handle escapes.
1148 switch (*LastEmitted) {
1149 default: Done = false; break;
1150 case '$': // $$ -> $
1151 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1152 O << '$';
1153 ++LastEmitted; // Consume second '$' character.
1154 break;
1155 case '(': // $( -> same as GCC's { character.
1156 ++LastEmitted; // Consume '(' character.
1157 if (CurVariant != -1) {
1158 cerr << "Nested variants found in inline asm string: '"
1159 << AsmStr << "'\n";
1160 exit(1);
1161 }
1162 CurVariant = 0; // We're in the first variant now.
1163 break;
1164 case '|':
1165 ++LastEmitted; // consume '|' character.
1166 if (CurVariant == -1) {
1167 cerr << "Found '|' character outside of variant in inline asm "
1168 << "string: '" << AsmStr << "'\n";
1169 exit(1);
1170 }
1171 ++CurVariant; // We're in the next variant.
1172 break;
1173 case ')': // $) -> same as GCC's } char.
1174 ++LastEmitted; // consume ')' character.
1175 if (CurVariant == -1) {
1176 cerr << "Found '}' character outside of variant in inline asm "
1177 << "string: '" << AsmStr << "'\n";
1178 exit(1);
1179 }
1180 CurVariant = -1;
1181 break;
1182 }
1183 if (Done) break;
1184
1185 bool HasCurlyBraces = false;
1186 if (*LastEmitted == '{') { // ${variable}
1187 ++LastEmitted; // Consume '{' character.
1188 HasCurlyBraces = true;
1189 }
1190
1191 const char *IDStart = LastEmitted;
1192 char *IDEnd;
1193 errno = 0;
1194 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1195 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1196 cerr << "Bad $ operand number in inline asm string: '"
1197 << AsmStr << "'\n";
1198 exit(1);
1199 }
1200 LastEmitted = IDEnd;
1201
1202 char Modifier[2] = { 0, 0 };
1203
1204 if (HasCurlyBraces) {
1205 // If we have curly braces, check for a modifier character. This
1206 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1207 if (*LastEmitted == ':') {
1208 ++LastEmitted; // Consume ':' character.
1209 if (*LastEmitted == 0) {
1210 cerr << "Bad ${:} expression in inline asm string: '"
1211 << AsmStr << "'\n";
1212 exit(1);
1213 }
1214
1215 Modifier[0] = *LastEmitted;
1216 ++LastEmitted; // Consume modifier character.
1217 }
1218
1219 if (*LastEmitted != '}') {
1220 cerr << "Bad ${} expression in inline asm string: '"
1221 << AsmStr << "'\n";
1222 exit(1);
1223 }
1224 ++LastEmitted; // Consume '}' character.
1225 }
1226
1227 if ((unsigned)Val >= NumOperands-1) {
1228 cerr << "Invalid $ operand number in inline asm string: '"
1229 << AsmStr << "'\n";
1230 exit(1);
1231 }
1232
1233 // Okay, we finally have a value number. Ask the target to print this
1234 // operand!
1235 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1236 unsigned OpNo = 1;
1237
1238 bool Error = false;
1239
1240 // Scan to find the machine operand number for the operand.
1241 for (; Val; --Val) {
1242 if (OpNo >= MI->getNumOperands()) break;
Chris Lattnerda4cff12007-12-30 20:50:28 +00001243 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 OpNo += (OpFlags >> 3) + 1;
1245 }
1246
1247 if (OpNo >= MI->getNumOperands()) {
1248 Error = true;
1249 } else {
Chris Lattnerda4cff12007-12-30 20:50:28 +00001250 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 ++OpNo; // Skip over the ID number.
1252
Dale Johannesencfb19e62007-11-05 21:20:28 +00001253 if (Modifier[0]=='l') // labels are target independent
Chris Lattner6017d482007-12-30 23:10:15 +00001254 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
Dale Johannesencfb19e62007-11-05 21:20:28 +00001255 false, false);
1256 else {
1257 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1258 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1259 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1260 Modifier[0] ? Modifier : 0);
1261 } else {
1262 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1263 Modifier[0] ? Modifier : 0);
1264 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 }
1266 }
1267 if (Error) {
1268 cerr << "Invalid operand found in inline asm: '"
1269 << AsmStr << "'\n";
1270 MI->dump();
1271 exit(1);
1272 }
1273 }
1274 break;
1275 }
1276 }
1277 }
1278 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1279}
1280
1281/// printLabel - This method prints a local label used by debug and
1282/// exception handling tables.
1283void AsmPrinter::printLabel(const MachineInstr *MI) const {
Chris Lattnerda4cff12007-12-30 20:50:28 +00001284 O << "\n" << TAI->getPrivateGlobalPrefix()
1285 << "label" << MI->getOperand(0).getImm() << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286}
1287
Evan Chenga53c40a2008-02-01 09:10:45 +00001288void AsmPrinter::printLabel(unsigned Id) const {
1289 O << "\n" << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1290}
1291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1293/// instruction, using the specified assembler variant. Targets should
1294/// overried this to format as appropriate.
1295bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1296 unsigned AsmVariant, const char *ExtraCode) {
1297 // Target doesn't support this yet!
1298 return true;
1299}
1300
1301bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1302 unsigned AsmVariant,
1303 const char *ExtraCode) {
1304 // Target doesn't support this yet!
1305 return true;
1306}
1307
1308/// printBasicBlockLabel - This method prints the label for the specified
1309/// MachineBasicBlock
1310void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1311 bool printColon,
1312 bool printComment) const {
Evan Cheng477013c2007-10-14 05:57:21 +00001313 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1314 << MBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 if (printColon)
1316 O << ':';
1317 if (printComment && MBB->getBasicBlock())
Dan Gohman0912cda2007-07-30 15:06:25 +00001318 O << '\t' << TAI->getCommentString() << ' '
1319 << MBB->getBasicBlock()->getName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320}
1321
Evan Cheng6fb06762007-11-09 01:32:10 +00001322/// printPICJumpTableSetLabel - This method prints a set label for the
1323/// specified MachineBasicBlock for a jumptable entry.
1324void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1325 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 if (!TAI->getSetDirective())
1327 return;
1328
1329 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001330 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 printBasicBlockLabel(MBB, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001332 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1333 << '_' << uid << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334}
1335
Evan Cheng6fb06762007-11-09 01:32:10 +00001336void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1337 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 if (!TAI->getSetDirective())
1339 return;
1340
1341 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001342 << getFunctionNumber() << '_' << uid << '_' << uid2
1343 << "_set_" << MBB->getNumber() << ',';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 printBasicBlockLabel(MBB, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001345 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1346 << '_' << uid << '_' << uid2 << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347}
1348
1349/// printDataDirective - This method prints the asm directive for the
1350/// specified type.
1351void AsmPrinter::printDataDirective(const Type *type) {
1352 const TargetData *TD = TM.getTargetData();
1353 switch (type->getTypeID()) {
1354 case Type::IntegerTyID: {
1355 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1356 if (BitWidth <= 8)
1357 O << TAI->getData8bitsDirective();
1358 else if (BitWidth <= 16)
1359 O << TAI->getData16bitsDirective();
1360 else if (BitWidth <= 32)
1361 O << TAI->getData32bitsDirective();
1362 else if (BitWidth <= 64) {
1363 assert(TAI->getData64bitsDirective() &&
1364 "Target cannot handle 64-bit constant exprs!");
1365 O << TAI->getData64bitsDirective();
1366 }
1367 break;
1368 }
1369 case Type::PointerTyID:
1370 if (TD->getPointerSize() == 8) {
1371 assert(TAI->getData64bitsDirective() &&
1372 "Target cannot handle 64-bit pointer exprs!");
1373 O << TAI->getData64bitsDirective();
1374 } else {
1375 O << TAI->getData32bitsDirective();
1376 }
1377 break;
1378 case Type::FloatTyID: case Type::DoubleTyID:
Dale Johannesen3b5303b2007-09-28 18:06:58 +00001379 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 assert (0 && "Should have already output floating point constant.");
1381 default:
1382 assert (0 && "Can't handle printing this type of thing");
1383 break;
1384 }
1385}
1386