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/MachineCodeForBasicBlock.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/Module.h"
24 #include "llvm/SlotCalculator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "Support/StringExtras.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 &) {
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 const char *getPassName() const {
195 return "Output Sparc Assembly for Functions";
198 virtual bool doInitialization(Module &M) {
203 virtual bool runOnFunction(Function &F) {
210 virtual bool doFinalization(Module &M) {
215 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
216 AU.setPreservesAll();
219 void emitFunction(const Function &F);
221 void emitBasicBlock(const BasicBlock *BB);
222 void emitMachineInst(const MachineInstr *MI);
224 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
225 void printOneOperand(const MachineOperand &Op);
227 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
228 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
230 unsigned getOperandMask(unsigned Opcode) {
232 case SUBcc: return 1 << 3; // Remove CC argument
233 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
234 default: return 0; // By default, don't hack operands...
240 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
241 unsigned int opNum) {
242 switch (MI->getOpCode()) {
244 case JMPLRET: return (opNum == 0);
245 default: return false;
251 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
252 unsigned int opNum) {
253 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
255 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
262 #define PrintOp1PlusOp2(Op1, Op2) \
263 printOneOperand(Op1); \
265 printOneOperand(Op2);
268 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
271 const MachineOperand& Op = MI->getOperand(opNum);
273 if (OpIsBranchTargetLabel(MI, opNum))
275 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
278 else if (OpIsMemoryAddressBase(MI, opNum))
281 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
294 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
296 switch (op.getOperandType())
298 case MachineOperand::MO_VirtualRegister:
299 case MachineOperand::MO_CCRegister:
300 case MachineOperand::MO_MachineRegister:
302 int RegNum = (int)op.getAllocatedRegNum();
304 // better to print code with NULL registers than to die
305 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
306 toAsm << "<NULL VALUE>";
308 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
313 case MachineOperand::MO_PCRelativeDisp:
315 const Value *Val = op.getVRegValue();
316 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
318 if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
320 else if (const Function *M = dyn_cast<Function>(Val))
322 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
324 else if (const Constant *CV = dyn_cast<Constant>(Val))
327 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
331 case MachineOperand::MO_SignExtendedImmed:
332 toAsm << op.getImmedValue();
335 case MachineOperand::MO_UnextendedImmed:
336 toAsm << (uint64_t) op.getImmedValue();
340 toAsm << op; // use dump field
347 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
349 unsigned Opcode = MI->getOpCode();
351 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
352 return; // IGNORE PHI NODES
354 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
356 unsigned Mask = getOperandMask(Opcode);
358 bool NeedComma = false;
360 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
361 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
362 if (NeedComma) toAsm << ", "; // Handle comma outputing
364 N = printOperands(MI, OpNum);
373 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
375 // Emit a label for the basic block
376 toAsm << getID(BB) << ":\n";
378 // Get the vector of machine instructions corresponding to this bb.
379 const MachineCodeForBasicBlock &MIs = MachineCodeForBasicBlock::get(BB);
380 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
382 // Loop over all of the instructions in the basic block...
383 for (; MII != MIE; ++MII)
384 emitMachineInst(*MII);
385 toAsm << "\n"; // Seperate BB's with newlines
389 SparcFunctionAsmPrinter::emitFunction(const Function &F)
391 string methName = getID(&F);
392 toAsm << "!****** Outputing Function: " << methName << " ******\n";
393 enterSection(AsmPrinter::Text);
394 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
395 //toAsm << "\t.type\t" << methName << ",#function\n";
396 toAsm << "\t.type\t" << methName << ", 2\n";
397 toAsm << methName << ":\n";
399 // Output code for all of the basic blocks in the function...
400 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I)
403 // Output a .size directive so the debugger knows the extents of the function
404 toAsm << ".EndOf_" << methName << ":\n\t.size "
405 << methName << ", .EndOf_"
406 << methName << "-" << methName << "\n";
408 // Put some spaces between the functions
412 } // End anonymous namespace
414 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
415 return new SparcFunctionAsmPrinter(Out, *this);
422 //===----------------------------------------------------------------------===//
423 // SparcFunctionAsmPrinter Code
424 //===----------------------------------------------------------------------===//
428 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
430 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
431 : AsmPrinter(os, t) {}
433 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
435 virtual bool run(Module &M) {
437 emitGlobalsAndConstants(M);
442 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
443 AU.setPreservesAll();
447 void emitGlobalsAndConstants(const Module &M);
449 void printGlobalVariable(const GlobalVariable *GV);
450 void printSingleConstant( const Constant* CV);
451 void printConstantValueOnly(const Constant* CV);
452 void printConstant( const Constant* CV, std::string valID = "");
454 static void FoldConstants(const Module &M,
455 std::hash_set<const Constant*> &moduleConstants);
459 // Can we treat the specified array as a string? Only if it is an array of
460 // ubytes or non-negative sbytes.
462 static bool isStringCompatible(const ConstantArray *CPA) {
463 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
464 if (ETy == Type::UByteTy) return true;
465 if (ETy != Type::SByteTy) return false;
467 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
468 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
474 // toOctal - Convert the low order bits of X into an octal letter
475 static inline char toOctal(int X) {
479 // getAsCString - Return the specified array as a C compatible string, only if
480 // the predicate isStringCompatible is true.
482 static string getAsCString(const ConstantArray *CPA) {
483 assert(isStringCompatible(CPA) && "Array is not string compatible!");
486 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
488 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
489 unsigned char C = (ETy == Type::SByteTy) ?
490 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
491 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
495 } else if (isprint(C)) {
499 case '\a': Result += "\\a"; break;
500 case '\b': Result += "\\b"; break;
501 case '\f': Result += "\\f"; break;
502 case '\n': Result += "\\n"; break;
503 case '\r': Result += "\\r"; break;
504 case '\t': Result += "\\t"; break;
505 case '\v': Result += "\\v"; break;
508 Result += toOctal(C >> 6);
509 Result += toOctal(C >> 3);
510 Result += toOctal(C >> 0);
521 ArrayTypeIsString(const ArrayType* arrayType)
523 return (arrayType->getElementType() == Type::UByteTy ||
524 arrayType->getElementType() == Type::SByteTy);
528 TypeToDataDirective(const Type* type)
530 switch(type->getPrimitiveID())
532 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
534 case Type::UShortTyID: case Type::ShortTyID:
536 case Type::UIntTyID: case Type::IntTyID:
538 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
540 case Type::FloatTyID:
542 case Type::DoubleTyID:
544 case Type::ArrayTyID:
545 if (ArrayTypeIsString((ArrayType*) type))
548 return "<InvaliDataTypeForPrinting>";
550 return "<InvaliDataTypeForPrinting>";
554 // Get the size of the constant for the given target.
555 // If this is an unsized array, return 0.
558 ConstantToSize(const Constant* CV, const TargetMachine& target)
560 if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
562 const ArrayType *aty = cast<ArrayType>(CPA->getType());
563 if (ArrayTypeIsString(aty))
564 return 1 + CPA->getNumOperands();
567 return target.findOptimalStorageSize(CV->getType());
572 // Align data larger than one L1 cache line on L1 cache line boundaries.
573 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
576 SizeToAlignment(unsigned int size, const TargetMachine& target)
578 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
579 if (size > (unsigned) cacheLineSize / 2)
580 return cacheLineSize;
582 for (unsigned sz=1; /*no condition*/; sz *= 2)
587 // Get the size of the type and then use SizeToAlignment.
590 TypeToAlignment(const Type* type, const TargetMachine& target)
592 return SizeToAlignment(target.findOptimalStorageSize(type), target);
595 // Get the size of the constant and then use SizeToAlignment.
596 // Handles strings as a special case;
598 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
600 if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
601 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
602 return SizeToAlignment(1 + CPA->getNumOperands(), target);
604 return TypeToAlignment(CV->getType(), target);
608 // Print a single constant value.
610 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
612 assert(CV->getType() != Type::VoidTy &&
613 CV->getType() != Type::TypeTy &&
614 CV->getType() != Type::LabelTy &&
615 "Unexpected type for Constant");
617 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
618 && "Aggregate types should be handled outside this function");
620 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
622 if (CV->getType()->isPrimitiveType())
624 if (CV->getType()->isFloatingPoint()) {
625 // FP Constants are printed as integer constants to avoid losing
627 double Val = cast<ConstantFP>(CV)->getValue();
628 if (CV->getType() == Type::FloatTy) {
629 float FVal = (float)Val;
630 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
631 toAsm << *(unsigned int*)ProxyPtr;
632 } else if (CV->getType() == Type::DoubleTy) {
633 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
634 toAsm << *(uint64_t*)ProxyPtr;
636 assert(0 && "Unknown floating point type!");
639 toAsm << "\t! " << CV->getType()->getDescription()
640 << " value: " << Val << "\n";
642 WriteAsOperand(toAsm, CV, false, false) << "\n";
645 else if (const ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
647 assert(CPP->isNullValue() &&
648 "Cannot yet print non-null pointer constants to assembly");
651 else if (isa<ConstantPointerRef>(CV))
653 assert(0 && "Cannot yet initialize pointer refs in assembly");
657 assert(0 && "Unknown elementary type for constant");
661 // Print a constant value or values (it may be an aggregate).
662 // Uses printSingleConstant() to print each individual value.
664 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
666 const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
668 if (CPA && isStringCompatible(CPA))
669 { // print the string alone and return
670 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
673 { // Not a string. Print the values in successive locations
674 const std::vector<Use> &constValues = CPA->getValues();
675 for (unsigned i=0; i < constValues.size(); i++)
676 printConstantValueOnly(cast<Constant>(constValues[i].get()));
678 else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
679 { // Print the fields in successive locations
680 const std::vector<Use>& constValues = CPS->getValues();
681 for (unsigned i=0; i < constValues.size(); i++)
682 printConstantValueOnly(cast<Constant>(constValues[i].get()));
685 printSingleConstant(CV);
688 // Print a constant (which may be an aggregate) prefixed by all the
689 // appropriate directives. Uses printConstantValueOnly() to print the
692 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
694 if (valID.length() == 0)
697 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
699 // Print .size and .type only if it is not a string.
700 const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
701 if (CPA && isStringCompatible(CPA))
702 { // print it as a string and return
703 toAsm << valID << ":\n";
704 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
708 toAsm << "\t.type" << "\t" << valID << ",#object\n";
710 unsigned int constSize = ConstantToSize(CV, Target);
712 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
714 toAsm << valID << ":\n";
716 printConstantValueOnly(CV);
720 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
721 std::hash_set<const Constant*> &MC) {
722 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
723 if (!I->isExternal()) {
724 const std::hash_set<const Constant*> &pool =
725 MachineCodeForMethod::get(I).getConstantPoolValues();
726 MC.insert(pool.begin(), pool.end());
730 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
732 toAsm << "\t.global\t" << getID(GV) << "\n";
734 if (GV->hasInitializer())
735 printConstant(GV->getInitializer(), getID(GV));
737 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
739 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
740 toAsm << "\t.reserve\t" << getID(GV) << ","
741 << Target.findOptimalStorageSize(GV->getType()->getElementType())
747 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
748 // First, get the constants there were marked by the code generator for
749 // inclusion in the assembly code data area and fold them all into a
750 // single constant pool since there may be lots of duplicates. Also,
751 // lets force these constants into the slot table so that we can get
752 // unique names for unnamed constants also.
754 std::hash_set<const Constant*> moduleConstants;
755 FoldConstants(M, moduleConstants);
757 // Now, emit the three data sections separately; the cost of I/O should
758 // make up for the cost of extra passes over the globals list!
760 // Section 1 : Read-only data section (implies initialized)
761 enterSection(AsmPrinter::ReadOnlyData);
762 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
763 if (GI->hasInitializer() && GI->isConstant())
764 printGlobalVariable(GI);
766 for (std::hash_set<const Constant*>::const_iterator
767 I = moduleConstants.begin(),
768 E = moduleConstants.end(); I != E; ++I)
771 // Section 2 : Initialized read-write data section
772 enterSection(AsmPrinter::InitRWData);
773 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
774 if (GI->hasInitializer() && !GI->isConstant())
775 printGlobalVariable(GI);
777 // Section 3 : Uninitialized read-write data section
778 enterSection(AsmPrinter::UninitRWData);
779 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
780 if (!GI->hasInitializer())
781 printGlobalVariable(GI);
786 } // End anonymous namespace
788 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
789 return new SparcModuleAsmPrinter(Out, *this);