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/Support/Mangler.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Target/TargetMachine.h"
27 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
28 : FunctionNumber(0), O(o), TM(tm),
31 PrivateGlobalPrefix("."),
32 GlobalVarAddrPrefix(""),
33 GlobalVarAddrSuffix(""),
34 FunctionAddrPrefix(""),
35 FunctionAddrSuffix(""),
36 InlineAsmStart("#APP\n"),
37 InlineAsmEnd("#NO_APP\n"),
38 ZeroDirective("\t.zero\t"),
39 AsciiDirective("\t.ascii\t"),
40 AscizDirective("\t.asciz\t"),
41 Data8bitsDirective("\t.byte\t"),
42 Data16bitsDirective("\t.short\t"),
43 Data32bitsDirective("\t.long\t"),
44 Data64bitsDirective("\t.quad\t"),
45 AlignDirective("\t.align\t"),
46 AlignmentIsInBytes(true),
47 SwitchToSectionDirective("\t.section\t"),
48 ConstantPoolSection("\t.section .rodata\n"),
49 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
50 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
52 COMMDirective("\t.comm\t"),
53 COMMDirectiveTakesAlignment(true),
54 HasDotTypeDotSizeDirective(true) {
58 /// SwitchSection - Switch to the specified section of the executable if we
59 /// are not already in it!
61 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
64 if (GV && GV->hasSection())
65 NS = SwitchToSectionDirective + GV->getSection();
67 NS = std::string("\t")+NewSection;
69 if (CurrentSection != NS) {
71 if (!CurrentSection.empty())
72 O << CurrentSection << '\n';
76 bool AsmPrinter::doInitialization(Module &M) {
77 Mang = new Mangler(M, GlobalPrefix);
79 if (!M.getModuleInlineAsm().empty())
80 O << CommentString << " Start of file scope inline assembly\n"
81 << M.getModuleInlineAsm()
82 << "\n" << CommentString << " End of file scope inline assembly\n";
84 SwitchSection("", 0); // Reset back to no section.
86 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
87 DebugInfo->AnalyzeModule(M);
93 bool AsmPrinter::doFinalization(Module &M) {
94 delete Mang; Mang = 0;
98 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
99 // What's my mangled name?
100 CurrentFnName = Mang->getValueName(MF.getFunction());
101 IncrementFunctionNumber();
104 /// EmitConstantPool - Print to the current output stream assembly
105 /// representations of the constants in the constant pool MCP. This is
106 /// used to print out constants which have been "spilled to memory" by
107 /// the code generator.
109 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
110 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
111 if (CP.empty()) return;
112 const TargetData &TD = TM.getTargetData();
114 SwitchSection(ConstantPoolSection, 0);
115 EmitAlignment(MCP->getConstantPoolAlignment());
116 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
117 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
118 << ":\t\t\t\t\t" << CommentString << " ";
119 WriteTypeSymbolic(O, CP[i].Val->getType(), 0) << '\n';
120 EmitGlobalConstant(CP[i].Val);
122 unsigned EntSize = TM.getTargetData().getTypeSize(CP[i].Val->getType());
123 unsigned ValEnd = CP[i].Offset + EntSize;
124 // Emit inter-object padding for alignment.
125 EmitZeros(CP[i+1].Offset-ValEnd);
130 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
131 /// special global used by LLVM. If so, emit it and return true, otherwise
132 /// do nothing and return false.
133 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
134 // Ignore debug and non-emitted data.
135 if (GV->getSection() == "llvm.metadata") return true;
137 if (!GV->hasAppendingLinkage()) return false;
139 assert(GV->hasInitializer() && "Not a special LLVM global!");
141 if (GV->getName() == "llvm.used")
142 return true; // No need to emit this at all.
144 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
145 SwitchSection(StaticCtorsSection, 0);
147 EmitXXStructorList(GV->getInitializer());
151 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
152 SwitchSection(StaticDtorsSection, 0);
154 EmitXXStructorList(GV->getInitializer());
161 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
162 /// function pointers, ignoring the init priority.
163 void AsmPrinter::EmitXXStructorList(Constant *List) {
164 // Should be an array of '{ int, void ()* }' structs. The first value is the
165 // init priority, which we ignore.
166 if (!isa<ConstantArray>(List)) return;
167 ConstantArray *InitList = cast<ConstantArray>(List);
168 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
169 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
170 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
172 if (CS->getOperand(1)->isNullValue())
173 return; // Found a null terminator, exit printing.
174 // Emit the function pointer.
175 EmitGlobalConstant(CS->getOperand(1));
179 /// getPreferredAlignmentLog - Return the preferred alignment of the
180 /// specified global, returned in log form. This includes an explicitly
181 /// requested alignment (if the global has one).
182 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
183 unsigned Alignment = TM.getTargetData().getTypeAlignmentShift(GV->getType());
184 if (GV->getAlignment() > (1U << Alignment))
185 Alignment = Log2_32(GV->getAlignment());
187 if (GV->hasInitializer()) {
188 // Always round up alignment of global doubles to 8 bytes.
189 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
192 // If the global is not external, see if it is large. If so, give it a
194 if (TM.getTargetData().getTypeSize(GV->getType()->getElementType()) > 128)
195 Alignment = 4; // 16-byte alignment.
201 // EmitAlignment - Emit an alignment directive to the specified power of two.
202 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
203 if (GV && GV->getAlignment())
204 NumBits = Log2_32(GV->getAlignment());
205 if (NumBits == 0) return; // No need to emit alignment.
206 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
207 O << AlignDirective << NumBits << "\n";
210 /// EmitZeros - Emit a block of zeros.
212 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
215 O << ZeroDirective << NumZeros << "\n";
217 for (; NumZeros; --NumZeros)
218 O << Data8bitsDirective << "0\n";
223 // Print out the specified constant, without a storage class. Only the
224 // constants valid in constant expressions can occur here.
225 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
226 if (CV->isNullValue() || isa<UndefValue>(CV))
228 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
229 assert(CB == ConstantBool::True);
231 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
232 if (((CI->getValue() << 32) >> 32) == CI->getValue())
235 O << (uint64_t)CI->getValue();
236 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
238 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
239 // This is a constant address for a global variable or function. Use the
240 // name of the variable or function as the address value, possibly
241 // decorating it with GlobalVarAddrPrefix/Suffix or
242 // FunctionAddrPrefix/Suffix (these all default to "" )
243 if (isa<Function>(GV))
244 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
246 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
247 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
248 const TargetData &TD = TM.getTargetData();
249 switch(CE->getOpcode()) {
250 case Instruction::GetElementPtr: {
251 // generate a symbolic expression for the byte address
252 const Constant *ptrVal = CE->getOperand(0);
253 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
254 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
257 EmitConstantValueOnly(ptrVal);
259 O << ") + " << Offset;
261 O << ") - " << -Offset;
263 EmitConstantValueOnly(ptrVal);
267 case Instruction::Cast: {
268 // Support only non-converting or widening casts for now, that is, ones
269 // that do not involve a change in value. This assertion is really gross,
270 // and may not even be a complete check.
271 Constant *Op = CE->getOperand(0);
272 const Type *OpTy = Op->getType(), *Ty = CE->getType();
274 // Remember, kids, pointers can be losslessly converted back and forth
275 // into 32-bit or wider integers, regardless of signedness. :-P
276 assert(((isa<PointerType>(OpTy)
277 && (Ty == Type::LongTy || Ty == Type::ULongTy
278 || Ty == Type::IntTy || Ty == Type::UIntTy))
279 || (isa<PointerType>(Ty)
280 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
281 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
282 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
283 && OpTy->isLosslesslyConvertibleTo(Ty))))
284 && "FIXME: Don't yet support this kind of constant cast expr");
285 EmitConstantValueOnly(Op);
288 case Instruction::Add:
290 EmitConstantValueOnly(CE->getOperand(0));
292 EmitConstantValueOnly(CE->getOperand(1));
296 assert(0 && "Unsupported operator!");
299 assert(0 && "Unknown constant value!");
303 /// toOctal - Convert the low order bits of X into an octal digit.
305 static inline char toOctal(int X) {
309 /// printAsCString - Print the specified array as a C compatible string, only if
310 /// the predicate isString is true.
312 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
314 assert(CVA->isString() && "Array is not string compatible!");
317 for (unsigned i = 0; i != LastElt; ++i) {
319 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
323 } else if (C == '\\') {
325 } else if (isprint(C)) {
329 case '\b': O << "\\b"; break;
330 case '\f': O << "\\f"; break;
331 case '\n': O << "\\n"; break;
332 case '\r': O << "\\r"; break;
333 case '\t': O << "\\t"; break;
336 O << toOctal(C >> 6);
337 O << toOctal(C >> 3);
338 O << toOctal(C >> 0);
346 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
348 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
349 const TargetData &TD = TM.getTargetData();
351 if (CV->isNullValue() || isa<UndefValue>(CV)) {
352 EmitZeros(TD.getTypeSize(CV->getType()));
354 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
355 if (CVA->isString()) {
356 unsigned NumElts = CVA->getNumOperands();
357 if (AscizDirective && NumElts &&
358 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
360 printAsCString(O, CVA, NumElts-1);
363 printAsCString(O, CVA, NumElts);
366 } else { // Not a string. Print the values in successive locations
367 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
368 EmitGlobalConstant(CVA->getOperand(i));
371 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
372 // Print the fields in successive locations. Pad to align if needed!
373 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
374 uint64_t sizeSoFar = 0;
375 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
376 const Constant* field = CVS->getOperand(i);
378 // Check if padding is needed and insert one or more 0s.
379 uint64_t fieldSize = TD.getTypeSize(field->getType());
380 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
381 : cvsLayout->MemberOffsets[i+1])
382 - cvsLayout->MemberOffsets[i]) - fieldSize;
383 sizeSoFar += fieldSize + padSize;
385 // Now print the actual field value
386 EmitGlobalConstant(field);
388 // Insert the field padding unless it's zero bytes...
391 assert(sizeSoFar == cvsLayout->StructSize &&
392 "Layout of constant struct may be incorrect!");
394 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
395 // FP Constants are printed as integer constants to avoid losing
397 double Val = CFP->getValue();
398 if (CFP->getType() == Type::DoubleTy) {
399 if (Data64bitsDirective)
400 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
401 << " double value: " << Val << "\n";
402 else if (TD.isBigEndian()) {
403 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
404 << "\t" << CommentString << " double most significant word "
406 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
407 << "\t" << CommentString << " double least significant word "
410 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
411 << "\t" << CommentString << " double least significant word " << Val
413 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
414 << "\t" << CommentString << " double most significant word " << Val
419 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
420 << " float " << Val << "\n";
423 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
424 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
425 uint64_t Val = CI->getRawValue();
427 if (Data64bitsDirective)
428 O << Data64bitsDirective << Val << "\n";
429 else if (TD.isBigEndian()) {
430 O << Data32bitsDirective << unsigned(Val >> 32)
431 << "\t" << CommentString << " Double-word most significant word "
433 O << Data32bitsDirective << unsigned(Val)
434 << "\t" << CommentString << " Double-word least significant word "
437 O << Data32bitsDirective << unsigned(Val)
438 << "\t" << CommentString << " Double-word least significant word "
440 O << Data32bitsDirective << unsigned(Val >> 32)
441 << "\t" << CommentString << " Double-word most significant word "
446 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
447 const PackedType *PTy = CP->getType();
449 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
450 EmitGlobalConstant(CP->getOperand(I));
455 const Type *type = CV->getType();
456 switch (type->getTypeID()) {
458 case Type::UByteTyID: case Type::SByteTyID:
459 O << Data8bitsDirective;
461 case Type::UShortTyID: case Type::ShortTyID:
462 O << Data16bitsDirective;
464 case Type::PointerTyID:
465 if (TD.getPointerSize() == 8) {
466 O << Data64bitsDirective;
469 //Fall through for pointer size == int size
470 case Type::UIntTyID: case Type::IntTyID:
471 O << Data32bitsDirective;
473 case Type::ULongTyID: case Type::LongTyID:
474 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
475 O << Data64bitsDirective;
477 case Type::FloatTyID: case Type::DoubleTyID:
478 assert (0 && "Should have already output floating point constant.");
480 assert (0 && "Can't handle printing this type of thing");
483 EmitConstantValueOnly(CV);
487 /// printInlineAsm - This method formats and prints the specified machine
488 /// instruction that is an inline asm.
489 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
491 unsigned NumOperands = MI->getNumOperands();
493 // Count the number of register definitions.
494 unsigned NumDefs = 0;
495 for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
496 assert(NumDefs != NumOperands-1 && "No asm string?");
498 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
500 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
501 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
503 // The variant of the current asmprinter: FIXME: change.
504 int AsmPrinterVariant = 0;
506 int CurVariant = -1; // The number of the {.|.|.} region we are in.
507 const char *LastEmitted = AsmStr; // One past the last character emitted.
509 while (*LastEmitted) {
510 switch (*LastEmitted) {
512 // Not a special case, emit the string section literally.
513 const char *LiteralEnd = LastEmitted+1;
514 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
515 *LiteralEnd != '}' && *LiteralEnd != '$')
517 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
518 O.write(LastEmitted, LiteralEnd-LastEmitted);
519 LastEmitted = LiteralEnd;
523 ++LastEmitted; // Consume '$' character.
524 if (*LastEmitted == '$') { // $$ -> $
525 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
527 ++LastEmitted; // Consume second '$' character.
531 bool HasCurlyBraces = false;
532 if (*LastEmitted == '{') { // ${variable}
533 ++LastEmitted; // Consume '{' character.
534 HasCurlyBraces = true;
537 const char *IDStart = LastEmitted;
539 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
540 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
541 std::cerr << "Bad $ operand number in inline asm string: '"
547 char Modifier[2] = { 0, 0 };
549 if (HasCurlyBraces) {
550 // If we have curly braces, check for a modifier character. This
551 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
552 if (*LastEmitted == ':') {
553 ++LastEmitted; // Consume ':' character.
554 if (*LastEmitted == 0) {
555 std::cerr << "Bad ${:} expression in inline asm string: '"
560 Modifier[0] = *LastEmitted;
561 ++LastEmitted; // Consume modifier character.
564 if (*LastEmitted != '}') {
565 std::cerr << "Bad ${} expression in inline asm string: '"
569 ++LastEmitted; // Consume '}' character.
572 if ((unsigned)Val >= NumOperands-1) {
573 std::cerr << "Invalid $ operand number in inline asm string: '"
578 // Okay, we finally have a value number. Ask the target to print this
580 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
583 // Scan to find the machine operand number for the operand.
585 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
586 OpNo += (OpFlags >> 3) + 1;
589 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
590 ++OpNo; // Skip over the ID number.
593 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
594 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
595 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
596 Modifier[0] ? Modifier : 0);
598 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
599 Modifier[0] ? Modifier : 0);
602 std::cerr << "Invalid operand found in inline asm: '"
611 ++LastEmitted; // Consume '{' character.
612 if (CurVariant != -1) {
613 std::cerr << "Nested variants found in inline asm string: '"
617 CurVariant = 0; // We're in the first variant now.
620 ++LastEmitted; // consume '|' character.
621 if (CurVariant == -1) {
622 std::cerr << "Found '|' character outside of variant in inline asm "
623 << "string: '" << AsmStr << "'\n";
626 ++CurVariant; // We're in the next variant.
629 ++LastEmitted; // consume '}' character.
630 if (CurVariant == -1) {
631 std::cerr << "Found '}' character outside of variant in inline asm "
632 << "string: '" << AsmStr << "'\n";
639 O << "\n" << InlineAsmEnd;
642 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
643 /// instruction, using the specified assembler variant. Targets should
644 /// overried this to format as appropriate.
645 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
646 unsigned AsmVariant, const char *ExtraCode) {
647 // Target doesn't support this yet!
651 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
653 const char *ExtraCode) {
654 // Target doesn't support this yet!