1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
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 all of the stuff necessary to output a .s file from
11 // LLVM. The code in this file assumes that the specified module has already
12 // been compiled into the internal data structures of the Module.
14 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
15 // The FunctionPass is pipelined together with all of the rest of the code
16 // generation stages, and the Pass runs at the end to emit code for global
17 // variables and such.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFunctionInfo.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/SlotCalculator.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "Support/StringExtras.h"
31 #include "Support/Statistic.h"
32 #include "SparcInternals.h"
37 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39 class GlobalIdTable: public Annotation {
40 static AnnotationID AnnotId;
41 friend class AsmPrinter; // give access to AnnotId
43 typedef hash_map<const Value*, int> ValIdMap;
44 typedef ValIdMap::const_iterator ValIdMapConstIterator;
45 typedef ValIdMap:: iterator ValIdMapIterator;
47 SlotCalculator Table; // map anonymous values to unique integer IDs
48 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
50 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
53 AnnotationID GlobalIdTable::AnnotId =
54 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
56 //===---------------------------------------------------------------------===//
57 // Code Shared By the two printer passes, as a mixin
58 //===---------------------------------------------------------------------===//
61 GlobalIdTable* idTable;
64 const TargetMachine &Target;
74 AsmPrinter(std::ostream &os, const TargetMachine &T)
75 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
77 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
78 void startModule(Module &M) {
79 // Create the global id table if it does not already exist
80 idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
81 if (idTable == NULL) {
82 idTable = new GlobalIdTable(&M);
83 M.addAnnotation(idTable);
86 void startFunction(Function &F) {
87 // Make sure the slot table has information about this function...
88 idTable->Table.incorporateFunction(&F);
90 void endFunction(Function &) {
91 idTable->Table.purgeFunction(); // Forget all about F
96 // Check if a value is external or accessible from external code.
97 bool isExternal(const Value* V) {
98 const GlobalValue *GV = dyn_cast<GlobalValue>(V);
99 return GV && GV->hasExternalLinkage();
102 // enterSection - Use this method to enter a different section of the output
103 // executable. This is used to only output necessary section transitions.
105 void enterSection(enum Sections S) {
106 if (S == CurSection) return; // Only switch section if necessary
109 toAsm << "\n\t.section ";
112 default: assert(0 && "Bad section name!");
113 case Text: toAsm << "\".text\""; break;
114 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
115 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
116 case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
121 static std::string getValidSymbolName(const std::string &S) {
124 // Symbol names in Sparc assembly language have these rules:
125 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
126 // (b) A name beginning in "." is treated as a local name.
131 for (unsigned i = 0; i < S.size(); ++i)
134 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
139 Result += char('0' + ((unsigned char)C >> 4));
140 Result += char('0' + (C & 0xF));
146 // getID - Return a valid identifier for the specified value. Base it on
147 // the name of the identifier if possible (qualified by the type), and
148 // use a numbered value based on prefix otherwise.
149 // FPrefix is always prepended to the output identifier.
151 std::string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
152 std::string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
154 Result += V->hasName() ? V->getName() : std::string(Prefix);
156 // Qualify all internal names with a unique id.
157 if (!isExternal(V)) {
158 int valId = idTable->Table.getSlot(V);
160 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
161 if (I == idTable->valToIdMap.end())
162 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
166 Result = Result + "_" + itostr(valId);
168 // Replace or prefix problem characters in the name
169 Result = getValidSymbolName(Result);
175 // getID Wrappers - Ensure consistent usage...
176 std::string getID(const Function *F) {
177 return getID(F, "LLVMFunction_");
179 std::string getID(const BasicBlock *BB) {
180 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
182 std::string getID(const GlobalVariable *GV) {
183 return getID(GV, "LLVMGlobal_");
185 std::string getID(const Constant *CV) {
186 return getID(CV, "LLVMConst_", ".C_");
188 std::string getID(const GlobalValue *GV) {
189 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
191 else if (const Function *F = dyn_cast<Function>(GV))
193 assert(0 && "Unexpected type of GlobalValue!");
197 // Combines expressions
198 inline std::string ConstantArithExprToString(const ConstantExpr* CE,
199 const TargetMachine &TM,
200 const std::string &op) {
201 return "(" + valToExprString(CE->getOperand(0), TM) + op
202 + valToExprString(CE->getOperand(1), TM) + ")";
205 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
206 // and return this as a string.
207 std::string ConstantExprToString(const ConstantExpr* CE,
208 const TargetMachine& target) {
210 switch(CE->getOpcode()) {
211 case Instruction::GetElementPtr:
212 { // generate a symbolic expression for the byte address
213 const Value* ptrVal = CE->getOperand(0);
214 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
215 const TargetData &TD = target.getTargetData();
216 S += "(" + valToExprString(ptrVal, target) + ") + ("
217 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
221 case Instruction::Cast:
222 // Support only non-converting casts for now, i.e., a no-op.
223 // This assertion is not a complete check.
224 assert(target.getTargetData().getTypeSize(CE->getType()) ==
225 target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
226 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
229 case Instruction::Add:
230 S += ConstantArithExprToString(CE, target, ") + (");
233 case Instruction::Sub:
234 S += ConstantArithExprToString(CE, target, ") - (");
237 case Instruction::Mul:
238 S += ConstantArithExprToString(CE, target, ") * (");
241 case Instruction::Div:
242 S += ConstantArithExprToString(CE, target, ") / (");
245 case Instruction::Rem:
246 S += ConstantArithExprToString(CE, target, ") % (");
249 case Instruction::And:
250 // Logical && for booleans; bitwise & otherwise
251 S += ConstantArithExprToString(CE, target,
252 ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
255 case Instruction::Or:
256 // Logical || for booleans; bitwise | otherwise
257 S += ConstantArithExprToString(CE, target,
258 ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
261 case Instruction::Xor:
262 // Bitwise ^ for all types
263 S += ConstantArithExprToString(CE, target, ") ^ (");
267 assert(0 && "Unsupported operator in ConstantExprToString()");
274 // valToExprString - Helper function for ConstantExprToString().
275 // Appends result to argument string S.
277 std::string valToExprString(const Value* V, const TargetMachine& target) {
280 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
282 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
283 S += std::string(CB == ConstantBool::True ? "1" : "0");
284 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
285 S += itostr(CI->getValue());
286 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
287 S += utostr(CI->getValue());
288 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
289 S += ftostr(CFP->getValue());
290 else if (isa<ConstantPointerNull>(CV))
292 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
293 S += valToExprString(CPR->getValue(), target);
294 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
295 S += ConstantExprToString(CE, target);
299 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
306 assert(0 && "Cannot convert value to string");
307 S += "<illegal-value>";
316 //===----------------------------------------------------------------------===//
317 // SparcFunctionAsmPrinter Code
318 //===----------------------------------------------------------------------===//
320 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
321 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
322 : AsmPrinter(os, t) {}
324 const char *getPassName() const {
325 return "Output Sparc Assembly for Functions";
328 virtual bool doInitialization(Module &M) {
333 virtual bool runOnFunction(Function &F) {
340 virtual bool doFinalization(Module &M) {
345 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
346 AU.setPreservesAll();
349 void emitFunction(const Function &F);
351 void emitBasicBlock(const MachineBasicBlock &MBB);
352 void emitMachineInst(const MachineInstr *MI);
354 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
355 void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
357 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
358 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
360 unsigned getOperandMask(unsigned Opcode) {
363 case V9::SUBcci: return 1 << 3; // Remove CC argument
364 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
365 default: return 0; // By default, don't hack operands...
371 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
372 unsigned int opNum) {
373 switch (MI->getOpCode()) {
386 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
387 unsigned int opNum) {
388 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
390 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
397 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
398 printOneOperand(mop1, opCode); \
400 printOneOperand(mop2, opCode);
403 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
406 const MachineOperand& mop = MI->getOperand(opNum);
408 if (OpIsBranchTargetLabel(MI, opNum))
410 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
413 else if (OpIsMemoryAddressBase(MI, opNum))
416 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
422 printOneOperand(mop, MI->getOpCode());
428 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop,
429 MachineOpCode opCode)
431 bool needBitsFlag = true;
433 if (mop.opHiBits32())
435 else if (mop.opLoBits32())
437 else if (mop.opHiBits64())
439 else if (mop.opLoBits64())
442 needBitsFlag = false;
444 switch (mop.getType())
446 case MachineOperand::MO_VirtualRegister:
447 case MachineOperand::MO_CCRegister:
448 case MachineOperand::MO_MachineRegister:
450 int regNum = (int)mop.getAllocatedRegNum();
452 if (regNum == Target.getRegInfo().getInvalidRegNum()) {
453 // better to print code with NULL registers than to die
454 toAsm << "<NULL VALUE>";
456 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
461 case MachineOperand::MO_PCRelativeDisp:
463 const Value *Val = mop.getVRegValue();
464 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
466 if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
468 else if (const Function *M = dyn_cast<Function>(Val))
470 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
472 else if (const Constant *CV = dyn_cast<Constant>(Val))
475 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
479 case MachineOperand::MO_SignExtendedImmed:
480 toAsm << mop.getImmedValue();
483 case MachineOperand::MO_UnextendedImmed:
484 toAsm << (uint64_t) mop.getImmedValue();
488 toAsm << mop; // use dump field
497 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
499 unsigned Opcode = MI->getOpCode();
501 if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
502 return; // IGNORE PHI NODES
504 toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
506 unsigned Mask = getOperandMask(Opcode);
508 bool NeedComma = false;
510 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
511 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
512 if (NeedComma) toAsm << ", "; // Handle comma outputting
514 N = printOperands(MI, OpNum);
523 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
525 // Emit a label for the basic block
526 toAsm << getID(MBB.getBasicBlock()) << ":\n";
528 // Loop over all of the instructions in the basic block...
529 for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
531 emitMachineInst(*MII);
532 toAsm << "\n"; // Separate BB's with newlines
536 SparcFunctionAsmPrinter::emitFunction(const Function &F)
538 std::string methName = getID(&F);
539 toAsm << "!****** Outputing Function: " << methName << " ******\n";
540 enterSection(AsmPrinter::Text);
541 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
542 //toAsm << "\t.type\t" << methName << ",#function\n";
543 toAsm << "\t.type\t" << methName << ", 2\n";
544 toAsm << methName << ":\n";
546 // Output code for all of the basic blocks in the function...
547 MachineFunction &MF = MachineFunction::get(&F);
548 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
551 // Output a .size directive so the debugger knows the extents of the function
552 toAsm << ".EndOf_" << methName << ":\n\t.size "
553 << methName << ", .EndOf_"
554 << methName << "-" << methName << "\n";
556 // Put some spaces between the functions
560 } // End anonymous namespace
562 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
563 return new SparcFunctionAsmPrinter(Out, *this);
570 //===----------------------------------------------------------------------===//
571 // SparcFunctionAsmPrinter Code
572 //===----------------------------------------------------------------------===//
576 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
578 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
579 : AsmPrinter(os, t) {}
581 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
583 virtual bool run(Module &M) {
585 emitGlobalsAndConstants(M);
590 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
591 AU.setPreservesAll();
595 void emitGlobalsAndConstants (const Module &M);
597 void printGlobalVariable (const GlobalVariable *GV);
598 void PrintZeroBytesToPad (int numBytes);
599 void printSingleConstantValue (const Constant* CV);
600 void printConstantValueOnly (const Constant* CV, int numPadBytesAfter = 0);
601 void printConstant (const Constant* CV, std::string valID = "");
603 static void FoldConstants (const Module &M,
604 hash_set<const Constant*> &moduleConstants);
608 // Can we treat the specified array as a string? Only if it is an array of
609 // ubytes or non-negative sbytes.
611 static bool isStringCompatible(const ConstantArray *CVA) {
612 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
613 if (ETy == Type::UByteTy) return true;
614 if (ETy != Type::SByteTy) return false;
616 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
617 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
623 // toOctal - Convert the low order bits of X into an octal letter
624 static inline char toOctal(int X) {
628 // getAsCString - Return the specified array as a C compatible string, only if
629 // the predicate isStringCompatible is true.
631 static std::string getAsCString(const ConstantArray *CVA) {
632 assert(isStringCompatible(CVA) && "Array is not string compatible!");
635 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
637 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
638 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
642 } else if (C == '\\') {
644 } else if (isprint(C)) {
647 Result += '\\'; // print all other chars as octal value
648 Result += toOctal(C >> 6);
649 Result += toOctal(C >> 3);
650 Result += toOctal(C >> 0);
659 ArrayTypeIsString(const ArrayType* arrayType)
661 return (arrayType->getElementType() == Type::UByteTy ||
662 arrayType->getElementType() == Type::SByteTy);
666 inline const std::string
667 TypeToDataDirective(const Type* type)
669 switch(type->getPrimitiveID())
671 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
673 case Type::UShortTyID: case Type::ShortTyID:
675 case Type::UIntTyID: case Type::IntTyID:
677 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
679 case Type::FloatTyID:
681 case Type::DoubleTyID:
683 case Type::ArrayTyID:
684 if (ArrayTypeIsString((ArrayType*) type))
687 return "<InvaliDataTypeForPrinting>";
689 return "<InvaliDataTypeForPrinting>";
693 // Get the size of the type
696 TypeToSize(const Type* type, const TargetMachine& target)
698 return target.findOptimalStorageSize(type);
701 // Get the size of the constant for the given target.
702 // If this is an unsized array, return 0.
705 ConstantToSize(const Constant* CV, const TargetMachine& target)
707 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
709 const ArrayType *aty = cast<ArrayType>(CVA->getType());
710 if (ArrayTypeIsString(aty))
711 return 1 + CVA->getNumOperands();
714 return TypeToSize(CV->getType(), target);
717 // Align data larger than one L1 cache line on L1 cache line boundaries.
718 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
721 SizeToAlignment(unsigned int size, const TargetMachine& target)
723 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
724 if (size > (unsigned) cacheLineSize / 2)
725 return cacheLineSize;
727 for (unsigned sz=1; /*no condition*/; sz *= 2)
732 // Get the size of the type and then use SizeToAlignment.
735 TypeToAlignment(const Type* type, const TargetMachine& target)
737 return SizeToAlignment(TypeToSize(type, target), target);
740 // Get the size of the constant and then use SizeToAlignment.
741 // Handles strings as a special case;
743 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
745 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
746 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
747 return SizeToAlignment(1 + CVA->getNumOperands(), target);
749 return TypeToAlignment(CV->getType(), target);
753 // Print a single constant value.
755 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
757 assert(CV->getType() != Type::VoidTy &&
758 CV->getType() != Type::TypeTy &&
759 CV->getType() != Type::LabelTy &&
760 "Unexpected type for Constant");
762 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
763 && "Aggregate types should be handled outside this function");
765 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
767 if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
768 { // This is a constant address for a global variable or method.
769 // Use the name of the variable or method as the address value.
770 assert(isa<GlobalValue>(CPR->getValue()) && "Unexpected non-global");
771 toAsm << getID(CPR->getValue()) << "\n";
773 else if (isa<ConstantPointerNull>(CV))
774 { // Null pointer value
777 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
778 { // Constant expression built from operators, constants, and symbolic addrs
779 toAsm << ConstantExprToString(CE, Target) << "\n";
781 else if (CV->getType()->isPrimitiveType()) // Check primitive types last
783 if (CV->getType()->isFloatingPoint()) {
784 // FP Constants are printed as integer constants to avoid losing
786 double Val = cast<ConstantFP>(CV)->getValue();
787 if (CV->getType() == Type::FloatTy) {
788 float FVal = (float)Val;
789 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
790 toAsm << *(unsigned int*)ProxyPtr;
791 } else if (CV->getType() == Type::DoubleTy) {
792 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
793 toAsm << *(uint64_t*)ProxyPtr;
795 assert(0 && "Unknown floating point type!");
798 toAsm << "\t! " << CV->getType()->getDescription()
799 << " value: " << Val << "\n";
801 WriteAsOperand(toAsm, CV, false, false) << "\n";
806 assert(0 && "Unknown elementary type for constant");
811 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
813 for ( ; numBytes >= 8; numBytes -= 8)
814 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
818 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
823 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
826 // Print a constant value or values (it may be an aggregate).
827 // Uses printSingleConstantValue() to print each individual value.
829 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
830 int numPadBytesAfter /* = 0*/)
832 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
834 if (CVA && isStringCompatible(CVA))
835 { // print the string alone and return
836 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
839 { // Not a string. Print the values in successive locations
840 const std::vector<Use> &constValues = CVA->getValues();
841 for (unsigned i=0; i < constValues.size(); i++)
842 printConstantValueOnly(cast<Constant>(constValues[i].get()));
844 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
845 { // Print the fields in successive locations. Pad to align if needed!
846 const StructLayout *cvsLayout =
847 Target.getTargetData().getStructLayout(CVS->getType());
848 const std::vector<Use>& constValues = CVS->getValues();
849 unsigned sizeSoFar = 0;
850 for (unsigned i=0, N = constValues.size(); i < N; i++)
852 const Constant* field = cast<Constant>(constValues[i].get());
854 // Check if padding is needed and insert one or more 0s.
856 Target.getTargetData().getTypeSize(field->getType());
857 int padSize = ((i == N-1? cvsLayout->StructSize
858 : cvsLayout->MemberOffsets[i+1])
859 - cvsLayout->MemberOffsets[i]) - fieldSize;
860 sizeSoFar += (fieldSize + padSize);
862 // Now print the actual field value
863 printConstantValueOnly(field, padSize);
865 assert(sizeSoFar == cvsLayout->StructSize &&
866 "Layout of constant struct may be incorrect!");
869 printSingleConstantValue(CV);
871 if (numPadBytesAfter)
872 PrintZeroBytesToPad(numPadBytesAfter);
875 // Print a constant (which may be an aggregate) prefixed by all the
876 // appropriate directives. Uses printConstantValueOnly() to print the
879 SparcModuleAsmPrinter::printConstant(const Constant* CV, std::string valID)
881 if (valID.length() == 0)
884 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
886 // Print .size and .type only if it is not a string.
887 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
888 if (CVA && isStringCompatible(CVA))
889 { // print it as a string and return
890 toAsm << valID << ":\n";
891 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
895 toAsm << "\t.type" << "\t" << valID << ",#object\n";
897 unsigned int constSize = ConstantToSize(CV, Target);
899 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
901 toAsm << valID << ":\n";
903 printConstantValueOnly(CV);
907 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
908 hash_set<const Constant*> &MC) {
909 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
910 if (!I->isExternal()) {
911 const hash_set<const Constant*> &pool =
912 MachineFunction::get(I).getInfo()->getConstantPoolValues();
913 MC.insert(pool.begin(), pool.end());
917 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
919 if (GV->hasExternalLinkage())
920 toAsm << "\t.global\t" << getID(GV) << "\n";
922 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
923 printConstant(GV->getInitializer(), getID(GV));
925 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
927 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
928 toAsm << "\t.reserve\t" << getID(GV) << ","
929 << TypeToSize(GV->getType()->getElementType(), Target)
935 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
936 // First, get the constants there were marked by the code generator for
937 // inclusion in the assembly code data area and fold them all into a
938 // single constant pool since there may be lots of duplicates. Also,
939 // lets force these constants into the slot table so that we can get
940 // unique names for unnamed constants also.
942 hash_set<const Constant*> moduleConstants;
943 FoldConstants(M, moduleConstants);
945 // Output constants spilled to memory
946 enterSection(AsmPrinter::ReadOnlyData);
947 for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
948 E = moduleConstants.end(); I != E; ++I)
951 // Output global variables...
952 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
953 if (! GI->isExternal()) {
954 assert(GI->hasInitializer());
955 if (GI->isConstant())
956 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
957 else if (GI->getInitializer()->isNullValue())
958 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
960 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
962 printGlobalVariable(GI);
968 } // End anonymous namespace
970 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
971 return new SparcModuleAsmPrinter(Out, *this);