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 // The entry point of this file is the UltraSparc::emitAssembly method.
9 //===----------------------------------------------------------------------===//
11 #include "SparcInternals.h"
12 #include "llvm/Analysis/SlotCalculator.h"
13 #include "llvm/Transforms/Linker.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/ConstPoolVals.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/Method.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/HashExtras.h"
23 #include "llvm/Support/StringExtras.h"
29 class SparcAsmPrinter {
30 typedef hash_map<const Value*, int> ValIdMap;
31 typedef ValIdMap:: iterator ValIdMapIterator;
32 typedef ValIdMap::const_iterator ValIdMapConstIterator;
35 SlotCalculator Table; // map anonymous values to unique integer IDs
36 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
37 const UltraSparc &Target;
48 inline SparcAsmPrinter(ostream &o, const Module *M, const UltraSparc &t)
49 : toAsm(o), Table(SlotCalculator(M, true)), Target(t), CurSection(Unknown) {
54 void emitModule(const Module *M);
55 void emitMethod(const Method *M);
56 void emitGlobalsAndConstants(const Module* module);
57 //void processMethodArgument(const MethodArgument *MA);
58 void emitBasicBlock(const BasicBlock *BB);
59 void emitMachineInst(const MachineInstr *MI);
61 void printGlobalVariable( const GlobalVariable* GV);
62 void printSingleConstant( const ConstPoolVal* CV);
63 void printConstantValueOnly(const ConstPoolVal* CV);
64 void printConstant( const ConstPoolVal* CV, string valID=string(""));
66 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
67 void printOneOperand(const MachineOperand &Op);
69 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
70 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
72 // enterSection - Use this method to enter a different section of the output
73 // executable. This is used to only output neccesary section transitions.
75 void enterSection(enum Sections S) {
76 if (S == CurSection) return; // Only switch section if neccesary
79 toAsm << "\n\t.section ";
82 default: assert(0 && "Bad section name!");
83 case Text: toAsm << "\".text\""; break;
84 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
85 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
86 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
91 string getValidSymbolName(const string &S) {
94 // Symbol names in Sparc assembly language have these rules:
95 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
96 // (b) A name beginning in "." is treated as a local name.
97 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
99 if (S[0] == '_' || isdigit(S[0]))
102 for (unsigned i = 0; i < S.size(); ++i)
105 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
110 Result += char('0' + ((unsigned char)C >> 4));
111 Result += char('0' + (C & 0xF));
117 // getID - Return a valid identifier for the specified value. Base it on
118 // the name of the identifier if possible, use a numbered value based on
119 // prefix otherwise. FPrefix is always prepended to the output identifier.
121 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
123 string FP(FPrefix ? FPrefix : ""); // "Forced prefix"
125 Result = FP + V->getName();
127 int valId = Table.getValSlot(V);
129 ValIdMapConstIterator I = valToIdMap.find(V);
130 valId = (I == valToIdMap.end())? (valToIdMap[V] = valToIdMap.size())
133 Result = FP + string(Prefix) + itostr(valId);
135 return getValidSymbolName(Result);
138 // getID Wrappers - Ensure consistent usage...
139 string getID(const Module *M) {
140 return getID(M, "LLVMModule_");
142 string getID(const Method *M) {
143 return getID(M, "LLVMMethod_");
145 string getID(const BasicBlock *BB) {
146 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
148 string getID(const GlobalVariable *GV) {
149 return getID(GV, "LLVMGlobal_", ".G_");
151 string getID(const ConstPoolVal *CV) {
152 return getID(CV, "LLVMConst_", ".C_");
155 unsigned getOperandMask(unsigned Opcode) {
157 case SUBcc: return 1 << 3; // Remove CC argument
158 case BA: case BRZ: // Remove Arg #0, which is always null or xcc
159 case BRLEZ: case BRLZ:
160 case BRNZ: case BRGZ:
161 case BRGEZ: return 1 << 0;
163 default: return 0; // By default, don't hack operands...
169 SparcAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
170 unsigned int opNum) {
171 switch (MI->getOpCode()) {
173 case JMPLRET: return (opNum == 0);
174 default: return false;
180 SparcAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
181 unsigned int opNum) {
182 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
184 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
191 #define PrintOp1PlusOp2(Op1, Op2) \
192 printOneOperand(Op1); \
194 printOneOperand(Op2);
197 SparcAsmPrinter::printOperands(const MachineInstr *MI,
200 const MachineOperand& Op = MI->getOperand(opNum);
202 if (OpIsBranchTargetLabel(MI, opNum))
204 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
207 else if (OpIsMemoryAddressBase(MI, opNum))
210 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
223 SparcAsmPrinter::printOneOperand(const MachineOperand &op)
225 switch (op.getOperandType())
227 case MachineOperand::MO_VirtualRegister:
228 case MachineOperand::MO_CCRegister:
229 case MachineOperand::MO_MachineRegister:
231 int RegNum = (int)op.getAllocatedRegNum();
233 // ****this code is temporary till NULL Values are fixed
234 if (RegNum == 10000) {
235 toAsm << "<NULL VALUE>";
237 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
242 case MachineOperand::MO_PCRelativeDisp:
244 const Value *Val = op.getVRegValue();
246 toAsm << "\t<*NULL Value*>";
247 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
249 else if (const Method *M = dyn_cast<const Method>(Val))
251 else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
253 else if (const ConstPoolVal *CV = dyn_cast<const ConstPoolVal>(Val))
256 toAsm << "<unknown value=" << Val << ">";
260 case MachineOperand::MO_SignExtendedImmed:
261 case MachineOperand::MO_UnextendedImmed:
262 toAsm << op.getImmedValue();
266 toAsm << op; // use dump field
273 SparcAsmPrinter::emitMachineInst(const MachineInstr *MI)
275 unsigned Opcode = MI->getOpCode();
277 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
278 return; // IGNORE PHI NODES
280 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
282 unsigned Mask = getOperandMask(Opcode);
284 bool NeedComma = false;
286 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
287 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
288 if (NeedComma) toAsm << ", "; // Handle comma outputing
290 N = printOperands(MI, OpNum);
299 SparcAsmPrinter::emitBasicBlock(const BasicBlock *BB)
301 // Emit a label for the basic block
302 toAsm << getID(BB) << ":\n";
304 // Get the vector of machine instructions corresponding to this bb.
305 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
306 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
308 // Loop over all of the instructions in the basic block...
309 for (; MII != MIE; ++MII)
310 emitMachineInst(*MII);
311 toAsm << "\n"; // Seperate BB's with newlines
315 SparcAsmPrinter::emitMethod(const Method *M)
317 if (M->isExternal()) return;
319 // Make sure the slot table has information about this method...
320 Table.incorporateMethod(M);
322 string methName = getID(M);
323 toAsm << "!****** Outputing Method: " << methName << " ******\n";
325 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
326 //toAsm << "\t.type\t" << methName << ",#function\n";
327 toAsm << "\t.type\t" << methName << ", 2\n";
328 toAsm << methName << ":\n";
330 // Output code for all of the basic blocks in the method...
331 for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
334 // Output a .size directive so the debugger knows the extents of the function
335 toAsm << ".EndOf_" << methName << ":\n\t.size "
336 << methName << ", .EndOf_"
337 << methName << "-" << methName << endl;
339 // Put some spaces between the methods
342 // Forget all about M.
347 ArrayTypeIsString(ArrayType* arrayType)
349 return (arrayType->getElementType() == Type::UByteTy ||
350 arrayType->getElementType() == Type::SByteTy);
354 TypeToDataDirective(const Type* type)
356 switch(type->getPrimitiveID())
358 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
360 case Type::UShortTyID: case Type::ShortTyID:
362 case Type::UIntTyID: case Type::IntTyID:
364 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
366 case Type::FloatTyID:
368 case Type::DoubleTyID:
370 case Type::ArrayTyID:
371 if (ArrayTypeIsString((ArrayType*) type))
374 return "<InvaliDataTypeForPrinting>";
376 return "<InvaliDataTypeForPrinting>";
380 // Get the size of the constant for the given target.
381 // If this is an unsized array, return 0.
384 ConstantToSize(const ConstPoolVal* CV, const TargetMachine& target)
386 if (ConstPoolArray* CPA = dyn_cast<ConstPoolArray>(CV))
388 ArrayType *aty = cast<ArrayType>(CPA->getType());
389 if (ArrayTypeIsString(aty))
390 return 1 + CPA->getNumOperands();
391 else if (! aty->isSized())
395 return target.findOptimalStorageSize(CV->getType());
399 unsigned int TypeToSize(const Type* type, const TargetMachine& target)
401 return target.findOptimalStorageSize(type);
405 // Align data larger than one L1 cache line on L1 cache line boundaries.
406 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
409 SizeToAlignment(unsigned int size, const TargetMachine& target)
411 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
412 if (size > (unsigned) cacheLineSize / 2)
413 return cacheLineSize;
415 for (unsigned sz=1; /*no condition*/; sz *= 2)
420 // Get the size of the type and then use SizeToAlignment.
421 // If this is an unsized array, just return the L1 cache line size
422 // (viz., the default behavior for large global objects).
425 TypeToAlignment(const Type* type, const TargetMachine& target)
427 if (ArrayType* aty = dyn_cast<ArrayType>(type))
428 if (! aty->isSized())
429 return target.getCacheInfo().getCacheLineSize(1);
431 return SizeToAlignment(target.findOptimalStorageSize(type), target);
434 // Get the size of the constant and then use SizeToAlignment.
435 // Handles strings as a special case;
437 ConstantToAlignment(const ConstPoolVal* CV, const TargetMachine& target)
439 unsigned int constantSize;
440 if (ConstPoolArray* CPA = dyn_cast<ConstPoolArray>(CV))
441 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
442 return SizeToAlignment(1 + CPA->getNumOperands(), target);
444 return TypeToAlignment(CV->getType(), target);
448 // Print a single constant value.
450 SparcAsmPrinter::printSingleConstant(const ConstPoolVal* CV)
452 assert(CV->getType() != Type::VoidTy &&
453 CV->getType() != Type::TypeTy &&
454 CV->getType() != Type::LabelTy &&
455 "Unexpected type for ConstPoolVal");
457 assert((! isa<ConstPoolArray>( CV) && ! isa<ConstPoolStruct>(CV))
458 && "Collective types should be handled outside this function");
461 << TypeToDataDirective(CV->getType()) << "\t";
463 if (CV->getType()->isPrimitiveType())
465 if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
466 toAsm << "0r"; // FP constants must have this prefix
467 toAsm << CV->getStrValue() << endl;
469 else if (ConstPoolPointer* CPP = dyn_cast<ConstPoolPointer>(CV))
471 if (! CPP->isNullValue())
472 assert(0 && "Cannot yet print non-null pointer constants to assembly");
474 toAsm << (void*) NULL << endl;
476 else if (ConstPoolPointerRef* CPRef = dyn_cast<ConstPoolPointerRef>(CV))
478 assert(0 && "Cannot yet initialize pointer refs in assembly");
482 assert(0 && "Unknown elementary type for constant");
486 // Print a constant value or values (it may be an aggregate).
487 // Uses printSingleConstant() to print each individual value.
489 SparcAsmPrinter::printConstantValueOnly(const ConstPoolVal* CV)
491 ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CV);
493 if (CPA && isStringCompatible(CPA))
494 { // print the string alone and return
495 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << endl;
498 { // Not a string. Print the values in successive locations
499 const vector<Use>& constValues = CPA->getValues();
500 for (unsigned i=1; i < constValues.size(); i++)
501 this->printConstantValueOnly(cast<ConstPoolVal>(constValues[i].get()));
503 else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CV))
504 { // Print the fields in successive locations
505 const vector<Use>& constValues = CPS->getValues();
506 for (unsigned i=1; i < constValues.size(); i++)
507 this->printConstantValueOnly(cast<ConstPoolVal>(constValues[i].get()));
510 this->printSingleConstant(CV);
513 // Print a constant (which may be an aggregate) prefixed by all the
514 // appropriate directives. Uses printConstantValueOnly() to print the
517 SparcAsmPrinter::printConstant(const ConstPoolVal* CV, string valID)
519 if (valID.length() == 0)
522 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target)
525 // Print .size and .type only if it is not a string.
526 ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CV);
527 if (CPA && isStringCompatible(CPA))
528 { // print it as a string and return
529 toAsm << valID << ":" << endl;
530 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << endl;
534 toAsm << "\t.type" << "\t" << valID << ",#object" << endl;
536 unsigned int constSize = ConstantToSize(CV, Target);
538 toAsm << "\t.size" << "\t" << valID << ","
539 << constSize << endl;
541 toAsm << valID << ":" << endl;
543 this->printConstantValueOnly(CV);
548 SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
550 toAsm << "\t.global\t" << getID(GV) << endl;
552 if (GV->hasInitializer())
553 printConstant(GV->getInitializer(), getID(GV));
555 toAsm << "\t.align\t"
556 << TypeToAlignment(GV->getType()->getValueType(), Target) << endl;
557 toAsm << "\t.type\t" << getID(GV) << ",#object" << endl;
558 toAsm << "\t.reserve\t" << getID(GV) << ","
559 << TypeToSize(GV->getType()->getValueType(), Target)
566 FoldConstPools(const Module *M,
567 hash_set<const ConstPoolVal*>& moduleConstPool)
569 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
570 if (! (*I)->isExternal())
572 const hash_set<const ConstPoolVal*>& pool =
573 MachineCodeForMethod::get(*I).getConstantPoolValues();
574 moduleConstPool.insert(pool.begin(), pool.end());
580 SparcAsmPrinter::emitGlobalsAndConstants(const Module *M)
582 // First, get the constants there were marked by the code generator for
583 // inclusion in the assembly code data area and fold them all into a
584 // single constant pool since there may be lots of duplicates. Also,
585 // lets force these constants into the slot table so that we can get
586 // unique names for unnamed constants also.
588 hash_set<const ConstPoolVal*> moduleConstPool;
589 FoldConstPools(M, moduleConstPool);
591 // Now, emit the three data sections separately; the cost of I/O should
592 // make up for the cost of extra passes over the globals list!
594 // Read-only data section (implies initialized)
595 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
597 const GlobalVariable* GV = *GI;
598 if (GV->hasInitializer() && GV->isConstant())
600 if (GI == M->gbegin())
601 enterSection(ReadOnlyData);
602 printGlobalVariable(GV);
606 for (hash_set<const ConstPoolVal*>::const_iterator I=moduleConstPool.begin(),
607 E = moduleConstPool.end(); I != E; ++I)
610 // Initialized read-write data section
611 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
613 const GlobalVariable* GV = *GI;
614 if (GV->hasInitializer() && ! GV->isConstant())
616 if (GI == M->gbegin())
617 enterSection(InitRWData);
618 printGlobalVariable(GV);
622 // Uninitialized read-write data section
623 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
625 const GlobalVariable* GV = *GI;
626 if (! GV->hasInitializer())
628 if (GI == M->gbegin())
629 enterSection(UninitRWData);
630 printGlobalVariable(GV);
639 SparcAsmPrinter::emitModule(const Module *M)
641 // TODO: Look for a filename annotation on M to emit a .file directive
642 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
645 emitGlobalsAndConstants(M);
648 } // End anonymous namespace
652 // emitAssembly - Output assembly language code (a .s file) for the specified
653 // method. The specified method must have been compiled before this may be
657 UltraSparc::emitAssembly(const Module *M, ostream &toAsm) const
659 SparcAsmPrinter Print(toAsm, M, *this);