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