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 char AsmPrinter::ID = 0;
36 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
37 const TargetAsmInfo *T)
38 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
41 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
42 return TAI->getTextSection();
46 /// SwitchToTextSection - Switch to the specified text section of the executable
47 /// if we are not already in it!
49 void AsmPrinter::SwitchToTextSection(const char *NewSection,
50 const GlobalValue *GV) {
52 if (GV && GV->hasSection())
53 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
57 // If we're already in this section, we're done.
58 if (CurrentSection == NS) return;
60 // Close the current section, if applicable.
61 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
62 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
66 if (!CurrentSection.empty())
67 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
70 /// SwitchToDataSection - Switch to the specified data section of the executable
71 /// if we are not already in it!
73 void AsmPrinter::SwitchToDataSection(const char *NewSection,
74 const GlobalValue *GV) {
76 if (GV && GV->hasSection())
77 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
81 // If we're already in this section, we're done.
82 if (CurrentSection == NS) return;
84 // Close the current section, if applicable.
85 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
86 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
90 if (!CurrentSection.empty())
91 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
95 bool AsmPrinter::doInitialization(Module &M) {
96 Mang = new Mangler(M, TAI->getGlobalPrefix());
98 if (!M.getModuleInlineAsm().empty())
99 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
100 << M.getModuleInlineAsm()
101 << "\n" << TAI->getCommentString()
102 << " End of file scope inline assembly\n";
104 SwitchToDataSection(""); // Reset back to no section.
106 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
107 MMI->AnalyzeModule(M);
113 bool AsmPrinter::doFinalization(Module &M) {
114 if (TAI->getWeakRefDirective()) {
115 if (!ExtWeakSymbols.empty())
116 SwitchToDataSection("");
118 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
119 e = ExtWeakSymbols.end(); i != e; ++i) {
120 const GlobalValue *GV = *i;
121 std::string Name = Mang->getValueName(GV);
122 O << TAI->getWeakRefDirective() << Name << "\n";
126 if (TAI->getSetDirective()) {
127 if (!M.alias_empty())
128 SwitchToTextSection(TAI->getTextSection());
131 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
133 std::string Name = Mang->getValueName(I);
136 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
137 Target = Mang->getValueName(GV);
139 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
140 O << "\t.globl\t" << Name << "\n";
141 else if (I->hasWeakLinkage())
142 O << TAI->getWeakRefDirective() << Name << "\n";
143 else if (!I->hasInternalLinkage())
144 assert(0 && "Invalid alias linkage");
146 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
148 // If the aliasee has external weak linkage it can be referenced only by
149 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
150 // weak reference in such case.
151 if (GV->hasExternalWeakLinkage())
152 if (TAI->getWeakRefDirective())
153 O << TAI->getWeakRefDirective() << Target << "\n";
155 O << "\t.globl\t" << Target << "\n";
159 delete Mang; Mang = 0;
164 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
165 assert(MF && "No machine function?");
166 return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
167 TAI->getGlobalPrefix());
170 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
171 // What's my mangled name?
172 CurrentFnName = Mang->getValueName(MF.getFunction());
173 IncrementFunctionNumber();
176 /// EmitConstantPool - Print to the current output stream assembly
177 /// representations of the constants in the constant pool MCP. This is
178 /// used to print out constants which have been "spilled to memory" by
179 /// the code generator.
181 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
182 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
183 if (CP.empty()) return;
185 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
186 // in special sections.
187 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
188 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
189 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
190 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
191 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
192 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
193 MachineConstantPoolEntry CPE = CP[i];
194 const Type *Ty = CPE.getType();
195 if (TAI->getFourByteConstantSection() &&
196 TM.getTargetData()->getTypeSize(Ty) == 4)
197 FourByteCPs.push_back(std::make_pair(CPE, i));
198 else if (TAI->getEightByteConstantSection() &&
199 TM.getTargetData()->getTypeSize(Ty) == 8)
200 EightByteCPs.push_back(std::make_pair(CPE, i));
201 else if (TAI->getSixteenByteConstantSection() &&
202 TM.getTargetData()->getTypeSize(Ty) == 16)
203 SixteenByteCPs.push_back(std::make_pair(CPE, i));
205 OtherCPs.push_back(std::make_pair(CPE, i));
208 unsigned Alignment = MCP->getConstantPoolAlignment();
209 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
210 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
211 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
213 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
216 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
217 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
218 if (CP.empty()) return;
220 SwitchToDataSection(Section);
221 EmitAlignment(Alignment);
222 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
223 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
224 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
225 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
226 if (CP[i].first.isMachineConstantPoolEntry())
227 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
229 EmitGlobalConstant(CP[i].first.Val.ConstVal);
231 const Type *Ty = CP[i].first.getType();
233 TM.getTargetData()->getTypeSize(Ty);
234 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
235 // Emit inter-object padding for alignment.
236 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
241 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
242 /// by the current function to the current output stream.
244 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
245 MachineFunction &MF) {
246 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
247 if (JT.empty()) return;
248 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
250 // Use JumpTableDirective otherwise honor the entry size from the jump table
252 const char *JTEntryDirective = TAI->getJumpTableDirective();
253 bool HadJTEntryDirective = JTEntryDirective != NULL;
254 if (!HadJTEntryDirective) {
255 JTEntryDirective = MJTI->getEntrySize() == 4 ?
256 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
259 // Pick the directive to use to print the jump table entries, and switch to
260 // the appropriate section.
261 TargetLowering *LoweringInfo = TM.getTargetLowering();
263 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
264 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
265 !JumpTableDataSection) {
266 // In PIC mode, we need to emit the jump table to the same section as the
267 // function body itself, otherwise the label differences won't make sense.
268 // We should also do if the section name is NULL.
269 const Function *F = MF.getFunction();
270 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
272 SwitchToDataSection(JumpTableDataSection);
275 EmitAlignment(Log2_32(MJTI->getAlignment()));
277 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
278 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
280 // If this jump table was deleted, ignore it.
281 if (JTBBs.empty()) continue;
283 // For PIC codegen, if possible we want to use the SetDirective to reduce
284 // the number of relocations the assembler will generate for the jump table.
285 // Set directives are all printed before the jump table itself.
286 std::set<MachineBasicBlock*> EmittedSets;
287 if (TAI->getSetDirective() && IsPic)
288 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
289 if (EmittedSets.insert(JTBBs[ii]).second)
290 printSetLabel(i, JTBBs[ii]);
292 // On some targets (e.g. darwin) we want to emit two consequtive labels
293 // before each jump table. The first label is never referenced, but tells
294 // the assembler and linker the extents of the jump table object. The
295 // second label is actually referenced by the code.
296 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
297 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
299 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
300 << '_' << i << ":\n";
302 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
303 O << JTEntryDirective << ' ';
304 // If we have emitted set directives for the jump table entries, print
305 // them rather than the entries themselves. If we're emitting PIC, then
306 // emit the table entries as differences between two text section labels.
307 // If we're emitting non-PIC code, then emit the entries as direct
308 // references to the target basic blocks.
309 if (!EmittedSets.empty()) {
310 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
311 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
313 printBasicBlockLabel(JTBBs[ii], false, false);
314 // If the arch uses custom Jump Table directives, don't calc relative to
316 if (!HadJTEntryDirective)
317 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
318 << getFunctionNumber() << '_' << i;
320 printBasicBlockLabel(JTBBs[ii], false, false);
327 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
328 /// special global used by LLVM. If so, emit it and return true, otherwise
329 /// do nothing and return false.
330 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
331 if (GV->getName() == "llvm.used") {
332 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
333 EmitLLVMUsedList(GV->getInitializer());
337 // Ignore debug and non-emitted data.
338 if (GV->getSection() == "llvm.metadata") return true;
340 if (!GV->hasAppendingLinkage()) return false;
342 assert(GV->hasInitializer() && "Not a special LLVM global!");
344 const TargetData *TD = TM.getTargetData();
345 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
346 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
347 SwitchToDataSection(TAI->getStaticCtorsSection());
348 EmitAlignment(Align, 0);
349 EmitXXStructorList(GV->getInitializer());
353 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
354 SwitchToDataSection(TAI->getStaticDtorsSection());
355 EmitAlignment(Align, 0);
356 EmitXXStructorList(GV->getInitializer());
363 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
364 /// global in the specified llvm.used list as being used with this directive.
365 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
366 const char *Directive = TAI->getUsedDirective();
368 // Should be an array of 'sbyte*'.
369 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
370 if (InitList == 0) return;
372 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
374 EmitConstantValueOnly(InitList->getOperand(i));
379 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
380 /// function pointers, ignoring the init priority.
381 void AsmPrinter::EmitXXStructorList(Constant *List) {
382 // Should be an array of '{ int, void ()* }' structs. The first value is the
383 // init priority, which we ignore.
384 if (!isa<ConstantArray>(List)) return;
385 ConstantArray *InitList = cast<ConstantArray>(List);
386 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
387 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
388 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
390 if (CS->getOperand(1)->isNullValue())
391 return; // Found a null terminator, exit printing.
392 // Emit the function pointer.
393 EmitGlobalConstant(CS->getOperand(1));
397 /// getGlobalLinkName - Returns the asm/link name of of the specified
398 /// global variable. Should be overridden by each target asm printer to
399 /// generate the appropriate value.
400 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
401 std::string LinkName;
403 if (isa<Function>(GV)) {
404 LinkName += TAI->getFunctionAddrPrefix();
405 LinkName += Mang->getValueName(GV);
406 LinkName += TAI->getFunctionAddrSuffix();
408 LinkName += TAI->getGlobalVarAddrPrefix();
409 LinkName += Mang->getValueName(GV);
410 LinkName += TAI->getGlobalVarAddrSuffix();
416 /// EmitExternalGlobal - Emit the external reference to a global variable.
417 /// Should be overridden if an indirect reference should be used.
418 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
419 O << getGlobalLinkName(GV);
424 //===----------------------------------------------------------------------===//
425 /// LEB 128 number encoding.
427 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
428 /// representing an unsigned leb128 value.
429 void AsmPrinter::PrintULEB128(unsigned Value) const {
431 unsigned Byte = Value & 0x7f;
433 if (Value) Byte |= 0x80;
434 O << "0x" << std::hex << Byte << std::dec;
435 if (Value) O << ", ";
439 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
441 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
445 Size += sizeof(int8_t);
450 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
451 /// representing a signed leb128 value.
452 void AsmPrinter::PrintSLEB128(int Value) const {
453 int Sign = Value >> (8 * sizeof(Value) - 1);
457 unsigned Byte = Value & 0x7f;
459 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
460 if (IsMore) Byte |= 0x80;
461 O << "0x" << std::hex << Byte << std::dec;
462 if (IsMore) O << ", ";
466 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
468 unsigned AsmPrinter::SizeSLEB128(int Value) {
470 int Sign = Value >> (8 * sizeof(Value) - 1);
474 unsigned Byte = Value & 0x7f;
476 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
477 Size += sizeof(int8_t);
482 //===--------------------------------------------------------------------===//
483 // Emission and print routines
486 /// PrintHex - Print a value as a hexidecimal value.
488 void AsmPrinter::PrintHex(int Value) const {
489 O << "0x" << std::hex << Value << std::dec;
492 /// EOL - Print a newline character to asm stream. If a comment is present
493 /// then it will be printed first. Comments should not contain '\n'.
494 void AsmPrinter::EOL() const {
497 void AsmPrinter::EOL(const std::string &Comment) const {
498 if (AsmVerbose && !Comment.empty()) {
500 << TAI->getCommentString()
507 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
508 /// unsigned leb128 value.
509 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
510 if (TAI->hasLEB128()) {
514 O << TAI->getData8bitsDirective();
519 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
520 /// signed leb128 value.
521 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
522 if (TAI->hasLEB128()) {
526 O << TAI->getData8bitsDirective();
531 /// EmitInt8 - Emit a byte directive and value.
533 void AsmPrinter::EmitInt8(int Value) const {
534 O << TAI->getData8bitsDirective();
535 PrintHex(Value & 0xFF);
538 /// EmitInt16 - Emit a short directive and value.
540 void AsmPrinter::EmitInt16(int Value) const {
541 O << TAI->getData16bitsDirective();
542 PrintHex(Value & 0xFFFF);
545 /// EmitInt32 - Emit a long directive and value.
547 void AsmPrinter::EmitInt32(int Value) const {
548 O << TAI->getData32bitsDirective();
552 /// EmitInt64 - Emit a long long directive and value.
554 void AsmPrinter::EmitInt64(uint64_t Value) const {
555 if (TAI->getData64bitsDirective()) {
556 O << TAI->getData64bitsDirective();
559 if (TM.getTargetData()->isBigEndian()) {
560 EmitInt32(unsigned(Value >> 32)); O << "\n";
561 EmitInt32(unsigned(Value));
563 EmitInt32(unsigned(Value)); O << "\n";
564 EmitInt32(unsigned(Value >> 32));
569 /// toOctal - Convert the low order bits of X into an octal digit.
571 static inline char toOctal(int X) {
575 /// printStringChar - Print a char, escaped if necessary.
577 static void printStringChar(std::ostream &O, unsigned char C) {
580 } else if (C == '\\') {
582 } else if (isprint(C)) {
586 case '\b': O << "\\b"; break;
587 case '\f': O << "\\f"; break;
588 case '\n': O << "\\n"; break;
589 case '\r': O << "\\r"; break;
590 case '\t': O << "\\t"; break;
593 O << toOctal(C >> 6);
594 O << toOctal(C >> 3);
595 O << toOctal(C >> 0);
601 /// EmitString - Emit a string with quotes and a null terminator.
602 /// Special characters are emitted properly.
603 /// \literal (Eg. '\t') \endliteral
604 void AsmPrinter::EmitString(const std::string &String) const {
605 const char* AscizDirective = TAI->getAscizDirective();
609 O << TAI->getAsciiDirective();
611 for (unsigned i = 0, N = String.size(); i < N; ++i) {
612 unsigned char C = String[i];
613 printStringChar(O, C);
622 //===----------------------------------------------------------------------===//
624 // EmitAlignment - Emit an alignment directive to the specified power of
625 // two boundary. For example, if you pass in 3 here, you will get an 8
626 // byte alignment. If a global value is specified, and if that global has
627 // an explicit alignment requested, it will unconditionally override the
628 // alignment request. However, if ForcedAlignBits is specified, this value
629 // has final say: the ultimate alignment will be the max of ForcedAlignBits
630 // and the alignment computed with NumBits and the global.
634 // if (GV && GV->hasalignment) Align = GV->getalignment();
635 // Align = std::max(Align, ForcedAlignBits);
637 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
638 unsigned ForcedAlignBits, bool UseFillExpr,
639 unsigned FillValue) const {
640 if (GV && GV->getAlignment())
641 NumBits = Log2_32(GV->getAlignment());
642 NumBits = std::max(NumBits, ForcedAlignBits);
644 if (NumBits == 0) return; // No need to emit alignment.
645 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
646 O << TAI->getAlignDirective() << NumBits;
647 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
652 /// EmitZeros - Emit a block of zeros.
654 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
656 if (TAI->getZeroDirective()) {
657 O << TAI->getZeroDirective() << NumZeros;
658 if (TAI->getZeroDirectiveSuffix())
659 O << TAI->getZeroDirectiveSuffix();
662 for (; NumZeros; --NumZeros)
663 O << TAI->getData8bitsDirective() << "0\n";
668 // Print out the specified constant, without a storage class. Only the
669 // constants valid in constant expressions can occur here.
670 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
671 if (CV->isNullValue() || isa<UndefValue>(CV))
673 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
674 O << CI->getZExtValue();
675 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
676 // This is a constant address for a global variable or function. Use the
677 // name of the variable or function as the address value, possibly
678 // decorating it with GlobalVarAddrPrefix/Suffix or
679 // FunctionAddrPrefix/Suffix (these all default to "" )
680 if (isa<Function>(GV)) {
681 O << TAI->getFunctionAddrPrefix()
682 << Mang->getValueName(GV)
683 << TAI->getFunctionAddrSuffix();
685 O << TAI->getGlobalVarAddrPrefix()
686 << Mang->getValueName(GV)
687 << TAI->getGlobalVarAddrSuffix();
689 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
690 const TargetData *TD = TM.getTargetData();
691 unsigned Opcode = CE->getOpcode();
693 case Instruction::GetElementPtr: {
694 // generate a symbolic expression for the byte address
695 const Constant *ptrVal = CE->getOperand(0);
696 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
697 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
701 EmitConstantValueOnly(ptrVal);
703 O << ") + " << Offset;
705 O << ") - " << -Offset;
707 EmitConstantValueOnly(ptrVal);
711 case Instruction::Trunc:
712 case Instruction::ZExt:
713 case Instruction::SExt:
714 case Instruction::FPTrunc:
715 case Instruction::FPExt:
716 case Instruction::UIToFP:
717 case Instruction::SIToFP:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
722 case Instruction::BitCast:
723 return EmitConstantValueOnly(CE->getOperand(0));
725 case Instruction::IntToPtr: {
726 // Handle casts to pointers by changing them into casts to the appropriate
727 // integer type. This promotes constant folding and simplifies this code.
728 Constant *Op = CE->getOperand(0);
729 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
730 return EmitConstantValueOnly(Op);
734 case Instruction::PtrToInt: {
735 // Support only foldable casts to/from pointers that can be eliminated by
736 // changing the pointer to the appropriately sized integer type.
737 Constant *Op = CE->getOperand(0);
738 const Type *Ty = CE->getType();
740 // We can emit the pointer value into this slot if the slot is an
741 // integer slot greater or equal to the size of the pointer.
742 if (Ty->isInteger() &&
743 TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
744 return EmitConstantValueOnly(Op);
746 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
747 EmitConstantValueOnly(Op);
750 case Instruction::Add:
751 case Instruction::Sub:
753 EmitConstantValueOnly(CE->getOperand(0));
754 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
755 EmitConstantValueOnly(CE->getOperand(1));
759 assert(0 && "Unsupported operator!");
762 assert(0 && "Unknown constant value!");
766 /// printAsCString - Print the specified array as a C compatible string, only if
767 /// the predicate isString is true.
769 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
771 assert(CVA->isString() && "Array is not string compatible!");
774 for (unsigned i = 0; i != LastElt; ++i) {
776 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
777 printStringChar(O, C);
782 /// EmitString - Emit a zero-byte-terminated string constant.
784 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
785 unsigned NumElts = CVA->getNumOperands();
786 if (TAI->getAscizDirective() && NumElts &&
787 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
788 O << TAI->getAscizDirective();
789 printAsCString(O, CVA, NumElts-1);
791 O << TAI->getAsciiDirective();
792 printAsCString(O, CVA, NumElts);
797 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
799 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
800 const TargetData *TD = TM.getTargetData();
802 if (CV->isNullValue() || isa<UndefValue>(CV)) {
803 EmitZeros(TD->getTypeSize(CV->getType()));
805 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
806 if (CVA->isString()) {
808 } else { // Not a string. Print the values in successive locations
809 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
810 EmitGlobalConstant(CVA->getOperand(i));
813 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
814 // Print the fields in successive locations. Pad to align if needed!
815 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
816 uint64_t sizeSoFar = 0;
817 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
818 const Constant* field = CVS->getOperand(i);
820 // Check if padding is needed and insert one or more 0s.
821 uint64_t fieldSize = TD->getTypeSize(field->getType());
822 uint64_t padSize = ((i == e-1? cvsLayout->getSizeInBytes()
823 : cvsLayout->getElementOffset(i+1))
824 - cvsLayout->getElementOffset(i)) - fieldSize;
825 sizeSoFar += fieldSize + padSize;
827 // Now print the actual field value
828 EmitGlobalConstant(field);
830 // Insert the field padding unless it's zero bytes...
833 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
834 "Layout of constant struct may be incorrect!");
836 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
837 // FP Constants are printed as integer constants to avoid losing
839 if (CFP->getType() == Type::DoubleTy) {
840 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
841 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
842 if (TAI->getData64bitsDirective())
843 O << TAI->getData64bitsDirective() << i << "\t"
844 << TAI->getCommentString() << " double value: " << Val << "\n";
845 else if (TD->isBigEndian()) {
846 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
847 << "\t" << TAI->getCommentString()
848 << " double most significant word " << Val << "\n";
849 O << TAI->getData32bitsDirective() << unsigned(i)
850 << "\t" << TAI->getCommentString()
851 << " double least significant word " << Val << "\n";
853 O << TAI->getData32bitsDirective() << unsigned(i)
854 << "\t" << TAI->getCommentString()
855 << " double least significant word " << Val << "\n";
856 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
857 << "\t" << TAI->getCommentString()
858 << " double most significant word " << Val << "\n";
861 } else if (CFP->getType() == Type::FloatTy) {
862 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
863 O << TAI->getData32bitsDirective()
864 << CFP->getValueAPF().convertToAPInt().getZExtValue()
865 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
867 } else if (CFP->getType() == Type::X86_FP80Ty) {
868 // all long double variants are printed as hex
869 const uint64_t *p = CFP->getValueAPF().convertToAPInt().getRawData();
870 if (TD->isBigEndian()) {
871 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
872 << "\t" << TAI->getCommentString()
873 << " long double most significant halfword\n";
874 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
875 << "\t" << TAI->getCommentString()
876 << " long double next halfword\n";
877 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
878 << "\t" << TAI->getCommentString()
879 << " long double next halfword\n";
880 O << TAI->getData16bitsDirective() << uint16_t(p[0])
881 << "\t" << TAI->getCommentString()
882 << " long double next halfword\n";
883 O << TAI->getData16bitsDirective() << uint16_t(p[1])
884 << "\t" << TAI->getCommentString()
885 << " long double least significant halfword\n";
887 O << TAI->getData16bitsDirective() << uint16_t(p[1])
888 << "\t" << TAI->getCommentString()
889 << " long double least significant halfword\n";
890 O << TAI->getData16bitsDirective() << uint16_t(p[0])
891 << "\t" << TAI->getCommentString()
892 << " long double next halfword\n";
893 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
894 << "\t" << TAI->getCommentString()
895 << " long double next halfword\n";
896 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
897 << "\t" << TAI->getCommentString()
898 << " long double next halfword\n";
899 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
900 << "\t" << TAI->getCommentString()
901 << " long double most significant halfword\n";
904 } else assert(0 && "Floating point constant type not handled");
905 } else if (CV->getType() == Type::Int64Ty) {
906 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
907 uint64_t Val = CI->getZExtValue();
909 if (TAI->getData64bitsDirective())
910 O << TAI->getData64bitsDirective() << Val << "\n";
911 else if (TD->isBigEndian()) {
912 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
913 << "\t" << TAI->getCommentString()
914 << " Double-word most significant word " << Val << "\n";
915 O << TAI->getData32bitsDirective() << unsigned(Val)
916 << "\t" << TAI->getCommentString()
917 << " Double-word least significant word " << Val << "\n";
919 O << TAI->getData32bitsDirective() << unsigned(Val)
920 << "\t" << TAI->getCommentString()
921 << " Double-word least significant word " << Val << "\n";
922 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
923 << "\t" << TAI->getCommentString()
924 << " Double-word most significant word " << Val << "\n";
928 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
929 const VectorType *PTy = CP->getType();
931 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
932 EmitGlobalConstant(CP->getOperand(I));
937 const Type *type = CV->getType();
938 printDataDirective(type);
939 EmitConstantValueOnly(CV);
944 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
945 // Target doesn't support this yet!
949 /// PrintSpecial - Print information related to the specified machine instr
950 /// that is independent of the operand, and may be independent of the instr
951 /// itself. This can be useful for portably encoding the comment character
952 /// or other bits of target-specific knowledge into the asmstrings. The
953 /// syntax used is ${:comment}. Targets can override this to add support
954 /// for their own strange codes.
955 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
956 if (!strcmp(Code, "private")) {
957 O << TAI->getPrivateGlobalPrefix();
958 } else if (!strcmp(Code, "comment")) {
959 O << TAI->getCommentString();
960 } else if (!strcmp(Code, "uid")) {
961 // Assign a unique ID to this machine instruction.
962 static const MachineInstr *LastMI = 0;
963 static const Function *F = 0;
964 static unsigned Counter = 0U-1;
966 // Comparing the address of MI isn't sufficient, because machineinstrs may
967 // be allocated to the same address across functions.
968 const Function *ThisF = MI->getParent()->getParent()->getFunction();
970 // If this is a new machine instruction, bump the counter.
971 if (LastMI != MI || F != ThisF) {
978 cerr << "Unknown special formatter '" << Code
979 << "' for machine instr: " << *MI;
985 /// printInlineAsm - This method formats and prints the specified machine
986 /// instruction that is an inline asm.
987 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
988 unsigned NumOperands = MI->getNumOperands();
990 // Count the number of register definitions.
991 unsigned NumDefs = 0;
992 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
994 assert(NumDefs != NumOperands-1 && "No asm string?");
996 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
998 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
999 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1001 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1002 if (AsmStr[0] == 0) {
1003 O << "\n"; // Tab already printed, avoid double indenting next instr.
1007 O << TAI->getInlineAsmStart() << "\n\t";
1009 // The variant of the current asmprinter.
1010 int AsmPrinterVariant = TAI->getAssemblerDialect();
1012 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1013 const char *LastEmitted = AsmStr; // One past the last character emitted.
1015 while (*LastEmitted) {
1016 switch (*LastEmitted) {
1018 // Not a special case, emit the string section literally.
1019 const char *LiteralEnd = LastEmitted+1;
1020 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1021 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1023 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1024 O.write(LastEmitted, LiteralEnd-LastEmitted);
1025 LastEmitted = LiteralEnd;
1029 ++LastEmitted; // Consume newline character.
1030 O << "\n"; // Indent code with newline.
1033 ++LastEmitted; // Consume '$' character.
1037 switch (*LastEmitted) {
1038 default: Done = false; break;
1039 case '$': // $$ -> $
1040 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1042 ++LastEmitted; // Consume second '$' character.
1044 case '(': // $( -> same as GCC's { character.
1045 ++LastEmitted; // Consume '(' character.
1046 if (CurVariant != -1) {
1047 cerr << "Nested variants found in inline asm string: '"
1051 CurVariant = 0; // We're in the first variant now.
1054 ++LastEmitted; // consume '|' character.
1055 if (CurVariant == -1) {
1056 cerr << "Found '|' character outside of variant in inline asm "
1057 << "string: '" << AsmStr << "'\n";
1060 ++CurVariant; // We're in the next variant.
1062 case ')': // $) -> same as GCC's } char.
1063 ++LastEmitted; // consume ')' character.
1064 if (CurVariant == -1) {
1065 cerr << "Found '}' character outside of variant in inline asm "
1066 << "string: '" << AsmStr << "'\n";
1074 bool HasCurlyBraces = false;
1075 if (*LastEmitted == '{') { // ${variable}
1076 ++LastEmitted; // Consume '{' character.
1077 HasCurlyBraces = true;
1080 const char *IDStart = LastEmitted;
1083 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1084 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1085 cerr << "Bad $ operand number in inline asm string: '"
1089 LastEmitted = IDEnd;
1091 char Modifier[2] = { 0, 0 };
1093 if (HasCurlyBraces) {
1094 // If we have curly braces, check for a modifier character. This
1095 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1096 if (*LastEmitted == ':') {
1097 ++LastEmitted; // Consume ':' character.
1098 if (*LastEmitted == 0) {
1099 cerr << "Bad ${:} expression in inline asm string: '"
1104 Modifier[0] = *LastEmitted;
1105 ++LastEmitted; // Consume modifier character.
1108 if (*LastEmitted != '}') {
1109 cerr << "Bad ${} expression in inline asm string: '"
1113 ++LastEmitted; // Consume '}' character.
1116 if ((unsigned)Val >= NumOperands-1) {
1117 cerr << "Invalid $ operand number in inline asm string: '"
1122 // Okay, we finally have a value number. Ask the target to print this
1124 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1129 // Scan to find the machine operand number for the operand.
1130 for (; Val; --Val) {
1131 if (OpNo >= MI->getNumOperands()) break;
1132 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1133 OpNo += (OpFlags >> 3) + 1;
1136 if (OpNo >= MI->getNumOperands()) {
1139 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1140 ++OpNo; // Skip over the ID number.
1142 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1143 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1144 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1145 Modifier[0] ? Modifier : 0);
1147 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1148 Modifier[0] ? Modifier : 0);
1152 cerr << "Invalid operand found in inline asm: '"
1162 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1165 /// printLabel - This method prints a local label used by debug and
1166 /// exception handling tables.
1167 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1169 << TAI->getPrivateGlobalPrefix()
1171 << MI->getOperand(0).getImmedValue()
1175 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1176 /// instruction, using the specified assembler variant. Targets should
1177 /// overried this to format as appropriate.
1178 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1179 unsigned AsmVariant, const char *ExtraCode) {
1180 // Target doesn't support this yet!
1184 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1185 unsigned AsmVariant,
1186 const char *ExtraCode) {
1187 // Target doesn't support this yet!
1191 /// printBasicBlockLabel - This method prints the label for the specified
1192 /// MachineBasicBlock
1193 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1195 bool printComment) const {
1196 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
1197 << MBB->getNumber();
1200 if (printComment && MBB->getBasicBlock())
1201 O << '\t' << TAI->getCommentString() << ' '
1202 << MBB->getBasicBlock()->getName();
1205 /// printSetLabel - This method prints a set label for the specified
1206 /// MachineBasicBlock
1207 void AsmPrinter::printSetLabel(unsigned uid,
1208 const MachineBasicBlock *MBB) const {
1209 if (!TAI->getSetDirective())
1212 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1213 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1214 printBasicBlockLabel(MBB, false, false);
1215 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1216 << '_' << uid << '\n';
1219 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
1220 const MachineBasicBlock *MBB) const {
1221 if (!TAI->getSetDirective())
1224 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1225 << getFunctionNumber() << '_' << uid << '_' << uid2
1226 << "_set_" << MBB->getNumber() << ',';
1227 printBasicBlockLabel(MBB, false, false);
1228 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1229 << '_' << uid << '_' << uid2 << '\n';
1232 /// printDataDirective - This method prints the asm directive for the
1234 void AsmPrinter::printDataDirective(const Type *type) {
1235 const TargetData *TD = TM.getTargetData();
1236 switch (type->getTypeID()) {
1237 case Type::IntegerTyID: {
1238 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1240 O << TAI->getData8bitsDirective();
1241 else if (BitWidth <= 16)
1242 O << TAI->getData16bitsDirective();
1243 else if (BitWidth <= 32)
1244 O << TAI->getData32bitsDirective();
1245 else if (BitWidth <= 64) {
1246 assert(TAI->getData64bitsDirective() &&
1247 "Target cannot handle 64-bit constant exprs!");
1248 O << TAI->getData64bitsDirective();
1252 case Type::PointerTyID:
1253 if (TD->getPointerSize() == 8) {
1254 assert(TAI->getData64bitsDirective() &&
1255 "Target cannot handle 64-bit pointer exprs!");
1256 O << TAI->getData64bitsDirective();
1258 O << TAI->getData32bitsDirective();
1261 case Type::FloatTyID: case Type::DoubleTyID:
1262 assert (0 && "Should have already output floating point constant.");
1264 assert (0 && "Can't handle printing this type of thing");