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"
24 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
25 : FunctionNumber(0), O(o), TM(tm),
28 PrivateGlobalPrefix("."),
29 GlobalVarAddrPrefix(""),
30 GlobalVarAddrSuffix(""),
31 FunctionAddrPrefix(""),
32 FunctionAddrSuffix(""),
33 ZeroDirective("\t.zero\t"),
34 AsciiDirective("\t.ascii\t"),
35 AscizDirective("\t.asciz\t"),
36 Data8bitsDirective("\t.byte\t"),
37 Data16bitsDirective("\t.short\t"),
38 Data32bitsDirective("\t.long\t"),
39 Data64bitsDirective("\t.quad\t"),
40 AlignDirective("\t.align\t"),
41 AlignmentIsInBytes(true),
42 SwitchToSectionDirective("\t.section\t"),
43 ConstantPoolSection("\t.section .rodata\n"),
44 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
45 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
47 COMMDirective("\t.comm\t"),
48 COMMDirectiveTakesAlignment(true),
49 HasDotTypeDotSizeDirective(true) {
53 /// SwitchSection - Switch to the specified section of the executable if we
54 /// are not already in it!
56 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
59 if (GV && GV->hasSection())
60 NS = SwitchToSectionDirective + GV->getSection();
62 NS = std::string("\t")+NewSection;
64 if (CurrentSection != NS) {
66 if (!CurrentSection.empty())
67 O << CurrentSection << '\n';
71 bool AsmPrinter::doInitialization(Module &M) {
72 Mang = new Mangler(M, GlobalPrefix);
73 SwitchSection("", 0); // Reset back to no section.
77 bool AsmPrinter::doFinalization(Module &M) {
78 delete Mang; Mang = 0;
82 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
83 // What's my mangled name?
84 CurrentFnName = Mang->getValueName(MF.getFunction());
85 IncrementFunctionNumber();
88 /// EmitConstantPool - Print to the current output stream assembly
89 /// representations of the constants in the constant pool MCP. This is
90 /// used to print out constants which have been "spilled to memory" by
91 /// the code generator.
93 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
94 const std::vector<Constant*> &CP = MCP->getConstants();
95 if (CP.empty()) return;
96 const TargetData &TD = TM.getTargetData();
98 SwitchSection(ConstantPoolSection, 0);
99 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
100 // FIXME: force doubles to be naturally aligned. We should handle this
101 // more correctly in the future.
102 unsigned Alignment = TD.getTypeAlignmentShift(CP[i]->getType());
103 if (CP[i]->getType() == Type::DoubleTy && Alignment < 3) Alignment = 3;
105 EmitAlignment(Alignment);
106 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
107 << ":\t\t\t\t\t" << CommentString << *CP[i] << '\n';
108 EmitGlobalConstant(CP[i]);
112 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
113 /// special global used by LLVM. If so, emit it and return true, otherwise
114 /// do nothing and return false.
115 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
116 assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
117 "Not a special LLVM global!");
119 if (GV->getName() == "llvm.used")
120 return true; // No need to emit this at all.
122 if (GV->getName() == "llvm.global_ctors") {
123 SwitchSection(StaticCtorsSection, 0);
125 EmitXXStructorList(GV->getInitializer());
129 if (GV->getName() == "llvm.global_dtors") {
130 SwitchSection(StaticDtorsSection, 0);
132 EmitXXStructorList(GV->getInitializer());
139 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
140 /// function pointers, ignoring the init priority.
141 void AsmPrinter::EmitXXStructorList(Constant *List) {
142 // Should be an array of '{ int, void ()* }' structs. The first value is the
143 // init priority, which we ignore.
144 if (!isa<ConstantArray>(List)) return;
145 ConstantArray *InitList = cast<ConstantArray>(List);
146 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
147 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
148 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
149 // Emit the function pointer.
150 EmitGlobalConstant(CS->getOperand(1));
155 // EmitAlignment - Emit an alignment directive to the specified power of two.
156 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
157 if (GV && GV->getAlignment())
158 NumBits = Log2_32(GV->getAlignment());
159 if (NumBits == 0) return; // No need to emit alignment.
160 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
161 O << AlignDirective << NumBits << "\n";
164 /// EmitZeros - Emit a block of zeros.
166 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
169 O << ZeroDirective << NumZeros << "\n";
171 for (; NumZeros; --NumZeros)
172 O << Data8bitsDirective << "0\n";
177 // Print out the specified constant, without a storage class. Only the
178 // constants valid in constant expressions can occur here.
179 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
180 if (CV->isNullValue() || isa<UndefValue>(CV))
182 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
183 assert(CB == ConstantBool::True);
185 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
186 if (((CI->getValue() << 32) >> 32) == CI->getValue())
189 O << (uint64_t)CI->getValue();
190 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
192 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
193 // This is a constant address for a global variable or function. Use the
194 // name of the variable or function as the address value, possibly
195 // decorating it with GlobalVarAddrPrefix/Suffix or
196 // FunctionAddrPrefix/Suffix (these all default to "" )
197 if (isa<Function>(GV))
198 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
200 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
201 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
202 const TargetData &TD = TM.getTargetData();
203 switch(CE->getOpcode()) {
204 case Instruction::GetElementPtr: {
205 // generate a symbolic expression for the byte address
206 const Constant *ptrVal = CE->getOperand(0);
207 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
208 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
211 EmitConstantValueOnly(ptrVal);
213 O << ") + " << Offset;
215 O << ") - " << -Offset;
217 EmitConstantValueOnly(ptrVal);
221 case Instruction::Cast: {
222 // Support only non-converting or widening casts for now, that is, ones
223 // that do not involve a change in value. This assertion is really gross,
224 // and may not even be a complete check.
225 Constant *Op = CE->getOperand(0);
226 const Type *OpTy = Op->getType(), *Ty = CE->getType();
228 // Remember, kids, pointers can be losslessly converted back and forth
229 // into 32-bit or wider integers, regardless of signedness. :-P
230 assert(((isa<PointerType>(OpTy)
231 && (Ty == Type::LongTy || Ty == Type::ULongTy
232 || Ty == Type::IntTy || Ty == Type::UIntTy))
233 || (isa<PointerType>(Ty)
234 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
235 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
236 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
237 && OpTy->isLosslesslyConvertibleTo(Ty))))
238 && "FIXME: Don't yet support this kind of constant cast expr");
239 EmitConstantValueOnly(Op);
242 case Instruction::Add:
244 EmitConstantValueOnly(CE->getOperand(0));
246 EmitConstantValueOnly(CE->getOperand(1));
250 assert(0 && "Unsupported operator!");
253 assert(0 && "Unknown constant value!");
257 /// toOctal - Convert the low order bits of X into an octal digit.
259 static inline char toOctal(int X) {
263 /// printAsCString - Print the specified array as a C compatible string, only if
264 /// the predicate isString is true.
266 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
268 assert(CVA->isString() && "Array is not string compatible!");
271 for (unsigned i = 0; i != LastElt; ++i) {
273 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
277 } else if (C == '\\') {
279 } else if (isprint(C)) {
283 case '\b': O << "\\b"; break;
284 case '\f': O << "\\f"; break;
285 case '\n': O << "\\n"; break;
286 case '\r': O << "\\r"; break;
287 case '\t': O << "\\t"; break;
290 O << toOctal(C >> 6);
291 O << toOctal(C >> 3);
292 O << toOctal(C >> 0);
300 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
302 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
303 const TargetData &TD = TM.getTargetData();
305 if (CV->isNullValue() || isa<UndefValue>(CV)) {
306 EmitZeros(TD.getTypeSize(CV->getType()));
308 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
309 if (CVA->isString()) {
310 unsigned NumElts = CVA->getNumOperands();
311 if (AscizDirective && NumElts &&
312 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
314 printAsCString(O, CVA, NumElts-1);
317 printAsCString(O, CVA, NumElts);
320 } else { // Not a string. Print the values in successive locations
321 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
322 EmitGlobalConstant(CVA->getOperand(i));
325 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
326 // Print the fields in successive locations. Pad to align if needed!
327 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
328 uint64_t sizeSoFar = 0;
329 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
330 const Constant* field = CVS->getOperand(i);
332 // Check if padding is needed and insert one or more 0s.
333 uint64_t fieldSize = TD.getTypeSize(field->getType());
334 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
335 : cvsLayout->MemberOffsets[i+1])
336 - cvsLayout->MemberOffsets[i]) - fieldSize;
337 sizeSoFar += fieldSize + padSize;
339 // Now print the actual field value
340 EmitGlobalConstant(field);
342 // Insert the field padding unless it's zero bytes...
345 assert(sizeSoFar == cvsLayout->StructSize &&
346 "Layout of constant struct may be incorrect!");
348 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
349 // FP Constants are printed as integer constants to avoid losing
351 double Val = CFP->getValue();
352 if (CFP->getType() == Type::DoubleTy) {
353 if (Data64bitsDirective)
354 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
355 << " double value: " << Val << "\n";
356 else if (TD.isBigEndian()) {
357 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
358 << "\t" << CommentString << " double most significant word "
360 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
361 << "\t" << CommentString << " double least significant word "
364 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
365 << "\t" << CommentString << " double least significant word " << Val
367 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
368 << "\t" << CommentString << " double most significant word " << Val
373 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
374 << " float " << Val << "\n";
377 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
378 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
379 uint64_t Val = CI->getRawValue();
381 if (Data64bitsDirective)
382 O << Data64bitsDirective << Val << "\n";
383 else if (TD.isBigEndian()) {
384 O << Data32bitsDirective << unsigned(Val >> 32)
385 << "\t" << CommentString << " Double-word most significant word "
387 O << Data32bitsDirective << unsigned(Val)
388 << "\t" << CommentString << " Double-word least significant word "
391 O << Data32bitsDirective << unsigned(Val)
392 << "\t" << CommentString << " Double-word least significant word "
394 O << Data32bitsDirective << unsigned(Val >> 32)
395 << "\t" << CommentString << " Double-word most significant word "
400 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
401 const PackedType *PTy = CP->getType();
403 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
404 EmitGlobalConstant(CP->getOperand(I));
409 const Type *type = CV->getType();
410 switch (type->getTypeID()) {
412 case Type::UByteTyID: case Type::SByteTyID:
413 O << Data8bitsDirective;
415 case Type::UShortTyID: case Type::ShortTyID:
416 O << Data16bitsDirective;
418 case Type::PointerTyID:
419 if (TD.getPointerSize() == 8) {
420 O << Data64bitsDirective;
423 //Fall through for pointer size == int size
424 case Type::UIntTyID: case Type::IntTyID:
425 O << Data32bitsDirective;
427 case Type::ULongTyID: case Type::LongTyID:
428 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
429 O << Data64bitsDirective;
431 case Type::FloatTyID: case Type::DoubleTyID:
432 assert (0 && "Should have already output floating point constant.");
434 assert (0 && "Can't handle printing this type of thing");
437 EmitConstantValueOnly(CV);