1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
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/Mangler.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
30 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
31 const TargetAsmInfo *T)
32 : FunctionNumber(0), O(o), TM(tm), TAI(T)
35 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
36 return TAI->getTextSection();
40 /// SwitchToTextSection - Switch to the specified text section of the executable
41 /// if we are not already in it!
43 void AsmPrinter::SwitchToTextSection(const char *NewSection,
44 const GlobalValue *GV) {
46 if (GV && GV->hasSection())
47 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
51 // If we're already in this section, we're done.
52 if (CurrentSection == NS) return;
54 // Close the current section, if applicable.
55 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
56 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
60 if (!CurrentSection.empty())
61 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
64 /// SwitchToDataSection - Switch to the specified data section of the executable
65 /// if we are not already in it!
67 void AsmPrinter::SwitchToDataSection(const char *NewSection,
68 const GlobalValue *GV) {
70 if (GV && GV->hasSection())
71 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
75 // If we're already in this section, we're done.
76 if (CurrentSection == NS) return;
78 // Close the current section, if applicable.
79 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
80 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
84 if (!CurrentSection.empty())
85 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
89 bool AsmPrinter::doInitialization(Module &M) {
90 Mang = new Mangler(M, TAI->getGlobalPrefix());
92 if (!M.getModuleInlineAsm().empty())
93 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
94 << M.getModuleInlineAsm()
95 << "\n" << TAI->getCommentString()
96 << " End of file scope inline assembly\n";
98 SwitchToDataSection("", 0); // Reset back to no section.
100 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
101 DebugInfo->AnalyzeModule(M);
107 bool AsmPrinter::doFinalization(Module &M) {
108 delete Mang; Mang = 0;
112 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
113 // What's my mangled name?
114 CurrentFnName = Mang->getValueName(MF.getFunction());
115 IncrementFunctionNumber();
118 /// EmitConstantPool - Print to the current output stream assembly
119 /// representations of the constants in the constant pool MCP. This is
120 /// used to print out constants which have been "spilled to memory" by
121 /// the code generator.
123 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
124 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
125 if (CP.empty()) return;
127 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
128 // in special sections.
129 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
130 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
131 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
132 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
133 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
134 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
135 MachineConstantPoolEntry CPE = CP[i];
136 const Type *Ty = CPE.getType();
137 if (TAI->getFourByteConstantSection() &&
138 TM.getTargetData()->getTypeSize(Ty) == 4)
139 FourByteCPs.push_back(std::make_pair(CPE, i));
140 else if (TAI->getEightByteConstantSection() &&
141 TM.getTargetData()->getTypeSize(Ty) == 8)
142 EightByteCPs.push_back(std::make_pair(CPE, i));
143 else if (TAI->getSixteenByteConstantSection() &&
144 TM.getTargetData()->getTypeSize(Ty) == 16)
145 SixteenByteCPs.push_back(std::make_pair(CPE, i));
147 OtherCPs.push_back(std::make_pair(CPE, i));
150 unsigned Alignment = MCP->getConstantPoolAlignment();
151 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
152 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
153 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
155 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
158 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
159 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
160 if (CP.empty()) return;
162 SwitchToDataSection(Section, 0);
163 EmitAlignment(Alignment);
164 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
165 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
166 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
167 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
168 if (CP[i].first.isMachineConstantPoolEntry())
169 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
171 EmitGlobalConstant(CP[i].first.Val.ConstVal);
173 const Type *Ty = CP[i].first.getType();
175 TM.getTargetData()->getTypeSize(Ty);
176 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
177 // Emit inter-object padding for alignment.
178 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
183 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
184 /// by the current function to the current output stream.
186 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI) {
187 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
188 if (JT.empty()) return;
189 const TargetData *TD = TM.getTargetData();
191 // JTEntryDirective is a string to print sizeof(ptr) for non-PIC jump tables,
192 // and 32 bits for PIC since PIC jump table entries are differences, not
193 // pointers to blocks.
194 // Use the architecture specific relocation directive, if it is set
195 const char *JTEntryDirective = TAI->getJumpTableDirective();
196 if (!JTEntryDirective)
197 JTEntryDirective = TAI->getData32bitsDirective();
199 // Pick the directive to use to print the jump table entries, and switch to
200 // the appropriate section.
201 if (TM.getRelocationModel() == Reloc::PIC_) {
202 SwitchToTextSection(TAI->getJumpTableTextSection(), 0);
204 SwitchToDataSection(TAI->getJumpTableDataSection(), 0);
205 if (TD->getPointerSize() == 8)
206 JTEntryDirective = TAI->getData64bitsDirective();
208 EmitAlignment(Log2_32(TD->getPointerAlignment()));
210 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
211 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
213 // For PIC codegen, if possible we want to use the SetDirective to reduce
214 // the number of relocations the assembler will generate for the jump table.
215 // Set directives are all printed before the jump table itself.
216 std::set<MachineBasicBlock*> EmittedSets;
217 if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
218 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
219 if (EmittedSets.insert(JTBBs[ii]).second)
220 printSetLabel(i, JTBBs[ii]);
222 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
223 << '_' << i << ":\n";
225 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
226 O << JTEntryDirective << ' ';
227 // If we have emitted set directives for the jump table entries, print
228 // them rather than the entries themselves. If we're emitting PIC, then
229 // emit the table entries as differences between two text section labels.
230 // If we're emitting non-PIC code, then emit the entries as direct
231 // references to the target basic blocks.
232 if (!EmittedSets.empty()) {
233 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
234 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
235 } else if (TM.getRelocationModel() == Reloc::PIC_) {
236 printBasicBlockLabel(JTBBs[ii], false, false);
237 //If the arch uses custom Jump Table directives, don't calc relative to JT
238 if (!TAI->getJumpTableDirective())
239 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
240 << getFunctionNumber() << '_' << i;
242 printBasicBlockLabel(JTBBs[ii], false, false);
249 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
250 /// special global used by LLVM. If so, emit it and return true, otherwise
251 /// do nothing and return false.
252 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
253 // Ignore debug and non-emitted data.
254 if (GV->getSection() == "llvm.metadata") return true;
256 if (!GV->hasAppendingLinkage()) return false;
258 assert(GV->hasInitializer() && "Not a special LLVM global!");
260 if (GV->getName() == "llvm.used") {
261 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
262 EmitLLVMUsedList(GV->getInitializer());
266 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
267 SwitchToDataSection(TAI->getStaticCtorsSection(), 0);
269 EmitXXStructorList(GV->getInitializer());
273 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
274 SwitchToDataSection(TAI->getStaticDtorsSection(), 0);
276 EmitXXStructorList(GV->getInitializer());
283 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
284 /// global in the specified llvm.used list as being used with this directive.
285 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
286 const char *Directive = TAI->getUsedDirective();
288 // Should be an array of 'sbyte*'.
289 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
290 if (InitList == 0) return;
292 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
294 EmitConstantValueOnly(InitList->getOperand(i));
299 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
300 /// function pointers, ignoring the init priority.
301 void AsmPrinter::EmitXXStructorList(Constant *List) {
302 // Should be an array of '{ int, void ()* }' structs. The first value is the
303 // init priority, which we ignore.
304 if (!isa<ConstantArray>(List)) return;
305 ConstantArray *InitList = cast<ConstantArray>(List);
306 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
307 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
308 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
310 if (CS->getOperand(1)->isNullValue())
311 return; // Found a null terminator, exit printing.
312 // Emit the function pointer.
313 EmitGlobalConstant(CS->getOperand(1));
317 /// getPreferredAlignmentLog - Return the preferred alignment of the
318 /// specified global, returned in log form. This includes an explicitly
319 /// requested alignment (if the global has one).
320 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
321 const Type *ElemType = GV->getType()->getElementType();
322 unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(ElemType);
323 if (GV->getAlignment() > (1U << Alignment))
324 Alignment = Log2_32(GV->getAlignment());
326 if (GV->hasInitializer()) {
327 // Always round up alignment of global doubles to 8 bytes.
328 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
331 // If the global is not external, see if it is large. If so, give it a
333 if (TM.getTargetData()->getTypeSize(ElemType) > 128)
334 Alignment = 4; // 16-byte alignment.
340 // EmitAlignment - Emit an alignment directive to the specified power of two.
341 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
342 if (GV && GV->getAlignment())
343 NumBits = Log2_32(GV->getAlignment());
344 if (NumBits == 0) return; // No need to emit alignment.
345 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
346 O << TAI->getAlignDirective() << NumBits << "\n";
349 /// EmitZeros - Emit a block of zeros.
351 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
353 if (TAI->getZeroDirective()) {
354 O << TAI->getZeroDirective() << NumZeros;
355 if (TAI->getZeroDirectiveSuffix())
356 O << TAI->getZeroDirectiveSuffix();
359 for (; NumZeros; --NumZeros)
360 O << TAI->getData8bitsDirective() << "0\n";
365 // Print out the specified constant, without a storage class. Only the
366 // constants valid in constant expressions can occur here.
367 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
368 if (CV->isNullValue() || isa<UndefValue>(CV))
370 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
371 assert(CB->getValue());
373 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
374 if (((CI->getValue() << 32) >> 32) == CI->getValue())
377 O << (uint64_t)CI->getValue();
378 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
380 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
381 // This is a constant address for a global variable or function. Use the
382 // name of the variable or function as the address value, possibly
383 // decorating it with GlobalVarAddrPrefix/Suffix or
384 // FunctionAddrPrefix/Suffix (these all default to "" )
385 if (isa<Function>(GV)) {
386 O << TAI->getFunctionAddrPrefix()
387 << Mang->getValueName(GV)
388 << TAI->getFunctionAddrSuffix();
390 O << TAI->getGlobalVarAddrPrefix()
391 << Mang->getValueName(GV)
392 << TAI->getGlobalVarAddrSuffix();
394 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
395 const TargetData *TD = TM.getTargetData();
396 switch(CE->getOpcode()) {
397 case Instruction::GetElementPtr: {
398 // generate a symbolic expression for the byte address
399 const Constant *ptrVal = CE->getOperand(0);
400 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
401 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
404 EmitConstantValueOnly(ptrVal);
406 O << ") + " << Offset;
408 O << ") - " << -Offset;
410 EmitConstantValueOnly(ptrVal);
414 case Instruction::Cast: {
415 // Support only foldable casts to/from pointers that can be eliminated by
416 // changing the pointer to the appropriately sized integer type.
417 Constant *Op = CE->getOperand(0);
418 const Type *OpTy = Op->getType(), *Ty = CE->getType();
420 // Handle casts to pointers by changing them into casts to the appropriate
421 // integer type. This promotes constant folding and simplifies this code.
422 if (isa<PointerType>(Ty)) {
423 const Type *IntPtrTy = TD->getIntPtrType();
424 Op = ConstantExpr::getCast(Op, IntPtrTy);
425 return EmitConstantValueOnly(Op);
428 // We know the dest type is not a pointer. Is the src value a pointer or
430 if (isa<PointerType>(OpTy) || OpTy->isIntegral()) {
431 // We can emit the pointer value into this slot if the slot is an
432 // integer slot greater or equal to the size of the pointer.
433 if (Ty->isIntegral() && TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
434 return EmitConstantValueOnly(Op);
437 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
438 EmitConstantValueOnly(Op);
441 case Instruction::Add:
443 EmitConstantValueOnly(CE->getOperand(0));
445 EmitConstantValueOnly(CE->getOperand(1));
449 assert(0 && "Unsupported operator!");
452 assert(0 && "Unknown constant value!");
456 /// toOctal - Convert the low order bits of X into an octal digit.
458 static inline char toOctal(int X) {
462 /// printAsCString - Print the specified array as a C compatible string, only if
463 /// the predicate isString is true.
465 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
467 assert(CVA->isString() && "Array is not string compatible!");
470 for (unsigned i = 0; i != LastElt; ++i) {
472 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
476 } else if (C == '\\') {
478 } else if (isprint(C)) {
482 case '\b': O << "\\b"; break;
483 case '\f': O << "\\f"; break;
484 case '\n': O << "\\n"; break;
485 case '\r': O << "\\r"; break;
486 case '\t': O << "\\t"; break;
489 O << toOctal(C >> 6);
490 O << toOctal(C >> 3);
491 O << toOctal(C >> 0);
499 /// EmitString - Emit a zero-byte-terminated string constant.
501 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
502 unsigned NumElts = CVA->getNumOperands();
503 if (TAI->getAscizDirective() && NumElts &&
504 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
505 O << TAI->getAscizDirective();
506 printAsCString(O, CVA, NumElts-1);
508 O << TAI->getAsciiDirective();
509 printAsCString(O, CVA, NumElts);
514 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
516 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
517 const TargetData *TD = TM.getTargetData();
519 if (CV->isNullValue() || isa<UndefValue>(CV)) {
520 EmitZeros(TD->getTypeSize(CV->getType()));
522 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
523 if (CVA->isString()) {
525 } else { // Not a string. Print the values in successive locations
526 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
527 EmitGlobalConstant(CVA->getOperand(i));
530 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
531 // Print the fields in successive locations. Pad to align if needed!
532 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
533 uint64_t sizeSoFar = 0;
534 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
535 const Constant* field = CVS->getOperand(i);
537 // Check if padding is needed and insert one or more 0s.
538 uint64_t fieldSize = TD->getTypeSize(field->getType());
539 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
540 : cvsLayout->MemberOffsets[i+1])
541 - cvsLayout->MemberOffsets[i]) - fieldSize;
542 sizeSoFar += fieldSize + padSize;
544 // Now print the actual field value
545 EmitGlobalConstant(field);
547 // Insert the field padding unless it's zero bytes...
550 assert(sizeSoFar == cvsLayout->StructSize &&
551 "Layout of constant struct may be incorrect!");
553 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
554 // FP Constants are printed as integer constants to avoid losing
556 double Val = CFP->getValue();
557 if (CFP->getType() == Type::DoubleTy) {
558 if (TAI->getData64bitsDirective())
559 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
560 << TAI->getCommentString() << " double value: " << Val << "\n";
561 else if (TD->isBigEndian()) {
562 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
563 << "\t" << TAI->getCommentString()
564 << " double most significant word " << Val << "\n";
565 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
566 << "\t" << TAI->getCommentString()
567 << " double least significant word " << Val << "\n";
569 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
570 << "\t" << TAI->getCommentString()
571 << " double least significant word " << Val << "\n";
572 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
573 << "\t" << TAI->getCommentString()
574 << " double most significant word " << Val << "\n";
578 O << TAI->getData32bitsDirective() << FloatToBits(Val)
579 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
582 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
583 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
584 uint64_t Val = CI->getRawValue();
586 if (TAI->getData64bitsDirective())
587 O << TAI->getData64bitsDirective() << Val << "\n";
588 else if (TD->isBigEndian()) {
589 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
590 << "\t" << TAI->getCommentString()
591 << " Double-word most significant word " << Val << "\n";
592 O << TAI->getData32bitsDirective() << unsigned(Val)
593 << "\t" << TAI->getCommentString()
594 << " Double-word least significant word " << Val << "\n";
596 O << TAI->getData32bitsDirective() << unsigned(Val)
597 << "\t" << TAI->getCommentString()
598 << " Double-word least significant word " << Val << "\n";
599 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
600 << "\t" << TAI->getCommentString()
601 << " Double-word most significant word " << Val << "\n";
605 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
606 const PackedType *PTy = CP->getType();
608 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
609 EmitGlobalConstant(CP->getOperand(I));
614 const Type *type = CV->getType();
615 printDataDirective(type);
616 EmitConstantValueOnly(CV);
621 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
622 // Target doesn't support this yet!
626 /// PrintSpecial - Print information related to the specified machine instr
627 /// that is independent of the operand, and may be independent of the instr
628 /// itself. This can be useful for portably encoding the comment character
629 /// or other bits of target-specific knowledge into the asmstrings. The
630 /// syntax used is ${:comment}. Targets can override this to add support
631 /// for their own strange codes.
632 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
633 if (!strcmp(Code, "private")) {
634 O << TAI->getPrivateGlobalPrefix();
635 } else if (!strcmp(Code, "comment")) {
636 O << TAI->getCommentString();
637 } else if (!strcmp(Code, "uid")) {
638 // Assign a unique ID to this machine instruction.
639 static const MachineInstr *LastMI = 0;
640 static unsigned Counter = 0U-1;
641 // If this is a new machine instruction, bump the counter.
642 if (LastMI != MI) { ++Counter; LastMI = MI; }
645 std::cerr << "Unknown special formatter '" << Code
646 << "' for machine instr: " << *MI;
652 /// printInlineAsm - This method formats and prints the specified machine
653 /// instruction that is an inline asm.
654 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
655 unsigned NumOperands = MI->getNumOperands();
657 // Count the number of register definitions.
658 unsigned NumDefs = 0;
659 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
661 assert(NumDefs != NumOperands-1 && "No asm string?");
663 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
665 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
666 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
668 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
669 if (AsmStr[0] == 0) {
670 O << "\n"; // Tab already printed, avoid double indenting next instr.
674 O << TAI->getInlineAsmStart() << "\n\t";
676 // The variant of the current asmprinter: FIXME: change.
677 int AsmPrinterVariant = 0;
679 int CurVariant = -1; // The number of the {.|.|.} region we are in.
680 const char *LastEmitted = AsmStr; // One past the last character emitted.
682 while (*LastEmitted) {
683 switch (*LastEmitted) {
685 // Not a special case, emit the string section literally.
686 const char *LiteralEnd = LastEmitted+1;
687 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
688 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
690 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
691 O.write(LastEmitted, LiteralEnd-LastEmitted);
692 LastEmitted = LiteralEnd;
696 ++LastEmitted; // Consume newline character.
697 O << "\n\t"; // Indent code with newline.
700 ++LastEmitted; // Consume '$' character.
704 switch (*LastEmitted) {
705 default: Done = false; break;
707 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
709 ++LastEmitted; // Consume second '$' character.
711 case '(': // $( -> same as GCC's { character.
712 ++LastEmitted; // Consume '(' character.
713 if (CurVariant != -1) {
714 std::cerr << "Nested variants found in inline asm string: '"
718 CurVariant = 0; // We're in the first variant now.
721 ++LastEmitted; // consume '|' character.
722 if (CurVariant == -1) {
723 std::cerr << "Found '|' character outside of variant in inline asm "
724 << "string: '" << AsmStr << "'\n";
727 ++CurVariant; // We're in the next variant.
729 case ')': // $) -> same as GCC's } char.
730 ++LastEmitted; // consume ')' character.
731 if (CurVariant == -1) {
732 std::cerr << "Found '}' character outside of variant in inline asm "
733 << "string: '" << AsmStr << "'\n";
741 bool HasCurlyBraces = false;
742 if (*LastEmitted == '{') { // ${variable}
743 ++LastEmitted; // Consume '{' character.
744 HasCurlyBraces = true;
747 const char *IDStart = LastEmitted;
749 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
750 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
751 std::cerr << "Bad $ operand number in inline asm string: '"
757 char Modifier[2] = { 0, 0 };
759 if (HasCurlyBraces) {
760 // If we have curly braces, check for a modifier character. This
761 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
762 if (*LastEmitted == ':') {
763 ++LastEmitted; // Consume ':' character.
764 if (*LastEmitted == 0) {
765 std::cerr << "Bad ${:} expression in inline asm string: '"
770 Modifier[0] = *LastEmitted;
771 ++LastEmitted; // Consume modifier character.
774 if (*LastEmitted != '}') {
775 std::cerr << "Bad ${} expression in inline asm string: '"
779 ++LastEmitted; // Consume '}' character.
782 if ((unsigned)Val >= NumOperands-1) {
783 std::cerr << "Invalid $ operand number in inline asm string: '"
788 // Okay, we finally have a value number. Ask the target to print this
790 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
795 // Scan to find the machine operand number for the operand.
797 if (OpNo >= MI->getNumOperands()) break;
798 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
799 OpNo += (OpFlags >> 3) + 1;
802 if (OpNo >= MI->getNumOperands()) {
805 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
806 ++OpNo; // Skip over the ID number.
808 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
809 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
810 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
811 Modifier[0] ? Modifier : 0);
813 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
814 Modifier[0] ? Modifier : 0);
818 std::cerr << "Invalid operand found in inline asm: '"
828 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
831 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
832 /// instruction, using the specified assembler variant. Targets should
833 /// overried this to format as appropriate.
834 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
835 unsigned AsmVariant, const char *ExtraCode) {
836 // Target doesn't support this yet!
840 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
842 const char *ExtraCode) {
843 // Target doesn't support this yet!
847 /// printBasicBlockLabel - This method prints the label for the specified
848 /// MachineBasicBlock
849 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
851 bool printComment) const {
852 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
857 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
860 /// printSetLabel - This method prints a set label for the specified
861 /// MachineBasicBlock
862 void AsmPrinter::printSetLabel(unsigned uid,
863 const MachineBasicBlock *MBB) const {
864 if (!TAI->getSetDirective())
867 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
868 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
869 printBasicBlockLabel(MBB, false, false);
870 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
871 << '_' << uid << '\n';
874 /// printDataDirective - This method prints the asm directive for the
876 void AsmPrinter::printDataDirective(const Type *type) {
877 const TargetData *TD = TM.getTargetData();
878 switch (type->getTypeID()) {
880 case Type::UByteTyID: case Type::SByteTyID:
881 O << TAI->getData8bitsDirective();
883 case Type::UShortTyID: case Type::ShortTyID:
884 O << TAI->getData16bitsDirective();
886 case Type::PointerTyID:
887 if (TD->getPointerSize() == 8) {
888 assert(TAI->getData64bitsDirective() &&
889 "Target cannot handle 64-bit pointer exprs!");
890 O << TAI->getData64bitsDirective();
893 //Fall through for pointer size == int size
894 case Type::UIntTyID: case Type::IntTyID:
895 O << TAI->getData32bitsDirective();
897 case Type::ULongTyID: case Type::LongTyID:
898 assert(TAI->getData64bitsDirective() &&
899 "Target cannot handle 64-bit constant exprs!");
900 O << TAI->getData64bitsDirective();
902 case Type::FloatTyID: case Type::DoubleTyID:
903 assert (0 && "Should have already output floating point constant.");
905 assert (0 && "Can't handle printing this type of thing");