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"
29 #include "llvm/ADT/SmallPtrSet.h"
34 AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
36 char AsmPrinter::ID = 0;
37 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
38 const TargetAsmInfo *T)
39 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
42 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
43 return TAI->getTextSection();
47 /// SwitchToTextSection - Switch to the specified text section of the executable
48 /// if we are not already in it!
50 void AsmPrinter::SwitchToTextSection(const char *NewSection,
51 const GlobalValue *GV) {
53 if (GV && GV->hasSection())
54 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
58 // If we're already in this section, we're done.
59 if (CurrentSection == NS) return;
61 // Close the current section, if applicable.
62 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
63 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
67 if (!CurrentSection.empty())
68 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
71 /// SwitchToDataSection - Switch to the specified data section of the executable
72 /// if we are not already in it!
74 void AsmPrinter::SwitchToDataSection(const char *NewSection,
75 const GlobalValue *GV) {
77 if (GV && GV->hasSection())
78 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
82 // If we're already in this section, we're done.
83 if (CurrentSection == NS) return;
85 // Close the current section, if applicable.
86 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
87 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
91 if (!CurrentSection.empty())
92 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
96 bool AsmPrinter::doInitialization(Module &M) {
97 Mang = new Mangler(M, TAI->getGlobalPrefix());
99 if (!M.getModuleInlineAsm().empty())
100 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
101 << M.getModuleInlineAsm()
102 << "\n" << TAI->getCommentString()
103 << " End of file scope inline assembly\n";
105 SwitchToDataSection(""); // Reset back to no section.
107 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
108 MMI->AnalyzeModule(M);
114 bool AsmPrinter::doFinalization(Module &M) {
115 if (TAI->getWeakRefDirective()) {
116 if (!ExtWeakSymbols.empty())
117 SwitchToDataSection("");
119 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
120 e = ExtWeakSymbols.end(); i != e; ++i) {
121 const GlobalValue *GV = *i;
122 std::string Name = Mang->getValueName(GV);
123 O << TAI->getWeakRefDirective() << Name << "\n";
127 if (TAI->getSetDirective()) {
128 if (!M.alias_empty())
129 SwitchToTextSection(TAI->getTextSection());
132 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
134 std::string Name = Mang->getValueName(I);
137 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
138 Target = Mang->getValueName(GV);
140 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
141 O << "\t.globl\t" << Name << "\n";
142 else if (I->hasWeakLinkage())
143 O << TAI->getWeakRefDirective() << Name << "\n";
144 else if (!I->hasInternalLinkage())
145 assert(0 && "Invalid alias linkage");
147 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
149 // If the aliasee has external weak linkage it can be referenced only by
150 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
151 // weak reference in such case.
152 if (GV->hasExternalWeakLinkage())
153 if (TAI->getWeakRefDirective())
154 O << TAI->getWeakRefDirective() << Target << "\n";
156 O << "\t.globl\t" << Target << "\n";
160 delete Mang; Mang = 0;
164 std::string 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()->getABITypeSize(Ty) == 4)
197 FourByteCPs.push_back(std::make_pair(CPE, i));
198 else if (TAI->getEightByteConstantSection() &&
199 TM.getTargetData()->getABITypeSize(Ty) == 8)
200 EightByteCPs.push_back(std::make_pair(CPE, i));
201 else if (TAI->getSixteenByteConstantSection() &&
202 TM.getTargetData()->getABITypeSize(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()->getABITypeSize(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;
249 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
251 // Pick the directive to use to print the jump table entries, and switch to
252 // the appropriate section.
253 TargetLowering *LoweringInfo = TM.getTargetLowering();
255 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
256 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
257 !JumpTableDataSection) {
258 // In PIC mode, we need to emit the jump table to the same section as the
259 // function body itself, otherwise the label differences won't make sense.
260 // We should also do if the section name is NULL.
261 const Function *F = MF.getFunction();
262 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
264 SwitchToDataSection(JumpTableDataSection);
267 EmitAlignment(Log2_32(MJTI->getAlignment()));
269 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
270 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
272 // If this jump table was deleted, ignore it.
273 if (JTBBs.empty()) continue;
275 // For PIC codegen, if possible we want to use the SetDirective to reduce
276 // the number of relocations the assembler will generate for the jump table.
277 // Set directives are all printed before the jump table itself.
278 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
279 if (TAI->getSetDirective() && IsPic)
280 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
281 if (EmittedSets.insert(JTBBs[ii]))
282 printPICJumpTableSetLabel(i, JTBBs[ii]);
284 // On some targets (e.g. darwin) we want to emit two consequtive labels
285 // before each jump table. The first label is never referenced, but tells
286 // the assembler and linker the extents of the jump table object. The
287 // second label is actually referenced by the code.
288 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
289 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
291 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
292 << '_' << i << ":\n";
294 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
295 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
301 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
302 const MachineBasicBlock *MBB,
303 unsigned uid) const {
304 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
306 // Use JumpTableDirective otherwise honor the entry size from the jump table
308 const char *JTEntryDirective = TAI->getJumpTableDirective();
309 bool HadJTEntryDirective = JTEntryDirective != NULL;
310 if (!HadJTEntryDirective) {
311 JTEntryDirective = MJTI->getEntrySize() == 4 ?
312 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
315 O << JTEntryDirective << ' ';
317 // If we have emitted set directives for the jump table entries, print
318 // them rather than the entries themselves. If we're emitting PIC, then
319 // emit the table entries as differences between two text section labels.
320 // If we're emitting non-PIC code, then emit the entries as direct
321 // references to the target basic blocks.
323 if (TAI->getSetDirective()) {
324 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
325 << '_' << uid << "_set_" << MBB->getNumber();
327 printBasicBlockLabel(MBB, false, false);
328 // If the arch uses custom Jump Table directives, don't calc relative to
330 if (!HadJTEntryDirective)
331 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
332 << getFunctionNumber() << '_' << uid;
335 printBasicBlockLabel(MBB, false, false);
340 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
341 /// special global used by LLVM. If so, emit it and return true, otherwise
342 /// do nothing and return false.
343 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
344 if (GV->getName() == "llvm.used") {
345 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
346 EmitLLVMUsedList(GV->getInitializer());
350 // Ignore debug and non-emitted data.
351 if (GV->getSection() == "llvm.metadata") return true;
353 if (!GV->hasAppendingLinkage()) return false;
355 assert(GV->hasInitializer() && "Not a special LLVM global!");
357 const TargetData *TD = TM.getTargetData();
358 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
359 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
360 SwitchToDataSection(TAI->getStaticCtorsSection());
361 EmitAlignment(Align, 0);
362 EmitXXStructorList(GV->getInitializer());
366 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
367 SwitchToDataSection(TAI->getStaticDtorsSection());
368 EmitAlignment(Align, 0);
369 EmitXXStructorList(GV->getInitializer());
376 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
377 /// global in the specified llvm.used list as being used with this directive.
378 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
379 const char *Directive = TAI->getUsedDirective();
381 // Should be an array of 'sbyte*'.
382 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
383 if (InitList == 0) return;
385 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
387 EmitConstantValueOnly(InitList->getOperand(i));
392 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
393 /// function pointers, ignoring the init priority.
394 void AsmPrinter::EmitXXStructorList(Constant *List) {
395 // Should be an array of '{ int, void ()* }' structs. The first value is the
396 // init priority, which we ignore.
397 if (!isa<ConstantArray>(List)) return;
398 ConstantArray *InitList = cast<ConstantArray>(List);
399 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
400 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
401 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
403 if (CS->getOperand(1)->isNullValue())
404 return; // Found a null terminator, exit printing.
405 // Emit the function pointer.
406 EmitGlobalConstant(CS->getOperand(1));
410 /// getGlobalLinkName - Returns the asm/link name of of the specified
411 /// global variable. Should be overridden by each target asm printer to
412 /// generate the appropriate value.
413 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
414 std::string LinkName;
416 if (isa<Function>(GV)) {
417 LinkName += TAI->getFunctionAddrPrefix();
418 LinkName += Mang->getValueName(GV);
419 LinkName += TAI->getFunctionAddrSuffix();
421 LinkName += TAI->getGlobalVarAddrPrefix();
422 LinkName += Mang->getValueName(GV);
423 LinkName += TAI->getGlobalVarAddrSuffix();
429 /// EmitExternalGlobal - Emit the external reference to a global variable.
430 /// Should be overridden if an indirect reference should be used.
431 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
432 O << getGlobalLinkName(GV);
437 //===----------------------------------------------------------------------===//
438 /// LEB 128 number encoding.
440 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
441 /// representing an unsigned leb128 value.
442 void AsmPrinter::PrintULEB128(unsigned Value) const {
444 unsigned Byte = Value & 0x7f;
446 if (Value) Byte |= 0x80;
447 O << "0x" << std::hex << Byte << std::dec;
448 if (Value) O << ", ";
452 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
454 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
458 Size += sizeof(int8_t);
463 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
464 /// representing a signed leb128 value.
465 void AsmPrinter::PrintSLEB128(int Value) const {
466 int Sign = Value >> (8 * sizeof(Value) - 1);
470 unsigned Byte = Value & 0x7f;
472 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
473 if (IsMore) Byte |= 0x80;
474 O << "0x" << std::hex << Byte << std::dec;
475 if (IsMore) O << ", ";
479 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
481 unsigned AsmPrinter::SizeSLEB128(int Value) {
483 int Sign = Value >> (8 * sizeof(Value) - 1);
487 unsigned Byte = Value & 0x7f;
489 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
490 Size += sizeof(int8_t);
495 //===--------------------------------------------------------------------===//
496 // Emission and print routines
499 /// PrintHex - Print a value as a hexidecimal value.
501 void AsmPrinter::PrintHex(int Value) const {
502 O << "0x" << std::hex << Value << std::dec;
505 /// EOL - Print a newline character to asm stream. If a comment is present
506 /// then it will be printed first. Comments should not contain '\n'.
507 void AsmPrinter::EOL() const {
510 void AsmPrinter::EOL(const std::string &Comment) const {
511 if (AsmVerbose && !Comment.empty()) {
513 << TAI->getCommentString()
520 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
521 /// unsigned leb128 value.
522 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
523 if (TAI->hasLEB128()) {
527 O << TAI->getData8bitsDirective();
532 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
533 /// signed leb128 value.
534 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
535 if (TAI->hasLEB128()) {
539 O << TAI->getData8bitsDirective();
544 /// EmitInt8 - Emit a byte directive and value.
546 void AsmPrinter::EmitInt8(int Value) const {
547 O << TAI->getData8bitsDirective();
548 PrintHex(Value & 0xFF);
551 /// EmitInt16 - Emit a short directive and value.
553 void AsmPrinter::EmitInt16(int Value) const {
554 O << TAI->getData16bitsDirective();
555 PrintHex(Value & 0xFFFF);
558 /// EmitInt32 - Emit a long directive and value.
560 void AsmPrinter::EmitInt32(int Value) const {
561 O << TAI->getData32bitsDirective();
565 /// EmitInt64 - Emit a long long directive and value.
567 void AsmPrinter::EmitInt64(uint64_t Value) const {
568 if (TAI->getData64bitsDirective()) {
569 O << TAI->getData64bitsDirective();
572 if (TM.getTargetData()->isBigEndian()) {
573 EmitInt32(unsigned(Value >> 32)); O << "\n";
574 EmitInt32(unsigned(Value));
576 EmitInt32(unsigned(Value)); O << "\n";
577 EmitInt32(unsigned(Value >> 32));
582 /// toOctal - Convert the low order bits of X into an octal digit.
584 static inline char toOctal(int X) {
588 /// printStringChar - Print a char, escaped if necessary.
590 static void printStringChar(std::ostream &O, unsigned char C) {
593 } else if (C == '\\') {
595 } else if (isprint(C)) {
599 case '\b': O << "\\b"; break;
600 case '\f': O << "\\f"; break;
601 case '\n': O << "\\n"; break;
602 case '\r': O << "\\r"; break;
603 case '\t': O << "\\t"; break;
606 O << toOctal(C >> 6);
607 O << toOctal(C >> 3);
608 O << toOctal(C >> 0);
614 /// EmitString - Emit a string with quotes and a null terminator.
615 /// Special characters are emitted properly.
616 /// \literal (Eg. '\t') \endliteral
617 void AsmPrinter::EmitString(const std::string &String) const {
618 const char* AscizDirective = TAI->getAscizDirective();
622 O << TAI->getAsciiDirective();
624 for (unsigned i = 0, N = String.size(); i < N; ++i) {
625 unsigned char C = String[i];
626 printStringChar(O, C);
635 /// EmitFile - Emit a .file directive.
636 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
637 O << "\t.file\t" << Number << " \"";
638 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
639 unsigned char C = Name[i];
640 printStringChar(O, C);
646 //===----------------------------------------------------------------------===//
648 // EmitAlignment - Emit an alignment directive to the specified power of
649 // two boundary. For example, if you pass in 3 here, you will get an 8
650 // byte alignment. If a global value is specified, and if that global has
651 // an explicit alignment requested, it will unconditionally override the
652 // alignment request. However, if ForcedAlignBits is specified, this value
653 // has final say: the ultimate alignment will be the max of ForcedAlignBits
654 // and the alignment computed with NumBits and the global.
658 // if (GV && GV->hasalignment) Align = GV->getalignment();
659 // Align = std::max(Align, ForcedAlignBits);
661 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
662 unsigned ForcedAlignBits, bool UseFillExpr,
663 unsigned FillValue) const {
664 if (GV && GV->getAlignment())
665 NumBits = Log2_32(GV->getAlignment());
666 NumBits = std::max(NumBits, ForcedAlignBits);
668 if (NumBits == 0) return; // No need to emit alignment.
669 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
670 O << TAI->getAlignDirective() << NumBits;
671 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
676 /// EmitZeros - Emit a block of zeros.
678 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
680 if (TAI->getZeroDirective()) {
681 O << TAI->getZeroDirective() << NumZeros;
682 if (TAI->getZeroDirectiveSuffix())
683 O << TAI->getZeroDirectiveSuffix();
686 for (; NumZeros; --NumZeros)
687 O << TAI->getData8bitsDirective() << "0\n";
692 // Print out the specified constant, without a storage class. Only the
693 // constants valid in constant expressions can occur here.
694 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
695 if (CV->isNullValue() || isa<UndefValue>(CV))
697 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
698 O << CI->getZExtValue();
699 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
700 // This is a constant address for a global variable or function. Use the
701 // name of the variable or function as the address value, possibly
702 // decorating it with GlobalVarAddrPrefix/Suffix or
703 // FunctionAddrPrefix/Suffix (these all default to "" )
704 if (isa<Function>(GV)) {
705 O << TAI->getFunctionAddrPrefix()
706 << Mang->getValueName(GV)
707 << TAI->getFunctionAddrSuffix();
709 O << TAI->getGlobalVarAddrPrefix()
710 << Mang->getValueName(GV)
711 << TAI->getGlobalVarAddrSuffix();
713 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
714 const TargetData *TD = TM.getTargetData();
715 unsigned Opcode = CE->getOpcode();
717 case Instruction::GetElementPtr: {
718 // generate a symbolic expression for the byte address
719 const Constant *ptrVal = CE->getOperand(0);
720 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
721 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
725 EmitConstantValueOnly(ptrVal);
727 O << ") + " << Offset;
729 O << ") - " << -Offset;
731 EmitConstantValueOnly(ptrVal);
735 case Instruction::Trunc:
736 case Instruction::ZExt:
737 case Instruction::SExt:
738 case Instruction::FPTrunc:
739 case Instruction::FPExt:
740 case Instruction::UIToFP:
741 case Instruction::SIToFP:
742 case Instruction::FPToUI:
743 case Instruction::FPToSI:
744 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
746 case Instruction::BitCast:
747 return EmitConstantValueOnly(CE->getOperand(0));
749 case Instruction::IntToPtr: {
750 // Handle casts to pointers by changing them into casts to the appropriate
751 // integer type. This promotes constant folding and simplifies this code.
752 Constant *Op = CE->getOperand(0);
753 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
754 return EmitConstantValueOnly(Op);
758 case Instruction::PtrToInt: {
759 // Support only foldable casts to/from pointers that can be eliminated by
760 // changing the pointer to the appropriately sized integer type.
761 Constant *Op = CE->getOperand(0);
762 const Type *Ty = CE->getType();
764 // We can emit the pointer value into this slot if the slot is an
765 // integer slot greater or equal to the size of the pointer.
766 if (Ty->isInteger() &&
767 TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
768 return EmitConstantValueOnly(Op);
770 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
771 EmitConstantValueOnly(Op);
774 case Instruction::Add:
775 case Instruction::Sub:
777 EmitConstantValueOnly(CE->getOperand(0));
778 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
779 EmitConstantValueOnly(CE->getOperand(1));
783 assert(0 && "Unsupported operator!");
786 assert(0 && "Unknown constant value!");
790 /// printAsCString - Print the specified array as a C compatible string, only if
791 /// the predicate isString is true.
793 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
795 assert(CVA->isString() && "Array is not string compatible!");
798 for (unsigned i = 0; i != LastElt; ++i) {
800 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
801 printStringChar(O, C);
806 /// EmitString - Emit a zero-byte-terminated string constant.
808 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
809 unsigned NumElts = CVA->getNumOperands();
810 if (TAI->getAscizDirective() && NumElts &&
811 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
812 O << TAI->getAscizDirective();
813 printAsCString(O, CVA, NumElts-1);
815 O << TAI->getAsciiDirective();
816 printAsCString(O, CVA, NumElts);
821 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
822 /// If Packed is false, pad to the ABI size.
823 void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
824 const TargetData *TD = TM.getTargetData();
825 unsigned Size = Packed ?
826 TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
828 if (CV->isNullValue() || isa<UndefValue>(CV)) {
831 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
832 if (CVA->isString()) {
834 } else { // Not a string. Print the values in successive locations
835 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
836 EmitGlobalConstant(CVA->getOperand(i), false);
839 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
840 // Print the fields in successive locations. Pad to align if needed!
841 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
842 uint64_t sizeSoFar = 0;
843 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
844 const Constant* field = CVS->getOperand(i);
846 // Check if padding is needed and insert one or more 0s.
847 uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
848 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
849 - cvsLayout->getElementOffset(i)) - fieldSize;
850 sizeSoFar += fieldSize + padSize;
852 // Now print the actual field value without ABI size padding.
853 EmitGlobalConstant(field, true);
855 // Insert padding - this may include padding to increase the size of the
856 // current field up to the ABI size (if the struct is not packed) as well
857 // as padding to ensure that the next field starts at the right offset.
860 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
861 "Layout of constant struct may be incorrect!");
863 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
864 // FP Constants are printed as integer constants to avoid losing
866 if (CFP->getType() == Type::DoubleTy) {
867 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
868 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
869 if (TAI->getData64bitsDirective())
870 O << TAI->getData64bitsDirective() << i << "\t"
871 << TAI->getCommentString() << " double value: " << Val << "\n";
872 else if (TD->isBigEndian()) {
873 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
874 << "\t" << TAI->getCommentString()
875 << " double most significant word " << Val << "\n";
876 O << TAI->getData32bitsDirective() << unsigned(i)
877 << "\t" << TAI->getCommentString()
878 << " double least significant word " << Val << "\n";
880 O << TAI->getData32bitsDirective() << unsigned(i)
881 << "\t" << TAI->getCommentString()
882 << " double least significant word " << Val << "\n";
883 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
884 << "\t" << TAI->getCommentString()
885 << " double most significant word " << Val << "\n";
888 } else if (CFP->getType() == Type::FloatTy) {
889 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
890 O << TAI->getData32bitsDirective()
891 << CFP->getValueAPF().convertToAPInt().getZExtValue()
892 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
894 } else if (CFP->getType() == Type::X86_FP80Ty) {
895 // all long double variants are printed as hex
896 // api needed to prevent premature destruction
897 APInt api = CFP->getValueAPF().convertToAPInt();
898 const uint64_t *p = api.getRawData();
899 if (TD->isBigEndian()) {
900 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
901 << "\t" << TAI->getCommentString()
902 << " long double most significant halfword\n";
903 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
904 << "\t" << TAI->getCommentString()
905 << " long double next halfword\n";
906 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
907 << "\t" << TAI->getCommentString()
908 << " long double next halfword\n";
909 O << TAI->getData16bitsDirective() << uint16_t(p[0])
910 << "\t" << TAI->getCommentString()
911 << " long double next halfword\n";
912 O << TAI->getData16bitsDirective() << uint16_t(p[1])
913 << "\t" << TAI->getCommentString()
914 << " long double least significant halfword\n";
916 O << TAI->getData16bitsDirective() << uint16_t(p[1])
917 << "\t" << TAI->getCommentString()
918 << " long double least significant halfword\n";
919 O << TAI->getData16bitsDirective() << uint16_t(p[0])
920 << "\t" << TAI->getCommentString()
921 << " long double next halfword\n";
922 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
923 << "\t" << TAI->getCommentString()
924 << " long double next halfword\n";
925 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
926 << "\t" << TAI->getCommentString()
927 << " long double next halfword\n";
928 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
929 << "\t" << TAI->getCommentString()
930 << " long double most significant halfword\n";
932 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
934 } else if (CFP->getType() == Type::PPC_FP128Ty) {
935 // all long double variants are printed as hex
936 // api needed to prevent premature destruction
937 APInt api = CFP->getValueAPF().convertToAPInt();
938 const uint64_t *p = api.getRawData();
939 if (TD->isBigEndian()) {
940 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
941 << "\t" << TAI->getCommentString()
942 << " long double most significant word\n";
943 O << TAI->getData32bitsDirective() << uint32_t(p[0])
944 << "\t" << TAI->getCommentString()
945 << " long double next word\n";
946 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
947 << "\t" << TAI->getCommentString()
948 << " long double next word\n";
949 O << TAI->getData32bitsDirective() << uint32_t(p[1])
950 << "\t" << TAI->getCommentString()
951 << " long double least significant word\n";
953 O << TAI->getData32bitsDirective() << uint32_t(p[1])
954 << "\t" << TAI->getCommentString()
955 << " long double least significant word\n";
956 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
957 << "\t" << TAI->getCommentString()
958 << " long double next word\n";
959 O << TAI->getData32bitsDirective() << uint32_t(p[0])
960 << "\t" << TAI->getCommentString()
961 << " long double next word\n";
962 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
963 << "\t" << TAI->getCommentString()
964 << " long double most significant word\n";
967 } else assert(0 && "Floating point constant type not handled");
968 } else if (CV->getType() == Type::Int64Ty) {
969 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
970 uint64_t Val = CI->getZExtValue();
972 if (TAI->getData64bitsDirective())
973 O << TAI->getData64bitsDirective() << Val << "\n";
974 else if (TD->isBigEndian()) {
975 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
976 << "\t" << TAI->getCommentString()
977 << " Double-word most significant word " << Val << "\n";
978 O << TAI->getData32bitsDirective() << unsigned(Val)
979 << "\t" << TAI->getCommentString()
980 << " Double-word least significant word " << Val << "\n";
982 O << TAI->getData32bitsDirective() << unsigned(Val)
983 << "\t" << TAI->getCommentString()
984 << " Double-word least significant word " << Val << "\n";
985 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
986 << "\t" << TAI->getCommentString()
987 << " Double-word most significant word " << Val << "\n";
991 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
992 const VectorType *PTy = CP->getType();
994 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
995 EmitGlobalConstant(CP->getOperand(I), false);
1000 const Type *type = CV->getType();
1001 printDataDirective(type);
1002 EmitConstantValueOnly(CV);
1007 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1008 // Target doesn't support this yet!
1012 /// PrintSpecial - Print information related to the specified machine instr
1013 /// that is independent of the operand, and may be independent of the instr
1014 /// itself. This can be useful for portably encoding the comment character
1015 /// or other bits of target-specific knowledge into the asmstrings. The
1016 /// syntax used is ${:comment}. Targets can override this to add support
1017 /// for their own strange codes.
1018 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1019 if (!strcmp(Code, "private")) {
1020 O << TAI->getPrivateGlobalPrefix();
1021 } else if (!strcmp(Code, "comment")) {
1022 O << TAI->getCommentString();
1023 } else if (!strcmp(Code, "uid")) {
1024 // Assign a unique ID to this machine instruction.
1025 static const MachineInstr *LastMI = 0;
1026 static const Function *F = 0;
1027 static unsigned Counter = 0U-1;
1029 // Comparing the address of MI isn't sufficient, because machineinstrs may
1030 // be allocated to the same address across functions.
1031 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1033 // If this is a new machine instruction, bump the counter.
1034 if (LastMI != MI || F != ThisF) {
1041 cerr << "Unknown special formatter '" << Code
1042 << "' for machine instr: " << *MI;
1048 /// printInlineAsm - This method formats and prints the specified machine
1049 /// instruction that is an inline asm.
1050 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1051 unsigned NumOperands = MI->getNumOperands();
1053 // Count the number of register definitions.
1054 unsigned NumDefs = 0;
1055 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
1057 assert(NumDefs != NumOperands-1 && "No asm string?");
1059 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1061 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1062 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1064 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1065 if (AsmStr[0] == 0) {
1066 O << "\n"; // Tab already printed, avoid double indenting next instr.
1070 O << TAI->getInlineAsmStart() << "\n\t";
1072 // The variant of the current asmprinter.
1073 int AsmPrinterVariant = TAI->getAssemblerDialect();
1075 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1076 const char *LastEmitted = AsmStr; // One past the last character emitted.
1078 while (*LastEmitted) {
1079 switch (*LastEmitted) {
1081 // Not a special case, emit the string section literally.
1082 const char *LiteralEnd = LastEmitted+1;
1083 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1084 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1086 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1087 O.write(LastEmitted, LiteralEnd-LastEmitted);
1088 LastEmitted = LiteralEnd;
1092 ++LastEmitted; // Consume newline character.
1093 O << "\n"; // Indent code with newline.
1096 ++LastEmitted; // Consume '$' character.
1100 switch (*LastEmitted) {
1101 default: Done = false; break;
1102 case '$': // $$ -> $
1103 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1105 ++LastEmitted; // Consume second '$' character.
1107 case '(': // $( -> same as GCC's { character.
1108 ++LastEmitted; // Consume '(' character.
1109 if (CurVariant != -1) {
1110 cerr << "Nested variants found in inline asm string: '"
1114 CurVariant = 0; // We're in the first variant now.
1117 ++LastEmitted; // consume '|' character.
1118 if (CurVariant == -1) {
1119 cerr << "Found '|' character outside of variant in inline asm "
1120 << "string: '" << AsmStr << "'\n";
1123 ++CurVariant; // We're in the next variant.
1125 case ')': // $) -> same as GCC's } char.
1126 ++LastEmitted; // consume ')' character.
1127 if (CurVariant == -1) {
1128 cerr << "Found '}' character outside of variant in inline asm "
1129 << "string: '" << AsmStr << "'\n";
1137 bool HasCurlyBraces = false;
1138 if (*LastEmitted == '{') { // ${variable}
1139 ++LastEmitted; // Consume '{' character.
1140 HasCurlyBraces = true;
1143 const char *IDStart = LastEmitted;
1146 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1147 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1148 cerr << "Bad $ operand number in inline asm string: '"
1152 LastEmitted = IDEnd;
1154 char Modifier[2] = { 0, 0 };
1156 if (HasCurlyBraces) {
1157 // If we have curly braces, check for a modifier character. This
1158 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1159 if (*LastEmitted == ':') {
1160 ++LastEmitted; // Consume ':' character.
1161 if (*LastEmitted == 0) {
1162 cerr << "Bad ${:} expression in inline asm string: '"
1167 Modifier[0] = *LastEmitted;
1168 ++LastEmitted; // Consume modifier character.
1171 if (*LastEmitted != '}') {
1172 cerr << "Bad ${} expression in inline asm string: '"
1176 ++LastEmitted; // Consume '}' character.
1179 if ((unsigned)Val >= NumOperands-1) {
1180 cerr << "Invalid $ operand number in inline asm string: '"
1185 // Okay, we finally have a value number. Ask the target to print this
1187 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1192 // Scan to find the machine operand number for the operand.
1193 for (; Val; --Val) {
1194 if (OpNo >= MI->getNumOperands()) break;
1195 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1196 OpNo += (OpFlags >> 3) + 1;
1199 if (OpNo >= MI->getNumOperands()) {
1202 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1203 ++OpNo; // Skip over the ID number.
1205 if (Modifier[0]=='l') // labels are target independent
1206 printBasicBlockLabel(MI->getOperand(OpNo).getMachineBasicBlock(),
1209 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1210 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1211 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1212 Modifier[0] ? Modifier : 0);
1214 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1215 Modifier[0] ? Modifier : 0);
1220 cerr << "Invalid operand found in inline asm: '"
1230 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1233 /// printLabel - This method prints a local label used by debug and
1234 /// exception handling tables.
1235 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1237 << TAI->getPrivateGlobalPrefix()
1239 << MI->getOperand(0).getImmedValue()
1243 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1244 /// instruction, using the specified assembler variant. Targets should
1245 /// overried this to format as appropriate.
1246 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1247 unsigned AsmVariant, const char *ExtraCode) {
1248 // Target doesn't support this yet!
1252 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1253 unsigned AsmVariant,
1254 const char *ExtraCode) {
1255 // Target doesn't support this yet!
1259 /// printBasicBlockLabel - This method prints the label for the specified
1260 /// MachineBasicBlock
1261 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1263 bool printComment) const {
1264 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1265 << MBB->getNumber();
1268 if (printComment && MBB->getBasicBlock())
1269 O << '\t' << TAI->getCommentString() << ' '
1270 << MBB->getBasicBlock()->getName();
1273 /// printPICJumpTableSetLabel - This method prints a set label for the
1274 /// specified MachineBasicBlock for a jumptable entry.
1275 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1276 const MachineBasicBlock *MBB) const {
1277 if (!TAI->getSetDirective())
1280 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1281 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1282 printBasicBlockLabel(MBB, false, false);
1283 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1284 << '_' << uid << '\n';
1287 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1288 const MachineBasicBlock *MBB) const {
1289 if (!TAI->getSetDirective())
1292 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1293 << getFunctionNumber() << '_' << uid << '_' << uid2
1294 << "_set_" << MBB->getNumber() << ',';
1295 printBasicBlockLabel(MBB, false, false);
1296 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1297 << '_' << uid << '_' << uid2 << '\n';
1300 /// printDataDirective - This method prints the asm directive for the
1302 void AsmPrinter::printDataDirective(const Type *type) {
1303 const TargetData *TD = TM.getTargetData();
1304 switch (type->getTypeID()) {
1305 case Type::IntegerTyID: {
1306 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1308 O << TAI->getData8bitsDirective();
1309 else if (BitWidth <= 16)
1310 O << TAI->getData16bitsDirective();
1311 else if (BitWidth <= 32)
1312 O << TAI->getData32bitsDirective();
1313 else if (BitWidth <= 64) {
1314 assert(TAI->getData64bitsDirective() &&
1315 "Target cannot handle 64-bit constant exprs!");
1316 O << TAI->getData64bitsDirective();
1320 case Type::PointerTyID:
1321 if (TD->getPointerSize() == 8) {
1322 assert(TAI->getData64bitsDirective() &&
1323 "Target cannot handle 64-bit pointer exprs!");
1324 O << TAI->getData64bitsDirective();
1326 O << TAI->getData32bitsDirective();
1329 case Type::FloatTyID: case Type::DoubleTyID:
1330 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1331 assert (0 && "Should have already output floating point constant.");
1333 assert (0 && "Can't handle printing this type of thing");