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/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"
33 AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
35 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
36 const TargetAsmInfo *T)
37 : FunctionNumber(0), O(o), TM(tm), TAI(T)
40 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
41 return TAI->getTextSection();
45 /// SwitchToTextSection - Switch to the specified text section of the executable
46 /// if we are not already in it!
48 void AsmPrinter::SwitchToTextSection(const char *NewSection,
49 const GlobalValue *GV) {
51 if (GV && GV->hasSection())
52 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
56 // If we're already in this section, we're done.
57 if (CurrentSection == NS) return;
59 // Close the current section, if applicable.
60 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
61 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
65 if (!CurrentSection.empty())
66 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
69 /// SwitchToDataSection - Switch to the specified data section of the executable
70 /// if we are not already in it!
72 void AsmPrinter::SwitchToDataSection(const char *NewSection,
73 const GlobalValue *GV) {
75 if (GV && GV->hasSection())
76 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
80 // If we're already in this section, we're done.
81 if (CurrentSection == NS) return;
83 // Close the current section, if applicable.
84 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
85 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
89 if (!CurrentSection.empty())
90 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
94 bool AsmPrinter::doInitialization(Module &M) {
95 Mang = new Mangler(M, TAI->getGlobalPrefix());
97 if (!M.getModuleInlineAsm().empty())
98 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
99 << M.getModuleInlineAsm()
100 << "\n" << TAI->getCommentString()
101 << " End of file scope inline assembly\n";
103 SwitchToDataSection(""); // Reset back to no section.
105 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
106 MMI->AnalyzeModule(M);
112 bool AsmPrinter::doFinalization(Module &M) {
113 if (TAI->getWeakRefDirective()) {
114 if (!ExtWeakSymbols.empty())
115 SwitchToDataSection("");
117 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
118 e = ExtWeakSymbols.end(); i != e; ++i) {
119 const GlobalValue *GV = *i;
120 std::string Name = Mang->getValueName(GV);
121 O << TAI->getWeakRefDirective() << Name << "\n";
125 if (TAI->getSetDirective()) {
127 SwitchToTextSection(TAI->getTextSection());
130 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
132 const GlobalValue *Aliasee = I->getAliasee();
133 assert(Aliasee && "Aliasee cannot be null!");
134 std::string Target = Mang->getValueName(Aliasee);
135 std::string Name = Mang->getValueName(I);
137 // Aliases with external weak linkage was emitted already
138 if (I->hasExternalLinkage())
139 O << "\t.globl\t" << Name << "\n";
140 else if (I->hasWeakLinkage())
141 O << TAI->getWeakRefDirective() << Name << "\n";
142 else if (!I->hasInternalLinkage())
143 assert(0 && "Invalid alias linkage");
145 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
149 delete Mang; Mang = 0;
153 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
154 // What's my mangled name?
155 CurrentFnName = Mang->getValueName(MF.getFunction());
156 IncrementFunctionNumber();
159 /// EmitConstantPool - Print to the current output stream assembly
160 /// representations of the constants in the constant pool MCP. This is
161 /// used to print out constants which have been "spilled to memory" by
162 /// the code generator.
164 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
165 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
166 if (CP.empty()) return;
168 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
169 // in special sections.
170 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
171 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
172 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
173 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
174 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
175 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
176 MachineConstantPoolEntry CPE = CP[i];
177 const Type *Ty = CPE.getType();
178 if (TAI->getFourByteConstantSection() &&
179 TM.getTargetData()->getTypeSize(Ty) == 4)
180 FourByteCPs.push_back(std::make_pair(CPE, i));
181 else if (TAI->getEightByteConstantSection() &&
182 TM.getTargetData()->getTypeSize(Ty) == 8)
183 EightByteCPs.push_back(std::make_pair(CPE, i));
184 else if (TAI->getSixteenByteConstantSection() &&
185 TM.getTargetData()->getTypeSize(Ty) == 16)
186 SixteenByteCPs.push_back(std::make_pair(CPE, i));
188 OtherCPs.push_back(std::make_pair(CPE, i));
191 unsigned Alignment = MCP->getConstantPoolAlignment();
192 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
193 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
194 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
196 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
199 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
200 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
201 if (CP.empty()) return;
203 SwitchToDataSection(Section);
204 EmitAlignment(Alignment);
205 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
206 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
207 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
208 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
209 if (CP[i].first.isMachineConstantPoolEntry())
210 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
212 EmitGlobalConstant(CP[i].first.Val.ConstVal);
214 const Type *Ty = CP[i].first.getType();
216 TM.getTargetData()->getTypeSize(Ty);
217 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
218 // Emit inter-object padding for alignment.
219 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
224 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
225 /// by the current function to the current output stream.
227 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
228 MachineFunction &MF) {
229 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
230 if (JT.empty()) return;
231 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
233 // Use JumpTableDirective otherwise honor the entry size from the jump table
235 const char *JTEntryDirective = TAI->getJumpTableDirective();
236 bool HadJTEntryDirective = JTEntryDirective != NULL;
237 if (!HadJTEntryDirective) {
238 JTEntryDirective = MJTI->getEntrySize() == 4 ?
239 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
242 // Pick the directive to use to print the jump table entries, and switch to
243 // the appropriate section.
244 TargetLowering *LoweringInfo = TM.getTargetLowering();
246 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
247 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
248 !JumpTableDataSection) {
249 // In PIC mode, we need to emit the jump table to the same section as the
250 // function body itself, otherwise the label differences won't make sense.
251 // We should also do if the section name is NULL.
252 const Function *F = MF.getFunction();
253 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
255 SwitchToDataSection(JumpTableDataSection);
258 EmitAlignment(Log2_32(MJTI->getAlignment()));
260 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
261 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
263 // If this jump table was deleted, ignore it.
264 if (JTBBs.empty()) continue;
266 // For PIC codegen, if possible we want to use the SetDirective to reduce
267 // the number of relocations the assembler will generate for the jump table.
268 // Set directives are all printed before the jump table itself.
269 std::set<MachineBasicBlock*> EmittedSets;
270 if (TAI->getSetDirective() && IsPic)
271 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
272 if (EmittedSets.insert(JTBBs[ii]).second)
273 printSetLabel(i, JTBBs[ii]);
275 // On some targets (e.g. darwin) we want to emit two consequtive labels
276 // before each jump table. The first label is never referenced, but tells
277 // the assembler and linker the extents of the jump table object. The
278 // second label is actually referenced by the code.
279 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
280 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
282 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
283 << '_' << i << ":\n";
285 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
286 O << JTEntryDirective << ' ';
287 // If we have emitted set directives for the jump table entries, print
288 // them rather than the entries themselves. If we're emitting PIC, then
289 // emit the table entries as differences between two text section labels.
290 // If we're emitting non-PIC code, then emit the entries as direct
291 // references to the target basic blocks.
292 if (!EmittedSets.empty()) {
293 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
294 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
296 printBasicBlockLabel(JTBBs[ii], false, false);
297 // If the arch uses custom Jump Table directives, don't calc relative to
299 if (!HadJTEntryDirective)
300 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
301 << getFunctionNumber() << '_' << i;
303 printBasicBlockLabel(JTBBs[ii], false, false);
310 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
311 /// special global used by LLVM. If so, emit it and return true, otherwise
312 /// do nothing and return false.
313 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
314 // Ignore debug and non-emitted data.
315 if (GV->getSection() == "llvm.metadata") return true;
317 if (!GV->hasAppendingLinkage()) return false;
319 assert(GV->hasInitializer() && "Not a special LLVM global!");
321 if (GV->getName() == "llvm.used") {
322 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
323 EmitLLVMUsedList(GV->getInitializer());
327 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
328 SwitchToDataSection(TAI->getStaticCtorsSection());
330 EmitXXStructorList(GV->getInitializer());
334 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
335 SwitchToDataSection(TAI->getStaticDtorsSection());
337 EmitXXStructorList(GV->getInitializer());
344 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
345 /// global in the specified llvm.used list as being used with this directive.
346 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
347 const char *Directive = TAI->getUsedDirective();
349 // Should be an array of 'sbyte*'.
350 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
351 if (InitList == 0) return;
353 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
355 EmitConstantValueOnly(InitList->getOperand(i));
360 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
361 /// function pointers, ignoring the init priority.
362 void AsmPrinter::EmitXXStructorList(Constant *List) {
363 // Should be an array of '{ int, void ()* }' structs. The first value is the
364 // init priority, which we ignore.
365 if (!isa<ConstantArray>(List)) return;
366 ConstantArray *InitList = cast<ConstantArray>(List);
367 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
368 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
369 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
371 if (CS->getOperand(1)->isNullValue())
372 return; // Found a null terminator, exit printing.
373 // Emit the function pointer.
374 EmitGlobalConstant(CS->getOperand(1));
378 /// getGlobalLinkName - Returns the asm/link name of of the specified
379 /// global variable. Should be overridden by each target asm printer to
380 /// generate the appropriate value.
381 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
382 std::string LinkName;
384 if (isa<Function>(GV)) {
385 LinkName += TAI->getFunctionAddrPrefix();
386 LinkName += Mang->getValueName(GV);
387 LinkName += TAI->getFunctionAddrSuffix();
389 LinkName += TAI->getGlobalVarAddrPrefix();
390 LinkName += Mang->getValueName(GV);
391 LinkName += TAI->getGlobalVarAddrSuffix();
397 /// EmitExternalGlobal - Emit the external reference to a global variable.
398 /// Should be overridden if an indirect reference should be used.
399 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
400 O << getGlobalLinkName(GV);
405 //===----------------------------------------------------------------------===//
406 /// LEB 128 number encoding.
408 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
409 /// representing an unsigned leb128 value.
410 void AsmPrinter::PrintULEB128(unsigned Value) const {
412 unsigned Byte = Value & 0x7f;
414 if (Value) Byte |= 0x80;
415 O << "0x" << std::hex << Byte << std::dec;
416 if (Value) O << ", ";
420 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
422 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
426 Size += sizeof(int8_t);
431 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
432 /// representing a signed leb128 value.
433 void AsmPrinter::PrintSLEB128(int Value) const {
434 int Sign = Value >> (8 * sizeof(Value) - 1);
438 unsigned Byte = Value & 0x7f;
440 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
441 if (IsMore) Byte |= 0x80;
442 O << "0x" << std::hex << Byte << std::dec;
443 if (IsMore) O << ", ";
447 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
449 unsigned AsmPrinter::SizeSLEB128(int Value) {
451 int Sign = Value >> (8 * sizeof(Value) - 1);
455 unsigned Byte = Value & 0x7f;
457 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
458 Size += sizeof(int8_t);
463 //===--------------------------------------------------------------------===//
464 // Emission and print routines
467 /// PrintHex - Print a value as a hexidecimal value.
469 void AsmPrinter::PrintHex(int Value) const {
470 O << "0x" << std::hex << Value << std::dec;
473 /// EOL - Print a newline character to asm stream. If a comment is present
474 /// then it will be printed first. Comments should not contain '\n'.
475 void AsmPrinter::EOL() const {
478 void AsmPrinter::EOL(const std::string &Comment) const {
479 if (AsmVerbose && !Comment.empty()) {
481 << TAI->getCommentString()
488 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
489 /// unsigned leb128 value.
490 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
491 if (TAI->hasLEB128()) {
495 O << TAI->getData8bitsDirective();
500 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
501 /// signed leb128 value.
502 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
503 if (TAI->hasLEB128()) {
507 O << TAI->getData8bitsDirective();
512 /// EmitInt8 - Emit a byte directive and value.
514 void AsmPrinter::EmitInt8(int Value) const {
515 O << TAI->getData8bitsDirective();
516 PrintHex(Value & 0xFF);
519 /// EmitInt16 - Emit a short directive and value.
521 void AsmPrinter::EmitInt16(int Value) const {
522 O << TAI->getData16bitsDirective();
523 PrintHex(Value & 0xFFFF);
526 /// EmitInt32 - Emit a long directive and value.
528 void AsmPrinter::EmitInt32(int Value) const {
529 O << TAI->getData32bitsDirective();
533 /// EmitInt64 - Emit a long long directive and value.
535 void AsmPrinter::EmitInt64(uint64_t Value) const {
536 if (TAI->getData64bitsDirective()) {
537 O << TAI->getData64bitsDirective();
540 if (TM.getTargetData()->isBigEndian()) {
541 EmitInt32(unsigned(Value >> 32)); O << "\n";
542 EmitInt32(unsigned(Value));
544 EmitInt32(unsigned(Value)); O << "\n";
545 EmitInt32(unsigned(Value >> 32));
550 /// toOctal - Convert the low order bits of X into an octal digit.
552 static inline char toOctal(int X) {
556 /// printStringChar - Print a char, escaped if necessary.
558 static void printStringChar(std::ostream &O, unsigned char C) {
561 } else if (C == '\\') {
563 } else if (isprint(C)) {
567 case '\b': O << "\\b"; break;
568 case '\f': O << "\\f"; break;
569 case '\n': O << "\\n"; break;
570 case '\r': O << "\\r"; break;
571 case '\t': O << "\\t"; break;
574 O << toOctal(C >> 6);
575 O << toOctal(C >> 3);
576 O << toOctal(C >> 0);
582 /// EmitString - Emit a string with quotes and a null terminator.
583 /// Special characters are emitted properly.
584 /// \literal (Eg. '\t') \endliteral
585 void AsmPrinter::EmitString(const std::string &String) const {
586 const char* AscizDirective = TAI->getAscizDirective();
590 O << TAI->getAsciiDirective();
592 for (unsigned i = 0, N = String.size(); i < N; ++i) {
593 unsigned char C = String[i];
594 printStringChar(O, C);
603 //===----------------------------------------------------------------------===//
605 // EmitAlignment - Emit an alignment directive to the specified power of two.
606 // Use the maximum of the specified alignment and the alignment from the
607 // specified GlobalValue (if any).
608 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
609 if (GV && GV->getAlignment())
610 NumBits = std::max(NumBits, Log2_32(GV->getAlignment()));
611 if (NumBits == 0) return; // No need to emit alignment.
612 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
613 O << TAI->getAlignDirective() << NumBits << "\n";
617 /// EmitZeros - Emit a block of zeros.
619 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
621 if (TAI->getZeroDirective()) {
622 O << TAI->getZeroDirective() << NumZeros;
623 if (TAI->getZeroDirectiveSuffix())
624 O << TAI->getZeroDirectiveSuffix();
627 for (; NumZeros; --NumZeros)
628 O << TAI->getData8bitsDirective() << "0\n";
633 // Print out the specified constant, without a storage class. Only the
634 // constants valid in constant expressions can occur here.
635 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
636 if (CV->isNullValue() || isa<UndefValue>(CV))
638 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
639 O << CI->getZExtValue();
640 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
641 // This is a constant address for a global variable or function. Use the
642 // name of the variable or function as the address value, possibly
643 // decorating it with GlobalVarAddrPrefix/Suffix or
644 // FunctionAddrPrefix/Suffix (these all default to "" )
645 if (isa<Function>(GV)) {
646 O << TAI->getFunctionAddrPrefix()
647 << Mang->getValueName(GV)
648 << TAI->getFunctionAddrSuffix();
650 O << TAI->getGlobalVarAddrPrefix()
651 << Mang->getValueName(GV)
652 << TAI->getGlobalVarAddrSuffix();
654 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
655 const TargetData *TD = TM.getTargetData();
656 unsigned Opcode = CE->getOpcode();
658 case Instruction::GetElementPtr: {
659 // generate a symbolic expression for the byte address
660 const Constant *ptrVal = CE->getOperand(0);
661 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
662 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
666 EmitConstantValueOnly(ptrVal);
668 O << ") + " << Offset;
670 O << ") - " << -Offset;
672 EmitConstantValueOnly(ptrVal);
676 case Instruction::Trunc:
677 case Instruction::ZExt:
678 case Instruction::SExt:
679 case Instruction::FPTrunc:
680 case Instruction::FPExt:
681 case Instruction::UIToFP:
682 case Instruction::SIToFP:
683 case Instruction::FPToUI:
684 case Instruction::FPToSI:
685 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
687 case Instruction::BitCast:
688 return EmitConstantValueOnly(CE->getOperand(0));
690 case Instruction::IntToPtr: {
691 // Handle casts to pointers by changing them into casts to the appropriate
692 // integer type. This promotes constant folding and simplifies this code.
693 Constant *Op = CE->getOperand(0);
694 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
695 return EmitConstantValueOnly(Op);
699 case Instruction::PtrToInt: {
700 // Support only foldable casts to/from pointers that can be eliminated by
701 // changing the pointer to the appropriately sized integer type.
702 Constant *Op = CE->getOperand(0);
703 const Type *Ty = CE->getType();
705 // We can emit the pointer value into this slot if the slot is an
706 // integer slot greater or equal to the size of the pointer.
707 if (Ty->isInteger() &&
708 TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
709 return EmitConstantValueOnly(Op);
711 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
712 EmitConstantValueOnly(Op);
715 case Instruction::Add:
716 case Instruction::Sub:
718 EmitConstantValueOnly(CE->getOperand(0));
719 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
720 EmitConstantValueOnly(CE->getOperand(1));
724 assert(0 && "Unsupported operator!");
727 assert(0 && "Unknown constant value!");
731 /// printAsCString - Print the specified array as a C compatible string, only if
732 /// the predicate isString is true.
734 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
736 assert(CVA->isString() && "Array is not string compatible!");
739 for (unsigned i = 0; i != LastElt; ++i) {
741 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
742 printStringChar(O, C);
747 /// EmitString - Emit a zero-byte-terminated string constant.
749 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
750 unsigned NumElts = CVA->getNumOperands();
751 if (TAI->getAscizDirective() && NumElts &&
752 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
753 O << TAI->getAscizDirective();
754 printAsCString(O, CVA, NumElts-1);
756 O << TAI->getAsciiDirective();
757 printAsCString(O, CVA, NumElts);
762 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
764 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
765 const TargetData *TD = TM.getTargetData();
767 if (CV->isNullValue() || isa<UndefValue>(CV)) {
768 EmitZeros(TD->getTypeSize(CV->getType()));
770 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
771 if (CVA->isString()) {
773 } else { // Not a string. Print the values in successive locations
774 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
775 EmitGlobalConstant(CVA->getOperand(i));
778 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
779 // Print the fields in successive locations. Pad to align if needed!
780 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
781 uint64_t sizeSoFar = 0;
782 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
783 const Constant* field = CVS->getOperand(i);
785 // Check if padding is needed and insert one or more 0s.
786 uint64_t fieldSize = TD->getTypeSize(field->getType());
787 uint64_t padSize = ((i == e-1? cvsLayout->getSizeInBytes()
788 : cvsLayout->getElementOffset(i+1))
789 - cvsLayout->getElementOffset(i)) - fieldSize;
790 sizeSoFar += fieldSize + padSize;
792 // Now print the actual field value
793 EmitGlobalConstant(field);
795 // Insert the field padding unless it's zero bytes...
798 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
799 "Layout of constant struct may be incorrect!");
801 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
802 // FP Constants are printed as integer constants to avoid losing
804 double Val = CFP->getValue();
805 if (CFP->getType() == Type::DoubleTy) {
806 if (TAI->getData64bitsDirective())
807 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
808 << TAI->getCommentString() << " double value: " << Val << "\n";
809 else if (TD->isBigEndian()) {
810 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
811 << "\t" << TAI->getCommentString()
812 << " double most significant word " << Val << "\n";
813 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
814 << "\t" << TAI->getCommentString()
815 << " double least significant word " << Val << "\n";
817 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
818 << "\t" << TAI->getCommentString()
819 << " double least significant word " << Val << "\n";
820 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
821 << "\t" << TAI->getCommentString()
822 << " double most significant word " << Val << "\n";
826 O << TAI->getData32bitsDirective() << FloatToBits(Val)
827 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
830 } else if (CV->getType() == Type::Int64Ty) {
831 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
832 uint64_t Val = CI->getZExtValue();
834 if (TAI->getData64bitsDirective())
835 O << TAI->getData64bitsDirective() << Val << "\n";
836 else if (TD->isBigEndian()) {
837 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
838 << "\t" << TAI->getCommentString()
839 << " Double-word most significant word " << Val << "\n";
840 O << TAI->getData32bitsDirective() << unsigned(Val)
841 << "\t" << TAI->getCommentString()
842 << " Double-word least significant word " << Val << "\n";
844 O << TAI->getData32bitsDirective() << unsigned(Val)
845 << "\t" << TAI->getCommentString()
846 << " Double-word least significant word " << Val << "\n";
847 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
848 << "\t" << TAI->getCommentString()
849 << " Double-word most significant word " << Val << "\n";
853 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
854 const VectorType *PTy = CP->getType();
856 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
857 EmitGlobalConstant(CP->getOperand(I));
862 const Type *type = CV->getType();
863 printDataDirective(type);
864 EmitConstantValueOnly(CV);
869 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
870 // Target doesn't support this yet!
874 /// PrintSpecial - Print information related to the specified machine instr
875 /// that is independent of the operand, and may be independent of the instr
876 /// itself. This can be useful for portably encoding the comment character
877 /// or other bits of target-specific knowledge into the asmstrings. The
878 /// syntax used is ${:comment}. Targets can override this to add support
879 /// for their own strange codes.
880 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
881 if (!strcmp(Code, "private")) {
882 O << TAI->getPrivateGlobalPrefix();
883 } else if (!strcmp(Code, "comment")) {
884 O << TAI->getCommentString();
885 } else if (!strcmp(Code, "uid")) {
886 // Assign a unique ID to this machine instruction.
887 static const MachineInstr *LastMI = 0;
888 static const Function *F = 0;
889 static unsigned Counter = 0U-1;
891 // Comparing the address of MI isn't sufficient, because machineinstrs may
892 // be allocated to the same address across functions.
893 const Function *ThisF = MI->getParent()->getParent()->getFunction();
895 // If this is a new machine instruction, bump the counter.
896 if (LastMI != MI || F != ThisF) {
903 cerr << "Unknown special formatter '" << Code
904 << "' for machine instr: " << *MI;
910 /// printInlineAsm - This method formats and prints the specified machine
911 /// instruction that is an inline asm.
912 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
913 unsigned NumOperands = MI->getNumOperands();
915 // Count the number of register definitions.
916 unsigned NumDefs = 0;
917 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
919 assert(NumDefs != NumOperands-1 && "No asm string?");
921 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
923 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
924 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
926 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
927 if (AsmStr[0] == 0) {
928 O << "\n"; // Tab already printed, avoid double indenting next instr.
932 O << TAI->getInlineAsmStart() << "\n\t";
934 // The variant of the current asmprinter.
935 int AsmPrinterVariant = TAI->getAssemblerDialect();
937 int CurVariant = -1; // The number of the {.|.|.} region we are in.
938 const char *LastEmitted = AsmStr; // One past the last character emitted.
940 while (*LastEmitted) {
941 switch (*LastEmitted) {
943 // Not a special case, emit the string section literally.
944 const char *LiteralEnd = LastEmitted+1;
945 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
946 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
948 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
949 O.write(LastEmitted, LiteralEnd-LastEmitted);
950 LastEmitted = LiteralEnd;
954 ++LastEmitted; // Consume newline character.
955 O << "\n\t"; // Indent code with newline.
958 ++LastEmitted; // Consume '$' character.
962 switch (*LastEmitted) {
963 default: Done = false; break;
965 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
967 ++LastEmitted; // Consume second '$' character.
969 case '(': // $( -> same as GCC's { character.
970 ++LastEmitted; // Consume '(' character.
971 if (CurVariant != -1) {
972 cerr << "Nested variants found in inline asm string: '"
976 CurVariant = 0; // We're in the first variant now.
979 ++LastEmitted; // consume '|' character.
980 if (CurVariant == -1) {
981 cerr << "Found '|' character outside of variant in inline asm "
982 << "string: '" << AsmStr << "'\n";
985 ++CurVariant; // We're in the next variant.
987 case ')': // $) -> same as GCC's } char.
988 ++LastEmitted; // consume ')' character.
989 if (CurVariant == -1) {
990 cerr << "Found '}' character outside of variant in inline asm "
991 << "string: '" << AsmStr << "'\n";
999 bool HasCurlyBraces = false;
1000 if (*LastEmitted == '{') { // ${variable}
1001 ++LastEmitted; // Consume '{' character.
1002 HasCurlyBraces = true;
1005 const char *IDStart = LastEmitted;
1008 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1009 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1010 cerr << "Bad $ operand number in inline asm string: '"
1014 LastEmitted = IDEnd;
1016 char Modifier[2] = { 0, 0 };
1018 if (HasCurlyBraces) {
1019 // If we have curly braces, check for a modifier character. This
1020 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1021 if (*LastEmitted == ':') {
1022 ++LastEmitted; // Consume ':' character.
1023 if (*LastEmitted == 0) {
1024 cerr << "Bad ${:} expression in inline asm string: '"
1029 Modifier[0] = *LastEmitted;
1030 ++LastEmitted; // Consume modifier character.
1033 if (*LastEmitted != '}') {
1034 cerr << "Bad ${} expression in inline asm string: '"
1038 ++LastEmitted; // Consume '}' character.
1041 if ((unsigned)Val >= NumOperands-1) {
1042 cerr << "Invalid $ operand number in inline asm string: '"
1047 // Okay, we finally have a value number. Ask the target to print this
1049 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1054 // Scan to find the machine operand number for the operand.
1055 for (; Val; --Val) {
1056 if (OpNo >= MI->getNumOperands()) break;
1057 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1058 OpNo += (OpFlags >> 3) + 1;
1061 if (OpNo >= MI->getNumOperands()) {
1064 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1065 ++OpNo; // Skip over the ID number.
1067 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1068 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1069 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1070 Modifier[0] ? Modifier : 0);
1072 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1073 Modifier[0] ? Modifier : 0);
1077 cerr << "Invalid operand found in inline asm: '"
1087 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1090 /// printLabel - This method prints a local label used by debug and
1091 /// exception handling tables.
1092 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1094 << TAI->getPrivateGlobalPrefix()
1096 << MI->getOperand(0).getImmedValue()
1100 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1101 /// instruction, using the specified assembler variant. Targets should
1102 /// overried this to format as appropriate.
1103 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1104 unsigned AsmVariant, const char *ExtraCode) {
1105 // Target doesn't support this yet!
1109 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1110 unsigned AsmVariant,
1111 const char *ExtraCode) {
1112 // Target doesn't support this yet!
1116 /// printBasicBlockLabel - This method prints the label for the specified
1117 /// MachineBasicBlock
1118 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1120 bool printComment) const {
1121 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
1122 << MBB->getNumber();
1125 if (printComment && MBB->getBasicBlock())
1126 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
1129 /// printSetLabel - This method prints a set label for the specified
1130 /// MachineBasicBlock
1131 void AsmPrinter::printSetLabel(unsigned uid,
1132 const MachineBasicBlock *MBB) const {
1133 if (!TAI->getSetDirective())
1136 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1137 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1138 printBasicBlockLabel(MBB, false, false);
1139 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1140 << '_' << uid << '\n';
1143 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
1144 const MachineBasicBlock *MBB) const {
1145 if (!TAI->getSetDirective())
1148 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1149 << getFunctionNumber() << '_' << uid << '_' << uid2
1150 << "_set_" << MBB->getNumber() << ',';
1151 printBasicBlockLabel(MBB, false, false);
1152 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1153 << '_' << uid << '_' << uid2 << '\n';
1156 /// printDataDirective - This method prints the asm directive for the
1158 void AsmPrinter::printDataDirective(const Type *type) {
1159 const TargetData *TD = TM.getTargetData();
1160 switch (type->getTypeID()) {
1161 case Type::IntegerTyID: {
1162 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1164 O << TAI->getData8bitsDirective();
1165 else if (BitWidth <= 16)
1166 O << TAI->getData16bitsDirective();
1167 else if (BitWidth <= 32)
1168 O << TAI->getData32bitsDirective();
1169 else if (BitWidth <= 64) {
1170 assert(TAI->getData64bitsDirective() &&
1171 "Target cannot handle 64-bit constant exprs!");
1172 O << TAI->getData64bitsDirective();
1176 case Type::PointerTyID:
1177 if (TD->getPointerSize() == 8) {
1178 assert(TAI->getData64bitsDirective() &&
1179 "Target cannot handle 64-bit pointer exprs!");
1180 O << TAI->getData64bitsDirective();
1182 O << TAI->getData32bitsDirective();
1185 case Type::FloatTyID: case Type::DoubleTyID:
1186 assert (0 && "Should have already output floating point constant.");
1188 assert (0 && "Can't handle printing this type of thing");