1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Support/raw_ostream.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/Target/TargetOptions.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
37 char AsmPrinter::ID = 0;
38 AsmPrinter::AsmPrinter(raw_ostream &o, TargetMachine &tm,
39 const TargetAsmInfo *T)
40 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
41 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
42 IsInTextSection(false)
45 AsmPrinter::~AsmPrinter() {
46 for (gcp_iterator I = GCMetadataPrinters.begin(),
47 E = GCMetadataPrinters.end(); I != E; ++I)
51 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
52 return TAI->getTextSection();
56 /// SwitchToTextSection - Switch to the specified text section of the executable
57 /// if we are not already in it!
59 void AsmPrinter::SwitchToTextSection(const char *NewSection,
60 const GlobalValue *GV) {
62 if (GV && GV->hasSection())
63 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
67 // If we're already in this section, we're done.
68 if (CurrentSection == NS) return;
70 // Close the current section, if applicable.
71 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
72 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
76 if (!CurrentSection.empty())
77 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
79 IsInTextSection = true;
82 /// SwitchToDataSection - Switch to the specified data section of the executable
83 /// if we are not already in it!
85 void AsmPrinter::SwitchToDataSection(const char *NewSection,
86 const GlobalValue *GV) {
88 if (GV && GV->hasSection())
89 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
93 // If we're already in this section, we're done.
94 if (CurrentSection == NS) return;
96 // Close the current section, if applicable.
97 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
98 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
102 if (!CurrentSection.empty())
103 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
105 IsInTextSection = false;
108 /// SwitchToSection - Switch to the specified section of the executable if we
109 /// are not already in it!
110 void AsmPrinter::SwitchToSection(const Section* NS) {
111 const std::string& NewSection = NS->getName();
113 // If we're already in this section, we're done.
114 if (CurrentSection == NewSection) return;
116 // Close the current section, if applicable.
117 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
118 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
120 // FIXME: Make CurrentSection a Section* in the future
121 CurrentSection = NewSection;
123 if (!CurrentSection.empty())
124 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
126 IsInTextSection = (NS->getFlags() & SectionFlags::Code);
129 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
130 MachineFunctionPass::getAnalysisUsage(AU);
131 AU.addRequired<GCModuleInfo>();
134 bool AsmPrinter::doInitialization(Module &M) {
135 Mang = new Mangler(M, TAI->getGlobalPrefix());
137 GCModuleInfo *MI = getAnalysisToUpdate<GCModuleInfo>();
138 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
139 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
140 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
141 MP->beginAssembly(O, *this, *TAI);
143 if (!M.getModuleInlineAsm().empty())
144 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
145 << M.getModuleInlineAsm()
146 << '\n' << TAI->getCommentString()
147 << " End of file scope inline assembly\n";
149 SwitchToDataSection(""); // Reset back to no section.
151 MMI = getAnalysisToUpdate<MachineModuleInfo>();
152 if (MMI) MMI->AnalyzeModule(M);
157 bool AsmPrinter::doFinalization(Module &M) {
158 if (TAI->getWeakRefDirective()) {
159 if (!ExtWeakSymbols.empty())
160 SwitchToDataSection("");
162 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
163 e = ExtWeakSymbols.end(); i != e; ++i) {
164 const GlobalValue *GV = *i;
165 std::string Name = Mang->getValueName(GV);
166 O << TAI->getWeakRefDirective() << Name << '\n';
170 if (TAI->getSetDirective()) {
171 if (!M.alias_empty())
172 SwitchToTextSection(TAI->getTextSection());
175 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
177 std::string Name = Mang->getValueName(I);
180 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
181 Target = Mang->getValueName(GV);
183 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
184 O << "\t.globl\t" << Name << '\n';
185 else if (I->hasWeakLinkage())
186 O << TAI->getWeakRefDirective() << Name << '\n';
187 else if (!I->hasInternalLinkage())
188 assert(0 && "Invalid alias linkage");
190 if (I->hasHiddenVisibility()) {
191 if (const char *Directive = TAI->getHiddenDirective())
192 O << Directive << Name << '\n';
193 } else if (I->hasProtectedVisibility()) {
194 if (const char *Directive = TAI->getProtectedDirective())
195 O << Directive << Name << '\n';
198 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
200 // If the aliasee has external weak linkage it can be referenced only by
201 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
202 // weak reference in such case.
203 if (GV->hasExternalWeakLinkage()) {
204 if (TAI->getWeakRefDirective())
205 O << TAI->getWeakRefDirective() << Target << '\n';
207 O << "\t.globl\t" << Target << '\n';
212 GCModuleInfo *MI = getAnalysisToUpdate<GCModuleInfo>();
213 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
214 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
215 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
216 MP->finishAssembly(O, *this, *TAI);
218 // If we don't have any trampolines, then we don't require stack memory
219 // to be executable. Some targets have a directive to declare this.
220 Function* InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
221 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
222 if (TAI->getNonexecutableStackDirective())
223 O << TAI->getNonexecutableStackDirective() << '\n';
225 delete Mang; Mang = 0;
229 std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
230 assert(MF && "No machine function?");
231 std::string Name = MF->getFunction()->getName();
233 Name = Mang->getValueName(MF->getFunction());
234 return Mang->makeNameProper(Name + ".eh", TAI->getGlobalPrefix());
237 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
238 // What's my mangled name?
239 CurrentFnName = Mang->getValueName(MF.getFunction());
240 IncrementFunctionNumber();
243 /// EmitConstantPool - Print to the current output stream assembly
244 /// representations of the constants in the constant pool MCP. This is
245 /// used to print out constants which have been "spilled to memory" by
246 /// the code generator.
248 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
249 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
250 if (CP.empty()) return;
252 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
253 // in special sections.
254 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
255 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
256 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
257 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
258 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
259 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
260 MachineConstantPoolEntry CPE = CP[i];
261 const Type *Ty = CPE.getType();
262 if (TAI->getFourByteConstantSection() &&
263 TM.getTargetData()->getABITypeSize(Ty) == 4)
264 FourByteCPs.push_back(std::make_pair(CPE, i));
265 else if (TAI->getEightByteConstantSection() &&
266 TM.getTargetData()->getABITypeSize(Ty) == 8)
267 EightByteCPs.push_back(std::make_pair(CPE, i));
268 else if (TAI->getSixteenByteConstantSection() &&
269 TM.getTargetData()->getABITypeSize(Ty) == 16)
270 SixteenByteCPs.push_back(std::make_pair(CPE, i));
272 OtherCPs.push_back(std::make_pair(CPE, i));
275 unsigned Alignment = MCP->getConstantPoolAlignment();
276 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
277 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
278 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
280 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
283 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
284 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
285 if (CP.empty()) return;
287 SwitchToDataSection(Section);
288 EmitAlignment(Alignment);
289 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
290 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
291 << CP[i].second << ":\t\t\t\t\t";
292 // O << TAI->getCommentString() << ' ' <<
293 // WriteTypeSymbolic(O, CP[i].first.getType(), 0);
295 if (CP[i].first.isMachineConstantPoolEntry())
296 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
298 EmitGlobalConstant(CP[i].first.Val.ConstVal);
300 const Type *Ty = CP[i].first.getType();
302 TM.getTargetData()->getABITypeSize(Ty);
303 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
304 // Emit inter-object padding for alignment.
305 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
310 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
311 /// by the current function to the current output stream.
313 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
314 MachineFunction &MF) {
315 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
316 if (JT.empty()) return;
318 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
320 // Pick the directive to use to print the jump table entries, and switch to
321 // the appropriate section.
322 TargetLowering *LoweringInfo = TM.getTargetLowering();
324 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
325 const Function *F = MF.getFunction();
326 unsigned SectionFlags = TAI->SectionFlagsForGlobal(F);
327 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
328 !JumpTableDataSection ||
329 SectionFlags & SectionFlags::Linkonce) {
330 // In PIC mode, we need to emit the jump table to the same section as the
331 // function body itself, otherwise the label differences won't make sense.
332 // We should also do if the section name is NULL or function is declared in
333 // discardable section.
334 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
336 SwitchToDataSection(JumpTableDataSection);
339 EmitAlignment(Log2_32(MJTI->getAlignment()));
341 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
342 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
344 // If this jump table was deleted, ignore it.
345 if (JTBBs.empty()) continue;
347 // For PIC codegen, if possible we want to use the SetDirective to reduce
348 // the number of relocations the assembler will generate for the jump table.
349 // Set directives are all printed before the jump table itself.
350 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
351 if (TAI->getSetDirective() && IsPic)
352 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
353 if (EmittedSets.insert(JTBBs[ii]))
354 printPICJumpTableSetLabel(i, JTBBs[ii]);
356 // On some targets (e.g. darwin) we want to emit two consequtive labels
357 // before each jump table. The first label is never referenced, but tells
358 // the assembler and linker the extents of the jump table object. The
359 // second label is actually referenced by the code.
360 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
361 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
363 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
364 << '_' << i << ":\n";
366 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
367 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
373 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
374 const MachineBasicBlock *MBB,
375 unsigned uid) const {
376 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
378 // Use JumpTableDirective otherwise honor the entry size from the jump table
380 const char *JTEntryDirective = TAI->getJumpTableDirective();
381 bool HadJTEntryDirective = JTEntryDirective != NULL;
382 if (!HadJTEntryDirective) {
383 JTEntryDirective = MJTI->getEntrySize() == 4 ?
384 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
387 O << JTEntryDirective << ' ';
389 // If we have emitted set directives for the jump table entries, print
390 // them rather than the entries themselves. If we're emitting PIC, then
391 // emit the table entries as differences between two text section labels.
392 // If we're emitting non-PIC code, then emit the entries as direct
393 // references to the target basic blocks.
395 if (TAI->getSetDirective()) {
396 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
397 << '_' << uid << "_set_" << MBB->getNumber();
399 printBasicBlockLabel(MBB, false, false, false);
400 // If the arch uses custom Jump Table directives, don't calc relative to
402 if (!HadJTEntryDirective)
403 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
404 << getFunctionNumber() << '_' << uid;
407 printBasicBlockLabel(MBB, false, false, false);
412 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
413 /// special global used by LLVM. If so, emit it and return true, otherwise
414 /// do nothing and return false.
415 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
416 if (GV->getName() == "llvm.used") {
417 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
418 EmitLLVMUsedList(GV->getInitializer());
422 // Ignore debug and non-emitted data.
423 if (GV->getSection() == "llvm.metadata") return true;
425 if (!GV->hasAppendingLinkage()) return false;
427 assert(GV->hasInitializer() && "Not a special LLVM global!");
429 const TargetData *TD = TM.getTargetData();
430 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
431 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
432 SwitchToDataSection(TAI->getStaticCtorsSection());
433 EmitAlignment(Align, 0);
434 EmitXXStructorList(GV->getInitializer());
438 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
439 SwitchToDataSection(TAI->getStaticDtorsSection());
440 EmitAlignment(Align, 0);
441 EmitXXStructorList(GV->getInitializer());
448 /// findGlobalValue - if CV is an expression equivalent to a single
449 /// global value, return that value.
450 const GlobalValue * AsmPrinter::findGlobalValue(const Constant *CV) {
451 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
453 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
454 const TargetData *TD = TM.getTargetData();
455 unsigned Opcode = CE->getOpcode();
457 case Instruction::GetElementPtr: {
458 const Constant *ptrVal = CE->getOperand(0);
459 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
460 if (TD->getIndexedOffset(ptrVal->getType(), &idxVec[0], idxVec.size()))
462 return findGlobalValue(ptrVal);
464 case Instruction::BitCast:
465 return findGlobalValue(CE->getOperand(0));
473 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
474 /// global in the specified llvm.used list for which emitUsedDirectiveFor
475 /// is true, as being used with this directive.
477 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
478 const char *Directive = TAI->getUsedDirective();
480 // Should be an array of 'sbyte*'.
481 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
482 if (InitList == 0) return;
484 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
485 const GlobalValue *GV = findGlobalValue(InitList->getOperand(i));
486 if (TAI->emitUsedDirectiveFor(GV, Mang)) {
488 EmitConstantValueOnly(InitList->getOperand(i));
494 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
495 /// function pointers, ignoring the init priority.
496 void AsmPrinter::EmitXXStructorList(Constant *List) {
497 // Should be an array of '{ int, void ()* }' structs. The first value is the
498 // init priority, which we ignore.
499 if (!isa<ConstantArray>(List)) return;
500 ConstantArray *InitList = cast<ConstantArray>(List);
501 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
502 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
503 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
505 if (CS->getOperand(1)->isNullValue())
506 return; // Found a null terminator, exit printing.
507 // Emit the function pointer.
508 EmitGlobalConstant(CS->getOperand(1));
512 /// getGlobalLinkName - Returns the asm/link name of of the specified
513 /// global variable. Should be overridden by each target asm printer to
514 /// generate the appropriate value.
515 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
516 std::string LinkName;
518 if (isa<Function>(GV)) {
519 LinkName += TAI->getFunctionAddrPrefix();
520 LinkName += Mang->getValueName(GV);
521 LinkName += TAI->getFunctionAddrSuffix();
523 LinkName += TAI->getGlobalVarAddrPrefix();
524 LinkName += Mang->getValueName(GV);
525 LinkName += TAI->getGlobalVarAddrSuffix();
531 /// EmitExternalGlobal - Emit the external reference to a global variable.
532 /// Should be overridden if an indirect reference should be used.
533 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
534 O << getGlobalLinkName(GV);
539 //===----------------------------------------------------------------------===//
540 /// LEB 128 number encoding.
542 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
543 /// representing an unsigned leb128 value.
544 void AsmPrinter::PrintULEB128(unsigned Value) const {
546 unsigned Byte = Value & 0x7f;
548 if (Value) Byte |= 0x80;
549 O << "0x" << utohexstr(Byte);
550 if (Value) O << ", ";
554 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
555 /// representing a signed leb128 value.
556 void AsmPrinter::PrintSLEB128(int Value) const {
557 int Sign = Value >> (8 * sizeof(Value) - 1);
561 unsigned Byte = Value & 0x7f;
563 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
564 if (IsMore) Byte |= 0x80;
565 O << "0x" << utohexstr(Byte);
566 if (IsMore) O << ", ";
570 //===--------------------------------------------------------------------===//
571 // Emission and print routines
574 /// PrintHex - Print a value as a hexidecimal value.
576 void AsmPrinter::PrintHex(int Value) const {
577 O << "0x" << utohexstr(static_cast<unsigned>(Value));
580 /// EOL - Print a newline character to asm stream. If a comment is present
581 /// then it will be printed first. Comments should not contain '\n'.
582 void AsmPrinter::EOL() const {
586 void AsmPrinter::EOL(const std::string &Comment) const {
587 if (VerboseAsm && !Comment.empty()) {
589 << TAI->getCommentString()
596 void AsmPrinter::EOL(const char* Comment) const {
597 if (VerboseAsm && *Comment) {
599 << TAI->getCommentString()
606 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
607 /// unsigned leb128 value.
608 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
609 if (TAI->hasLEB128()) {
613 O << TAI->getData8bitsDirective();
618 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
619 /// signed leb128 value.
620 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
621 if (TAI->hasLEB128()) {
625 O << TAI->getData8bitsDirective();
630 /// EmitInt8 - Emit a byte directive and value.
632 void AsmPrinter::EmitInt8(int Value) const {
633 O << TAI->getData8bitsDirective();
634 PrintHex(Value & 0xFF);
637 /// EmitInt16 - Emit a short directive and value.
639 void AsmPrinter::EmitInt16(int Value) const {
640 O << TAI->getData16bitsDirective();
641 PrintHex(Value & 0xFFFF);
644 /// EmitInt32 - Emit a long directive and value.
646 void AsmPrinter::EmitInt32(int Value) const {
647 O << TAI->getData32bitsDirective();
651 /// EmitInt64 - Emit a long long directive and value.
653 void AsmPrinter::EmitInt64(uint64_t Value) const {
654 if (TAI->getData64bitsDirective()) {
655 O << TAI->getData64bitsDirective();
658 if (TM.getTargetData()->isBigEndian()) {
659 EmitInt32(unsigned(Value >> 32)); O << '\n';
660 EmitInt32(unsigned(Value));
662 EmitInt32(unsigned(Value)); O << '\n';
663 EmitInt32(unsigned(Value >> 32));
668 /// toOctal - Convert the low order bits of X into an octal digit.
670 static inline char toOctal(int X) {
674 /// printStringChar - Print a char, escaped if necessary.
676 static void printStringChar(raw_ostream &O, char C) {
679 } else if (C == '\\') {
681 } else if (isprint(C)) {
685 case '\b': O << "\\b"; break;
686 case '\f': O << "\\f"; break;
687 case '\n': O << "\\n"; break;
688 case '\r': O << "\\r"; break;
689 case '\t': O << "\\t"; break;
692 O << toOctal(C >> 6);
693 O << toOctal(C >> 3);
694 O << toOctal(C >> 0);
700 /// EmitString - Emit a string with quotes and a null terminator.
701 /// Special characters are emitted properly.
702 /// \literal (Eg. '\t') \endliteral
703 void AsmPrinter::EmitString(const std::string &String) const {
704 const char* AscizDirective = TAI->getAscizDirective();
708 O << TAI->getAsciiDirective();
710 for (unsigned i = 0, N = String.size(); i < N; ++i) {
711 unsigned char C = String[i];
712 printStringChar(O, C);
721 /// EmitFile - Emit a .file directive.
722 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
723 O << "\t.file\t" << Number << " \"";
724 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
725 unsigned char C = Name[i];
726 printStringChar(O, C);
732 //===----------------------------------------------------------------------===//
734 // EmitAlignment - Emit an alignment directive to the specified power of
735 // two boundary. For example, if you pass in 3 here, you will get an 8
736 // byte alignment. If a global value is specified, and if that global has
737 // an explicit alignment requested, it will unconditionally override the
738 // alignment request. However, if ForcedAlignBits is specified, this value
739 // has final say: the ultimate alignment will be the max of ForcedAlignBits
740 // and the alignment computed with NumBits and the global.
744 // if (GV && GV->hasalignment) Align = GV->getalignment();
745 // Align = std::max(Align, ForcedAlignBits);
747 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
748 unsigned ForcedAlignBits,
749 bool UseFillExpr) const {
750 if (GV && GV->getAlignment())
751 NumBits = Log2_32(GV->getAlignment());
752 NumBits = std::max(NumBits, ForcedAlignBits);
754 if (NumBits == 0) return; // No need to emit alignment.
755 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
756 O << TAI->getAlignDirective() << NumBits;
758 unsigned FillValue = TAI->getTextAlignFillValue();
759 UseFillExpr &= IsInTextSection && FillValue;
760 if (UseFillExpr) O << ",0x" << utohexstr(FillValue);
765 /// EmitZeros - Emit a block of zeros.
767 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
769 if (TAI->getZeroDirective()) {
770 O << TAI->getZeroDirective() << NumZeros;
771 if (TAI->getZeroDirectiveSuffix())
772 O << TAI->getZeroDirectiveSuffix();
775 for (; NumZeros; --NumZeros)
776 O << TAI->getData8bitsDirective() << "0\n";
781 // Print out the specified constant, without a storage class. Only the
782 // constants valid in constant expressions can occur here.
783 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
784 if (CV->isNullValue() || isa<UndefValue>(CV))
786 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
787 O << CI->getZExtValue();
788 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
789 // This is a constant address for a global variable or function. Use the
790 // name of the variable or function as the address value, possibly
791 // decorating it with GlobalVarAddrPrefix/Suffix or
792 // FunctionAddrPrefix/Suffix (these all default to "" )
793 if (isa<Function>(GV)) {
794 O << TAI->getFunctionAddrPrefix()
795 << Mang->getValueName(GV)
796 << TAI->getFunctionAddrSuffix();
798 O << TAI->getGlobalVarAddrPrefix()
799 << Mang->getValueName(GV)
800 << TAI->getGlobalVarAddrSuffix();
802 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
803 const TargetData *TD = TM.getTargetData();
804 unsigned Opcode = CE->getOpcode();
806 case Instruction::GetElementPtr: {
807 // generate a symbolic expression for the byte address
808 const Constant *ptrVal = CE->getOperand(0);
809 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
810 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
814 EmitConstantValueOnly(ptrVal);
816 O << ") + " << Offset;
818 O << ") - " << -Offset;
820 EmitConstantValueOnly(ptrVal);
824 case Instruction::Trunc:
825 case Instruction::ZExt:
826 case Instruction::SExt:
827 case Instruction::FPTrunc:
828 case Instruction::FPExt:
829 case Instruction::UIToFP:
830 case Instruction::SIToFP:
831 case Instruction::FPToUI:
832 case Instruction::FPToSI:
833 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
835 case Instruction::BitCast:
836 return EmitConstantValueOnly(CE->getOperand(0));
838 case Instruction::IntToPtr: {
839 // Handle casts to pointers by changing them into casts to the appropriate
840 // integer type. This promotes constant folding and simplifies this code.
841 Constant *Op = CE->getOperand(0);
842 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
843 return EmitConstantValueOnly(Op);
847 case Instruction::PtrToInt: {
848 // Support only foldable casts to/from pointers that can be eliminated by
849 // changing the pointer to the appropriately sized integer type.
850 Constant *Op = CE->getOperand(0);
851 const Type *Ty = CE->getType();
853 // We can emit the pointer value into this slot if the slot is an
854 // integer slot greater or equal to the size of the pointer.
855 if (TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
856 return EmitConstantValueOnly(Op);
859 EmitConstantValueOnly(Op);
860 APInt ptrMask = APInt::getAllOnesValue(TD->getABITypeSizeInBits(Ty));
863 ptrMask.toStringUnsigned(S);
864 O << ") & " << S.c_str() << ')';
867 case Instruction::Add:
868 case Instruction::Sub:
869 case Instruction::And:
870 case Instruction::Or:
871 case Instruction::Xor:
873 EmitConstantValueOnly(CE->getOperand(0));
876 case Instruction::Add:
879 case Instruction::Sub:
882 case Instruction::And:
885 case Instruction::Or:
888 case Instruction::Xor:
895 EmitConstantValueOnly(CE->getOperand(1));
899 assert(0 && "Unsupported operator!");
902 assert(0 && "Unknown constant value!");
906 /// printAsCString - Print the specified array as a C compatible string, only if
907 /// the predicate isString is true.
909 static void printAsCString(raw_ostream &O, const ConstantArray *CVA,
911 assert(CVA->isString() && "Array is not string compatible!");
914 for (unsigned i = 0; i != LastElt; ++i) {
916 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
917 printStringChar(O, C);
922 /// EmitString - Emit a zero-byte-terminated string constant.
924 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
925 unsigned NumElts = CVA->getNumOperands();
926 if (TAI->getAscizDirective() && NumElts &&
927 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
928 O << TAI->getAscizDirective();
929 printAsCString(O, CVA, NumElts-1);
931 O << TAI->getAsciiDirective();
932 printAsCString(O, CVA, NumElts);
937 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
938 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
939 const TargetData *TD = TM.getTargetData();
940 unsigned Size = TD->getABITypeSize(CV->getType());
942 if (CV->isNullValue() || isa<UndefValue>(CV)) {
945 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
946 if (CVA->isString()) {
948 } else { // Not a string. Print the values in successive locations
949 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
950 EmitGlobalConstant(CVA->getOperand(i));
953 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
954 // Print the fields in successive locations. Pad to align if needed!
955 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
956 uint64_t sizeSoFar = 0;
957 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
958 const Constant* field = CVS->getOperand(i);
960 // Check if padding is needed and insert one or more 0s.
961 uint64_t fieldSize = TD->getABITypeSize(field->getType());
962 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
963 - cvsLayout->getElementOffset(i)) - fieldSize;
964 sizeSoFar += fieldSize + padSize;
966 // Now print the actual field value.
967 EmitGlobalConstant(field);
969 // Insert padding - this may include padding to increase the size of the
970 // current field up to the ABI size (if the struct is not packed) as well
971 // as padding to ensure that the next field starts at the right offset.
974 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
975 "Layout of constant struct may be incorrect!");
977 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
978 // FP Constants are printed as integer constants to avoid losing
980 if (CFP->getType() == Type::DoubleTy) {
981 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
982 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
983 if (TAI->getData64bitsDirective())
984 O << TAI->getData64bitsDirective() << i << '\t'
985 << TAI->getCommentString() << " double value: " << Val << '\n';
986 else if (TD->isBigEndian()) {
987 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
988 << '\t' << TAI->getCommentString()
989 << " double most significant word " << Val << '\n';
990 O << TAI->getData32bitsDirective() << unsigned(i)
991 << '\t' << TAI->getCommentString()
992 << " double least significant word " << Val << '\n';
994 O << TAI->getData32bitsDirective() << unsigned(i)
995 << '\t' << TAI->getCommentString()
996 << " double least significant word " << Val << '\n';
997 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
998 << '\t' << TAI->getCommentString()
999 << " double most significant word " << Val << '\n';
1002 } else if (CFP->getType() == Type::FloatTy) {
1003 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1004 O << TAI->getData32bitsDirective()
1005 << CFP->getValueAPF().convertToAPInt().getZExtValue()
1006 << '\t' << TAI->getCommentString() << " float " << Val << '\n';
1008 } else if (CFP->getType() == Type::X86_FP80Ty) {
1009 // all long double variants are printed as hex
1010 // api needed to prevent premature destruction
1011 APInt api = CFP->getValueAPF().convertToAPInt();
1012 const uint64_t *p = api.getRawData();
1013 APFloat DoubleVal = CFP->getValueAPF();
1014 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
1015 if (TD->isBigEndian()) {
1016 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
1017 << '\t' << TAI->getCommentString()
1018 << " long double most significant halfword of ~"
1019 << DoubleVal.convertToDouble() << '\n';
1020 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
1021 << '\t' << TAI->getCommentString()
1022 << " long double next halfword\n";
1023 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
1024 << '\t' << TAI->getCommentString()
1025 << " long double next halfword\n";
1026 O << TAI->getData16bitsDirective() << uint16_t(p[0])
1027 << '\t' << TAI->getCommentString()
1028 << " long double next halfword\n";
1029 O << TAI->getData16bitsDirective() << uint16_t(p[1])
1030 << '\t' << TAI->getCommentString()
1031 << " long double least significant halfword\n";
1033 O << TAI->getData16bitsDirective() << uint16_t(p[1])
1034 << '\t' << TAI->getCommentString()
1035 << " long double least significant halfword of ~"
1036 << DoubleVal.convertToDouble() << '\n';
1037 O << TAI->getData16bitsDirective() << uint16_t(p[0])
1038 << '\t' << TAI->getCommentString()
1039 << " long double next halfword\n";
1040 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
1041 << '\t' << TAI->getCommentString()
1042 << " long double next halfword\n";
1043 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
1044 << '\t' << TAI->getCommentString()
1045 << " long double next halfword\n";
1046 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
1047 << '\t' << TAI->getCommentString()
1048 << " long double most significant halfword\n";
1050 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
1052 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1053 // all long double variants are printed as hex
1054 // api needed to prevent premature destruction
1055 APInt api = CFP->getValueAPF().convertToAPInt();
1056 const uint64_t *p = api.getRawData();
1057 if (TD->isBigEndian()) {
1058 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
1059 << '\t' << TAI->getCommentString()
1060 << " long double most significant word\n";
1061 O << TAI->getData32bitsDirective() << uint32_t(p[0])
1062 << '\t' << TAI->getCommentString()
1063 << " long double next word\n";
1064 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
1065 << '\t' << TAI->getCommentString()
1066 << " long double next word\n";
1067 O << TAI->getData32bitsDirective() << uint32_t(p[1])
1068 << '\t' << TAI->getCommentString()
1069 << " long double least significant word\n";
1071 O << TAI->getData32bitsDirective() << uint32_t(p[1])
1072 << '\t' << TAI->getCommentString()
1073 << " long double least significant word\n";
1074 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
1075 << '\t' << TAI->getCommentString()
1076 << " long double next word\n";
1077 O << TAI->getData32bitsDirective() << uint32_t(p[0])
1078 << '\t' << TAI->getCommentString()
1079 << " long double next word\n";
1080 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
1081 << '\t' << TAI->getCommentString()
1082 << " long double most significant word\n";
1085 } else assert(0 && "Floating point constant type not handled");
1086 } else if (CV->getType()->isInteger() &&
1087 cast<IntegerType>(CV->getType())->getBitWidth() >= 64) {
1088 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1089 unsigned BitWidth = CI->getBitWidth();
1090 assert(isPowerOf2_32(BitWidth) &&
1091 "Non-power-of-2-sized integers not handled!");
1093 // We don't expect assemblers to support integer data directives
1094 // for more than 64 bits, so we emit the data in at most 64-bit
1095 // quantities at a time.
1096 const uint64_t *RawData = CI->getValue().getRawData();
1097 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1099 if (TD->isBigEndian())
1100 Val = RawData[e - i - 1];
1104 if (TAI->getData64bitsDirective())
1105 O << TAI->getData64bitsDirective() << Val << '\n';
1106 else if (TD->isBigEndian()) {
1107 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1108 << '\t' << TAI->getCommentString()
1109 << " Double-word most significant word " << Val << '\n';
1110 O << TAI->getData32bitsDirective() << unsigned(Val)
1111 << '\t' << TAI->getCommentString()
1112 << " Double-word least significant word " << Val << '\n';
1114 O << TAI->getData32bitsDirective() << unsigned(Val)
1115 << '\t' << TAI->getCommentString()
1116 << " Double-word least significant word " << Val << '\n';
1117 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1118 << '\t' << TAI->getCommentString()
1119 << " Double-word most significant word " << Val << '\n';
1124 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1125 const VectorType *PTy = CP->getType();
1127 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1128 EmitGlobalConstant(CP->getOperand(I));
1133 const Type *type = CV->getType();
1134 printDataDirective(type);
1135 EmitConstantValueOnly(CV);
1136 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1138 CI->getValue().toStringUnsigned(S, 16);
1139 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1144 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1145 // Target doesn't support this yet!
1149 /// PrintSpecial - Print information related to the specified machine instr
1150 /// that is independent of the operand, and may be independent of the instr
1151 /// itself. This can be useful for portably encoding the comment character
1152 /// or other bits of target-specific knowledge into the asmstrings. The
1153 /// syntax used is ${:comment}. Targets can override this to add support
1154 /// for their own strange codes.
1155 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1156 if (!strcmp(Code, "private")) {
1157 O << TAI->getPrivateGlobalPrefix();
1158 } else if (!strcmp(Code, "comment")) {
1159 O << TAI->getCommentString();
1160 } else if (!strcmp(Code, "uid")) {
1161 // Assign a unique ID to this machine instruction.
1162 static const MachineInstr *LastMI = 0;
1163 static const Function *F = 0;
1164 static unsigned Counter = 0U-1;
1166 // Comparing the address of MI isn't sufficient, because machineinstrs may
1167 // be allocated to the same address across functions.
1168 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1170 // If this is a new machine instruction, bump the counter.
1171 if (LastMI != MI || F != ThisF) {
1178 cerr << "Unknown special formatter '" << Code
1179 << "' for machine instr: " << *MI;
1185 /// printInlineAsm - This method formats and prints the specified machine
1186 /// instruction that is an inline asm.
1187 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1188 unsigned NumOperands = MI->getNumOperands();
1190 // Count the number of register definitions.
1191 unsigned NumDefs = 0;
1192 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
1194 assert(NumDefs != NumOperands-1 && "No asm string?");
1196 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1198 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1199 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1201 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1202 // These are useful to see where empty asm's wound up.
1203 if (AsmStr[0] == 0) {
1204 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1208 O << TAI->getInlineAsmStart() << "\n\t";
1210 // The variant of the current asmprinter.
1211 int AsmPrinterVariant = TAI->getAssemblerDialect();
1213 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1214 const char *LastEmitted = AsmStr; // One past the last character emitted.
1216 while (*LastEmitted) {
1217 switch (*LastEmitted) {
1219 // Not a special case, emit the string section literally.
1220 const char *LiteralEnd = LastEmitted+1;
1221 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1222 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1224 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1225 O.write(LastEmitted, LiteralEnd-LastEmitted);
1226 LastEmitted = LiteralEnd;
1230 ++LastEmitted; // Consume newline character.
1231 O << '\n'; // Indent code with newline.
1234 ++LastEmitted; // Consume '$' character.
1238 switch (*LastEmitted) {
1239 default: Done = false; break;
1240 case '$': // $$ -> $
1241 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1243 ++LastEmitted; // Consume second '$' character.
1245 case '(': // $( -> same as GCC's { character.
1246 ++LastEmitted; // Consume '(' character.
1247 if (CurVariant != -1) {
1248 cerr << "Nested variants found in inline asm string: '"
1252 CurVariant = 0; // We're in the first variant now.
1255 ++LastEmitted; // consume '|' character.
1256 if (CurVariant == -1) {
1257 cerr << "Found '|' character outside of variant in inline asm "
1258 << "string: '" << AsmStr << "'\n";
1261 ++CurVariant; // We're in the next variant.
1263 case ')': // $) -> same as GCC's } char.
1264 ++LastEmitted; // consume ')' character.
1265 if (CurVariant == -1) {
1266 cerr << "Found '}' character outside of variant in inline asm "
1267 << "string: '" << AsmStr << "'\n";
1275 bool HasCurlyBraces = false;
1276 if (*LastEmitted == '{') { // ${variable}
1277 ++LastEmitted; // Consume '{' character.
1278 HasCurlyBraces = true;
1281 const char *IDStart = LastEmitted;
1284 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1285 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1286 cerr << "Bad $ operand number in inline asm string: '"
1290 LastEmitted = IDEnd;
1292 char Modifier[2] = { 0, 0 };
1294 if (HasCurlyBraces) {
1295 // If we have curly braces, check for a modifier character. This
1296 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1297 if (*LastEmitted == ':') {
1298 ++LastEmitted; // Consume ':' character.
1299 if (*LastEmitted == 0) {
1300 cerr << "Bad ${:} expression in inline asm string: '"
1305 Modifier[0] = *LastEmitted;
1306 ++LastEmitted; // Consume modifier character.
1309 if (*LastEmitted != '}') {
1310 cerr << "Bad ${} expression in inline asm string: '"
1314 ++LastEmitted; // Consume '}' character.
1317 if ((unsigned)Val >= NumOperands-1) {
1318 cerr << "Invalid $ operand number in inline asm string: '"
1323 // Okay, we finally have a value number. Ask the target to print this
1325 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1330 // Scan to find the machine operand number for the operand.
1331 for (; Val; --Val) {
1332 if (OpNo >= MI->getNumOperands()) break;
1333 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1334 OpNo += (OpFlags >> 3) + 1;
1337 if (OpNo >= MI->getNumOperands()) {
1340 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1341 ++OpNo; // Skip over the ID number.
1343 if (Modifier[0]=='l') // labels are target independent
1344 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1345 false, false, false);
1347 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1348 if ((OpFlags & 7) == 4) {
1349 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1350 Modifier[0] ? Modifier : 0);
1352 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1353 Modifier[0] ? Modifier : 0);
1358 cerr << "Invalid operand found in inline asm: '"
1368 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1371 /// printImplicitDef - This method prints the specified machine instruction
1372 /// that is an implicit def.
1373 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1374 O << '\t' << TAI->getCommentString() << " implicit-def: "
1375 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1378 /// printLabel - This method prints a local label used by debug and
1379 /// exception handling tables.
1380 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1381 printLabel(MI->getOperand(0).getImm());
1384 void AsmPrinter::printLabel(unsigned Id) const {
1385 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1388 /// printDeclare - This method prints a local variable declaration used by
1390 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1391 /// entry into dwarf table.
1392 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1393 int FI = MI->getOperand(0).getIndex();
1394 GlobalValue *GV = MI->getOperand(1).getGlobal();
1395 MMI->RecordVariable(GV, FI);
1398 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1399 /// instruction, using the specified assembler variant. Targets should
1400 /// overried this to format as appropriate.
1401 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1402 unsigned AsmVariant, const char *ExtraCode) {
1403 // Target doesn't support this yet!
1407 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1408 unsigned AsmVariant,
1409 const char *ExtraCode) {
1410 // Target doesn't support this yet!
1414 /// printBasicBlockLabel - This method prints the label for the specified
1415 /// MachineBasicBlock
1416 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1419 bool printComment) const {
1421 unsigned Align = MBB->getAlignment();
1423 EmitAlignment(Log2_32(Align));
1426 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1427 << MBB->getNumber();
1430 if (printComment && MBB->getBasicBlock())
1431 O << '\t' << TAI->getCommentString() << ' '
1432 << MBB->getBasicBlock()->getNameStart();
1435 /// printPICJumpTableSetLabel - This method prints a set label for the
1436 /// specified MachineBasicBlock for a jumptable entry.
1437 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1438 const MachineBasicBlock *MBB) const {
1439 if (!TAI->getSetDirective())
1442 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1443 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1444 printBasicBlockLabel(MBB, false, false, false);
1445 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1446 << '_' << uid << '\n';
1449 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1450 const MachineBasicBlock *MBB) const {
1451 if (!TAI->getSetDirective())
1454 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1455 << getFunctionNumber() << '_' << uid << '_' << uid2
1456 << "_set_" << MBB->getNumber() << ',';
1457 printBasicBlockLabel(MBB, false, false, false);
1458 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1459 << '_' << uid << '_' << uid2 << '\n';
1462 /// printDataDirective - This method prints the asm directive for the
1464 void AsmPrinter::printDataDirective(const Type *type) {
1465 const TargetData *TD = TM.getTargetData();
1466 switch (type->getTypeID()) {
1467 case Type::IntegerTyID: {
1468 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1470 O << TAI->getData8bitsDirective();
1471 else if (BitWidth <= 16)
1472 O << TAI->getData16bitsDirective();
1473 else if (BitWidth <= 32)
1474 O << TAI->getData32bitsDirective();
1475 else if (BitWidth <= 64) {
1476 assert(TAI->getData64bitsDirective() &&
1477 "Target cannot handle 64-bit constant exprs!");
1478 O << TAI->getData64bitsDirective();
1480 assert(0 && "Target cannot handle given data directive width!");
1484 case Type::PointerTyID:
1485 if (TD->getPointerSize() == 8) {
1486 assert(TAI->getData64bitsDirective() &&
1487 "Target cannot handle 64-bit pointer exprs!");
1488 O << TAI->getData64bitsDirective();
1490 O << TAI->getData32bitsDirective();
1493 case Type::FloatTyID: case Type::DoubleTyID:
1494 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1495 assert (0 && "Should have already output floating point constant.");
1497 assert (0 && "Can't handle printing this type of thing");
1502 void AsmPrinter::printSuffixedName(const char *Name, const char *Suffix,
1503 const char *Prefix) {
1506 O << TAI->getPrivateGlobalPrefix();
1507 if (Prefix) O << Prefix;
1519 void AsmPrinter::printSuffixedName(const std::string &Name, const char* Suffix) {
1520 printSuffixedName(Name.c_str(), Suffix);
1523 void AsmPrinter::printVisibility(const std::string& Name,
1524 unsigned Visibility) const {
1525 if (Visibility == GlobalValue::HiddenVisibility) {
1526 if (const char *Directive = TAI->getHiddenDirective())
1527 O << Directive << Name << '\n';
1528 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1529 if (const char *Directive = TAI->getProtectedDirective())
1530 O << Directive << Name << '\n';
1534 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1535 if (!S->usesMetadata())
1538 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1539 if (GCPI != GCMetadataPrinters.end())
1540 return GCPI->second;
1542 const char *Name = S->getName().c_str();
1544 for (GCMetadataPrinterRegistry::iterator
1545 I = GCMetadataPrinterRegistry::begin(),
1546 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1547 if (strcmp(Name, I->getName()) == 0) {
1548 GCMetadataPrinter *GMP = I->instantiate();
1550 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1554 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";