Implement the AsmPrinter::getPreferredAlignmentLog method.
[oota-llvm.git] / lib / CodeGen / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
22 #include <iostream>
23 #include <cerrno>
24 using namespace llvm;
25
26 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
27 : FunctionNumber(0), O(o), TM(tm),
28   CommentString("#"),
29   GlobalPrefix(""),
30   PrivateGlobalPrefix("."),
31   GlobalVarAddrPrefix(""),
32   GlobalVarAddrSuffix(""),
33   FunctionAddrPrefix(""),
34   FunctionAddrSuffix(""),
35   ZeroDirective("\t.zero\t"),
36   AsciiDirective("\t.ascii\t"),
37   AscizDirective("\t.asciz\t"),
38   Data8bitsDirective("\t.byte\t"),
39   Data16bitsDirective("\t.short\t"),
40   Data32bitsDirective("\t.long\t"),
41   Data64bitsDirective("\t.quad\t"),
42   AlignDirective("\t.align\t"),
43   AlignmentIsInBytes(true),
44   SwitchToSectionDirective("\t.section\t"),
45   ConstantPoolSection("\t.section .rodata\n"),
46   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
47   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
48   LCOMMDirective(0),
49   COMMDirective("\t.comm\t"),
50   COMMDirectiveTakesAlignment(true),
51   HasDotTypeDotSizeDirective(true) {
52 }
53
54
55 /// SwitchSection - Switch to the specified section of the executable if we
56 /// are not already in it!
57 ///
58 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
59   std::string NS;
60   
61   if (GV && GV->hasSection())
62     NS = SwitchToSectionDirective + GV->getSection();
63   else
64     NS = std::string("\t")+NewSection;
65   
66   if (CurrentSection != NS) {
67     CurrentSection = NS;
68     if (!CurrentSection.empty())
69       O << CurrentSection << '\n';
70   }
71 }
72
73 bool AsmPrinter::doInitialization(Module &M) {
74   Mang = new Mangler(M, GlobalPrefix);
75   
76   if (!M.getModuleInlineAsm().empty())
77     O << CommentString << " Start of file scope inline assembly\n"
78       << M.getModuleInlineAsm()
79       << "\n" << CommentString << " End of file scope inline assembly\n";
80
81   SwitchSection("", 0);   // Reset back to no section.
82   
83   if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
84     DebugInfo->AnalyzeModule(M);
85   }
86   
87   return false;
88 }
89
90 bool AsmPrinter::doFinalization(Module &M) {
91   delete Mang; Mang = 0;
92   return false;
93 }
94
95 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
96   // What's my mangled name?
97   CurrentFnName = Mang->getValueName(MF.getFunction());
98   IncrementFunctionNumber();
99 }
100
101 /// EmitConstantPool - Print to the current output stream assembly
102 /// representations of the constants in the constant pool MCP. This is
103 /// used to print out constants which have been "spilled to memory" by
104 /// the code generator.
105 ///
106 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
107   const std::vector<std::pair<Constant*, unsigned> > &CP = MCP->getConstants();
108   if (CP.empty()) return;
109   const TargetData &TD = TM.getTargetData();
110   
111   SwitchSection(ConstantPoolSection, 0);
112   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
113     // FIXME: force doubles to be naturally aligned.  We should handle this
114     // more correctly in the future.
115     unsigned Alignment = CP[i].second;
116     if (Alignment == 0) {
117       Alignment = TD.getTypeAlignmentShift(CP[i].first->getType());
118       if (CP[i].first->getType() == Type::DoubleTy && Alignment < 3)
119         Alignment = 3;
120     }
121     
122     EmitAlignment(Alignment);
123     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
124       << ":\t\t\t\t\t" << CommentString << *CP[i].first << '\n';
125     EmitGlobalConstant(CP[i].first);
126   }
127 }
128
129 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
130 /// special global used by LLVM.  If so, emit it and return true, otherwise
131 /// do nothing and return false.
132 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
133   assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
134          "Not a special LLVM global!");
135   
136   if (GV->getName() == "llvm.used")
137     return true;  // No need to emit this at all.
138
139   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
140     SwitchSection(StaticCtorsSection, 0);
141     EmitAlignment(2, 0);
142     EmitXXStructorList(GV->getInitializer());
143     return true;
144   } 
145   
146   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
147     SwitchSection(StaticDtorsSection, 0);
148     EmitAlignment(2, 0);
149     EmitXXStructorList(GV->getInitializer());
150     return true;
151   }
152   
153   return false;
154 }
155
156 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
157 /// function pointers, ignoring the init priority.
158 void AsmPrinter::EmitXXStructorList(Constant *List) {
159   // Should be an array of '{ int, void ()* }' structs.  The first value is the
160   // init priority, which we ignore.
161   if (!isa<ConstantArray>(List)) return;
162   ConstantArray *InitList = cast<ConstantArray>(List);
163   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
164     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
165       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
166
167       if (CS->getOperand(1)->isNullValue())
168         return;  // Found a null terminator, exit printing.
169       // Emit the function pointer.
170       EmitGlobalConstant(CS->getOperand(1));
171     }
172 }
173
174 /// getPreferredAlignmentLog - Return the preferred alignment of the
175 /// specified global, returned in log form.  This includes an explicitly
176 /// requested alignment (if the global has one).
177 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
178   unsigned Alignment = TM.getTargetData().getTypeAlignmentShift(GV->getType());
179   if (GV->getAlignment() > (1U << Alignment))
180     Alignment = Log2_32(GV->getAlignment());
181   
182   if (GV->hasInitializer() && Alignment < 4) {
183     // If the global is not external, see if it is large.  If so, give it a
184     // larger alignment.
185     if (TM.getTargetData().getTypeSize(GV->getType()->getElementType()) > 128)
186       Alignment = 4;    // 16-byte alignment.
187   }
188   return Alignment;
189 }
190
191 // EmitAlignment - Emit an alignment directive to the specified power of two.
192 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
193   if (GV && GV->getAlignment())
194     NumBits = Log2_32(GV->getAlignment());
195   if (NumBits == 0) return;   // No need to emit alignment.
196   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
197   O << AlignDirective << NumBits << "\n";
198 }
199
200 /// EmitZeros - Emit a block of zeros.
201 ///
202 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
203   if (NumZeros) {
204     if (ZeroDirective)
205       O << ZeroDirective << NumZeros << "\n";
206     else {
207       for (; NumZeros; --NumZeros)
208         O << Data8bitsDirective << "0\n";
209     }
210   }
211 }
212
213 // Print out the specified constant, without a storage class.  Only the
214 // constants valid in constant expressions can occur here.
215 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
216   if (CV->isNullValue() || isa<UndefValue>(CV))
217     O << "0";
218   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
219     assert(CB == ConstantBool::True);
220     O << "1";
221   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
222     if (((CI->getValue() << 32) >> 32) == CI->getValue())
223       O << CI->getValue();
224     else
225       O << (uint64_t)CI->getValue();
226   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
227     O << CI->getValue();
228   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
229     // This is a constant address for a global variable or function. Use the
230     // name of the variable or function as the address value, possibly
231     // decorating it with GlobalVarAddrPrefix/Suffix or
232     // FunctionAddrPrefix/Suffix (these all default to "" )
233     if (isa<Function>(GV))
234       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
235     else
236       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
237   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
238     const TargetData &TD = TM.getTargetData();
239     switch(CE->getOpcode()) {
240     case Instruction::GetElementPtr: {
241       // generate a symbolic expression for the byte address
242       const Constant *ptrVal = CE->getOperand(0);
243       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
244       if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
245         if (Offset)
246           O << "(";
247         EmitConstantValueOnly(ptrVal);
248         if (Offset > 0)
249           O << ") + " << Offset;
250         else if (Offset < 0)
251           O << ") - " << -Offset;
252       } else {
253         EmitConstantValueOnly(ptrVal);
254       }
255       break;
256     }
257     case Instruction::Cast: {
258       // Support only non-converting or widening casts for now, that is, ones
259       // that do not involve a change in value.  This assertion is really gross,
260       // and may not even be a complete check.
261       Constant *Op = CE->getOperand(0);
262       const Type *OpTy = Op->getType(), *Ty = CE->getType();
263
264       // Remember, kids, pointers can be losslessly converted back and forth
265       // into 32-bit or wider integers, regardless of signedness. :-P
266       assert(((isa<PointerType>(OpTy)
267                && (Ty == Type::LongTy || Ty == Type::ULongTy
268                    || Ty == Type::IntTy || Ty == Type::UIntTy))
269               || (isa<PointerType>(Ty)
270                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
271                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
272               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
273                    && OpTy->isLosslesslyConvertibleTo(Ty))))
274              && "FIXME: Don't yet support this kind of constant cast expr");
275       EmitConstantValueOnly(Op);
276       break;
277     }
278     case Instruction::Add:
279       O << "(";
280       EmitConstantValueOnly(CE->getOperand(0));
281       O << ") + (";
282       EmitConstantValueOnly(CE->getOperand(1));
283       O << ")";
284       break;
285     default:
286       assert(0 && "Unsupported operator!");
287     }
288   } else {
289     assert(0 && "Unknown constant value!");
290   }
291 }
292
293 /// toOctal - Convert the low order bits of X into an octal digit.
294 ///
295 static inline char toOctal(int X) {
296   return (X&7)+'0';
297 }
298
299 /// printAsCString - Print the specified array as a C compatible string, only if
300 /// the predicate isString is true.
301 ///
302 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
303                            unsigned LastElt) {
304   assert(CVA->isString() && "Array is not string compatible!");
305
306   O << "\"";
307   for (unsigned i = 0; i != LastElt; ++i) {
308     unsigned char C =
309         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
310
311     if (C == '"') {
312       O << "\\\"";
313     } else if (C == '\\') {
314       O << "\\\\";
315     } else if (isprint(C)) {
316       O << C;
317     } else {
318       switch(C) {
319       case '\b': O << "\\b"; break;
320       case '\f': O << "\\f"; break;
321       case '\n': O << "\\n"; break;
322       case '\r': O << "\\r"; break;
323       case '\t': O << "\\t"; break;
324       default:
325         O << '\\';
326         O << toOctal(C >> 6);
327         O << toOctal(C >> 3);
328         O << toOctal(C >> 0);
329         break;
330       }
331     }
332   }
333   O << "\"";
334 }
335
336 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
337 ///
338 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
339   const TargetData &TD = TM.getTargetData();
340
341   if (CV->isNullValue() || isa<UndefValue>(CV)) {
342     EmitZeros(TD.getTypeSize(CV->getType()));
343     return;
344   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
345     if (CVA->isString()) {
346       unsigned NumElts = CVA->getNumOperands();
347       if (AscizDirective && NumElts && 
348           cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
349         O << AscizDirective;
350         printAsCString(O, CVA, NumElts-1);
351       } else {
352         O << AsciiDirective;
353         printAsCString(O, CVA, NumElts);
354       }
355       O << "\n";
356     } else { // Not a string.  Print the values in successive locations
357       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
358         EmitGlobalConstant(CVA->getOperand(i));
359     }
360     return;
361   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
362     // Print the fields in successive locations. Pad to align if needed!
363     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
364     uint64_t sizeSoFar = 0;
365     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
366       const Constant* field = CVS->getOperand(i);
367
368       // Check if padding is needed and insert one or more 0s.
369       uint64_t fieldSize = TD.getTypeSize(field->getType());
370       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
371                            : cvsLayout->MemberOffsets[i+1])
372                           - cvsLayout->MemberOffsets[i]) - fieldSize;
373       sizeSoFar += fieldSize + padSize;
374
375       // Now print the actual field value
376       EmitGlobalConstant(field);
377
378       // Insert the field padding unless it's zero bytes...
379       EmitZeros(padSize);
380     }
381     assert(sizeSoFar == cvsLayout->StructSize &&
382            "Layout of constant struct may be incorrect!");
383     return;
384   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
385     // FP Constants are printed as integer constants to avoid losing
386     // precision...
387     double Val = CFP->getValue();
388     if (CFP->getType() == Type::DoubleTy) {
389       if (Data64bitsDirective)
390         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
391           << " double value: " << Val << "\n";
392       else if (TD.isBigEndian()) {
393         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
394           << "\t" << CommentString << " double most significant word "
395           << Val << "\n";
396         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
397           << "\t" << CommentString << " double least significant word "
398           << Val << "\n";
399       } else {
400         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
401           << "\t" << CommentString << " double least significant word " << Val
402           << "\n";
403         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
404           << "\t" << CommentString << " double most significant word " << Val
405           << "\n";
406       }
407       return;
408     } else {
409       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
410         << " float " << Val << "\n";
411       return;
412     }
413   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
414     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
415       uint64_t Val = CI->getRawValue();
416
417       if (Data64bitsDirective)
418         O << Data64bitsDirective << Val << "\n";
419       else if (TD.isBigEndian()) {
420         O << Data32bitsDirective << unsigned(Val >> 32)
421           << "\t" << CommentString << " Double-word most significant word "
422           << Val << "\n";
423         O << Data32bitsDirective << unsigned(Val)
424           << "\t" << CommentString << " Double-word least significant word "
425           << Val << "\n";
426       } else {
427         O << Data32bitsDirective << unsigned(Val)
428           << "\t" << CommentString << " Double-word least significant word "
429           << Val << "\n";
430         O << Data32bitsDirective << unsigned(Val >> 32)
431           << "\t" << CommentString << " Double-word most significant word "
432           << Val << "\n";
433       }
434       return;
435     }
436   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
437     const PackedType *PTy = CP->getType();
438     
439     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
440       EmitGlobalConstant(CP->getOperand(I));
441     
442     return;
443   }
444
445   const Type *type = CV->getType();
446   switch (type->getTypeID()) {
447   case Type::BoolTyID:
448   case Type::UByteTyID: case Type::SByteTyID:
449     O << Data8bitsDirective;
450     break;
451   case Type::UShortTyID: case Type::ShortTyID:
452     O << Data16bitsDirective;
453     break;
454   case Type::PointerTyID:
455     if (TD.getPointerSize() == 8) {
456       O << Data64bitsDirective;
457       break;
458     }
459     //Fall through for pointer size == int size
460   case Type::UIntTyID: case Type::IntTyID:
461     O << Data32bitsDirective;
462     break;
463   case Type::ULongTyID: case Type::LongTyID:
464     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
465     O << Data64bitsDirective;
466     break;
467   case Type::FloatTyID: case Type::DoubleTyID:
468     assert (0 && "Should have already output floating point constant.");
469   default:
470     assert (0 && "Can't handle printing this type of thing");
471     break;
472   }
473   EmitConstantValueOnly(CV);
474   O << "\n";
475 }
476
477 /// printInlineAsm - This method formats and prints the specified machine
478 /// instruction that is an inline asm.
479 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
480   unsigned NumOperands = MI->getNumOperands();
481   
482   // Count the number of register definitions.
483   unsigned NumDefs = 0;
484   for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
485     assert(NumDefs != NumOperands-1 && "No asm string?");
486   
487   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
488
489   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
490   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
491
492   // The variant of the current asmprinter: FIXME: change.
493   int AsmPrinterVariant = 0;
494   
495   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
496   const char *LastEmitted = AsmStr; // One past the last character emitted.
497   
498   while (*LastEmitted) {
499     switch (*LastEmitted) {
500     default: {
501       // Not a special case, emit the string section literally.
502       const char *LiteralEnd = LastEmitted+1;
503       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
504              *LiteralEnd != '}' && *LiteralEnd != '$')
505         ++LiteralEnd;
506       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
507         O.write(LastEmitted, LiteralEnd-LastEmitted);
508       LastEmitted = LiteralEnd;
509       break;
510     }
511     case '$': {
512       ++LastEmitted;   // Consume '$' character.
513       if (*LastEmitted == '$') { // $$ -> $
514         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
515           O << '$';
516         ++LastEmitted;  // Consume second '$' character.
517         break;
518       }
519       
520       bool HasCurlyBraces = false;
521       if (*LastEmitted == '{') {     // ${variable}
522         ++LastEmitted;               // Consume '{' character.
523         HasCurlyBraces = true;
524       }
525       
526       const char *IDStart = LastEmitted;
527       char *IDEnd;
528       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
529       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
530         std::cerr << "Bad $ operand number in inline asm string: '" 
531                   << AsmStr << "'\n";
532         exit(1);
533       }
534       LastEmitted = IDEnd;
535       
536       if (HasCurlyBraces) {
537         if (*LastEmitted != '}') {
538           std::cerr << "Bad ${} expression in inline asm string: '" 
539                     << AsmStr << "'\n";
540           exit(1);
541         }
542         ++LastEmitted;    // Consume '}' character.
543       }
544       
545       if ((unsigned)Val >= NumOperands-1) {
546         std::cerr << "Invalid $ operand number in inline asm string: '" 
547                   << AsmStr << "'\n";
548         exit(1);
549       }
550       
551       // Okay, we finally have an operand number.  Ask the target to print this
552       // operand!
553       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
554         if (const_cast<AsmPrinter*>(this)->
555                 PrintAsmOperand(MI, Val+1, AsmPrinterVariant)) {
556           std::cerr << "Invalid operand found in inline asm: '"
557                     << AsmStr << "'\n";
558           MI->dump();
559           exit(1);
560         }
561       break;
562     }
563     case '{':
564       ++LastEmitted;      // Consume '{' character.
565       if (CurVariant != -1) {
566         std::cerr << "Nested variants found in inline asm string: '"
567                   << AsmStr << "'\n";
568         exit(1);
569       }
570       CurVariant = 0;     // We're in the first variant now.
571       break;
572     case '|':
573       ++LastEmitted;  // consume '|' character.
574       if (CurVariant == -1) {
575         std::cerr << "Found '|' character outside of variant in inline asm "
576                   << "string: '" << AsmStr << "'\n";
577         exit(1);
578       }
579       ++CurVariant;   // We're in the next variant.
580       break;
581     case '}':
582       ++LastEmitted;  // consume '}' character.
583       if (CurVariant == -1) {
584         std::cerr << "Found '}' character outside of variant in inline asm "
585                   << "string: '" << AsmStr << "'\n";
586         exit(1);
587       }
588       CurVariant = -1;
589       break;
590     }
591   }
592   O << "\n";
593 }
594
595 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
596 /// instruction, using the specified assembler variant.  Targets should
597 /// overried this to format as appropriate.
598 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
599                                  unsigned AsmVariant) {
600   // Target doesn't support this yet!
601   return true;
602 }