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/MachineCodeForMethod.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Annotation.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/Module.h"
24 #include "llvm/SlotCalculator.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "Support/StringExtras.h"
27 #include "Support/HashExtras.h"
33 class GlobalIdTable: public Annotation {
34 static AnnotationID AnnotId;
35 friend class AsmPrinter; // give access to AnnotId
37 typedef std::hash_map<const Value*, int> ValIdMap;
38 typedef ValIdMap::const_iterator ValIdMapConstIterator;
39 typedef ValIdMap:: iterator ValIdMapIterator;
41 SlotCalculator Table; // map anonymous values to unique integer IDs
42 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
44 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
47 AnnotationID GlobalIdTable::AnnotId =
48 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
50 //===---------------------------------------------------------------------===//
51 // Code Shared By the two printer passes, as a mixin
52 //===---------------------------------------------------------------------===//
55 GlobalIdTable* idTable;
58 const TargetMachine &Target;
68 AsmPrinter(std::ostream &os, const TargetMachine &T)
69 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
71 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
72 void startModule(Module *M) {
73 // Create the global id table if it does not already exist
74 idTable = (GlobalIdTable*) M->getAnnotation(GlobalIdTable::AnnotId);
75 if (idTable == NULL) {
76 idTable = new GlobalIdTable(M);
77 M->addAnnotation(idTable);
80 void startFunction(Function *F) {
81 // Make sure the slot table has information about this function...
82 idTable->Table.incorporateFunction(F);
84 void endFunction(Function *F) {
85 idTable->Table.purgeFunction(); // Forget all about F
90 // Check if a name is external or accessible from external code.
91 // Only functions can currently be external. "main" is the only name
92 // that is visible externally.
93 bool isExternal(const Value* V) {
94 const Function *F = dyn_cast<Function>(V);
95 return F && (F->isExternal() || F->getName() == "main");
98 // enterSection - Use this method to enter a different section of the output
99 // executable. This is used to only output neccesary section transitions.
101 void enterSection(enum Sections S) {
102 if (S == CurSection) return; // Only switch section if neccesary
105 toAsm << "\n\t.section ";
108 default: assert(0 && "Bad section name!");
109 case Text: toAsm << "\".text\""; break;
110 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
111 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
112 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
117 static std::string getValidSymbolName(const string &S) {
120 // Symbol names in Sparc assembly language have these rules:
121 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
122 // (b) A name beginning in "." is treated as a local name.
123 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
125 if (S[0] == '_' || isdigit(S[0]))
128 for (unsigned i = 0; i < S.size(); ++i)
131 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
136 Result += char('0' + ((unsigned char)C >> 4));
137 Result += char('0' + (C & 0xF));
143 // getID - Return a valid identifier for the specified value. Base it on
144 // the name of the identifier if possible (qualified by the type), and
145 // use a numbered value based on prefix otherwise.
146 // FPrefix is always prepended to the output identifier.
148 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
149 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
151 Result = Result + (V->hasName()? V->getName() : string(Prefix));
153 // Qualify all internal names with a unique id.
154 if (!isExternal(V)) {
155 int valId = idTable->Table.getValSlot(V);
157 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
158 if (I == idTable->valToIdMap.end())
159 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
163 Result = Result + "_" + itostr(valId);
166 return getValidSymbolName(Result);
169 // getID Wrappers - Ensure consistent usage...
170 string getID(const Function *F) {
171 return getID(F, "LLVMFunction_");
173 string getID(const BasicBlock *BB) {
174 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
176 string getID(const GlobalVariable *GV) {
177 return getID(GV, "LLVMGlobal_", ".G_");
179 string getID(const Constant *CV) {
180 return getID(CV, "LLVMConst_", ".C_");
186 //===----------------------------------------------------------------------===//
187 // SparcFunctionAsmPrinter Code
188 //===----------------------------------------------------------------------===//
190 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
191 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
192 : AsmPrinter(os, t) {}
194 virtual bool doInitialization(Module *M) {
199 virtual bool runOnFunction(Function *F) {
206 virtual bool doFinalization(Module *M) {
211 void emitFunction(const Function *F);
213 void emitBasicBlock(const BasicBlock *BB);
214 void emitMachineInst(const MachineInstr *MI);
216 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
217 void printOneOperand(const MachineOperand &Op);
219 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
220 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
222 unsigned getOperandMask(unsigned Opcode) {
224 case SUBcc: return 1 << 3; // Remove CC argument
225 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
226 default: return 0; // By default, don't hack operands...
232 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
233 unsigned int opNum) {
234 switch (MI->getOpCode()) {
236 case JMPLRET: return (opNum == 0);
237 default: return false;
243 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
244 unsigned int opNum) {
245 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
247 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
254 #define PrintOp1PlusOp2(Op1, Op2) \
255 printOneOperand(Op1); \
257 printOneOperand(Op2);
260 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
263 const MachineOperand& Op = MI->getOperand(opNum);
265 if (OpIsBranchTargetLabel(MI, opNum))
267 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
270 else if (OpIsMemoryAddressBase(MI, opNum))
273 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
286 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
288 switch (op.getOperandType())
290 case MachineOperand::MO_VirtualRegister:
291 case MachineOperand::MO_CCRegister:
292 case MachineOperand::MO_MachineRegister:
294 int RegNum = (int)op.getAllocatedRegNum();
296 // better to print code with NULL registers than to die
297 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
298 toAsm << "<NULL VALUE>";
300 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
305 case MachineOperand::MO_PCRelativeDisp:
307 const Value *Val = op.getVRegValue();
309 toAsm << "\t<*NULL Value*>";
310 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
312 else if (const Function *M = dyn_cast<Function>(Val))
314 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
316 else if (const Constant *CV = dyn_cast<Constant>(Val))
319 toAsm << "<unknown value=" << Val << ">";
323 case MachineOperand::MO_SignExtendedImmed:
324 case MachineOperand::MO_UnextendedImmed:
325 toAsm << (long)op.getImmedValue();
329 toAsm << op; // use dump field
336 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
338 unsigned Opcode = MI->getOpCode();
340 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
341 return; // IGNORE PHI NODES
343 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
345 unsigned Mask = getOperandMask(Opcode);
347 bool NeedComma = false;
349 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
350 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
351 if (NeedComma) toAsm << ", "; // Handle comma outputing
353 N = printOperands(MI, OpNum);
362 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
364 // Emit a label for the basic block
365 toAsm << getID(BB) << ":\n";
367 // Get the vector of machine instructions corresponding to this bb.
368 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
369 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
371 // Loop over all of the instructions in the basic block...
372 for (; MII != MIE; ++MII)
373 emitMachineInst(*MII);
374 toAsm << "\n"; // Seperate BB's with newlines
378 SparcFunctionAsmPrinter::emitFunction(const Function *M)
380 string methName = getID(M);
381 toAsm << "!****** Outputing Function: " << methName << " ******\n";
382 enterSection(AsmPrinter::Text);
383 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
384 //toAsm << "\t.type\t" << methName << ",#function\n";
385 toAsm << "\t.type\t" << methName << ", 2\n";
386 toAsm << methName << ":\n";
388 // Output code for all of the basic blocks in the function...
389 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
392 // Output a .size directive so the debugger knows the extents of the function
393 toAsm << ".EndOf_" << methName << ":\n\t.size "
394 << methName << ", .EndOf_"
395 << methName << "-" << methName << "\n";
397 // Put some spaces between the functions
401 } // End anonymous namespace
403 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
404 return new SparcFunctionAsmPrinter(Out, *this);
411 //===----------------------------------------------------------------------===//
412 // SparcFunctionAsmPrinter Code
413 //===----------------------------------------------------------------------===//
417 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
419 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
420 : AsmPrinter(os, t) {}
422 virtual bool run(Module *M) {
424 emitGlobalsAndConstants(M);
429 void emitGlobalsAndConstants(const Module *M);
431 void printGlobalVariable(const GlobalVariable *GV);
432 void printSingleConstant( const Constant* CV);
433 void printConstantValueOnly(const Constant* CV);
434 void printConstant( const Constant* CV, std::string valID = "");
436 static void FoldConstants(const Module *M,
437 std::hash_set<const Constant*> &moduleConstants);
442 // Can we treat the specified array as a string? Only if it is an array of
443 // ubytes or non-negative sbytes.
445 static bool isStringCompatible(ConstantArray *CPA) {
446 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
447 if (ETy == Type::UByteTy) return true;
448 if (ETy != Type::SByteTy) return false;
450 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
451 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
457 // toOctal - Convert the low order bits of X into an octal letter
458 static inline char toOctal(int X) {
462 // getAsCString - Return the specified array as a C compatible string, only if
463 // the predicate isStringCompatible is true.
465 static string getAsCString(ConstantArray *CPA) {
466 assert(isStringCompatible(CPA) && "Array is not string compatible!");
469 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
471 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
472 unsigned char C = (ETy == Type::SByteTy) ?
473 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
474 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
480 case '\a': Result += "\\a"; break;
481 case '\b': Result += "\\b"; break;
482 case '\f': Result += "\\f"; break;
483 case '\n': Result += "\\n"; break;
484 case '\r': Result += "\\r"; break;
485 case '\t': Result += "\\t"; break;
486 case '\v': Result += "\\v"; break;
489 Result += toOctal(C >> 6);
490 Result += toOctal(C >> 3);
491 Result += toOctal(C >> 0);
502 ArrayTypeIsString(ArrayType* arrayType)
504 return (arrayType->getElementType() == Type::UByteTy ||
505 arrayType->getElementType() == Type::SByteTy);
509 TypeToDataDirective(const Type* type)
511 switch(type->getPrimitiveID())
513 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
515 case Type::UShortTyID: case Type::ShortTyID:
517 case Type::UIntTyID: case Type::IntTyID:
519 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
521 case Type::FloatTyID:
523 case Type::DoubleTyID:
525 case Type::ArrayTyID:
526 if (ArrayTypeIsString((ArrayType*) type))
529 return "<InvaliDataTypeForPrinting>";
531 return "<InvaliDataTypeForPrinting>";
535 // Get the size of the constant for the given target.
536 // If this is an unsized array, return 0.
539 ConstantToSize(const Constant* CV, const TargetMachine& target)
541 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
543 ArrayType *aty = cast<ArrayType>(CPA->getType());
544 if (ArrayTypeIsString(aty))
545 return 1 + CPA->getNumOperands();
548 return target.findOptimalStorageSize(CV->getType());
553 // Align data larger than one L1 cache line on L1 cache line boundaries.
554 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
557 SizeToAlignment(unsigned int size, const TargetMachine& target)
559 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
560 if (size > (unsigned) cacheLineSize / 2)
561 return cacheLineSize;
563 for (unsigned sz=1; /*no condition*/; sz *= 2)
568 // Get the size of the type and then use SizeToAlignment.
571 TypeToAlignment(const Type* type, const TargetMachine& target)
573 return SizeToAlignment(target.findOptimalStorageSize(type), target);
576 // Get the size of the constant and then use SizeToAlignment.
577 // Handles strings as a special case;
579 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
581 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
582 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
583 return SizeToAlignment(1 + CPA->getNumOperands(), target);
585 return TypeToAlignment(CV->getType(), target);
589 // Print a single constant value.
591 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
593 assert(CV->getType() != Type::VoidTy &&
594 CV->getType() != Type::TypeTy &&
595 CV->getType() != Type::LabelTy &&
596 "Unexpected type for Constant");
598 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
599 && "Aggregate types should be handled outside this function");
601 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
603 if (CV->getType()->isPrimitiveType())
605 if (CV->getType()->isFloatingPoint()) {
606 // FP Constants are printed as integer constants to avoid losing
608 double Val = cast<ConstantFP>(CV)->getValue();
609 if (CV->getType() == Type::FloatTy) {
610 float FVal = (float)Val;
611 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
612 toAsm << *(unsigned int*)ProxyPtr;
613 } else if (CV->getType() == Type::DoubleTy) {
614 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
615 toAsm << *(uint64_t*)ProxyPtr;
617 assert(0 && "Unknown floating point type!");
620 toAsm << "\t! " << CV->getType()->getDescription()
621 << " value: " << Val << "\n";
623 WriteAsOperand(toAsm, CV, false, false) << "\n";
626 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
628 assert(CPP->isNullValue() &&
629 "Cannot yet print non-null pointer constants to assembly");
632 else if (isa<ConstantPointerRef>(CV))
634 assert(0 && "Cannot yet initialize pointer refs in assembly");
638 assert(0 && "Unknown elementary type for constant");
642 // Print a constant value or values (it may be an aggregate).
643 // Uses printSingleConstant() to print each individual value.
645 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
647 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
649 if (CPA && isStringCompatible(CPA))
650 { // print the string alone and return
651 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
654 { // Not a string. Print the values in successive locations
655 const std::vector<Use> &constValues = CPA->getValues();
656 for (unsigned i=1; i < constValues.size(); i++)
657 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
659 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
660 { // Print the fields in successive locations
661 const std::vector<Use>& constValues = CPS->getValues();
662 for (unsigned i=1; i < constValues.size(); i++)
663 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
666 this->printSingleConstant(CV);
669 // Print a constant (which may be an aggregate) prefixed by all the
670 // appropriate directives. Uses printConstantValueOnly() to print the
673 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
675 if (valID.length() == 0)
678 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
680 // Print .size and .type only if it is not a string.
681 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
682 if (CPA && isStringCompatible(CPA))
683 { // print it as a string and return
684 toAsm << valID << ":\n";
685 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
689 toAsm << "\t.type" << "\t" << valID << ",#object\n";
691 unsigned int constSize = ConstantToSize(CV, Target);
693 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
695 toAsm << valID << ":\n";
697 printConstantValueOnly(CV);
701 void SparcModuleAsmPrinter::FoldConstants(const Module *M,
702 std::hash_set<const Constant*> &MC) {
703 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
704 if (!(*I)->isExternal()) {
705 const std::hash_set<const Constant*> &pool =
706 MachineCodeForMethod::get(*I).getConstantPoolValues();
707 MC.insert(pool.begin(), pool.end());
711 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
713 toAsm << "\t.global\t" << getID(GV) << "\n";
715 if (GV->hasInitializer())
716 printConstant(GV->getInitializer(), getID(GV));
718 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
720 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
721 toAsm << "\t.reserve\t" << getID(GV) << ","
722 << Target.findOptimalStorageSize(GV->getType()->getElementType())
728 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
729 // First, get the constants there were marked by the code generator for
730 // inclusion in the assembly code data area and fold them all into a
731 // single constant pool since there may be lots of duplicates. Also,
732 // lets force these constants into the slot table so that we can get
733 // unique names for unnamed constants also.
735 std::hash_set<const Constant*> moduleConstants;
736 FoldConstants(M, moduleConstants);
738 // Now, emit the three data sections separately; the cost of I/O should
739 // make up for the cost of extra passes over the globals list!
741 // Section 1 : Read-only data section (implies initialized)
742 enterSection(AsmPrinter::ReadOnlyData);
743 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
744 if ((*GI)->hasInitializer() && (*GI)->isConstant())
745 printGlobalVariable(*GI);
747 for (std::hash_set<const Constant*>::const_iterator
748 I = moduleConstants.begin(),
749 E = moduleConstants.end(); I != E; ++I)
752 // Section 2 : Initialized read-write data section
753 enterSection(AsmPrinter::InitRWData);
754 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
755 if ((*GI)->hasInitializer() && ! (*GI)->isConstant())
756 printGlobalVariable(*GI);
758 // Section 3 : Uninitialized read-write data section
759 enterSection(AsmPrinter::UninitRWData);
760 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
761 if (! (*GI)->hasInitializer())
762 printGlobalVariable(*GI);
767 } // End anonymous namespace
769 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
770 return new SparcModuleAsmPrinter(Out, *this);