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/DerivedTypes.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Module.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/Support/Mangler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Target/TargetMachine.h"
25 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
26 : FunctionNumber(0), O(o), TM(tm),
29 PrivateGlobalPrefix("."),
30 GlobalVarAddrPrefix(""),
31 GlobalVarAddrSuffix(""),
32 FunctionAddrPrefix(""),
33 FunctionAddrSuffix(""),
34 ZeroDirective("\t.zero\t"),
35 AsciiDirective("\t.ascii\t"),
36 AscizDirective("\t.asciz\t"),
37 Data8bitsDirective("\t.byte\t"),
38 Data16bitsDirective("\t.short\t"),
39 Data32bitsDirective("\t.long\t"),
40 Data64bitsDirective("\t.quad\t"),
41 AlignDirective("\t.align\t"),
42 AlignmentIsInBytes(true),
43 SwitchToSectionDirective("\t.section\t"),
44 ConstantPoolSection("\t.section .rodata\n"),
45 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
46 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
48 COMMDirective("\t.comm\t"),
49 COMMDirectiveTakesAlignment(true),
50 HasDotTypeDotSizeDirective(true) {
54 /// SwitchSection - Switch to the specified section of the executable if we
55 /// are not already in it!
57 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
60 if (GV && GV->hasSection())
61 NS = SwitchToSectionDirective + GV->getSection();
63 NS = std::string("\t")+NewSection;
65 if (CurrentSection != NS) {
67 if (!CurrentSection.empty())
68 O << CurrentSection << '\n';
72 bool AsmPrinter::doInitialization(Module &M) {
73 Mang = new Mangler(M, GlobalPrefix);
75 if (!M.getModuleInlineAsm().empty())
76 O << CommentString << " Start of file scope inline assembly\n"
77 << M.getModuleInlineAsm()
78 << "\n" << CommentString << " End of file scope inline assembly\n";
80 SwitchSection("", 0); // Reset back to no section.
82 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
83 DebugInfo->AnalyzeModule(M);
89 bool AsmPrinter::doFinalization(Module &M) {
90 delete Mang; Mang = 0;
94 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
95 // What's my mangled name?
96 CurrentFnName = Mang->getValueName(MF.getFunction());
97 IncrementFunctionNumber();
100 /// EmitConstantPool - Print to the current output stream assembly
101 /// representations of the constants in the constant pool MCP. This is
102 /// used to print out constants which have been "spilled to memory" by
103 /// the code generator.
105 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
106 const std::vector<Constant*> &CP = MCP->getConstants();
107 if (CP.empty()) return;
108 const TargetData &TD = TM.getTargetData();
110 SwitchSection(ConstantPoolSection, 0);
111 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
112 // FIXME: force doubles to be naturally aligned. We should handle this
113 // more correctly in the future.
114 unsigned Alignment = TD.getTypeAlignmentShift(CP[i]->getType());
115 if (CP[i]->getType() == Type::DoubleTy && Alignment < 3) Alignment = 3;
117 EmitAlignment(Alignment);
118 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
119 << ":\t\t\t\t\t" << CommentString << *CP[i] << '\n';
120 EmitGlobalConstant(CP[i]);
124 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
125 /// special global used by LLVM. If so, emit it and return true, otherwise
126 /// do nothing and return false.
127 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
128 assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
129 "Not a special LLVM global!");
131 if (GV->getName() == "llvm.used")
132 return true; // No need to emit this at all.
134 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
135 SwitchSection(StaticCtorsSection, 0);
137 EmitXXStructorList(GV->getInitializer());
141 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
142 SwitchSection(StaticDtorsSection, 0);
144 EmitXXStructorList(GV->getInitializer());
151 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
152 /// function pointers, ignoring the init priority.
153 void AsmPrinter::EmitXXStructorList(Constant *List) {
154 // Should be an array of '{ int, void ()* }' structs. The first value is the
155 // init priority, which we ignore.
156 if (!isa<ConstantArray>(List)) return;
157 ConstantArray *InitList = cast<ConstantArray>(List);
158 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
159 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
160 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
162 if (CS->getOperand(1)->isNullValue())
163 return; // Found a null terminator, exit printing.
164 // Emit the function pointer.
165 EmitGlobalConstant(CS->getOperand(1));
170 // EmitAlignment - Emit an alignment directive to the specified power of two.
171 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
172 if (GV && GV->getAlignment())
173 NumBits = Log2_32(GV->getAlignment());
174 if (NumBits == 0) return; // No need to emit alignment.
175 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
176 O << AlignDirective << NumBits << "\n";
179 /// EmitZeros - Emit a block of zeros.
181 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
184 O << ZeroDirective << NumZeros << "\n";
186 for (; NumZeros; --NumZeros)
187 O << Data8bitsDirective << "0\n";
192 // Print out the specified constant, without a storage class. Only the
193 // constants valid in constant expressions can occur here.
194 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
195 if (CV->isNullValue() || isa<UndefValue>(CV))
197 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
198 assert(CB == ConstantBool::True);
200 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
201 if (((CI->getValue() << 32) >> 32) == CI->getValue())
204 O << (uint64_t)CI->getValue();
205 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
207 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
208 // This is a constant address for a global variable or function. Use the
209 // name of the variable or function as the address value, possibly
210 // decorating it with GlobalVarAddrPrefix/Suffix or
211 // FunctionAddrPrefix/Suffix (these all default to "" )
212 if (isa<Function>(GV))
213 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
215 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
216 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
217 const TargetData &TD = TM.getTargetData();
218 switch(CE->getOpcode()) {
219 case Instruction::GetElementPtr: {
220 // generate a symbolic expression for the byte address
221 const Constant *ptrVal = CE->getOperand(0);
222 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
223 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
226 EmitConstantValueOnly(ptrVal);
228 O << ") + " << Offset;
230 O << ") - " << -Offset;
232 EmitConstantValueOnly(ptrVal);
236 case Instruction::Cast: {
237 // Support only non-converting or widening casts for now, that is, ones
238 // that do not involve a change in value. This assertion is really gross,
239 // and may not even be a complete check.
240 Constant *Op = CE->getOperand(0);
241 const Type *OpTy = Op->getType(), *Ty = CE->getType();
243 // Remember, kids, pointers can be losslessly converted back and forth
244 // into 32-bit or wider integers, regardless of signedness. :-P
245 assert(((isa<PointerType>(OpTy)
246 && (Ty == Type::LongTy || Ty == Type::ULongTy
247 || Ty == Type::IntTy || Ty == Type::UIntTy))
248 || (isa<PointerType>(Ty)
249 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
250 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
251 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
252 && OpTy->isLosslesslyConvertibleTo(Ty))))
253 && "FIXME: Don't yet support this kind of constant cast expr");
254 EmitConstantValueOnly(Op);
257 case Instruction::Add:
259 EmitConstantValueOnly(CE->getOperand(0));
261 EmitConstantValueOnly(CE->getOperand(1));
265 assert(0 && "Unsupported operator!");
268 assert(0 && "Unknown constant value!");
272 /// toOctal - Convert the low order bits of X into an octal digit.
274 static inline char toOctal(int X) {
278 /// printAsCString - Print the specified array as a C compatible string, only if
279 /// the predicate isString is true.
281 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
283 assert(CVA->isString() && "Array is not string compatible!");
286 for (unsigned i = 0; i != LastElt; ++i) {
288 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
292 } else if (C == '\\') {
294 } else if (isprint(C)) {
298 case '\b': O << "\\b"; break;
299 case '\f': O << "\\f"; break;
300 case '\n': O << "\\n"; break;
301 case '\r': O << "\\r"; break;
302 case '\t': O << "\\t"; break;
305 O << toOctal(C >> 6);
306 O << toOctal(C >> 3);
307 O << toOctal(C >> 0);
315 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
317 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
318 const TargetData &TD = TM.getTargetData();
320 if (CV->isNullValue() || isa<UndefValue>(CV)) {
321 EmitZeros(TD.getTypeSize(CV->getType()));
323 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
324 if (CVA->isString()) {
325 unsigned NumElts = CVA->getNumOperands();
326 if (AscizDirective && NumElts &&
327 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
329 printAsCString(O, CVA, NumElts-1);
332 printAsCString(O, CVA, NumElts);
335 } else { // Not a string. Print the values in successive locations
336 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
337 EmitGlobalConstant(CVA->getOperand(i));
340 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
341 // Print the fields in successive locations. Pad to align if needed!
342 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
343 uint64_t sizeSoFar = 0;
344 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
345 const Constant* field = CVS->getOperand(i);
347 // Check if padding is needed and insert one or more 0s.
348 uint64_t fieldSize = TD.getTypeSize(field->getType());
349 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
350 : cvsLayout->MemberOffsets[i+1])
351 - cvsLayout->MemberOffsets[i]) - fieldSize;
352 sizeSoFar += fieldSize + padSize;
354 // Now print the actual field value
355 EmitGlobalConstant(field);
357 // Insert the field padding unless it's zero bytes...
360 assert(sizeSoFar == cvsLayout->StructSize &&
361 "Layout of constant struct may be incorrect!");
363 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
364 // FP Constants are printed as integer constants to avoid losing
366 double Val = CFP->getValue();
367 if (CFP->getType() == Type::DoubleTy) {
368 if (Data64bitsDirective)
369 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
370 << " double value: " << Val << "\n";
371 else if (TD.isBigEndian()) {
372 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
373 << "\t" << CommentString << " double most significant word "
375 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
376 << "\t" << CommentString << " double least significant word "
379 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
380 << "\t" << CommentString << " double least significant word " << Val
382 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
383 << "\t" << CommentString << " double most significant word " << Val
388 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
389 << " float " << Val << "\n";
392 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
393 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
394 uint64_t Val = CI->getRawValue();
396 if (Data64bitsDirective)
397 O << Data64bitsDirective << Val << "\n";
398 else if (TD.isBigEndian()) {
399 O << Data32bitsDirective << unsigned(Val >> 32)
400 << "\t" << CommentString << " Double-word most significant word "
402 O << Data32bitsDirective << unsigned(Val)
403 << "\t" << CommentString << " Double-word least significant word "
406 O << Data32bitsDirective << unsigned(Val)
407 << "\t" << CommentString << " Double-word least significant word "
409 O << Data32bitsDirective << unsigned(Val >> 32)
410 << "\t" << CommentString << " Double-word most significant word "
415 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
416 const PackedType *PTy = CP->getType();
418 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
419 EmitGlobalConstant(CP->getOperand(I));
424 const Type *type = CV->getType();
425 switch (type->getTypeID()) {
427 case Type::UByteTyID: case Type::SByteTyID:
428 O << Data8bitsDirective;
430 case Type::UShortTyID: case Type::ShortTyID:
431 O << Data16bitsDirective;
433 case Type::PointerTyID:
434 if (TD.getPointerSize() == 8) {
435 O << Data64bitsDirective;
438 //Fall through for pointer size == int size
439 case Type::UIntTyID: case Type::IntTyID:
440 O << Data32bitsDirective;
442 case Type::ULongTyID: case Type::LongTyID:
443 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
444 O << Data64bitsDirective;
446 case Type::FloatTyID: case Type::DoubleTyID:
447 assert (0 && "Should have already output floating point constant.");
449 assert (0 && "Can't handle printing this type of thing");
452 EmitConstantValueOnly(CV);
456 /// printInlineAsm - This method formats and prints the specified machine
457 /// instruction that is an inline asm.
458 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
459 unsigned NumOperands = MI->getNumOperands();
461 // Count the number of register definitions.
462 unsigned NumDefs = 0;
463 for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
464 assert(NumDefs != NumOperands-1 && "No asm string?");
466 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
468 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();