blob: 65892c10a58a505b8ef99efc5a2c06500447db04 [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"
19#include "llvm/CodeGen/MachineConstantPool.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Mangler.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/Streams.h"
25#include "llvm/Target/TargetAsmInfo.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetMachine.h"
Evan Cheng6fb06762007-11-09 01:32:10 +000029#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include <cerrno>
31using namespace llvm;
32
33static cl::opt<bool>
34AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
35
36char AsmPrinter::ID = 0;
37AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
38 const TargetAsmInfo *T)
Evan Cheng477013c2007-10-14 05:57:21 +000039 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040{}
41
42std::string AsmPrinter::getSectionForFunction(const Function &F) const {
43 return TAI->getTextSection();
44}
45
46
47/// SwitchToTextSection - Switch to the specified text section of the executable
48/// if we are not already in it!
49///
50void AsmPrinter::SwitchToTextSection(const char *NewSection,
51 const GlobalValue *GV) {
52 std::string NS;
53 if (GV && GV->hasSection())
54 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
55 else
56 NS = NewSection;
57
58 // If we're already in this section, we're done.
59 if (CurrentSection == NS) return;
60
61 // Close the current section, if applicable.
62 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
63 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
64
65 CurrentSection = NS;
66
67 if (!CurrentSection.empty())
68 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
69}
70
71/// SwitchToDataSection - Switch to the specified data section of the executable
72/// if we are not already in it!
73///
74void AsmPrinter::SwitchToDataSection(const char *NewSection,
75 const GlobalValue *GV) {
76 std::string NS;
77 if (GV && GV->hasSection())
78 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
79 else
80 NS = NewSection;
81
82 // If we're already in this section, we're done.
83 if (CurrentSection == NS) return;
84
85 // Close the current section, if applicable.
86 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
87 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
88
89 CurrentSection = NS;
90
91 if (!CurrentSection.empty())
92 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
93}
94
95
96bool AsmPrinter::doInitialization(Module &M) {
97 Mang = new Mangler(M, TAI->getGlobalPrefix());
98
99 if (!M.getModuleInlineAsm().empty())
100 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
101 << M.getModuleInlineAsm()
102 << "\n" << TAI->getCommentString()
103 << " End of file scope inline assembly\n";
104
105 SwitchToDataSection(""); // Reset back to no section.
106
107 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
108 MMI->AnalyzeModule(M);
109 }
110
111 return false;
112}
113
114bool AsmPrinter::doFinalization(Module &M) {
115 if (TAI->getWeakRefDirective()) {
116 if (!ExtWeakSymbols.empty())
117 SwitchToDataSection("");
118
119 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
120 e = ExtWeakSymbols.end(); i != e; ++i) {
121 const GlobalValue *GV = *i;
122 std::string Name = Mang->getValueName(GV);
123 O << TAI->getWeakRefDirective() << Name << "\n";
124 }
125 }
126
127 if (TAI->getSetDirective()) {
128 if (!M.alias_empty())
129 SwitchToTextSection(TAI->getTextSection());
130
131 O << "\n";
132 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
133 I!=E; ++I) {
134 std::string Name = Mang->getValueName(I);
135 std::string Target;
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000136
137 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
138 Target = Mang->getValueName(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000140 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 O << "\t.globl\t" << Name << "\n";
142 else if (I->hasWeakLinkage())
143 O << TAI->getWeakRefDirective() << Name << "\n";
144 else if (!I->hasInternalLinkage())
145 assert(0 && "Invalid alias linkage");
146
147 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000148
149 // If the aliasee has external weak linkage it can be referenced only by
150 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
151 // weak reference in such case.
152 if (GV->hasExternalWeakLinkage())
153 if (TAI->getWeakRefDirective())
154 O << TAI->getWeakRefDirective() << Target << "\n";
155 else
156 O << "\t.globl\t" << Target << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 }
158 }
159
160 delete Mang; Mang = 0;
161 return false;
162}
163
Bill Wendlinge9ecdcf2007-09-18 09:10:16 +0000164std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
Bill Wendlingef9211a2007-09-18 01:47:22 +0000165 assert(MF && "No machine function?");
Bill Wendlingd2144aa2007-09-18 05:03:44 +0000166 return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
167 TAI->getGlobalPrefix());
Bill Wendlingef9211a2007-09-18 01:47:22 +0000168}
169
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
171 // What's my mangled name?
172 CurrentFnName = Mang->getValueName(MF.getFunction());
Evan Cheng477013c2007-10-14 05:57:21 +0000173 IncrementFunctionNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174}
175
176/// EmitConstantPool - Print to the current output stream assembly
177/// representations of the constants in the constant pool MCP. This is
178/// used to print out constants which have been "spilled to memory" by
179/// the code generator.
180///
181void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
182 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
183 if (CP.empty()) return;
184
185 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
186 // in special sections.
187 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
188 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
189 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
190 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
191 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
192 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
193 MachineConstantPoolEntry CPE = CP[i];
194 const Type *Ty = CPE.getType();
195 if (TAI->getFourByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000196 TM.getTargetData()->getABITypeSize(Ty) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 FourByteCPs.push_back(std::make_pair(CPE, i));
198 else if (TAI->getEightByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000199 TM.getTargetData()->getABITypeSize(Ty) == 8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 EightByteCPs.push_back(std::make_pair(CPE, i));
201 else if (TAI->getSixteenByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000202 TM.getTargetData()->getABITypeSize(Ty) == 16)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 SixteenByteCPs.push_back(std::make_pair(CPE, i));
204 else
205 OtherCPs.push_back(std::make_pair(CPE, i));
206 }
207
208 unsigned Alignment = MCP->getConstantPoolAlignment();
209 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
210 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
211 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
212 SixteenByteCPs);
213 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
214}
215
216void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
217 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
218 if (CP.empty()) return;
219
220 SwitchToDataSection(Section);
221 EmitAlignment(Alignment);
222 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Evan Cheng477013c2007-10-14 05:57:21 +0000223 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
224 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
226 if (CP[i].first.isMachineConstantPoolEntry())
227 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
228 else
229 EmitGlobalConstant(CP[i].first.Val.ConstVal);
230 if (i != e-1) {
231 const Type *Ty = CP[i].first.getType();
232 unsigned EntSize =
Duncan Sands8157ef42007-11-05 00:04:43 +0000233 TM.getTargetData()->getABITypeSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
235 // Emit inter-object padding for alignment.
236 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
237 }
238 }
239}
240
241/// EmitJumpTableInfo - Print assembly representations of the jump tables used
242/// by the current function to the current output stream.
243///
244void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
245 MachineFunction &MF) {
246 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
247 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000248
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
250
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 // Pick the directive to use to print the jump table entries, and switch to
252 // the appropriate section.
253 TargetLowering *LoweringInfo = TM.getTargetLowering();
254
255 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
256 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
257 !JumpTableDataSection) {
258 // In PIC mode, we need to emit the jump table to the same section as the
259 // function body itself, otherwise the label differences won't make sense.
260 // We should also do if the section name is NULL.
261 const Function *F = MF.getFunction();
262 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
263 } else {
264 SwitchToDataSection(JumpTableDataSection);
265 }
266
267 EmitAlignment(Log2_32(MJTI->getAlignment()));
268
269 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
270 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
271
272 // If this jump table was deleted, ignore it.
273 if (JTBBs.empty()) continue;
274
275 // For PIC codegen, if possible we want to use the SetDirective to reduce
276 // the number of relocations the assembler will generate for the jump table.
277 // Set directives are all printed before the jump table itself.
Evan Cheng6fb06762007-11-09 01:32:10 +0000278 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 if (TAI->getSetDirective() && IsPic)
280 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Evan Cheng6fb06762007-11-09 01:32:10 +0000281 if (EmittedSets.insert(JTBBs[ii]))
282 printPICJumpTableSetLabel(i, JTBBs[ii]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283
284 // On some targets (e.g. darwin) we want to emit two consequtive labels
285 // before each jump table. The first label is never referenced, but tells
286 // the assembler and linker the extents of the jump table object. The
287 // second label is actually referenced by the code.
288 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
Evan Cheng477013c2007-10-14 05:57:21 +0000289 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290
Evan Cheng477013c2007-10-14 05:57:21 +0000291 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
292 << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293
294 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000295 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 O << '\n';
297 }
298 }
299}
300
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000301void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
302 const MachineBasicBlock *MBB,
303 unsigned uid) const {
304 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
305
306 // Use JumpTableDirective otherwise honor the entry size from the jump table
307 // info.
308 const char *JTEntryDirective = TAI->getJumpTableDirective();
309 bool HadJTEntryDirective = JTEntryDirective != NULL;
310 if (!HadJTEntryDirective) {
311 JTEntryDirective = MJTI->getEntrySize() == 4 ?
312 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
313 }
314
315 O << JTEntryDirective << ' ';
316
317 // If we have emitted set directives for the jump table entries, print
318 // them rather than the entries themselves. If we're emitting PIC, then
319 // emit the table entries as differences between two text section labels.
320 // If we're emitting non-PIC code, then emit the entries as direct
321 // references to the target basic blocks.
322 if (IsPic) {
323 if (TAI->getSetDirective()) {
324 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
325 << '_' << uid << "_set_" << MBB->getNumber();
326 } else {
327 printBasicBlockLabel(MBB, false, false);
328 // If the arch uses custom Jump Table directives, don't calc relative to
329 // JT
330 if (!HadJTEntryDirective)
331 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
332 << getFunctionNumber() << '_' << uid;
333 }
334 } else {
335 printBasicBlockLabel(MBB, false, false);
336 }
337}
338
339
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
341/// special global used by LLVM. If so, emit it and return true, otherwise
342/// do nothing and return false.
343bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000344 if (GV->getName() == "llvm.used") {
345 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
346 EmitLLVMUsedList(GV->getInitializer());
347 return true;
348 }
349
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 // Ignore debug and non-emitted data.
351 if (GV->getSection() == "llvm.metadata") return true;
352
353 if (!GV->hasAppendingLinkage()) return false;
354
355 assert(GV->hasInitializer() && "Not a special LLVM global!");
356
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 const TargetData *TD = TM.getTargetData();
358 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
359 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
360 SwitchToDataSection(TAI->getStaticCtorsSection());
361 EmitAlignment(Align, 0);
362 EmitXXStructorList(GV->getInitializer());
363 return true;
364 }
365
366 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
367 SwitchToDataSection(TAI->getStaticDtorsSection());
368 EmitAlignment(Align, 0);
369 EmitXXStructorList(GV->getInitializer());
370 return true;
371 }
372
373 return false;
374}
375
376/// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
377/// global in the specified llvm.used list as being used with this directive.
378void AsmPrinter::EmitLLVMUsedList(Constant *List) {
379 const char *Directive = TAI->getUsedDirective();
380
381 // Should be an array of 'sbyte*'.
382 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
383 if (InitList == 0) return;
384
385 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
386 O << Directive;
387 EmitConstantValueOnly(InitList->getOperand(i));
388 O << "\n";
389 }
390}
391
392/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
393/// function pointers, ignoring the init priority.
394void AsmPrinter::EmitXXStructorList(Constant *List) {
395 // Should be an array of '{ int, void ()* }' structs. The first value is the
396 // init priority, which we ignore.
397 if (!isa<ConstantArray>(List)) return;
398 ConstantArray *InitList = cast<ConstantArray>(List);
399 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
400 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
401 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
402
403 if (CS->getOperand(1)->isNullValue())
404 return; // Found a null terminator, exit printing.
405 // Emit the function pointer.
406 EmitGlobalConstant(CS->getOperand(1));
407 }
408}
409
410/// getGlobalLinkName - Returns the asm/link name of of the specified
411/// global variable. Should be overridden by each target asm printer to
412/// generate the appropriate value.
413const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
414 std::string LinkName;
415
416 if (isa<Function>(GV)) {
417 LinkName += TAI->getFunctionAddrPrefix();
418 LinkName += Mang->getValueName(GV);
419 LinkName += TAI->getFunctionAddrSuffix();
420 } else {
421 LinkName += TAI->getGlobalVarAddrPrefix();
422 LinkName += Mang->getValueName(GV);
423 LinkName += TAI->getGlobalVarAddrSuffix();
424 }
425
426 return LinkName;
427}
428
429/// EmitExternalGlobal - Emit the external reference to a global variable.
430/// Should be overridden if an indirect reference should be used.
431void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
432 O << getGlobalLinkName(GV);
433}
434
435
436
437//===----------------------------------------------------------------------===//
438/// LEB 128 number encoding.
439
440/// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
441/// representing an unsigned leb128 value.
442void AsmPrinter::PrintULEB128(unsigned Value) const {
443 do {
444 unsigned Byte = Value & 0x7f;
445 Value >>= 7;
446 if (Value) Byte |= 0x80;
447 O << "0x" << std::hex << Byte << std::dec;
448 if (Value) O << ", ";
449 } while (Value);
450}
451
452/// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
453/// value.
454unsigned AsmPrinter::SizeULEB128(unsigned Value) {
455 unsigned Size = 0;
456 do {
457 Value >>= 7;
458 Size += sizeof(int8_t);
459 } while (Value);
460 return Size;
461}
462
463/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
464/// representing a signed leb128 value.
465void AsmPrinter::PrintSLEB128(int Value) const {
466 int Sign = Value >> (8 * sizeof(Value) - 1);
467 bool IsMore;
468
469 do {
470 unsigned Byte = Value & 0x7f;
471 Value >>= 7;
472 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
473 if (IsMore) Byte |= 0x80;
474 O << "0x" << std::hex << Byte << std::dec;
475 if (IsMore) O << ", ";
476 } while (IsMore);
477}
478
479/// SizeSLEB128 - Compute the number of bytes required for a signed leb128
480/// value.
481unsigned AsmPrinter::SizeSLEB128(int Value) {
482 unsigned Size = 0;
483 int Sign = Value >> (8 * sizeof(Value) - 1);
484 bool IsMore;
485
486 do {
487 unsigned Byte = Value & 0x7f;
488 Value >>= 7;
489 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
490 Size += sizeof(int8_t);
491 } while (IsMore);
492 return Size;
493}
494
495//===--------------------------------------------------------------------===//
496// Emission and print routines
497//
498
499/// PrintHex - Print a value as a hexidecimal value.
500///
501void AsmPrinter::PrintHex(int Value) const {
502 O << "0x" << std::hex << Value << std::dec;
503}
504
505/// EOL - Print a newline character to asm stream. If a comment is present
506/// then it will be printed first. Comments should not contain '\n'.
507void AsmPrinter::EOL() const {
508 O << "\n";
509}
510void AsmPrinter::EOL(const std::string &Comment) const {
511 if (AsmVerbose && !Comment.empty()) {
512 O << "\t"
513 << TAI->getCommentString()
514 << " "
515 << Comment;
516 }
517 O << "\n";
518}
519
520/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
521/// unsigned leb128 value.
522void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
523 if (TAI->hasLEB128()) {
524 O << "\t.uleb128\t"
525 << Value;
526 } else {
527 O << TAI->getData8bitsDirective();
528 PrintULEB128(Value);
529 }
530}
531
532/// EmitSLEB128Bytes - print an assembler byte data directive to compose a
533/// signed leb128 value.
534void AsmPrinter::EmitSLEB128Bytes(int Value) const {
535 if (TAI->hasLEB128()) {
536 O << "\t.sleb128\t"
537 << Value;
538 } else {
539 O << TAI->getData8bitsDirective();
540 PrintSLEB128(Value);
541 }
542}
543
544/// EmitInt8 - Emit a byte directive and value.
545///
546void AsmPrinter::EmitInt8(int Value) const {
547 O << TAI->getData8bitsDirective();
548 PrintHex(Value & 0xFF);
549}
550
551/// EmitInt16 - Emit a short directive and value.
552///
553void AsmPrinter::EmitInt16(int Value) const {
554 O << TAI->getData16bitsDirective();
555 PrintHex(Value & 0xFFFF);
556}
557
558/// EmitInt32 - Emit a long directive and value.
559///
560void AsmPrinter::EmitInt32(int Value) const {
561 O << TAI->getData32bitsDirective();
562 PrintHex(Value);
563}
564
565/// EmitInt64 - Emit a long long directive and value.
566///
567void AsmPrinter::EmitInt64(uint64_t Value) const {
568 if (TAI->getData64bitsDirective()) {
569 O << TAI->getData64bitsDirective();
570 PrintHex(Value);
571 } else {
572 if (TM.getTargetData()->isBigEndian()) {
573 EmitInt32(unsigned(Value >> 32)); O << "\n";
574 EmitInt32(unsigned(Value));
575 } else {
576 EmitInt32(unsigned(Value)); O << "\n";
577 EmitInt32(unsigned(Value >> 32));
578 }
579 }
580}
581
582/// toOctal - Convert the low order bits of X into an octal digit.
583///
584static inline char toOctal(int X) {
585 return (X&7)+'0';
586}
587
588/// printStringChar - Print a char, escaped if necessary.
589///
590static void printStringChar(std::ostream &O, unsigned char C) {
591 if (C == '"') {
592 O << "\\\"";
593 } else if (C == '\\') {
594 O << "\\\\";
595 } else if (isprint(C)) {
596 O << C;
597 } else {
598 switch(C) {
599 case '\b': O << "\\b"; break;
600 case '\f': O << "\\f"; break;
601 case '\n': O << "\\n"; break;
602 case '\r': O << "\\r"; break;
603 case '\t': O << "\\t"; break;
604 default:
605 O << '\\';
606 O << toOctal(C >> 6);
607 O << toOctal(C >> 3);
608 O << toOctal(C >> 0);
609 break;
610 }
611 }
612}
613
614/// EmitString - Emit a string with quotes and a null terminator.
615/// Special characters are emitted properly.
616/// \literal (Eg. '\t') \endliteral
617void AsmPrinter::EmitString(const std::string &String) const {
618 const char* AscizDirective = TAI->getAscizDirective();
619 if (AscizDirective)
620 O << AscizDirective;
621 else
622 O << TAI->getAsciiDirective();
623 O << "\"";
624 for (unsigned i = 0, N = String.size(); i < N; ++i) {
625 unsigned char C = String[i];
626 printStringChar(O, C);
627 }
628 if (AscizDirective)
629 O << "\"";
630 else
631 O << "\\0\"";
632}
633
634
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000635/// EmitFile - Emit a .file directive.
636void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
637 O << "\t.file\t" << Number << " \"";
638 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
639 unsigned char C = Name[i];
640 printStringChar(O, C);
641 }
642 O << "\"";
643}
644
645
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646//===----------------------------------------------------------------------===//
647
648// EmitAlignment - Emit an alignment directive to the specified power of
649// two boundary. For example, if you pass in 3 here, you will get an 8
650// byte alignment. If a global value is specified, and if that global has
651// an explicit alignment requested, it will unconditionally override the
652// alignment request. However, if ForcedAlignBits is specified, this value
653// has final say: the ultimate alignment will be the max of ForcedAlignBits
654// and the alignment computed with NumBits and the global.
655//
656// The algorithm is:
657// Align = NumBits;
658// if (GV && GV->hasalignment) Align = GV->getalignment();
659// Align = std::max(Align, ForcedAlignBits);
660//
661void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Chengc1f41aa2007-07-25 23:35:07 +0000662 unsigned ForcedAlignBits, bool UseFillExpr,
663 unsigned FillValue) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 if (GV && GV->getAlignment())
665 NumBits = Log2_32(GV->getAlignment());
666 NumBits = std::max(NumBits, ForcedAlignBits);
667
668 if (NumBits == 0) return; // No need to emit alignment.
669 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
Evan Chengc1f41aa2007-07-25 23:35:07 +0000670 O << TAI->getAlignDirective() << NumBits;
671 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
672 O << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673}
674
675
676/// EmitZeros - Emit a block of zeros.
677///
678void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
679 if (NumZeros) {
680 if (TAI->getZeroDirective()) {
681 O << TAI->getZeroDirective() << NumZeros;
682 if (TAI->getZeroDirectiveSuffix())
683 O << TAI->getZeroDirectiveSuffix();
684 O << "\n";
685 } else {
686 for (; NumZeros; --NumZeros)
687 O << TAI->getData8bitsDirective() << "0\n";
688 }
689 }
690}
691
692// Print out the specified constant, without a storage class. Only the
693// constants valid in constant expressions can occur here.
694void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
695 if (CV->isNullValue() || isa<UndefValue>(CV))
696 O << "0";
697 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
698 O << CI->getZExtValue();
699 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
700 // This is a constant address for a global variable or function. Use the
701 // name of the variable or function as the address value, possibly
702 // decorating it with GlobalVarAddrPrefix/Suffix or
703 // FunctionAddrPrefix/Suffix (these all default to "" )
704 if (isa<Function>(GV)) {
705 O << TAI->getFunctionAddrPrefix()
706 << Mang->getValueName(GV)
707 << TAI->getFunctionAddrSuffix();
708 } else {
709 O << TAI->getGlobalVarAddrPrefix()
710 << Mang->getValueName(GV)
711 << TAI->getGlobalVarAddrSuffix();
712 }
713 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
714 const TargetData *TD = TM.getTargetData();
715 unsigned Opcode = CE->getOpcode();
716 switch (Opcode) {
717 case Instruction::GetElementPtr: {
718 // generate a symbolic expression for the byte address
719 const Constant *ptrVal = CE->getOperand(0);
720 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
721 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
722 idxVec.size())) {
723 if (Offset)
724 O << "(";
725 EmitConstantValueOnly(ptrVal);
726 if (Offset > 0)
727 O << ") + " << Offset;
728 else if (Offset < 0)
729 O << ") - " << -Offset;
730 } else {
731 EmitConstantValueOnly(ptrVal);
732 }
733 break;
734 }
735 case Instruction::Trunc:
736 case Instruction::ZExt:
737 case Instruction::SExt:
738 case Instruction::FPTrunc:
739 case Instruction::FPExt:
740 case Instruction::UIToFP:
741 case Instruction::SIToFP:
742 case Instruction::FPToUI:
743 case Instruction::FPToSI:
744 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
745 break;
746 case Instruction::BitCast:
747 return EmitConstantValueOnly(CE->getOperand(0));
748
749 case Instruction::IntToPtr: {
750 // Handle casts to pointers by changing them into casts to the appropriate
751 // integer type. This promotes constant folding and simplifies this code.
752 Constant *Op = CE->getOperand(0);
753 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
754 return EmitConstantValueOnly(Op);
755 }
756
757
758 case Instruction::PtrToInt: {
759 // Support only foldable casts to/from pointers that can be eliminated by
760 // changing the pointer to the appropriately sized integer type.
761 Constant *Op = CE->getOperand(0);
762 const Type *Ty = CE->getType();
763
764 // We can emit the pointer value into this slot if the slot is an
765 // integer slot greater or equal to the size of the pointer.
766 if (Ty->isInteger() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000767 TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 return EmitConstantValueOnly(Op);
769
770 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
771 EmitConstantValueOnly(Op);
772 break;
773 }
774 case Instruction::Add:
775 case Instruction::Sub:
Anton Korobeynikovd3b58742007-12-18 20:53:41 +0000776 case Instruction::And:
777 case Instruction::Or:
778 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 O << "(";
780 EmitConstantValueOnly(CE->getOperand(0));
Anton Korobeynikovd3b58742007-12-18 20:53:41 +0000781 O << ")";
782 switch (Opcode) {
783 case Instruction::Add:
784 O << " + ";
785 break;
786 case Instruction::Sub:
787 O << " - ";
788 break;
789 case Instruction::And:
790 O << " & ";
791 break;
792 case Instruction::Or:
793 O << " | ";
794 break;
795 case Instruction::Xor:
796 O << " ^ ";
797 break;
798 default:
799 break;
800 }
801 O << "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 EmitConstantValueOnly(CE->getOperand(1));
803 O << ")";
804 break;
805 default:
806 assert(0 && "Unsupported operator!");
807 }
808 } else {
809 assert(0 && "Unknown constant value!");
810 }
811}
812
813/// printAsCString - Print the specified array as a C compatible string, only if
814/// the predicate isString is true.
815///
816static void printAsCString(std::ostream &O, const ConstantArray *CVA,
817 unsigned LastElt) {
818 assert(CVA->isString() && "Array is not string compatible!");
819
820 O << "\"";
821 for (unsigned i = 0; i != LastElt; ++i) {
822 unsigned char C =
823 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
824 printStringChar(O, C);
825 }
826 O << "\"";
827}
828
829/// EmitString - Emit a zero-byte-terminated string constant.
830///
831void AsmPrinter::EmitString(const ConstantArray *CVA) const {
832 unsigned NumElts = CVA->getNumOperands();
833 if (TAI->getAscizDirective() && NumElts &&
834 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
835 O << TAI->getAscizDirective();
836 printAsCString(O, CVA, NumElts-1);
837 } else {
838 O << TAI->getAsciiDirective();
839 printAsCString(O, CVA, NumElts);
840 }
841 O << "\n";
842}
843
844/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Duncan Sands8157ef42007-11-05 00:04:43 +0000845/// If Packed is false, pad to the ABI size.
846void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 const TargetData *TD = TM.getTargetData();
Duncan Sands8157ef42007-11-05 00:04:43 +0000848 unsigned Size = Packed ?
849 TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850
851 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Duncan Sands8157ef42007-11-05 00:04:43 +0000852 EmitZeros(Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 return;
854 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
855 if (CVA->isString()) {
856 EmitString(CVA);
857 } else { // Not a string. Print the values in successive locations
Duncan Sands8157ef42007-11-05 00:04:43 +0000858 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
859 EmitGlobalConstant(CVA->getOperand(i), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 }
861 return;
862 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
863 // Print the fields in successive locations. Pad to align if needed!
864 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
865 uint64_t sizeSoFar = 0;
866 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
867 const Constant* field = CVS->getOperand(i);
868
869 // Check if padding is needed and insert one or more 0s.
Duncan Sands8157ef42007-11-05 00:04:43 +0000870 uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000871 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 - cvsLayout->getElementOffset(i)) - fieldSize;
873 sizeSoFar += fieldSize + padSize;
874
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000875 // Now print the actual field value without ABI size padding.
876 EmitGlobalConstant(field, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000878 // Insert padding - this may include padding to increase the size of the
879 // current field up to the ABI size (if the struct is not packed) as well
880 // as padding to ensure that the next field starts at the right offset.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000881 EmitZeros(padSize);
882 }
883 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
884 "Layout of constant struct may be incorrect!");
885 return;
886 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
887 // FP Constants are printed as integer constants to avoid losing
888 // precision...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 if (CFP->getType() == Type::DoubleTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000890 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000891 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 if (TAI->getData64bitsDirective())
Dale Johannesen1616e902007-09-11 18:32:33 +0000893 O << TAI->getData64bitsDirective() << i << "\t"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 << TAI->getCommentString() << " double value: " << Val << "\n";
895 else if (TD->isBigEndian()) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000896 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 << "\t" << TAI->getCommentString()
898 << " double most significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000899 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 << "\t" << TAI->getCommentString()
901 << " double least significant word " << Val << "\n";
902 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +0000903 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904 << "\t" << TAI->getCommentString()
905 << " double least significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000906 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 << "\t" << TAI->getCommentString()
908 << " double most significant word " << Val << "\n";
909 }
910 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000911 } else if (CFP->getType() == Type::FloatTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000912 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
913 O << TAI->getData32bitsDirective()
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000914 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
916 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000917 } else if (CFP->getType() == Type::X86_FP80Ty) {
918 // all long double variants are printed as hex
Dale Johannesen693aa822007-09-26 23:20:33 +0000919 // api needed to prevent premature destruction
920 APInt api = CFP->getValueAPF().convertToAPInt();
921 const uint64_t *p = api.getRawData();
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000922 if (TD->isBigEndian()) {
923 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
924 << "\t" << TAI->getCommentString()
925 << " long double most significant halfword\n";
926 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
927 << "\t" << TAI->getCommentString()
928 << " long double next halfword\n";
929 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
930 << "\t" << TAI->getCommentString()
931 << " long double next halfword\n";
932 O << TAI->getData16bitsDirective() << uint16_t(p[0])
933 << "\t" << TAI->getCommentString()
934 << " long double next halfword\n";
935 O << TAI->getData16bitsDirective() << uint16_t(p[1])
936 << "\t" << TAI->getCommentString()
937 << " long double least significant halfword\n";
938 } else {
939 O << TAI->getData16bitsDirective() << uint16_t(p[1])
940 << "\t" << TAI->getCommentString()
941 << " long double least significant halfword\n";
942 O << TAI->getData16bitsDirective() << uint16_t(p[0])
943 << "\t" << TAI->getCommentString()
944 << " long double next halfword\n";
945 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
946 << "\t" << TAI->getCommentString()
947 << " long double next halfword\n";
948 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
949 << "\t" << TAI->getCommentString()
950 << " long double next halfword\n";
951 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
952 << "\t" << TAI->getCommentString()
953 << " long double most significant halfword\n";
954 }
Duncan Sands8157ef42007-11-05 00:04:43 +0000955 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000956 return;
Dale Johannesend3b6af32007-10-11 23:32:15 +0000957 } else if (CFP->getType() == Type::PPC_FP128Ty) {
958 // all long double variants are printed as hex
959 // api needed to prevent premature destruction
960 APInt api = CFP->getValueAPF().convertToAPInt();
961 const uint64_t *p = api.getRawData();
962 if (TD->isBigEndian()) {
963 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
964 << "\t" << TAI->getCommentString()
965 << " long double most significant word\n";
966 O << TAI->getData32bitsDirective() << uint32_t(p[0])
967 << "\t" << TAI->getCommentString()
968 << " long double next word\n";
969 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
970 << "\t" << TAI->getCommentString()
971 << " long double next word\n";
972 O << TAI->getData32bitsDirective() << uint32_t(p[1])
973 << "\t" << TAI->getCommentString()
974 << " long double least significant word\n";
975 } else {
976 O << TAI->getData32bitsDirective() << uint32_t(p[1])
977 << "\t" << TAI->getCommentString()
978 << " long double least significant word\n";
979 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
980 << "\t" << TAI->getCommentString()
981 << " long double next word\n";
982 O << TAI->getData32bitsDirective() << uint32_t(p[0])
983 << "\t" << TAI->getCommentString()
984 << " long double next word\n";
985 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
986 << "\t" << TAI->getCommentString()
987 << " long double most significant word\n";
988 }
989 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000990 } else assert(0 && "Floating point constant type not handled");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 } else if (CV->getType() == Type::Int64Ty) {
992 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
993 uint64_t Val = CI->getZExtValue();
994
995 if (TAI->getData64bitsDirective())
996 O << TAI->getData64bitsDirective() << Val << "\n";
997 else if (TD->isBigEndian()) {
998 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
999 << "\t" << TAI->getCommentString()
1000 << " Double-word most significant word " << Val << "\n";
1001 O << TAI->getData32bitsDirective() << unsigned(Val)
1002 << "\t" << TAI->getCommentString()
1003 << " Double-word least significant word " << Val << "\n";
1004 } else {
1005 O << TAI->getData32bitsDirective() << unsigned(Val)
1006 << "\t" << TAI->getCommentString()
1007 << " Double-word least significant word " << Val << "\n";
1008 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1009 << "\t" << TAI->getCommentString()
1010 << " Double-word most significant word " << Val << "\n";
1011 }
1012 return;
1013 }
1014 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1015 const VectorType *PTy = CP->getType();
1016
1017 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
Duncan Sands8157ef42007-11-05 00:04:43 +00001018 EmitGlobalConstant(CP->getOperand(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019
1020 return;
1021 }
1022
1023 const Type *type = CV->getType();
1024 printDataDirective(type);
1025 EmitConstantValueOnly(CV);
1026 O << "\n";
1027}
1028
1029void
1030AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1031 // Target doesn't support this yet!
1032 abort();
1033}
1034
1035/// PrintSpecial - Print information related to the specified machine instr
1036/// that is independent of the operand, and may be independent of the instr
1037/// itself. This can be useful for portably encoding the comment character
1038/// or other bits of target-specific knowledge into the asmstrings. The
1039/// syntax used is ${:comment}. Targets can override this to add support
1040/// for their own strange codes.
1041void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1042 if (!strcmp(Code, "private")) {
1043 O << TAI->getPrivateGlobalPrefix();
1044 } else if (!strcmp(Code, "comment")) {
1045 O << TAI->getCommentString();
1046 } else if (!strcmp(Code, "uid")) {
1047 // Assign a unique ID to this machine instruction.
1048 static const MachineInstr *LastMI = 0;
1049 static const Function *F = 0;
1050 static unsigned Counter = 0U-1;
1051
1052 // Comparing the address of MI isn't sufficient, because machineinstrs may
1053 // be allocated to the same address across functions.
1054 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1055
1056 // If this is a new machine instruction, bump the counter.
1057 if (LastMI != MI || F != ThisF) {
1058 ++Counter;
1059 LastMI = MI;
1060 F = ThisF;
1061 }
1062 O << Counter;
1063 } else {
1064 cerr << "Unknown special formatter '" << Code
1065 << "' for machine instr: " << *MI;
1066 exit(1);
1067 }
1068}
1069
1070
1071/// printInlineAsm - This method formats and prints the specified machine
1072/// instruction that is an inline asm.
1073void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1074 unsigned NumOperands = MI->getNumOperands();
1075
1076 // Count the number of register definitions.
1077 unsigned NumDefs = 0;
Dan Gohman38a9a9f2007-09-14 20:33:02 +00001078 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 ++NumDefs)
1080 assert(NumDefs != NumOperands-1 && "No asm string?");
1081
1082 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1083
1084 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1085 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1086
1087 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1088 if (AsmStr[0] == 0) {
1089 O << "\n"; // Tab already printed, avoid double indenting next instr.
1090 return;
1091 }
1092
1093 O << TAI->getInlineAsmStart() << "\n\t";
1094
1095 // The variant of the current asmprinter.
1096 int AsmPrinterVariant = TAI->getAssemblerDialect();
1097
1098 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1099 const char *LastEmitted = AsmStr; // One past the last character emitted.
1100
1101 while (*LastEmitted) {
1102 switch (*LastEmitted) {
1103 default: {
1104 // Not a special case, emit the string section literally.
1105 const char *LiteralEnd = LastEmitted+1;
1106 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1107 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1108 ++LiteralEnd;
1109 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1110 O.write(LastEmitted, LiteralEnd-LastEmitted);
1111 LastEmitted = LiteralEnd;
1112 break;
1113 }
1114 case '\n':
1115 ++LastEmitted; // Consume newline character.
1116 O << "\n"; // Indent code with newline.
1117 break;
1118 case '$': {
1119 ++LastEmitted; // Consume '$' character.
1120 bool Done = true;
1121
1122 // Handle escapes.
1123 switch (*LastEmitted) {
1124 default: Done = false; break;
1125 case '$': // $$ -> $
1126 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1127 O << '$';
1128 ++LastEmitted; // Consume second '$' character.
1129 break;
1130 case '(': // $( -> same as GCC's { character.
1131 ++LastEmitted; // Consume '(' character.
1132 if (CurVariant != -1) {
1133 cerr << "Nested variants found in inline asm string: '"
1134 << AsmStr << "'\n";
1135 exit(1);
1136 }
1137 CurVariant = 0; // We're in the first variant now.
1138 break;
1139 case '|':
1140 ++LastEmitted; // consume '|' character.
1141 if (CurVariant == -1) {
1142 cerr << "Found '|' character outside of variant in inline asm "
1143 << "string: '" << AsmStr << "'\n";
1144 exit(1);
1145 }
1146 ++CurVariant; // We're in the next variant.
1147 break;
1148 case ')': // $) -> same as GCC's } char.
1149 ++LastEmitted; // consume ')' character.
1150 if (CurVariant == -1) {
1151 cerr << "Found '}' character outside of variant in inline asm "
1152 << "string: '" << AsmStr << "'\n";
1153 exit(1);
1154 }
1155 CurVariant = -1;
1156 break;
1157 }
1158 if (Done) break;
1159
1160 bool HasCurlyBraces = false;
1161 if (*LastEmitted == '{') { // ${variable}
1162 ++LastEmitted; // Consume '{' character.
1163 HasCurlyBraces = true;
1164 }
1165
1166 const char *IDStart = LastEmitted;
1167 char *IDEnd;
1168 errno = 0;
1169 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1170 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1171 cerr << "Bad $ operand number in inline asm string: '"
1172 << AsmStr << "'\n";
1173 exit(1);
1174 }
1175 LastEmitted = IDEnd;
1176
1177 char Modifier[2] = { 0, 0 };
1178
1179 if (HasCurlyBraces) {
1180 // If we have curly braces, check for a modifier character. This
1181 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1182 if (*LastEmitted == ':') {
1183 ++LastEmitted; // Consume ':' character.
1184 if (*LastEmitted == 0) {
1185 cerr << "Bad ${:} expression in inline asm string: '"
1186 << AsmStr << "'\n";
1187 exit(1);
1188 }
1189
1190 Modifier[0] = *LastEmitted;
1191 ++LastEmitted; // Consume modifier character.
1192 }
1193
1194 if (*LastEmitted != '}') {
1195 cerr << "Bad ${} expression in inline asm string: '"
1196 << AsmStr << "'\n";
1197 exit(1);
1198 }
1199 ++LastEmitted; // Consume '}' character.
1200 }
1201
1202 if ((unsigned)Val >= NumOperands-1) {
1203 cerr << "Invalid $ operand number in inline asm string: '"
1204 << AsmStr << "'\n";
1205 exit(1);
1206 }
1207
1208 // Okay, we finally have a value number. Ask the target to print this
1209 // operand!
1210 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1211 unsigned OpNo = 1;
1212
1213 bool Error = false;
1214
1215 // Scan to find the machine operand number for the operand.
1216 for (; Val; --Val) {
1217 if (OpNo >= MI->getNumOperands()) break;
1218 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1219 OpNo += (OpFlags >> 3) + 1;
1220 }
1221
1222 if (OpNo >= MI->getNumOperands()) {
1223 Error = true;
1224 } else {
1225 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1226 ++OpNo; // Skip over the ID number.
1227
Dale Johannesencfb19e62007-11-05 21:20:28 +00001228 if (Modifier[0]=='l') // labels are target independent
1229 printBasicBlockLabel(MI->getOperand(OpNo).getMachineBasicBlock(),
1230 false, false);
1231 else {
1232 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1233 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1234 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1235 Modifier[0] ? Modifier : 0);
1236 } else {
1237 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1238 Modifier[0] ? Modifier : 0);
1239 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 }
1241 }
1242 if (Error) {
1243 cerr << "Invalid operand found in inline asm: '"
1244 << AsmStr << "'\n";
1245 MI->dump();
1246 exit(1);
1247 }
1248 }
1249 break;
1250 }
1251 }
1252 }
1253 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1254}
1255
1256/// printLabel - This method prints a local label used by debug and
1257/// exception handling tables.
1258void AsmPrinter::printLabel(const MachineInstr *MI) const {
1259 O << "\n"
1260 << TAI->getPrivateGlobalPrefix()
1261 << "label"
1262 << MI->getOperand(0).getImmedValue()
1263 << ":\n";
1264}
1265
1266/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1267/// instruction, using the specified assembler variant. Targets should
1268/// overried this to format as appropriate.
1269bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1270 unsigned AsmVariant, const char *ExtraCode) {
1271 // Target doesn't support this yet!
1272 return true;
1273}
1274
1275bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1276 unsigned AsmVariant,
1277 const char *ExtraCode) {
1278 // Target doesn't support this yet!
1279 return true;
1280}
1281
1282/// printBasicBlockLabel - This method prints the label for the specified
1283/// MachineBasicBlock
1284void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1285 bool printColon,
1286 bool printComment) const {
Evan Cheng477013c2007-10-14 05:57:21 +00001287 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1288 << MBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 if (printColon)
1290 O << ':';
1291 if (printComment && MBB->getBasicBlock())
Dan Gohman0912cda2007-07-30 15:06:25 +00001292 O << '\t' << TAI->getCommentString() << ' '
1293 << MBB->getBasicBlock()->getName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294}
1295
Evan Cheng6fb06762007-11-09 01:32:10 +00001296/// printPICJumpTableSetLabel - This method prints a set label for the
1297/// specified MachineBasicBlock for a jumptable entry.
1298void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1299 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 if (!TAI->getSetDirective())
1301 return;
1302
1303 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001304 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 printBasicBlockLabel(MBB, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001306 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1307 << '_' << uid << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308}
1309
Evan Cheng6fb06762007-11-09 01:32:10 +00001310void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1311 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 if (!TAI->getSetDirective())
1313 return;
1314
1315 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001316 << getFunctionNumber() << '_' << uid << '_' << uid2
1317 << "_set_" << MBB->getNumber() << ',';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 printBasicBlockLabel(MBB, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001319 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1320 << '_' << uid << '_' << uid2 << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321}
1322
1323/// printDataDirective - This method prints the asm directive for the
1324/// specified type.
1325void AsmPrinter::printDataDirective(const Type *type) {
1326 const TargetData *TD = TM.getTargetData();
1327 switch (type->getTypeID()) {
1328 case Type::IntegerTyID: {
1329 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1330 if (BitWidth <= 8)
1331 O << TAI->getData8bitsDirective();
1332 else if (BitWidth <= 16)
1333 O << TAI->getData16bitsDirective();
1334 else if (BitWidth <= 32)
1335 O << TAI->getData32bitsDirective();
1336 else if (BitWidth <= 64) {
1337 assert(TAI->getData64bitsDirective() &&
1338 "Target cannot handle 64-bit constant exprs!");
1339 O << TAI->getData64bitsDirective();
1340 }
1341 break;
1342 }
1343 case Type::PointerTyID:
1344 if (TD->getPointerSize() == 8) {
1345 assert(TAI->getData64bitsDirective() &&
1346 "Target cannot handle 64-bit pointer exprs!");
1347 O << TAI->getData64bitsDirective();
1348 } else {
1349 O << TAI->getData32bitsDirective();
1350 }
1351 break;
1352 case Type::FloatTyID: case Type::DoubleTyID:
Dale Johannesen3b5303b2007-09-28 18:06:58 +00001353 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 assert (0 && "Should have already output floating point constant.");
1355 default:
1356 assert (0 && "Can't handle printing this type of thing");
1357 break;
1358 }
1359}
1360