1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
3 // This file implements all of the stuff neccesary to output a .s file from
4 // LLVM. The code in this file assumes that the specified module has already
5 // been compiled into the internal data structures of the Module.
7 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
8 // The FunctionPass is pipelined together with all of the rest of the code
9 // generation stages, and the Pass runs at the end to emit code for global
10 // variables and such.
12 //===----------------------------------------------------------------------===//
14 #include "SparcInternals.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFunctionInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/SlotCalculator.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "Support/StringExtras.h"
29 class GlobalIdTable: public Annotation {
30 static AnnotationID AnnotId;
31 friend class AsmPrinter; // give access to AnnotId
33 typedef hash_map<const Value*, int> ValIdMap;
34 typedef ValIdMap::const_iterator ValIdMapConstIterator;
35 typedef ValIdMap:: iterator ValIdMapIterator;
37 SlotCalculator Table; // map anonymous values to unique integer IDs
38 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
40 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
43 AnnotationID GlobalIdTable::AnnotId =
44 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
46 //===---------------------------------------------------------------------===//
47 // Code Shared By the two printer passes, as a mixin
48 //===---------------------------------------------------------------------===//
51 GlobalIdTable* idTable;
54 const TargetMachine &Target;
64 AsmPrinter(std::ostream &os, const TargetMachine &T)
65 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
67 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
68 void startModule(Module &M) {
69 // Create the global id table if it does not already exist
70 idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
71 if (idTable == NULL) {
72 idTable = new GlobalIdTable(&M);
73 M.addAnnotation(idTable);
76 void startFunction(Function &F) {
77 // Make sure the slot table has information about this function...
78 idTable->Table.incorporateFunction(&F);
80 void endFunction(Function &) {
81 idTable->Table.purgeFunction(); // Forget all about F
86 // Check if a value is external or accessible from external code.
87 bool isExternal(const Value* V) {
88 const GlobalValue *GV = dyn_cast<GlobalValue>(V);
89 return GV && GV->hasExternalLinkage();
92 // enterSection - Use this method to enter a different section of the output
93 // executable. This is used to only output neccesary section transitions.
95 void enterSection(enum Sections S) {
96 if (S == CurSection) return; // Only switch section if neccesary
99 toAsm << "\n\t.section ";
102 default: assert(0 && "Bad section name!");
103 case Text: toAsm << "\".text\""; break;
104 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
105 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
106 case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
111 static string getValidSymbolName(const string &S) {
114 // Symbol names in Sparc assembly language have these rules:
115 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
116 // (b) A name beginning in "." is treated as a local name.
121 for (unsigned i = 0; i < S.size(); ++i)
124 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
129 Result += char('0' + ((unsigned char)C >> 4));
130 Result += char('0' + (C & 0xF));
136 // getID - Return a valid identifier for the specified value. Base it on
137 // the name of the identifier if possible (qualified by the type), and
138 // use a numbered value based on prefix otherwise.
139 // FPrefix is always prepended to the output identifier.
141 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
142 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
144 Result += V->hasName() ? V->getName() : string(Prefix);
146 // Qualify all internal names with a unique id.
147 if (!isExternal(V)) {
148 int valId = idTable->Table.getValSlot(V);
150 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
151 if (I == idTable->valToIdMap.end())
152 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
156 Result = Result + "_" + itostr(valId);
158 // Replace or prefix problem characters in the name
159 Result = getValidSymbolName(Result);
165 // getID Wrappers - Ensure consistent usage...
166 string getID(const Function *F) {
167 return getID(F, "LLVMFunction_");
169 string getID(const BasicBlock *BB) {
170 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
172 string getID(const GlobalVariable *GV) {
173 return getID(GV, "LLVMGlobal_");
175 string getID(const Constant *CV) {
176 return getID(CV, "LLVMConst_", ".C_");
178 string getID(const GlobalValue *GV) {
179 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
181 else if (const Function *F = dyn_cast<Function>(GV))
183 assert(0 && "Unexpected type of GlobalValue!");
187 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
188 // and return this as a string.
189 string ConstantExprToString(const ConstantExpr* CE,
190 const TargetMachine& target) {
192 switch(CE->getOpcode()) {
193 case Instruction::GetElementPtr:
194 { // generate a symbolic expression for the byte address
195 const Value* ptrVal = CE->getOperand(0);
196 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
197 const TargetData &TD = target.getTargetData();
198 S += "(" + valToExprString(ptrVal, target) + ") + ("
199 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
203 case Instruction::Cast:
204 // Support only non-converting casts for now, i.e., a no-op.
205 // This assertion is not a complete check.
206 assert(target.getTargetData().getTypeSize(CE->getType()) ==
207 target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
208 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
211 case Instruction::Add:
212 S += "(" + valToExprString(CE->getOperand(0), target) + ") + ("
213 + valToExprString(CE->getOperand(1), target) + ")";
216 case Instruction::Sub:
217 S += "(" + valToExprString(CE->getOperand(0), target) + ") - ("
218 + valToExprString(CE->getOperand(1), target) + ")";
221 case Instruction::Mul:
222 S += "(" + valToExprString(CE->getOperand(0), target) + ") * ("
223 + valToExprString(CE->getOperand(1), target) + ")";
226 case Instruction::Div:
227 S += "(" + valToExprString(CE->getOperand(0), target) + ") / ("
228 + valToExprString(CE->getOperand(1), target) + ")";
231 case Instruction::Rem:
232 S += "(" + valToExprString(CE->getOperand(0), target) + ") % ("
233 + valToExprString(CE->getOperand(1), target) + ")";
236 case Instruction::And:
237 // Logical && for booleans; bitwise & otherwise
238 S += "(" + valToExprString(CE->getOperand(0), target)
239 + ((CE->getType() == Type::BoolTy)? ") && (" : ") & (")
240 + valToExprString(CE->getOperand(1), target) + ")";
243 case Instruction::Or:
244 // Logical || for booleans; bitwise | otherwise
245 S += "(" + valToExprString(CE->getOperand(0), target)
246 + ((CE->getType() == Type::BoolTy)? ") || (" : ") | (")
247 + valToExprString(CE->getOperand(1), target) + ")";
250 case Instruction::Xor:
251 // Bitwise ^ for all types
252 S += "(" + valToExprString(CE->getOperand(0), target) + ") ^ ("
253 + valToExprString(CE->getOperand(1), target) + ")";
257 assert(0 && "Unsupported operator in ConstantExprToString()");
264 // valToExprString - Helper function for ConstantExprToString().
265 // Appends result to argument string S.
267 string valToExprString(const Value* V, const TargetMachine& target) {
270 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
272 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
273 S += string(CB == ConstantBool::True ? "1" : "0");
274 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
275 S += itostr(CI->getValue());
276 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
277 S += utostr(CI->getValue());
278 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
279 S += ftostr(CFP->getValue());
280 else if (isa<ConstantPointerNull>(CV))
282 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
283 S += valToExprString(CPR->getValue(), target);
284 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
285 S += ConstantExprToString(CE, target);
289 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
296 assert(0 && "Cannot convert value to string");
297 S += "<illegal-value>";
306 //===----------------------------------------------------------------------===//
307 // SparcFunctionAsmPrinter Code
308 //===----------------------------------------------------------------------===//
310 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
311 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
312 : AsmPrinter(os, t) {}
314 const char *getPassName() const {
315 return "Output Sparc Assembly for Functions";
318 virtual bool doInitialization(Module &M) {
323 virtual bool runOnFunction(Function &F) {
330 virtual bool doFinalization(Module &M) {
335 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
336 AU.setPreservesAll();
339 void emitFunction(const Function &F);
341 void emitBasicBlock(const MachineBasicBlock &MBB);
342 void emitMachineInst(const MachineInstr *MI);
344 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
345 void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
347 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
348 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
350 unsigned getOperandMask(unsigned Opcode) {
353 case V9::SUBcci: return 1 << 3; // Remove CC argument
354 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
355 default: return 0; // By default, don't hack operands...
361 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
362 unsigned int opNum) {
363 switch (MI->getOpCode()) {
376 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
377 unsigned int opNum) {
378 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
380 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
387 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
388 printOneOperand(mop1, opCode); \
390 printOneOperand(mop2, opCode);
393 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
396 const MachineOperand& mop = MI->getOperand(opNum);
398 if (OpIsBranchTargetLabel(MI, opNum))
400 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
403 else if (OpIsMemoryAddressBase(MI, opNum))
406 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
412 printOneOperand(mop, MI->getOpCode());
418 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop,
419 MachineOpCode opCode)
421 bool needBitsFlag = true;
423 if (mop.opHiBits32())
425 else if (mop.opLoBits32())
427 else if (mop.opHiBits64())
429 else if (mop.opLoBits64())
432 needBitsFlag = false;
434 switch (mop.getType())
436 case MachineOperand::MO_VirtualRegister:
437 case MachineOperand::MO_CCRegister:
438 case MachineOperand::MO_MachineRegister:
440 int regNum = (int)mop.getAllocatedRegNum();
442 if (regNum == Target.getRegInfo().getInvalidRegNum()) {
443 // better to print code with NULL registers than to die
444 toAsm << "<NULL VALUE>";
446 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
451 case MachineOperand::MO_PCRelativeDisp:
453 const Value *Val = mop.getVRegValue();
454 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
456 if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
458 else if (const Function *M = dyn_cast<Function>(Val))
460 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
462 else if (const Constant *CV = dyn_cast<Constant>(Val))
465 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
469 case MachineOperand::MO_SignExtendedImmed:
470 toAsm << mop.getImmedValue();
473 case MachineOperand::MO_UnextendedImmed:
474 toAsm << (uint64_t) mop.getImmedValue();
478 toAsm << mop; // use dump field
488 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
490 unsigned Opcode = MI->getOpCode();
492 if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
493 return; // IGNORE PHI NODES
495 toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
497 unsigned Mask = getOperandMask(Opcode);
499 bool NeedComma = false;
501 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
502 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
503 if (NeedComma) toAsm << ", "; // Handle comma outputing
505 N = printOperands(MI, OpNum);
513 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
515 // Emit a label for the basic block
516 toAsm << getID(MBB.getBasicBlock()) << ":\n";
518 // Loop over all of the instructions in the basic block...
519 for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
521 emitMachineInst(*MII);
522 toAsm << "\n"; // Separate BB's with newlines
526 SparcFunctionAsmPrinter::emitFunction(const Function &F)
528 string methName = getID(&F);
529 toAsm << "!****** Outputing Function: " << methName << " ******\n";
530 enterSection(AsmPrinter::Text);
531 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
532 //toAsm << "\t.type\t" << methName << ",#function\n";
533 toAsm << "\t.type\t" << methName << ", 2\n";
534 toAsm << methName << ":\n";
536 // Output code for all of the basic blocks in the function...
537 MachineFunction &MF = MachineFunction::get(&F);
538 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
541 // Output a .size directive so the debugger knows the extents of the function
542 toAsm << ".EndOf_" << methName << ":\n\t.size "
543 << methName << ", .EndOf_"
544 << methName << "-" << methName << "\n";
546 // Put some spaces between the functions
550 } // End anonymous namespace
552 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
553 return new SparcFunctionAsmPrinter(Out, *this);
560 //===----------------------------------------------------------------------===//
561 // SparcFunctionAsmPrinter Code
562 //===----------------------------------------------------------------------===//
566 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
568 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
569 : AsmPrinter(os, t) {}
571 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
573 virtual bool run(Module &M) {
575 emitGlobalsAndConstants(M);
580 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
581 AU.setPreservesAll();
585 void emitGlobalsAndConstants (const Module &M);
587 void printGlobalVariable (const GlobalVariable *GV);
588 void PrintZeroBytesToPad (int numBytes);
589 void printSingleConstantValue (const Constant* CV);
590 void printConstantValueOnly (const Constant* CV, int numPadBytesAfter = 0);
591 void printConstant (const Constant* CV, string valID = "");
593 static void FoldConstants (const Module &M,
594 hash_set<const Constant*> &moduleConstants);
598 // Can we treat the specified array as a string? Only if it is an array of
599 // ubytes or non-negative sbytes.
601 static bool isStringCompatible(const ConstantArray *CVA) {
602 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
603 if (ETy == Type::UByteTy) return true;
604 if (ETy != Type::SByteTy) return false;
606 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
607 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
613 // toOctal - Convert the low order bits of X into an octal letter
614 static inline char toOctal(int X) {
618 // getAsCString - Return the specified array as a C compatible string, only if
619 // the predicate isStringCompatible is true.
621 static string getAsCString(const ConstantArray *CVA) {
622 assert(isStringCompatible(CVA) && "Array is not string compatible!");
625 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
627 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
628 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
632 } else if (C == '\\') {
634 } else if (isprint(C)) {
637 Result += '\\'; // print all other chars as octal value
638 Result += toOctal(C >> 6);
639 Result += toOctal(C >> 3);
640 Result += toOctal(C >> 0);
649 ArrayTypeIsString(const ArrayType* arrayType)
651 return (arrayType->getElementType() == Type::UByteTy ||
652 arrayType->getElementType() == Type::SByteTy);
657 TypeToDataDirective(const Type* type)
659 switch(type->getPrimitiveID())
661 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
663 case Type::UShortTyID: case Type::ShortTyID:
665 case Type::UIntTyID: case Type::IntTyID:
667 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
669 case Type::FloatTyID:
671 case Type::DoubleTyID:
673 case Type::ArrayTyID:
674 if (ArrayTypeIsString((ArrayType*) type))
677 return "<InvaliDataTypeForPrinting>";
679 return "<InvaliDataTypeForPrinting>";
683 // Get the size of the type
686 TypeToSize(const Type* type, const TargetMachine& target)
688 return target.findOptimalStorageSize(type);
691 // Get the size of the constant for the given target.
692 // If this is an unsized array, return 0.
695 ConstantToSize(const Constant* CV, const TargetMachine& target)
697 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
699 const ArrayType *aty = cast<ArrayType>(CVA->getType());
700 if (ArrayTypeIsString(aty))
701 return 1 + CVA->getNumOperands();
704 return TypeToSize(CV->getType(), target);
707 // Align data larger than one L1 cache line on L1 cache line boundaries.
708 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
711 SizeToAlignment(unsigned int size, const TargetMachine& target)
713 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
714 if (size > (unsigned) cacheLineSize / 2)
715 return cacheLineSize;
717 for (unsigned sz=1; /*no condition*/; sz *= 2)
722 // Get the size of the type and then use SizeToAlignment.
725 TypeToAlignment(const Type* type, const TargetMachine& target)
727 return SizeToAlignment(TypeToSize(type, target), target);
730 // Get the size of the constant and then use SizeToAlignment.
731 // Handles strings as a special case;
733 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
735 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
736 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
737 return SizeToAlignment(1 + CVA->getNumOperands(), target);
739 return TypeToAlignment(CV->getType(), target);
743 // Print a single constant value.
745 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
747 assert(CV->getType() != Type::VoidTy &&
748 CV->getType() != Type::TypeTy &&
749 CV->getType() != Type::LabelTy &&
750 "Unexpected type for Constant");
752 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
753 && "Aggregate types should be handled outside this function");
755 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
757 if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
758 { // This is a constant address for a global variable or method.
759 // Use the name of the variable or method as the address value.
760 assert(isa<GlobalValue>(CPR->getValue()) && "Unexpected non-global");
761 toAsm << getID(CPR->getValue()) << "\n";
763 else if (isa<ConstantPointerNull>(CV))
764 { // Null pointer value
767 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
768 { // Constant expression built from operators, constants, and symbolic addrs
769 toAsm << ConstantExprToString(CE, Target) << "\n";
771 else if (CV->getType()->isPrimitiveType()) // Check primitive types last
773 if (CV->getType()->isFloatingPoint()) {
774 // FP Constants are printed as integer constants to avoid losing
776 double Val = cast<ConstantFP>(CV)->getValue();
777 if (CV->getType() == Type::FloatTy) {
778 float FVal = (float)Val;
779 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
780 toAsm << *(unsigned int*)ProxyPtr;
781 } else if (CV->getType() == Type::DoubleTy) {
782 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
783 toAsm << *(uint64_t*)ProxyPtr;
785 assert(0 && "Unknown floating point type!");
788 toAsm << "\t! " << CV->getType()->getDescription()
789 << " value: " << Val << "\n";
791 WriteAsOperand(toAsm, CV, false, false) << "\n";
796 assert(0 && "Unknown elementary type for constant");
801 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
803 for ( ; numBytes >= 8; numBytes -= 8)
804 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
808 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
813 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
816 // Print a constant value or values (it may be an aggregate).
817 // Uses printSingleConstantValue() to print each individual value.
819 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
820 int numPadBytesAfter /* = 0*/)
822 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
824 if (CVA && isStringCompatible(CVA))
825 { // print the string alone and return
826 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
829 { // Not a string. Print the values in successive locations
830 const std::vector<Use> &constValues = CVA->getValues();
831 for (unsigned i=0; i < constValues.size(); i++)
832 printConstantValueOnly(cast<Constant>(constValues[i].get()));
834 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
835 { // Print the fields in successive locations. Pad to align if needed!
836 const StructLayout *cvsLayout =
837 Target.getTargetData().getStructLayout(CVS->getType());
838 const std::vector<Use>& constValues = CVS->getValues();
839 unsigned sizeSoFar = 0;
840 for (unsigned i=0, N = constValues.size(); i < N; i++)
842 const Constant* field = cast<Constant>(constValues[i].get());
844 // Check if padding is needed and insert one or more 0s.
846 Target.getTargetData().getTypeSize(field->getType());
847 int padSize = ((i == N-1? cvsLayout->StructSize
848 : cvsLayout->MemberOffsets[i+1])
849 - cvsLayout->MemberOffsets[i]) - fieldSize;
850 sizeSoFar += (fieldSize + padSize);
852 // Now print the actual field value
853 printConstantValueOnly(field, padSize);
855 assert(sizeSoFar == cvsLayout->StructSize &&
856 "Layout of constant struct may be incorrect!");
859 printSingleConstantValue(CV);
861 if (numPadBytesAfter)
862 PrintZeroBytesToPad(numPadBytesAfter);
865 // Print a constant (which may be an aggregate) prefixed by all the
866 // appropriate directives. Uses printConstantValueOnly() to print the
869 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
871 if (valID.length() == 0)
874 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
876 // Print .size and .type only if it is not a string.
877 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
878 if (CVA && isStringCompatible(CVA))
879 { // print it as a string and return
880 toAsm << valID << ":\n";
881 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
885 toAsm << "\t.type" << "\t" << valID << ",#object\n";
887 unsigned int constSize = ConstantToSize(CV, Target);
889 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
891 toAsm << valID << ":\n";
893 printConstantValueOnly(CV);
897 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
898 hash_set<const Constant*> &MC) {
899 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
900 if (!I->isExternal()) {
901 const hash_set<const Constant*> &pool =
902 MachineFunction::get(I).getInfo()->getConstantPoolValues();
903 MC.insert(pool.begin(), pool.end());
907 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
909 if (GV->hasExternalLinkage())
910 toAsm << "\t.global\t" << getID(GV) << "\n";
912 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
913 printConstant(GV->getInitializer(), getID(GV));
915 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
917 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
918 toAsm << "\t.reserve\t" << getID(GV) << ","
919 << TypeToSize(GV->getType()->getElementType(), Target)
925 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
926 // First, get the constants there were marked by the code generator for
927 // inclusion in the assembly code data area and fold them all into a
928 // single constant pool since there may be lots of duplicates. Also,
929 // lets force these constants into the slot table so that we can get
930 // unique names for unnamed constants also.
932 hash_set<const Constant*> moduleConstants;
933 FoldConstants(M, moduleConstants);
935 // Output constants spilled to memory
936 enterSection(AsmPrinter::ReadOnlyData);
937 for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
938 E = moduleConstants.end(); I != E; ++I)
941 // Output global variables...
942 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
943 if (! GI->isExternal()) {
944 assert(GI->hasInitializer());
945 if (GI->isConstant())
946 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
947 else if (GI->getInitializer()->isNullValue())
948 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
950 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
952 printGlobalVariable(GI);
958 } // End anonymous namespace
960 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
961 return new SparcModuleAsmPrinter(Out, *this);