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/Support/Streams.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
32 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
33 const TargetAsmInfo *T)
34 : FunctionNumber(0), O(o), TM(tm), TAI(T)
37 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
38 return TAI->getTextSection();
42 /// SwitchToTextSection - Switch to the specified text section of the executable
43 /// if we are not already in it!
45 void AsmPrinter::SwitchToTextSection(const char *NewSection,
46 const GlobalValue *GV) {
48 if (GV && GV->hasSection())
49 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
53 // If we're already in this section, we're done.
54 if (CurrentSection == NS) return;
56 // Close the current section, if applicable.
57 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
58 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
62 if (!CurrentSection.empty())
63 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
66 /// SwitchToDataSection - Switch to the specified data section of the executable
67 /// if we are not already in it!
69 void AsmPrinter::SwitchToDataSection(const char *NewSection,
70 const GlobalValue *GV) {
72 if (GV && GV->hasSection())
73 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
77 // If we're already in this section, we're done.
78 if (CurrentSection == NS) return;
80 // Close the current section, if applicable.
81 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
82 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
86 if (!CurrentSection.empty())
87 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
91 bool AsmPrinter::doInitialization(Module &M) {
92 Mang = new Mangler(M, TAI->getGlobalPrefix());
94 if (!M.getModuleInlineAsm().empty())
95 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
96 << M.getModuleInlineAsm()
97 << "\n" << TAI->getCommentString()
98 << " End of file scope inline assembly\n";
100 SwitchToDataSection(""); // Reset back to no section.
102 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
103 DebugInfo->AnalyzeModule(M);
109 bool AsmPrinter::doFinalization(Module &M) {
110 delete Mang; Mang = 0;
114 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
115 // What's my mangled name?
116 CurrentFnName = Mang->getValueName(MF.getFunction());
117 IncrementFunctionNumber();
120 /// EmitConstantPool - Print to the current output stream assembly
121 /// representations of the constants in the constant pool MCP. This is
122 /// used to print out constants which have been "spilled to memory" by
123 /// the code generator.
125 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
126 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
127 if (CP.empty()) return;
129 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
130 // in special sections.
131 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
132 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
133 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
134 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
135 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
136 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
137 MachineConstantPoolEntry CPE = CP[i];
138 const Type *Ty = CPE.getType();
139 if (TAI->getFourByteConstantSection() &&
140 TM.getTargetData()->getTypeSize(Ty) == 4)
141 FourByteCPs.push_back(std::make_pair(CPE, i));
142 else if (TAI->getEightByteConstantSection() &&
143 TM.getTargetData()->getTypeSize(Ty) == 8)
144 EightByteCPs.push_back(std::make_pair(CPE, i));
145 else if (TAI->getSixteenByteConstantSection() &&
146 TM.getTargetData()->getTypeSize(Ty) == 16)
147 SixteenByteCPs.push_back(std::make_pair(CPE, i));
149 OtherCPs.push_back(std::make_pair(CPE, i));
152 unsigned Alignment = MCP->getConstantPoolAlignment();
153 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
154 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
155 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
157 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
160 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
161 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
162 if (CP.empty()) return;
164 SwitchToDataSection(Section);
165 EmitAlignment(Alignment);
166 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
167 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
168 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
169 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
170 if (CP[i].first.isMachineConstantPoolEntry())
171 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
173 EmitGlobalConstant(CP[i].first.Val.ConstVal);
175 const Type *Ty = CP[i].first.getType();
177 TM.getTargetData()->getTypeSize(Ty);
178 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
179 // Emit inter-object padding for alignment.
180 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
185 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
186 /// by the current function to the current output stream.
188 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
189 MachineFunction &MF) {
190 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
191 if (JT.empty()) return;
192 const TargetData *TD = TM.getTargetData();
194 // JTEntryDirective is a string to print sizeof(ptr) for non-PIC jump tables,
195 // and 32 bits for PIC since PIC jump table entries are differences, not
196 // pointers to blocks.
197 // Use the architecture specific relocation directive, if it is set
198 const char *JTEntryDirective = TAI->getJumpTableDirective();
199 if (!JTEntryDirective)
200 JTEntryDirective = TAI->getData32bitsDirective();
202 // Pick the directive to use to print the jump table entries, and switch to
203 // the appropriate section.
204 if (TM.getRelocationModel() == Reloc::PIC_) {
205 TargetLowering *LoweringInfo = TM.getTargetLowering();
206 if (LoweringInfo && LoweringInfo->usesGlobalOffsetTable()) {
207 SwitchToDataSection(TAI->getJumpTableDataSection());
208 if (TD->getPointerSize() == 8 && !JTEntryDirective)
209 JTEntryDirective = TAI->getData64bitsDirective();
211 // In PIC mode, we need to emit the jump table to the same section as the
212 // function body itself, otherwise the label differences won't make sense.
213 const Function *F = MF.getFunction();
214 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
217 SwitchToDataSection(TAI->getJumpTableDataSection());
218 if (TD->getPointerSize() == 8)
219 JTEntryDirective = TAI->getData64bitsDirective();
221 EmitAlignment(Log2_32(TD->getPointerAlignment()));
223 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
224 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
226 // If this jump table was deleted, ignore it.
227 if (JTBBs.empty()) continue;
229 // For PIC codegen, if possible we want to use the SetDirective to reduce
230 // the number of relocations the assembler will generate for the jump table.
231 // Set directives are all printed before the jump table itself.
232 std::set<MachineBasicBlock*> EmittedSets;
233 if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
234 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
235 if (EmittedSets.insert(JTBBs[ii]).second)
236 printSetLabel(i, JTBBs[ii]);
238 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
239 << '_' << i << ":\n";
241 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
242 O << JTEntryDirective << ' ';
243 // If we have emitted set directives for the jump table entries, print
244 // them rather than the entries themselves. If we're emitting PIC, then
245 // emit the table entries as differences between two text section labels.
246 // If we're emitting non-PIC code, then emit the entries as direct
247 // references to the target basic blocks.
248 if (!EmittedSets.empty()) {
249 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
250 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
251 } else if (TM.getRelocationModel() == Reloc::PIC_) {
252 printBasicBlockLabel(JTBBs[ii], false, false);
253 //If the arch uses custom Jump Table directives, don't calc relative to JT
254 if (!TAI->getJumpTableDirective())
255 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
256 << getFunctionNumber() << '_' << i;
258 printBasicBlockLabel(JTBBs[ii], false, false);
265 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
266 /// special global used by LLVM. If so, emit it and return true, otherwise
267 /// do nothing and return false.
268 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
269 // Ignore debug and non-emitted data.
270 if (GV->getSection() == "llvm.metadata") return true;
272 if (!GV->hasAppendingLinkage()) return false;
274 assert(GV->hasInitializer() && "Not a special LLVM global!");
276 if (GV->getName() == "llvm.used") {
277 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
278 EmitLLVMUsedList(GV->getInitializer());
282 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
283 SwitchToDataSection(TAI->getStaticCtorsSection());
285 EmitXXStructorList(GV->getInitializer());
289 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
290 SwitchToDataSection(TAI->getStaticDtorsSection());
292 EmitXXStructorList(GV->getInitializer());
299 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
300 /// global in the specified llvm.used list as being used with this directive.
301 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
302 const char *Directive = TAI->getUsedDirective();
304 // Should be an array of 'sbyte*'.
305 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
306 if (InitList == 0) return;
308 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
310 EmitConstantValueOnly(InitList->getOperand(i));
315 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
316 /// function pointers, ignoring the init priority.
317 void AsmPrinter::EmitXXStructorList(Constant *List) {
318 // Should be an array of '{ int, void ()* }' structs. The first value is the
319 // init priority, which we ignore.
320 if (!isa<ConstantArray>(List)) return;
321 ConstantArray *InitList = cast<ConstantArray>(List);
322 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
323 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
324 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
326 if (CS->getOperand(1)->isNullValue())
327 return; // Found a null terminator, exit printing.
328 // Emit the function pointer.
329 EmitGlobalConstant(CS->getOperand(1));
333 /// getGlobalLinkName - Returns the asm/link name of of the specified
334 /// global variable. Should be overridden by each target asm printer to
335 /// generate the appropriate value.
336 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
337 std::string LinkName;
339 if (isa<Function>(GV)) {
340 LinkName += TAI->getFunctionAddrPrefix();
341 LinkName += Mang->getValueName(GV);
342 LinkName += TAI->getFunctionAddrSuffix();
344 LinkName += TAI->getGlobalVarAddrPrefix();
345 LinkName += Mang->getValueName(GV);
346 LinkName += TAI->getGlobalVarAddrSuffix();
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 ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
386 if (CI->getType()->isSigned()) {
387 if (((CI->getSExtValue() << 32) >> 32) == CI->getSExtValue())
388 O << CI->getSExtValue();
390 O << (uint64_t)CI->getSExtValue();
392 O << CI->getZExtValue();
393 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
394 // This is a constant address for a global variable or function. Use the
395 // name of the variable or function as the address value, possibly
396 // decorating it with GlobalVarAddrPrefix/Suffix or
397 // FunctionAddrPrefix/Suffix (these all default to "" )
398 if (isa<Function>(GV)) {
399 O << TAI->getFunctionAddrPrefix()
400 << Mang->getValueName(GV)
401 << TAI->getFunctionAddrSuffix();
403 O << TAI->getGlobalVarAddrPrefix()
404 << Mang->getValueName(GV)
405 << TAI->getGlobalVarAddrSuffix();
407 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
408 const TargetData *TD = TM.getTargetData();
409 switch(CE->getOpcode()) {
410 case Instruction::GetElementPtr: {
411 // generate a symbolic expression for the byte address
412 const Constant *ptrVal = CE->getOperand(0);
413 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
414 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
417 EmitConstantValueOnly(ptrVal);
419 O << ") + " << Offset;
421 O << ") - " << -Offset;
423 EmitConstantValueOnly(ptrVal);
427 case Instruction::Trunc:
428 case Instruction::ZExt:
429 case Instruction::SExt:
430 case Instruction::FPTrunc:
431 case Instruction::FPExt:
432 case Instruction::UIToFP:
433 case Instruction::SIToFP:
434 case Instruction::FPToUI:
435 case Instruction::FPToSI:
436 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
438 case Instruction::IntToPtr:
439 case Instruction::PtrToInt:
440 case Instruction::BitCast: {
441 // Support only foldable casts to/from pointers that can be eliminated by
442 // changing the pointer to the appropriately sized integer type.
443 Constant *Op = CE->getOperand(0);
444 const Type *OpTy = Op->getType(), *Ty = CE->getType();
446 // Handle casts to pointers by changing them into casts to the appropriate
447 // integer type. This promotes constant folding and simplifies this code.
448 if (isa<PointerType>(Ty)) {
449 const Type *IntPtrTy = TD->getIntPtrType();
450 Op = ConstantExpr::getCast(Op, IntPtrTy);
451 return EmitConstantValueOnly(Op);
454 // We know the dest type is not a pointer. Is the src value a pointer or
456 if (isa<PointerType>(OpTy) || OpTy->isIntegral()) {
457 // We can emit the pointer value into this slot if the slot is an
458 // integer slot greater or equal to the size of the pointer.
459 if (Ty->isIntegral() && TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
460 return EmitConstantValueOnly(Op);
463 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
464 EmitConstantValueOnly(Op);
467 case Instruction::Add:
469 EmitConstantValueOnly(CE->getOperand(0));
471 EmitConstantValueOnly(CE->getOperand(1));
475 assert(0 && "Unsupported operator!");
478 assert(0 && "Unknown constant value!");
482 /// toOctal - Convert the low order bits of X into an octal digit.
484 static inline char toOctal(int X) {
488 /// printAsCString - Print the specified array as a C compatible string, only if
489 /// the predicate isString is true.
491 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
493 assert(CVA->isString() && "Array is not string compatible!");
496 for (unsigned i = 0; i != LastElt; ++i) {
498 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
502 } else if (C == '\\') {
504 } else if (isprint(C)) {
508 case '\b': O << "\\b"; break;
509 case '\f': O << "\\f"; break;
510 case '\n': O << "\\n"; break;
511 case '\r': O << "\\r"; break;
512 case '\t': O << "\\t"; break;
515 O << toOctal(C >> 6);
516 O << toOctal(C >> 3);
517 O << toOctal(C >> 0);
525 /// EmitString - Emit a zero-byte-terminated string constant.
527 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
528 unsigned NumElts = CVA->getNumOperands();
529 if (TAI->getAscizDirective() && NumElts &&
530 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
531 O << TAI->getAscizDirective();
532 printAsCString(O, CVA, NumElts-1);
534 O << TAI->getAsciiDirective();
535 printAsCString(O, CVA, NumElts);
540 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
542 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
543 const TargetData *TD = TM.getTargetData();
545 if (CV->isNullValue() || isa<UndefValue>(CV)) {
546 EmitZeros(TD->getTypeSize(CV->getType()));
548 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
549 if (CVA->isString()) {
551 } else { // Not a string. Print the values in successive locations
552 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
553 EmitGlobalConstant(CVA->getOperand(i));
556 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
557 // Print the fields in successive locations. Pad to align if needed!
558 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
559 uint64_t sizeSoFar = 0;
560 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
561 const Constant* field = CVS->getOperand(i);
563 // Check if padding is needed and insert one or more 0s.
564 uint64_t fieldSize = TD->getTypeSize(field->getType());
565 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
566 : cvsLayout->MemberOffsets[i+1])
567 - cvsLayout->MemberOffsets[i]) - fieldSize;
568 sizeSoFar += fieldSize + padSize;
570 // Now print the actual field value
571 EmitGlobalConstant(field);
573 // Insert the field padding unless it's zero bytes...
576 assert(sizeSoFar == cvsLayout->StructSize &&
577 "Layout of constant struct may be incorrect!");
579 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
580 // FP Constants are printed as integer constants to avoid losing
582 double Val = CFP->getValue();
583 if (CFP->getType() == Type::DoubleTy) {
584 if (TAI->getData64bitsDirective())
585 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
586 << TAI->getCommentString() << " double value: " << Val << "\n";
587 else if (TD->isBigEndian()) {
588 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
589 << "\t" << TAI->getCommentString()
590 << " double most significant word " << Val << "\n";
591 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
592 << "\t" << TAI->getCommentString()
593 << " double least significant word " << Val << "\n";
595 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
596 << "\t" << TAI->getCommentString()
597 << " double least significant word " << Val << "\n";
598 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
599 << "\t" << TAI->getCommentString()
600 << " double most significant word " << Val << "\n";
604 O << TAI->getData32bitsDirective() << FloatToBits(Val)
605 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
608 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
609 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
610 uint64_t Val = CI->getZExtValue();
612 if (TAI->getData64bitsDirective())
613 O << TAI->getData64bitsDirective() << Val << "\n";
614 else if (TD->isBigEndian()) {
615 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
616 << "\t" << TAI->getCommentString()
617 << " Double-word most significant word " << Val << "\n";
618 O << TAI->getData32bitsDirective() << unsigned(Val)
619 << "\t" << TAI->getCommentString()
620 << " Double-word least significant word " << Val << "\n";
622 O << TAI->getData32bitsDirective() << unsigned(Val)
623 << "\t" << TAI->getCommentString()
624 << " Double-word least significant word " << Val << "\n";
625 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
626 << "\t" << TAI->getCommentString()
627 << " Double-word most significant word " << Val << "\n";
631 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
632 const PackedType *PTy = CP->getType();
634 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
635 EmitGlobalConstant(CP->getOperand(I));
640 const Type *type = CV->getType();
641 printDataDirective(type);
642 EmitConstantValueOnly(CV);
647 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
648 // Target doesn't support this yet!
652 /// PrintSpecial - Print information related to the specified machine instr
653 /// that is independent of the operand, and may be independent of the instr
654 /// itself. This can be useful for portably encoding the comment character
655 /// or other bits of target-specific knowledge into the asmstrings. The
656 /// syntax used is ${:comment}. Targets can override this to add support
657 /// for their own strange codes.
658 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
659 if (!strcmp(Code, "private")) {
660 O << TAI->getPrivateGlobalPrefix();
661 } else if (!strcmp(Code, "comment")) {
662 O << TAI->getCommentString();
663 } else if (!strcmp(Code, "uid")) {
664 // Assign a unique ID to this machine instruction.
665 static const MachineInstr *LastMI = 0;
666 static unsigned Counter = 0U-1;
667 // If this is a new machine instruction, bump the counter.
668 if (LastMI != MI) { ++Counter; LastMI = MI; }
671 llvm_cerr << "Unknown special formatter '" << Code
672 << "' for machine instr: " << *MI;
678 /// printInlineAsm - This method formats and prints the specified machine
679 /// instruction that is an inline asm.
680 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
681 unsigned NumOperands = MI->getNumOperands();
683 // Count the number of register definitions.
684 unsigned NumDefs = 0;
685 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
687 assert(NumDefs != NumOperands-1 && "No asm string?");
689 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
691 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
692 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
694 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
695 if (AsmStr[0] == 0) {
696 O << "\n"; // Tab already printed, avoid double indenting next instr.
700 O << TAI->getInlineAsmStart() << "\n\t";
702 // The variant of the current asmprinter: FIXME: change.
703 int AsmPrinterVariant = 0;
705 int CurVariant = -1; // The number of the {.|.|.} region we are in.
706 const char *LastEmitted = AsmStr; // One past the last character emitted.
708 while (*LastEmitted) {
709 switch (*LastEmitted) {
711 // Not a special case, emit the string section literally.
712 const char *LiteralEnd = LastEmitted+1;
713 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
714 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
716 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
717 O.write(LastEmitted, LiteralEnd-LastEmitted);
718 LastEmitted = LiteralEnd;
722 ++LastEmitted; // Consume newline character.
723 O << "\n\t"; // Indent code with newline.
726 ++LastEmitted; // Consume '$' character.
730 switch (*LastEmitted) {
731 default: Done = false; break;
733 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
735 ++LastEmitted; // Consume second '$' character.
737 case '(': // $( -> same as GCC's { character.
738 ++LastEmitted; // Consume '(' character.
739 if (CurVariant != -1) {
740 llvm_cerr << "Nested variants found in inline asm string: '"
744 CurVariant = 0; // We're in the first variant now.
747 ++LastEmitted; // consume '|' character.
748 if (CurVariant == -1) {
749 llvm_cerr << "Found '|' character outside of variant in inline asm "
750 << "string: '" << AsmStr << "'\n";
753 ++CurVariant; // We're in the next variant.
755 case ')': // $) -> same as GCC's } char.
756 ++LastEmitted; // consume ')' character.
757 if (CurVariant == -1) {
758 llvm_cerr << "Found '}' character outside of variant in inline asm "
759 << "string: '" << AsmStr << "'\n";
767 bool HasCurlyBraces = false;
768 if (*LastEmitted == '{') { // ${variable}
769 ++LastEmitted; // Consume '{' character.
770 HasCurlyBraces = true;
773 const char *IDStart = LastEmitted;
775 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
776 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
777 llvm_cerr << "Bad $ operand number in inline asm string: '"
783 char Modifier[2] = { 0, 0 };
785 if (HasCurlyBraces) {
786 // If we have curly braces, check for a modifier character. This
787 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
788 if (*LastEmitted == ':') {
789 ++LastEmitted; // Consume ':' character.
790 if (*LastEmitted == 0) {
791 llvm_cerr << "Bad ${:} expression in inline asm string: '"
796 Modifier[0] = *LastEmitted;
797 ++LastEmitted; // Consume modifier character.
800 if (*LastEmitted != '}') {
801 llvm_cerr << "Bad ${} expression in inline asm string: '"
805 ++LastEmitted; // Consume '}' character.
808 if ((unsigned)Val >= NumOperands-1) {
809 llvm_cerr << "Invalid $ operand number in inline asm string: '"
814 // Okay, we finally have a value number. Ask the target to print this
816 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
821 // Scan to find the machine operand number for the operand.
823 if (OpNo >= MI->getNumOperands()) break;
824 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
825 OpNo += (OpFlags >> 3) + 1;
828 if (OpNo >= MI->getNumOperands()) {
831 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
832 ++OpNo; // Skip over the ID number.
834 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
835 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
836 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
837 Modifier[0] ? Modifier : 0);
839 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
840 Modifier[0] ? Modifier : 0);
844 llvm_cerr << "Invalid operand found in inline asm: '"
854 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
857 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
858 /// instruction, using the specified assembler variant. Targets should
859 /// overried this to format as appropriate.
860 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
861 unsigned AsmVariant, const char *ExtraCode) {
862 // Target doesn't support this yet!
866 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
868 const char *ExtraCode) {
869 // Target doesn't support this yet!
873 /// printBasicBlockLabel - This method prints the label for the specified
874 /// MachineBasicBlock
875 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
877 bool printComment) const {
878 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
882 if (printComment && MBB->getBasicBlock())
883 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
886 /// printSetLabel - This method prints a set label for the specified
887 /// MachineBasicBlock
888 void AsmPrinter::printSetLabel(unsigned uid,
889 const MachineBasicBlock *MBB) const {
890 if (!TAI->getSetDirective())
893 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
894 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
895 printBasicBlockLabel(MBB, false, false);
896 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
897 << '_' << uid << '\n';
900 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
901 const MachineBasicBlock *MBB) const {
902 if (!TAI->getSetDirective())
905 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
906 << getFunctionNumber() << '_' << uid << '_' << uid2
907 << "_set_" << MBB->getNumber() << ',';
908 printBasicBlockLabel(MBB, false, false);
909 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
910 << '_' << uid << '_' << uid2 << '\n';
913 /// printDataDirective - This method prints the asm directive for the
915 void AsmPrinter::printDataDirective(const Type *type) {
916 const TargetData *TD = TM.getTargetData();
917 switch (type->getTypeID()) {
919 case Type::UByteTyID: case Type::SByteTyID:
920 O << TAI->getData8bitsDirective();
922 case Type::UShortTyID: case Type::ShortTyID:
923 O << TAI->getData16bitsDirective();
925 case Type::PointerTyID:
926 if (TD->getPointerSize() == 8) {
927 assert(TAI->getData64bitsDirective() &&
928 "Target cannot handle 64-bit pointer exprs!");
929 O << TAI->getData64bitsDirective();
932 //Fall through for pointer size == int size
933 case Type::UIntTyID: case Type::IntTyID:
934 O << TAI->getData32bitsDirective();
936 case Type::ULongTyID: case Type::LongTyID:
937 assert(TAI->getData64bitsDirective() &&
938 "Target cannot handle 64-bit constant exprs!");
939 O << TAI->getData64bitsDirective();
941 case Type::FloatTyID: case Type::DoubleTyID:
942 assert (0 && "Should have already output floating point constant.");
944 assert (0 && "Can't handle printing this type of thing");