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()) {
126 if (!M.alias_empty())
127 SwitchToTextSection(TAI->getTextSection());
130 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
132 const Constant *Aliasee = dyn_cast_or_null<Constant>(I->getAliasee());
133 assert(Aliasee && "Aliasee cannot be null");
135 std::string Name = Mang->getValueName(I);
138 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Aliasee))
139 Target = Mang->getValueName(GV);
141 const ConstantExpr *CE = 0;
142 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
143 (CE->getOpcode() == Instruction::BitCast))
144 Target = Mang->getValueName(CE->getOperand(0));
146 assert(0 && "Unsupported aliasee");
149 if (I->hasExternalLinkage())
150 O << "\t.globl\t" << Name << "\n";
151 else if (I->hasWeakLinkage())
152 O << TAI->getWeakRefDirective() << Name << "\n";
153 else if (!I->hasInternalLinkage())
154 assert(0 && "Invalid alias linkage");
156 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
160 delete Mang; Mang = 0;
164 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
165 // What's my mangled name?
166 CurrentFnName = Mang->getValueName(MF.getFunction());
167 IncrementFunctionNumber();
170 /// EmitConstantPool - Print to the current output stream assembly
171 /// representations of the constants in the constant pool MCP. This is
172 /// used to print out constants which have been "spilled to memory" by
173 /// the code generator.
175 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
176 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
177 if (CP.empty()) return;
179 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
180 // in special sections.
181 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
182 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
183 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
184 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
185 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
186 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
187 MachineConstantPoolEntry CPE = CP[i];
188 const Type *Ty = CPE.getType();
189 if (TAI->getFourByteConstantSection() &&
190 TM.getTargetData()->getTypeSize(Ty) == 4)
191 FourByteCPs.push_back(std::make_pair(CPE, i));
192 else if (TAI->getEightByteConstantSection() &&
193 TM.getTargetData()->getTypeSize(Ty) == 8)
194 EightByteCPs.push_back(std::make_pair(CPE, i));
195 else if (TAI->getSixteenByteConstantSection() &&
196 TM.getTargetData()->getTypeSize(Ty) == 16)
197 SixteenByteCPs.push_back(std::make_pair(CPE, i));
199 OtherCPs.push_back(std::make_pair(CPE, i));
202 unsigned Alignment = MCP->getConstantPoolAlignment();
203 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
204 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
205 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
207 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
210 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
211 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
212 if (CP.empty()) return;
214 SwitchToDataSection(Section);
215 EmitAlignment(Alignment);
216 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
217 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
218 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
219 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
220 if (CP[i].first.isMachineConstantPoolEntry())
221 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
223 EmitGlobalConstant(CP[i].first.Val.ConstVal);
225 const Type *Ty = CP[i].first.getType();
227 TM.getTargetData()->getTypeSize(Ty);
228 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
229 // Emit inter-object padding for alignment.
230 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
235 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
236 /// by the current function to the current output stream.
238 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
239 MachineFunction &MF) {
240 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
241 if (JT.empty()) return;
242 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
244 // Use JumpTableDirective otherwise honor the entry size from the jump table
246 const char *JTEntryDirective = TAI->getJumpTableDirective();
247 bool HadJTEntryDirective = JTEntryDirective != NULL;
248 if (!HadJTEntryDirective) {
249 JTEntryDirective = MJTI->getEntrySize() == 4 ?
250 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
253 // Pick the directive to use to print the jump table entries, and switch to
254 // the appropriate section.
255 TargetLowering *LoweringInfo = TM.getTargetLowering();
257 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
258 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
259 !JumpTableDataSection) {
260 // In PIC mode, we need to emit the jump table to the same section as the
261 // function body itself, otherwise the label differences won't make sense.
262 // We should also do if the section name is NULL.
263 const Function *F = MF.getFunction();
264 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
266 SwitchToDataSection(JumpTableDataSection);
269 EmitAlignment(Log2_32(MJTI->getAlignment()));
271 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
272 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
274 // If this jump table was deleted, ignore it.
275 if (JTBBs.empty()) continue;
277 // For PIC codegen, if possible we want to use the SetDirective to reduce
278 // the number of relocations the assembler will generate for the jump table.
279 // Set directives are all printed before the jump table itself.
280 std::set<MachineBasicBlock*> EmittedSets;
281 if (TAI->getSetDirective() && IsPic)
282 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
283 if (EmittedSets.insert(JTBBs[ii]).second)
284 printSetLabel(i, JTBBs[ii]);
286 // On some targets (e.g. darwin) we want to emit two consequtive labels
287 // before each jump table. The first label is never referenced, but tells
288 // the assembler and linker the extents of the jump table object. The
289 // second label is actually referenced by the code.
290 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
291 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
293 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
294 << '_' << i << ":\n";
296 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
297 O << JTEntryDirective << ' ';
298 // If we have emitted set directives for the jump table entries, print
299 // them rather than the entries themselves. If we're emitting PIC, then
300 // emit the table entries as differences between two text section labels.
301 // If we're emitting non-PIC code, then emit the entries as direct
302 // references to the target basic blocks.
303 if (!EmittedSets.empty()) {
304 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
305 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
307 printBasicBlockLabel(JTBBs[ii], false, false);
308 // If the arch uses custom Jump Table directives, don't calc relative to
310 if (!HadJTEntryDirective)
311 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
312 << getFunctionNumber() << '_' << i;
314 printBasicBlockLabel(JTBBs[ii], false, false);
321 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
322 /// special global used by LLVM. If so, emit it and return true, otherwise
323 /// do nothing and return false.
324 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
325 // Ignore debug and non-emitted data.
326 if (GV->getSection() == "llvm.metadata") return true;
328 if (!GV->hasAppendingLinkage()) return false;
330 assert(GV->hasInitializer() && "Not a special LLVM global!");
332 if (GV->getName() == "llvm.used") {
333 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
334 EmitLLVMUsedList(GV->getInitializer());
338 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
339 SwitchToDataSection(TAI->getStaticCtorsSection());
341 EmitXXStructorList(GV->getInitializer());
345 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
346 SwitchToDataSection(TAI->getStaticDtorsSection());
348 EmitXXStructorList(GV->getInitializer());
355 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
356 /// global in the specified llvm.used list as being used with this directive.
357 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
358 const char *Directive = TAI->getUsedDirective();
360 // Should be an array of 'sbyte*'.
361 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
362 if (InitList == 0) return;
364 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
366 EmitConstantValueOnly(InitList->getOperand(i));
371 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
372 /// function pointers, ignoring the init priority.
373 void AsmPrinter::EmitXXStructorList(Constant *List) {
374 // Should be an array of '{ int, void ()* }' structs. The first value is the
375 // init priority, which we ignore.
376 if (!isa<ConstantArray>(List)) return;
377 ConstantArray *InitList = cast<ConstantArray>(List);
378 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
379 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
380 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
382 if (CS->getOperand(1)->isNullValue())
383 return; // Found a null terminator, exit printing.
384 // Emit the function pointer.
385 EmitGlobalConstant(CS->getOperand(1));
389 /// getGlobalLinkName - Returns the asm/link name of of the specified
390 /// global variable. Should be overridden by each target asm printer to
391 /// generate the appropriate value.
392 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
393 std::string LinkName;
395 if (isa<Function>(GV)) {
396 LinkName += TAI->getFunctionAddrPrefix();
397 LinkName += Mang->getValueName(GV);
398 LinkName += TAI->getFunctionAddrSuffix();
400 LinkName += TAI->getGlobalVarAddrPrefix();
401 LinkName += Mang->getValueName(GV);
402 LinkName += TAI->getGlobalVarAddrSuffix();
408 /// EmitExternalGlobal - Emit the external reference to a global variable.
409 /// Should be overridden if an indirect reference should be used.
410 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
411 O << getGlobalLinkName(GV);
416 //===----------------------------------------------------------------------===//
417 /// LEB 128 number encoding.
419 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
420 /// representing an unsigned leb128 value.
421 void AsmPrinter::PrintULEB128(unsigned Value) const {
423 unsigned Byte = Value & 0x7f;
425 if (Value) Byte |= 0x80;
426 O << "0x" << std::hex << Byte << std::dec;
427 if (Value) O << ", ";
431 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
433 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
437 Size += sizeof(int8_t);
442 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
443 /// representing a signed leb128 value.
444 void AsmPrinter::PrintSLEB128(int Value) const {
445 int Sign = Value >> (8 * sizeof(Value) - 1);
449 unsigned Byte = Value & 0x7f;
451 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
452 if (IsMore) Byte |= 0x80;
453 O << "0x" << std::hex << Byte << std::dec;
454 if (IsMore) O << ", ";
458 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
460 unsigned AsmPrinter::SizeSLEB128(int Value) {
462 int Sign = Value >> (8 * sizeof(Value) - 1);
466 unsigned Byte = Value & 0x7f;
468 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
469 Size += sizeof(int8_t);
474 //===--------------------------------------------------------------------===//
475 // Emission and print routines
478 /// PrintHex - Print a value as a hexidecimal value.
480 void AsmPrinter::PrintHex(int Value) const {
481 O << "0x" << std::hex << Value << std::dec;
484 /// EOL - Print a newline character to asm stream. If a comment is present
485 /// then it will be printed first. Comments should not contain '\n'.
486 void AsmPrinter::EOL() const {
489 void AsmPrinter::EOL(const std::string &Comment) const {
490 if (AsmVerbose && !Comment.empty()) {
492 << TAI->getCommentString()
499 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
500 /// unsigned leb128 value.
501 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
502 if (TAI->hasLEB128()) {
506 O << TAI->getData8bitsDirective();
511 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
512 /// signed leb128 value.
513 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
514 if (TAI->hasLEB128()) {
518 O << TAI->getData8bitsDirective();
523 /// EmitInt8 - Emit a byte directive and value.
525 void AsmPrinter::EmitInt8(int Value) const {
526 O << TAI->getData8bitsDirective();
527 PrintHex(Value & 0xFF);
530 /// EmitInt16 - Emit a short directive and value.
532 void AsmPrinter::EmitInt16(int Value) const {
533 O << TAI->getData16bitsDirective();
534 PrintHex(Value & 0xFFFF);
537 /// EmitInt32 - Emit a long directive and value.
539 void AsmPrinter::EmitInt32(int Value) const {
540 O << TAI->getData32bitsDirective();
544 /// EmitInt64 - Emit a long long directive and value.
546 void AsmPrinter::EmitInt64(uint64_t Value) const {
547 if (TAI->getData64bitsDirective()) {
548 O << TAI->getData64bitsDirective();
551 if (TM.getTargetData()->isBigEndian()) {
552 EmitInt32(unsigned(Value >> 32)); O << "\n";
553 EmitInt32(unsigned(Value));
555 EmitInt32(unsigned(Value)); O << "\n";
556 EmitInt32(unsigned(Value >> 32));
561 /// toOctal - Convert the low order bits of X into an octal digit.
563 static inline char toOctal(int X) {
567 /// printStringChar - Print a char, escaped if necessary.
569 static void printStringChar(std::ostream &O, unsigned char C) {
572 } else if (C == '\\') {
574 } else if (isprint(C)) {
578 case '\b': O << "\\b"; break;
579 case '\f': O << "\\f"; break;
580 case '\n': O << "\\n"; break;
581 case '\r': O << "\\r"; break;
582 case '\t': O << "\\t"; break;
585 O << toOctal(C >> 6);
586 O << toOctal(C >> 3);
587 O << toOctal(C >> 0);
593 /// EmitString - Emit a string with quotes and a null terminator.
594 /// Special characters are emitted properly.
595 /// \literal (Eg. '\t') \endliteral
596 void AsmPrinter::EmitString(const std::string &String) const {
597 const char* AscizDirective = TAI->getAscizDirective();
601 O << TAI->getAsciiDirective();
603 for (unsigned i = 0, N = String.size(); i < N; ++i) {
604 unsigned char C = String[i];
605 printStringChar(O, C);
614 //===----------------------------------------------------------------------===//
616 // EmitAlignment - Emit an alignment directive to the specified power of two.
617 // Use the maximum of the specified alignment and the alignment from the
618 // specified GlobalValue (if any).
619 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
620 if (GV && GV->getAlignment())
621 NumBits = std::max(NumBits, Log2_32(GV->getAlignment()));
622 if (NumBits == 0) return; // No need to emit alignment.
623 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
624 O << TAI->getAlignDirective() << NumBits << "\n";
628 /// EmitZeros - Emit a block of zeros.
630 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
632 if (TAI->getZeroDirective()) {
633 O << TAI->getZeroDirective() << NumZeros;
634 if (TAI->getZeroDirectiveSuffix())
635 O << TAI->getZeroDirectiveSuffix();
638 for (; NumZeros; --NumZeros)
639 O << TAI->getData8bitsDirective() << "0\n";
644 // Print out the specified constant, without a storage class. Only the
645 // constants valid in constant expressions can occur here.
646 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
647 if (CV->isNullValue() || isa<UndefValue>(CV))
649 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
650 O << CI->getZExtValue();
651 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
652 // This is a constant address for a global variable or function. Use the
653 // name of the variable or function as the address value, possibly
654 // decorating it with GlobalVarAddrPrefix/Suffix or
655 // FunctionAddrPrefix/Suffix (these all default to "" )
656 if (isa<Function>(GV)) {
657 O << TAI->getFunctionAddrPrefix()
658 << Mang->getValueName(GV)
659 << TAI->getFunctionAddrSuffix();
661 O << TAI->getGlobalVarAddrPrefix()
662 << Mang->getValueName(GV)
663 << TAI->getGlobalVarAddrSuffix();
665 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
666 const TargetData *TD = TM.getTargetData();
667 unsigned Opcode = CE->getOpcode();
669 case Instruction::GetElementPtr: {
670 // generate a symbolic expression for the byte address
671 const Constant *ptrVal = CE->getOperand(0);
672 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
673 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
677 EmitConstantValueOnly(ptrVal);
679 O << ") + " << Offset;
681 O << ") - " << -Offset;
683 EmitConstantValueOnly(ptrVal);
687 case Instruction::Trunc:
688 case Instruction::ZExt:
689 case Instruction::SExt:
690 case Instruction::FPTrunc:
691 case Instruction::FPExt:
692 case Instruction::UIToFP:
693 case Instruction::SIToFP:
694 case Instruction::FPToUI:
695 case Instruction::FPToSI:
696 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
698 case Instruction::BitCast:
699 return EmitConstantValueOnly(CE->getOperand(0));
701 case Instruction::IntToPtr: {
702 // Handle casts to pointers by changing them into casts to the appropriate
703 // integer type. This promotes constant folding and simplifies this code.
704 Constant *Op = CE->getOperand(0);
705 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
706 return EmitConstantValueOnly(Op);
710 case Instruction::PtrToInt: {
711 // Support only foldable casts to/from pointers that can be eliminated by
712 // changing the pointer to the appropriately sized integer type.
713 Constant *Op = CE->getOperand(0);
714 const Type *Ty = CE->getType();
716 // We can emit the pointer value into this slot if the slot is an
717 // integer slot greater or equal to the size of the pointer.
718 if (Ty->isInteger() &&
719 TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
720 return EmitConstantValueOnly(Op);
722 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
723 EmitConstantValueOnly(Op);
726 case Instruction::Add:
727 case Instruction::Sub:
729 EmitConstantValueOnly(CE->getOperand(0));
730 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
731 EmitConstantValueOnly(CE->getOperand(1));
735 assert(0 && "Unsupported operator!");
738 assert(0 && "Unknown constant value!");
742 /// printAsCString - Print the specified array as a C compatible string, only if
743 /// the predicate isString is true.
745 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
747 assert(CVA->isString() && "Array is not string compatible!");
750 for (unsigned i = 0; i != LastElt; ++i) {
752 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
753 printStringChar(O, C);
758 /// EmitString - Emit a zero-byte-terminated string constant.
760 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
761 unsigned NumElts = CVA->getNumOperands();
762 if (TAI->getAscizDirective() && NumElts &&
763 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
764 O << TAI->getAscizDirective();
765 printAsCString(O, CVA, NumElts-1);
767 O << TAI->getAsciiDirective();
768 printAsCString(O, CVA, NumElts);
773 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
775 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
776 const TargetData *TD = TM.getTargetData();
778 if (CV->isNullValue() || isa<UndefValue>(CV)) {
779 EmitZeros(TD->getTypeSize(CV->getType()));
781 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
782 if (CVA->isString()) {
784 } else { // Not a string. Print the values in successive locations
785 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
786 EmitGlobalConstant(CVA->getOperand(i));
789 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
790 // Print the fields in successive locations. Pad to align if needed!
791 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
792 uint64_t sizeSoFar = 0;
793 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
794 const Constant* field = CVS->getOperand(i);
796 // Check if padding is needed and insert one or more 0s.
797 uint64_t fieldSize = TD->getTypeSize(field->getType());
798 uint64_t padSize = ((i == e-1? cvsLayout->getSizeInBytes()
799 : cvsLayout->getElementOffset(i+1))
800 - cvsLayout->getElementOffset(i)) - fieldSize;
801 sizeSoFar += fieldSize + padSize;
803 // Now print the actual field value
804 EmitGlobalConstant(field);
806 // Insert the field padding unless it's zero bytes...
809 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
810 "Layout of constant struct may be incorrect!");
812 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
813 // FP Constants are printed as integer constants to avoid losing
815 double Val = CFP->getValue();
816 if (CFP->getType() == Type::DoubleTy) {
817 if (TAI->getData64bitsDirective())
818 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
819 << TAI->getCommentString() << " double value: " << Val << "\n";
820 else if (TD->isBigEndian()) {
821 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
822 << "\t" << TAI->getCommentString()
823 << " double most significant word " << Val << "\n";
824 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
825 << "\t" << TAI->getCommentString()
826 << " double least significant word " << Val << "\n";
828 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
829 << "\t" << TAI->getCommentString()
830 << " double least significant word " << Val << "\n";
831 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
832 << "\t" << TAI->getCommentString()
833 << " double most significant word " << Val << "\n";
837 O << TAI->getData32bitsDirective() << FloatToBits(Val)
838 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
841 } else if (CV->getType() == Type::Int64Ty) {
842 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
843 uint64_t Val = CI->getZExtValue();
845 if (TAI->getData64bitsDirective())
846 O << TAI->getData64bitsDirective() << Val << "\n";
847 else if (TD->isBigEndian()) {
848 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
849 << "\t" << TAI->getCommentString()
850 << " Double-word most significant word " << Val << "\n";
851 O << TAI->getData32bitsDirective() << unsigned(Val)
852 << "\t" << TAI->getCommentString()
853 << " Double-word least significant word " << Val << "\n";
855 O << TAI->getData32bitsDirective() << unsigned(Val)
856 << "\t" << TAI->getCommentString()
857 << " Double-word least significant word " << Val << "\n";
858 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
859 << "\t" << TAI->getCommentString()
860 << " Double-word most significant word " << Val << "\n";
864 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
865 const VectorType *PTy = CP->getType();
867 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
868 EmitGlobalConstant(CP->getOperand(I));
873 const Type *type = CV->getType();
874 printDataDirective(type);
875 EmitConstantValueOnly(CV);
880 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
881 // Target doesn't support this yet!
885 /// PrintSpecial - Print information related to the specified machine instr
886 /// that is independent of the operand, and may be independent of the instr
887 /// itself. This can be useful for portably encoding the comment character
888 /// or other bits of target-specific knowledge into the asmstrings. The
889 /// syntax used is ${:comment}. Targets can override this to add support
890 /// for their own strange codes.
891 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
892 if (!strcmp(Code, "private")) {
893 O << TAI->getPrivateGlobalPrefix();
894 } else if (!strcmp(Code, "comment")) {
895 O << TAI->getCommentString();
896 } else if (!strcmp(Code, "uid")) {
897 // Assign a unique ID to this machine instruction.
898 static const MachineInstr *LastMI = 0;
899 static const Function *F = 0;
900 static unsigned Counter = 0U-1;
902 // Comparing the address of MI isn't sufficient, because machineinstrs may
903 // be allocated to the same address across functions.
904 const Function *ThisF = MI->getParent()->getParent()->getFunction();
906 // If this is a new machine instruction, bump the counter.
907 if (LastMI != MI || F != ThisF) {
914 cerr << "Unknown special formatter '" << Code
915 << "' for machine instr: " << *MI;
921 /// printInlineAsm - This method formats and prints the specified machine
922 /// instruction that is an inline asm.
923 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
924 unsigned NumOperands = MI->getNumOperands();
926 // Count the number of register definitions.
927 unsigned NumDefs = 0;
928 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
930 assert(NumDefs != NumOperands-1 && "No asm string?");
932 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
934 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
935 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
937 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
938 if (AsmStr[0] == 0) {
939 O << "\n"; // Tab already printed, avoid double indenting next instr.
943 O << TAI->getInlineAsmStart() << "\n\t";
945 // The variant of the current asmprinter.
946 int AsmPrinterVariant = TAI->getAssemblerDialect();
948 int CurVariant = -1; // The number of the {.|.|.} region we are in.
949 const char *LastEmitted = AsmStr; // One past the last character emitted.
951 while (*LastEmitted) {
952 switch (*LastEmitted) {
954 // Not a special case, emit the string section literally.
955 const char *LiteralEnd = LastEmitted+1;
956 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
957 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
959 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
960 O.write(LastEmitted, LiteralEnd-LastEmitted);
961 LastEmitted = LiteralEnd;
965 ++LastEmitted; // Consume newline character.
966 O << "\n\t"; // Indent code with newline.
969 ++LastEmitted; // Consume '$' character.
973 switch (*LastEmitted) {
974 default: Done = false; break;
976 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
978 ++LastEmitted; // Consume second '$' character.
980 case '(': // $( -> same as GCC's { character.
981 ++LastEmitted; // Consume '(' character.
982 if (CurVariant != -1) {
983 cerr << "Nested variants found in inline asm string: '"
987 CurVariant = 0; // We're in the first variant now.
990 ++LastEmitted; // consume '|' character.
991 if (CurVariant == -1) {
992 cerr << "Found '|' character outside of variant in inline asm "
993 << "string: '" << AsmStr << "'\n";
996 ++CurVariant; // We're in the next variant.
998 case ')': // $) -> same as GCC's } char.
999 ++LastEmitted; // consume ')' character.
1000 if (CurVariant == -1) {
1001 cerr << "Found '}' character outside of variant in inline asm "
1002 << "string: '" << AsmStr << "'\n";
1010 bool HasCurlyBraces = false;
1011 if (*LastEmitted == '{') { // ${variable}
1012 ++LastEmitted; // Consume '{' character.
1013 HasCurlyBraces = true;
1016 const char *IDStart = LastEmitted;
1019 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1020 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1021 cerr << "Bad $ operand number in inline asm string: '"
1025 LastEmitted = IDEnd;
1027 char Modifier[2] = { 0, 0 };
1029 if (HasCurlyBraces) {
1030 // If we have curly braces, check for a modifier character. This
1031 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1032 if (*LastEmitted == ':') {
1033 ++LastEmitted; // Consume ':' character.
1034 if (*LastEmitted == 0) {
1035 cerr << "Bad ${:} expression in inline asm string: '"
1040 Modifier[0] = *LastEmitted;
1041 ++LastEmitted; // Consume modifier character.
1044 if (*LastEmitted != '}') {
1045 cerr << "Bad ${} expression in inline asm string: '"
1049 ++LastEmitted; // Consume '}' character.
1052 if ((unsigned)Val >= NumOperands-1) {
1053 cerr << "Invalid $ operand number in inline asm string: '"
1058 // Okay, we finally have a value number. Ask the target to print this
1060 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1065 // Scan to find the machine operand number for the operand.
1066 for (; Val; --Val) {
1067 if (OpNo >= MI->getNumOperands()) break;
1068 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1069 OpNo += (OpFlags >> 3) + 1;
1072 if (OpNo >= MI->getNumOperands()) {
1075 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1076 ++OpNo; // Skip over the ID number.
1078 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1079 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1080 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1081 Modifier[0] ? Modifier : 0);
1083 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1084 Modifier[0] ? Modifier : 0);
1088 cerr << "Invalid operand found in inline asm: '"
1098 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1101 /// printLabel - This method prints a local label used by debug and
1102 /// exception handling tables.
1103 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1105 << TAI->getPrivateGlobalPrefix()
1107 << MI->getOperand(0).getImmedValue()
1111 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1112 /// instruction, using the specified assembler variant. Targets should
1113 /// overried this to format as appropriate.
1114 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1115 unsigned AsmVariant, const char *ExtraCode) {
1116 // Target doesn't support this yet!
1120 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1121 unsigned AsmVariant,
1122 const char *ExtraCode) {
1123 // Target doesn't support this yet!
1127 /// printBasicBlockLabel - This method prints the label for the specified
1128 /// MachineBasicBlock
1129 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1131 bool printComment) const {
1132 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
1133 << MBB->getNumber();
1136 if (printComment && MBB->getBasicBlock())
1137 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
1140 /// printSetLabel - This method prints a set label for the specified
1141 /// MachineBasicBlock
1142 void AsmPrinter::printSetLabel(unsigned uid,
1143 const MachineBasicBlock *MBB) const {
1144 if (!TAI->getSetDirective())
1147 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1148 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1149 printBasicBlockLabel(MBB, false, false);
1150 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1151 << '_' << uid << '\n';
1154 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
1155 const MachineBasicBlock *MBB) const {
1156 if (!TAI->getSetDirective())
1159 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1160 << getFunctionNumber() << '_' << uid << '_' << uid2
1161 << "_set_" << MBB->getNumber() << ',';
1162 printBasicBlockLabel(MBB, false, false);
1163 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1164 << '_' << uid << '_' << uid2 << '\n';
1167 /// printDataDirective - This method prints the asm directive for the
1169 void AsmPrinter::printDataDirective(const Type *type) {
1170 const TargetData *TD = TM.getTargetData();
1171 switch (type->getTypeID()) {
1172 case Type::IntegerTyID: {
1173 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1175 O << TAI->getData8bitsDirective();
1176 else if (BitWidth <= 16)
1177 O << TAI->getData16bitsDirective();
1178 else if (BitWidth <= 32)
1179 O << TAI->getData32bitsDirective();
1180 else if (BitWidth <= 64) {
1181 assert(TAI->getData64bitsDirective() &&
1182 "Target cannot handle 64-bit constant exprs!");
1183 O << TAI->getData64bitsDirective();
1187 case Type::PointerTyID:
1188 if (TD->getPointerSize() == 8) {
1189 assert(TAI->getData64bitsDirective() &&
1190 "Target cannot handle 64-bit pointer exprs!");
1191 O << TAI->getData64bitsDirective();
1193 O << TAI->getData32bitsDirective();
1196 case Type::FloatTyID: case Type::DoubleTyID:
1197 assert (0 && "Should have already output floating point constant.");
1199 assert (0 && "Can't handle printing this type of thing");