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/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
31 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
32 const TargetAsmInfo *T)
33 : FunctionNumber(0), O(o), TM(tm), TAI(T)
36 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
37 return TAI->getTextSection();
41 /// SwitchToTextSection - Switch to the specified text section of the executable
42 /// if we are not already in it!
44 void AsmPrinter::SwitchToTextSection(const char *NewSection,
45 const GlobalValue *GV) {
47 if (GV && GV->hasSection())
48 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
52 // If we're already in this section, we're done.
53 if (CurrentSection == NS) return;
55 // Close the current section, if applicable.
56 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
57 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
61 if (!CurrentSection.empty())
62 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
65 /// SwitchToDataSection - Switch to the specified data section of the executable
66 /// if we are not already in it!
68 void AsmPrinter::SwitchToDataSection(const char *NewSection,
69 const GlobalValue *GV) {
71 if (GV && GV->hasSection())
72 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
76 // If we're already in this section, we're done.
77 if (CurrentSection == NS) return;
79 // Close the current section, if applicable.
80 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
81 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
85 if (!CurrentSection.empty())
86 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
90 bool AsmPrinter::doInitialization(Module &M) {
91 Mang = new Mangler(M, TAI->getGlobalPrefix());
93 if (!M.getModuleInlineAsm().empty())
94 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
95 << M.getModuleInlineAsm()
96 << "\n" << TAI->getCommentString()
97 << " End of file scope inline assembly\n";
99 SwitchToDataSection("", 0); // Reset back to no section.
101 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
102 DebugInfo->AnalyzeModule(M);
108 bool AsmPrinter::doFinalization(Module &M) {
109 delete Mang; Mang = 0;
113 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
114 // What's my mangled name?
115 CurrentFnName = Mang->getValueName(MF.getFunction());
116 IncrementFunctionNumber();
119 /// EmitConstantPool - Print to the current output stream assembly
120 /// representations of the constants in the constant pool MCP. This is
121 /// used to print out constants which have been "spilled to memory" by
122 /// the code generator.
124 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
125 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
126 if (CP.empty()) return;
128 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
129 // in special sections.
130 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
131 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
132 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
133 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
134 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
135 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
136 MachineConstantPoolEntry CPE = CP[i];
137 const Type *Ty = CPE.getType();
138 if (TAI->getFourByteConstantSection() &&
139 TM.getTargetData()->getTypeSize(Ty) == 4)
140 FourByteCPs.push_back(std::make_pair(CPE, i));
141 else if (TAI->getEightByteConstantSection() &&
142 TM.getTargetData()->getTypeSize(Ty) == 8)
143 EightByteCPs.push_back(std::make_pair(CPE, i));
144 else if (TAI->getSixteenByteConstantSection() &&
145 TM.getTargetData()->getTypeSize(Ty) == 16)
146 SixteenByteCPs.push_back(std::make_pair(CPE, i));
148 OtherCPs.push_back(std::make_pair(CPE, i));
151 unsigned Alignment = MCP->getConstantPoolAlignment();
152 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
153 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
154 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
156 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
159 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
160 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
161 if (CP.empty()) return;
163 SwitchToDataSection(Section, 0);
164 EmitAlignment(Alignment);
165 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
166 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
167 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
168 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
169 if (CP[i].first.isMachineConstantPoolEntry())
170 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
172 EmitGlobalConstant(CP[i].first.Val.ConstVal);
174 const Type *Ty = CP[i].first.getType();
176 TM.getTargetData()->getTypeSize(Ty);
177 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
178 // Emit inter-object padding for alignment.
179 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
184 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
185 /// by the current function to the current output stream.
187 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
188 MachineFunction &MF) {
189 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
190 if (JT.empty()) return;
191 const TargetData *TD = TM.getTargetData();
193 // JTEntryDirective is a string to print sizeof(ptr) for non-PIC jump tables,
194 // and 32 bits for PIC since PIC jump table entries are differences, not
195 // pointers to blocks.
196 // Use the architecture specific relocation directive, if it is set
197 const char *JTEntryDirective = TAI->getJumpTableDirective();
198 if (!JTEntryDirective)
199 JTEntryDirective = TAI->getData32bitsDirective();
201 // Pick the directive to use to print the jump table entries, and switch to
202 // the appropriate section.
203 if (TM.getRelocationModel() == Reloc::PIC_) {
204 TargetLowering *LoweringInfo = TM.getTargetLowering();
205 if (LoweringInfo && LoweringInfo->usesGlobalOffsetTable()) {
206 SwitchToDataSection(TAI->getJumpTableDataSection(), 0);
207 if (TD->getPointerSize() == 8)
208 JTEntryDirective = TAI->getData64bitsDirective();
210 // In PIC mode, we need to emit the jump table to the same section as the
211 // function body itself, otherwise the label differences won't make sense.
212 const Function *F = MF.getFunction();
213 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
216 SwitchToDataSection(TAI->getJumpTableDataSection(), 0);
217 if (TD->getPointerSize() == 8)
218 JTEntryDirective = TAI->getData64bitsDirective();
220 EmitAlignment(Log2_32(TD->getPointerAlignment()));
222 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
223 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
225 // For PIC codegen, if possible we want to use the SetDirective to reduce
226 // the number of relocations the assembler will generate for the jump table.
227 // Set directives are all printed before the jump table itself.
228 std::set<MachineBasicBlock*> EmittedSets;
229 if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
230 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
231 if (EmittedSets.insert(JTBBs[ii]).second)
232 printSetLabel(i, JTBBs[ii]);
234 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
235 << '_' << i << ":\n";
237 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
238 O << JTEntryDirective << ' ';
239 // If we have emitted set directives for the jump table entries, print
240 // them rather than the entries themselves. If we're emitting PIC, then
241 // emit the table entries as differences between two text section labels.
242 // If we're emitting non-PIC code, then emit the entries as direct
243 // references to the target basic blocks.
244 if (!EmittedSets.empty()) {
245 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
246 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
247 } else if (TM.getRelocationModel() == Reloc::PIC_) {
248 printBasicBlockLabel(JTBBs[ii], false, false);
249 //If the arch uses custom Jump Table directives, don't calc relative to JT
250 if (!TAI->getJumpTableDirective())
251 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
252 << getFunctionNumber() << '_' << i;
254 printBasicBlockLabel(JTBBs[ii], false, false);
261 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
262 /// special global used by LLVM. If so, emit it and return true, otherwise
263 /// do nothing and return false.
264 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
265 // Ignore debug and non-emitted data.
266 if (GV->getSection() == "llvm.metadata") return true;
268 if (!GV->hasAppendingLinkage()) return false;
270 assert(GV->hasInitializer() && "Not a special LLVM global!");
272 if (GV->getName() == "llvm.used") {
273 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
274 EmitLLVMUsedList(GV->getInitializer());
278 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
279 SwitchToDataSection(TAI->getStaticCtorsSection(), 0);
281 EmitXXStructorList(GV->getInitializer());
285 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
286 SwitchToDataSection(TAI->getStaticDtorsSection(), 0);
288 EmitXXStructorList(GV->getInitializer());
295 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
296 /// global in the specified llvm.used list as being used with this directive.
297 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
298 const char *Directive = TAI->getUsedDirective();
300 // Should be an array of 'sbyte*'.
301 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
302 if (InitList == 0) return;
304 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
306 EmitConstantValueOnly(InitList->getOperand(i));
311 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
312 /// function pointers, ignoring the init priority.
313 void AsmPrinter::EmitXXStructorList(Constant *List) {
314 // Should be an array of '{ int, void ()* }' structs. The first value is the
315 // init priority, which we ignore.
316 if (!isa<ConstantArray>(List)) return;
317 ConstantArray *InitList = cast<ConstantArray>(List);
318 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
319 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
320 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
322 if (CS->getOperand(1)->isNullValue())
323 return; // Found a null terminator, exit printing.
324 // Emit the function pointer.
325 EmitGlobalConstant(CS->getOperand(1));
329 /// getPreferredAlignmentLog - Return the preferred alignment of the
330 /// specified global, returned in log form. This includes an explicitly
331 /// requested alignment (if the global has one).
332 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
333 const Type *ElemType = GV->getType()->getElementType();
334 unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(ElemType);
335 if (GV->getAlignment() > (1U << Alignment))
336 Alignment = Log2_32(GV->getAlignment());
338 if (GV->hasInitializer()) {
339 // Always round up alignment of global doubles to 8 bytes.
340 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
343 // If the global is not external, see if it is large. If so, give it a
345 if (TM.getTargetData()->getTypeSize(ElemType) > 128)
346 Alignment = 4; // 16-byte alignment.
352 // EmitAlignment - Emit an alignment directive to the specified power of two.
353 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
354 if (GV && GV->getAlignment())
355 NumBits = Log2_32(GV->getAlignment());
356 if (NumBits == 0) return; // No need to emit alignment.
357 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
358 O << TAI->getAlignDirective() << NumBits << "\n";
361 /// EmitZeros - Emit a block of zeros.
363 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
365 if (TAI->getZeroDirective()) {
366 O << TAI->getZeroDirective() << NumZeros;
367 if (TAI->getZeroDirectiveSuffix())
368 O << TAI->getZeroDirectiveSuffix();
371 for (; NumZeros; --NumZeros)
372 O << TAI->getData8bitsDirective() << "0\n";
377 // Print out the specified constant, without a storage class. Only the
378 // constants valid in constant expressions can occur here.
379 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
380 if (CV->isNullValue() || isa<UndefValue>(CV))
382 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
383 assert(CB->getValue());
385 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
386 if (((CI->getValue() << 32) >> 32) == CI->getValue())
389 O << (uint64_t)CI->getValue();
390 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
392 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
393 // This is a constant address for a global variable or function. Use the
394 // name of the variable or function as the address value, possibly
395 // decorating it with GlobalVarAddrPrefix/Suffix or
396 // FunctionAddrPrefix/Suffix (these all default to "" )
397 if (isa<Function>(GV)) {
398 O << TAI->getFunctionAddrPrefix()
399 << Mang->getValueName(GV)
400 << TAI->getFunctionAddrSuffix();
402 O << TAI->getGlobalVarAddrPrefix()
403 << Mang->getValueName(GV)
404 << TAI->getGlobalVarAddrSuffix();
406 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
407 const TargetData *TD = TM.getTargetData();
408 switch(CE->getOpcode()) {
409 case Instruction::GetElementPtr: {
410 // generate a symbolic expression for the byte address
411 const Constant *ptrVal = CE->getOperand(0);
412 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
413 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
416 EmitConstantValueOnly(ptrVal);
418 O << ") + " << Offset;
420 O << ") - " << -Offset;
422 EmitConstantValueOnly(ptrVal);
426 case Instruction::Cast: {
427 // Support only foldable casts to/from pointers that can be eliminated by
428 // changing the pointer to the appropriately sized integer type.
429 Constant *Op = CE->getOperand(0);
430 const Type *OpTy = Op->getType(), *Ty = CE->getType();
432 // Handle casts to pointers by changing them into casts to the appropriate
433 // integer type. This promotes constant folding and simplifies this code.
434 if (isa<PointerType>(Ty)) {
435 const Type *IntPtrTy = TD->getIntPtrType();
436 Op = ConstantExpr::getCast(Op, IntPtrTy);
437 return EmitConstantValueOnly(Op);
440 // We know the dest type is not a pointer. Is the src value a pointer or
442 if (isa<PointerType>(OpTy) || OpTy->isIntegral()) {
443 // We can emit the pointer value into this slot if the slot is an
444 // integer slot greater or equal to the size of the pointer.
445 if (Ty->isIntegral() && TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
446 return EmitConstantValueOnly(Op);
449 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
450 EmitConstantValueOnly(Op);
453 case Instruction::Add:
455 EmitConstantValueOnly(CE->getOperand(0));
457 EmitConstantValueOnly(CE->getOperand(1));
461 assert(0 && "Unsupported operator!");
464 assert(0 && "Unknown constant value!");
468 /// toOctal - Convert the low order bits of X into an octal digit.
470 static inline char toOctal(int X) {
474 /// printAsCString - Print the specified array as a C compatible string, only if
475 /// the predicate isString is true.
477 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
479 assert(CVA->isString() && "Array is not string compatible!");
482 for (unsigned i = 0; i != LastElt; ++i) {
484 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
488 } else if (C == '\\') {
490 } else if (isprint(C)) {
494 case '\b': O << "\\b"; break;
495 case '\f': O << "\\f"; break;
496 case '\n': O << "\\n"; break;
497 case '\r': O << "\\r"; break;
498 case '\t': O << "\\t"; break;
501 O << toOctal(C >> 6);
502 O << toOctal(C >> 3);
503 O << toOctal(C >> 0);
511 /// EmitString - Emit a zero-byte-terminated string constant.
513 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
514 unsigned NumElts = CVA->getNumOperands();
515 if (TAI->getAscizDirective() && NumElts &&
516 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
517 O << TAI->getAscizDirective();
518 printAsCString(O, CVA, NumElts-1);
520 O << TAI->getAsciiDirective();
521 printAsCString(O, CVA, NumElts);
526 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
528 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
529 const TargetData *TD = TM.getTargetData();
531 if (CV->isNullValue() || isa<UndefValue>(CV)) {
532 EmitZeros(TD->getTypeSize(CV->getType()));
534 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
535 if (CVA->isString()) {
537 } else { // Not a string. Print the values in successive locations
538 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
539 EmitGlobalConstant(CVA->getOperand(i));
542 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
543 // Print the fields in successive locations. Pad to align if needed!
544 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
545 uint64_t sizeSoFar = 0;
546 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
547 const Constant* field = CVS->getOperand(i);
549 // Check if padding is needed and insert one or more 0s.
550 uint64_t fieldSize = TD->getTypeSize(field->getType());
551 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
552 : cvsLayout->MemberOffsets[i+1])
553 - cvsLayout->MemberOffsets[i]) - fieldSize;
554 sizeSoFar += fieldSize + padSize;
556 // Now print the actual field value
557 EmitGlobalConstant(field);
559 // Insert the field padding unless it's zero bytes...
562 assert(sizeSoFar == cvsLayout->StructSize &&
563 "Layout of constant struct may be incorrect!");
565 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
566 // FP Constants are printed as integer constants to avoid losing
568 double Val = CFP->getValue();
569 if (CFP->getType() == Type::DoubleTy) {
570 if (TAI->getData64bitsDirective())
571 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
572 << TAI->getCommentString() << " double value: " << Val << "\n";
573 else if (TD->isBigEndian()) {
574 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
575 << "\t" << TAI->getCommentString()
576 << " double most significant word " << Val << "\n";
577 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
578 << "\t" << TAI->getCommentString()
579 << " double least significant word " << Val << "\n";
581 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
582 << "\t" << TAI->getCommentString()
583 << " double least significant word " << Val << "\n";
584 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
585 << "\t" << TAI->getCommentString()
586 << " double most significant word " << Val << "\n";
590 O << TAI->getData32bitsDirective() << FloatToBits(Val)
591 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
594 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
595 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
596 uint64_t Val = CI->getRawValue();
598 if (TAI->getData64bitsDirective())
599 O << TAI->getData64bitsDirective() << Val << "\n";
600 else if (TD->isBigEndian()) {
601 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
602 << "\t" << TAI->getCommentString()
603 << " Double-word most significant word " << Val << "\n";
604 O << TAI->getData32bitsDirective() << unsigned(Val)
605 << "\t" << TAI->getCommentString()
606 << " Double-word least significant word " << Val << "\n";
608 O << TAI->getData32bitsDirective() << unsigned(Val)
609 << "\t" << TAI->getCommentString()
610 << " Double-word least significant word " << Val << "\n";
611 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
612 << "\t" << TAI->getCommentString()
613 << " Double-word most significant word " << Val << "\n";
617 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
618 const PackedType *PTy = CP->getType();
620 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
621 EmitGlobalConstant(CP->getOperand(I));
626 const Type *type = CV->getType();
627 printDataDirective(type);
628 EmitConstantValueOnly(CV);
633 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
634 // Target doesn't support this yet!
638 /// PrintSpecial - Print information related to the specified machine instr
639 /// that is independent of the operand, and may be independent of the instr
640 /// itself. This can be useful for portably encoding the comment character
641 /// or other bits of target-specific knowledge into the asmstrings. The
642 /// syntax used is ${:comment}. Targets can override this to add support
643 /// for their own strange codes.
644 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
645 if (!strcmp(Code, "private")) {
646 O << TAI->getPrivateGlobalPrefix();
647 } else if (!strcmp(Code, "comment")) {
648 O << TAI->getCommentString();
649 } else if (!strcmp(Code, "uid")) {
650 // Assign a unique ID to this machine instruction.
651 static const MachineInstr *LastMI = 0;
652 static unsigned Counter = 0U-1;
653 // If this is a new machine instruction, bump the counter.
654 if (LastMI != MI) { ++Counter; LastMI = MI; }
657 std::cerr << "Unknown special formatter '" << Code
658 << "' for machine instr: " << *MI;
664 /// printInlineAsm - This method formats and prints the specified machine
665 /// instruction that is an inline asm.
666 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
667 unsigned NumOperands = MI->getNumOperands();
669 // Count the number of register definitions.
670 unsigned NumDefs = 0;
671 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
673 assert(NumDefs != NumOperands-1 && "No asm string?");
675 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
677 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
678 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
680 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
681 if (AsmStr[0] == 0) {
682 O << "\n"; // Tab already printed, avoid double indenting next instr.
686 O << TAI->getInlineAsmStart() << "\n\t";
688 // The variant of the current asmprinter: FIXME: change.
689 int AsmPrinterVariant = 0;
691 int CurVariant = -1; // The number of the {.|.|.} region we are in.
692 const char *LastEmitted = AsmStr; // One past the last character emitted.
694 while (*LastEmitted) {
695 switch (*LastEmitted) {
697 // Not a special case, emit the string section literally.
698 const char *LiteralEnd = LastEmitted+1;
699 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
700 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
702 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
703 O.write(LastEmitted, LiteralEnd-LastEmitted);
704 LastEmitted = LiteralEnd;
708 ++LastEmitted; // Consume newline character.
709 O << "\n\t"; // Indent code with newline.
712 ++LastEmitted; // Consume '$' character.
716 switch (*LastEmitted) {
717 default: Done = false; break;
719 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
721 ++LastEmitted; // Consume second '$' character.
723 case '(': // $( -> same as GCC's { character.
724 ++LastEmitted; // Consume '(' character.
725 if (CurVariant != -1) {
726 std::cerr << "Nested variants found in inline asm string: '"
730 CurVariant = 0; // We're in the first variant now.
733 ++LastEmitted; // consume '|' character.
734 if (CurVariant == -1) {
735 std::cerr << "Found '|' character outside of variant in inline asm "
736 << "string: '" << AsmStr << "'\n";
739 ++CurVariant; // We're in the next variant.
741 case ')': // $) -> same as GCC's } char.
742 ++LastEmitted; // consume ')' character.
743 if (CurVariant == -1) {
744 std::cerr << "Found '}' character outside of variant in inline asm "
745 << "string: '" << AsmStr << "'\n";
753 bool HasCurlyBraces = false;
754 if (*LastEmitted == '{') { // ${variable}
755 ++LastEmitted; // Consume '{' character.
756 HasCurlyBraces = true;
759 const char *IDStart = LastEmitted;
761 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
762 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
763 std::cerr << "Bad $ operand number in inline asm string: '"
769 char Modifier[2] = { 0, 0 };
771 if (HasCurlyBraces) {
772 // If we have curly braces, check for a modifier character. This
773 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
774 if (*LastEmitted == ':') {
775 ++LastEmitted; // Consume ':' character.
776 if (*LastEmitted == 0) {
777 std::cerr << "Bad ${:} expression in inline asm string: '"
782 Modifier[0] = *LastEmitted;
783 ++LastEmitted; // Consume modifier character.
786 if (*LastEmitted != '}') {
787 std::cerr << "Bad ${} expression in inline asm string: '"
791 ++LastEmitted; // Consume '}' character.
794 if ((unsigned)Val >= NumOperands-1) {
795 std::cerr << "Invalid $ operand number in inline asm string: '"
800 // Okay, we finally have a value number. Ask the target to print this
802 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
807 // Scan to find the machine operand number for the operand.
809 if (OpNo >= MI->getNumOperands()) break;
810 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
811 OpNo += (OpFlags >> 3) + 1;
814 if (OpNo >= MI->getNumOperands()) {
817 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
818 ++OpNo; // Skip over the ID number.
820 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
821 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
822 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
823 Modifier[0] ? Modifier : 0);
825 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
826 Modifier[0] ? Modifier : 0);
830 std::cerr << "Invalid operand found in inline asm: '"
840 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
843 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
844 /// instruction, using the specified assembler variant. Targets should
845 /// overried this to format as appropriate.
846 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
847 unsigned AsmVariant, const char *ExtraCode) {
848 // Target doesn't support this yet!
852 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
854 const char *ExtraCode) {
855 // Target doesn't support this yet!
859 /// printBasicBlockLabel - This method prints the label for the specified
860 /// MachineBasicBlock
861 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
863 bool printComment) const {
864 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
868 if (printComment && MBB->getBasicBlock())
869 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
872 /// printSetLabel - This method prints a set label for the specified
873 /// MachineBasicBlock
874 void AsmPrinter::printSetLabel(unsigned uid,
875 const MachineBasicBlock *MBB) const {
876 if (!TAI->getSetDirective())
879 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
880 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
881 printBasicBlockLabel(MBB, false, false);
882 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
883 << '_' << uid << '\n';
886 /// printDataDirective - This method prints the asm directive for the
888 void AsmPrinter::printDataDirective(const Type *type) {
889 const TargetData *TD = TM.getTargetData();
890 switch (type->getTypeID()) {
892 case Type::UByteTyID: case Type::SByteTyID:
893 O << TAI->getData8bitsDirective();
895 case Type::UShortTyID: case Type::ShortTyID:
896 O << TAI->getData16bitsDirective();
898 case Type::PointerTyID:
899 if (TD->getPointerSize() == 8) {
900 assert(TAI->getData64bitsDirective() &&
901 "Target cannot handle 64-bit pointer exprs!");
902 O << TAI->getData64bitsDirective();
905 //Fall through for pointer size == int size
906 case Type::UIntTyID: case Type::IntTyID:
907 O << TAI->getData32bitsDirective();
909 case Type::ULongTyID: case Type::LongTyID:
910 assert(TAI->getData64bitsDirective() &&
911 "Target cannot handle 64-bit constant exprs!");
912 O << TAI->getData64bitsDirective();
914 case Type::FloatTyID: case Type::DoubleTyID:
915 assert (0 && "Should have already output floating point constant.");
917 assert (0 && "Can't handle printing this type of thing");