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 printConstant(const ConstPoolVal* CV, string valID = string(""));
64 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
65 void printOneOperand(const MachineOperand &Op);
67 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
68 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
70 // enterSection - Use this method to enter a different section of the output
71 // executable. This is used to only output neccesary section transitions.
73 void enterSection(enum Sections S) {
74 if (S == CurSection) return; // Only switch section if neccesary
77 toAsm << "\n\t.section ";
80 default: assert(0 && "Bad section name!");
81 case Text: toAsm << "\".text\""; break;
82 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
83 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
84 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
89 string getValidSymbolName(const string &S) {
92 // Symbol names in Sparc assembly language have these rules:
93 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
94 // (b) A name beginning in "." is treated as a local name.
95 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
97 if (S[0] == '_' || isdigit(S[0]))
100 for (unsigned i = 0; i < S.size(); ++i)
103 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
108 Result += char('0' + ((unsigned char)C >> 4));
109 Result += char('0' + (C & 0xF));
115 // getID - Return a valid identifier for the specified value. Base it on
116 // the name of the identifier if possible, use a numbered value based on
117 // prefix otherwise. FPrefix is always prepended to the output identifier.
119 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
121 string FP(FPrefix ? FPrefix : ""); // "Forced prefix"
123 Result = FP + V->getName();
125 int valId = Table.getValSlot(V);
127 ValIdMapConstIterator I = valToIdMap.find(V);
128 valId = (I == valToIdMap.end())? (valToIdMap[V] = valToIdMap.size())
131 Result = FP + string(Prefix) + itostr(valId);
133 return getValidSymbolName(Result);
136 // getID Wrappers - Ensure consistent usage...
137 string getID(const Module *M) {
138 return getID(M, "LLVMModule_");
140 string getID(const Method *M) {
141 return getID(M, "LLVMMethod_");
143 string getID(const BasicBlock *BB) {
144 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
146 string getID(const GlobalVariable *GV) {
147 return getID(GV, "LLVMGlobal_", ".G_");
149 string getID(const ConstPoolVal *CV) {
150 return getID(CV, "LLVMConst_", ".C_");
153 unsigned getOperandMask(unsigned Opcode) {
155 case SUBcc: return 1 << 3; // Remove CC argument
156 case BA: case BRZ: // Remove Arg #0, which is always null or xcc
157 case BRLEZ: case BRLZ:
158 case BRNZ: case BRGZ:
159 case BRGEZ: return 1 << 0;
161 default: return 0; // By default, don't hack operands...
167 SparcAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
168 unsigned int opNum) {
169 switch (MI->getOpCode()) {
171 case JMPLRET: return (opNum == 0);
172 default: return false;
178 SparcAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
179 unsigned int opNum) {
180 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
182 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
189 #define PrintOp1PlusOp2(Op1, Op2) \
190 printOneOperand(Op1); toAsm << "+"; printOneOperand(Op2);
194 SparcAsmPrinter::printOperands(const MachineInstr *MI,
197 const MachineOperand& Op = MI->getOperand(opNum);
199 if (OpIsBranchTargetLabel(MI, opNum))
201 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
204 else if (OpIsMemoryAddressBase(MI, opNum))
207 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
220 SparcAsmPrinter::printOneOperand(const MachineOperand &op)
222 switch (op.getOperandType())
224 case MachineOperand::MO_VirtualRegister:
225 case MachineOperand::MO_CCRegister:
226 case MachineOperand::MO_MachineRegister:
228 int RegNum = (int)op.getAllocatedRegNum();
230 // ****this code is temporary till NULL Values are fixed
231 if (RegNum == 10000) {
232 toAsm << "<NULL VALUE>";
234 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
239 case MachineOperand::MO_PCRelativeDisp:
241 const Value *Val = op.getVRegValue();
243 toAsm << "\t<*NULL Value*>";
244 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
246 else if (const Method *M = dyn_cast<const Method>(Val))
248 else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
250 else if (const ConstPoolVal *CV = dyn_cast<const ConstPoolVal>(Val))
253 toAsm << "<unknown value=" << Val << ">";
257 case MachineOperand::MO_SignExtendedImmed:
258 case MachineOperand::MO_UnextendedImmed:
259 toAsm << op.getImmedValue();
263 toAsm << op; // use dump field
270 SparcAsmPrinter::emitMachineInst(const MachineInstr *MI)
272 unsigned Opcode = MI->getOpCode();
274 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
275 return; // IGNORE PHI NODES
277 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
279 unsigned Mask = getOperandMask(Opcode);
281 bool NeedComma = false;
283 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
284 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
285 if (NeedComma) toAsm << ", "; // Handle comma outputing
287 N = printOperands(MI, OpNum);
296 SparcAsmPrinter::emitBasicBlock(const BasicBlock *BB)
298 // Emit a label for the basic block
299 toAsm << getID(BB) << ":\n";
301 // Get the vector of machine instructions corresponding to this bb.
302 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
303 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
305 // Loop over all of the instructions in the basic block...
306 for (; MII != MIE; ++MII)
307 emitMachineInst(*MII);
308 toAsm << "\n"; // Seperate BB's with newlines
312 SparcAsmPrinter::emitMethod(const Method *M)
314 if (M->isExternal()) return;
316 // Make sure the slot table has information about this method...
317 Table.incorporateMethod(M);
319 string methName = getID(M);
320 toAsm << "!****** Outputing Method: " << methName << " ******\n";
322 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
323 //toAsm << "\t.type\t" << methName << ",#function\n";
324 toAsm << "\t.type\t" << methName << ", 2\n";
325 toAsm << methName << ":\n";
327 // Output code for all of the basic blocks in the method...
328 for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
331 // Output a .size directive so the debugger knows the extents of the function
332 toAsm << ".EndOf_" << methName << ":\n\t.size "
333 << methName << ", .EndOf_"
334 << methName << "-" << methName << endl;
336 // Put some spaces between the methods
339 // Forget all about M.
344 ArrayTypeIsString(ArrayType* arrayType)
346 return (arrayType->getElementType() == Type::UByteTy ||
347 arrayType->getElementType() == Type::SByteTy);
350 inline const string TypeToDataDirective(const Type* type)
352 switch(type->getPrimitiveID())
354 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
356 case Type::UShortTyID: case Type::ShortTyID:
358 case Type::UIntTyID: case Type::IntTyID:
360 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
362 case Type::FloatTyID:
364 case Type::DoubleTyID:
366 case Type::ArrayTyID:
367 if (ArrayTypeIsString((ArrayType*) type))
370 return "<InvaliDataTypeForPrinting>";
372 return "<InvaliDataTypeForPrinting>";
376 inline unsigned int ConstantToSize(const ConstPoolVal* CV,
377 const TargetMachine& target) {
378 if (ConstPoolArray* AV = dyn_cast<ConstPoolArray>(CV))
379 if (ArrayTypeIsString((ArrayType*) CV->getType()))
380 return 1 + AV->getNumOperands();
382 return target.findOptimalStorageSize(CV->getType());
387 unsigned int TypeToSize(const Type* type, const TargetMachine& target)
389 return target.findOptimalStorageSize(type);
394 TypeToAlignment(const Type* type, const TargetMachine& target)
396 if (type->getPrimitiveID() == Type::ArrayTyID &&
397 ArrayTypeIsString((ArrayType*) type))
398 return target.findOptimalStorageSize(Type::LongTy);
400 return target.findOptimalStorageSize(type);
405 SparcAsmPrinter::printConstant(const ConstPoolVal* CV, string valID)
407 if (valID.length() == 0)
410 assert(CV->getType() != Type::VoidTy &&
411 CV->getType() != Type::TypeTy &&
412 CV->getType() != Type::LabelTy &&
413 "Unexpected type for ConstPoolVal");
415 toAsm << "\t.align\t" << TypeToAlignment(CV->getType(), Target)
418 toAsm << valID << ":" << endl;
421 << TypeToDataDirective(CV->getType()) << "\t";
423 if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CV))
424 if (isStringCompatible(CPA))
426 toAsm << getAsCString(CPA) << endl;
430 if (CV->getType()->isPrimitiveType())
432 if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
433 toAsm << "0r"; // FP constants must have this prefix
434 toAsm << CV->getStrValue() << endl;
436 else if (ConstPoolPointer* CPP = dyn_cast<ConstPoolPointer>(CV))
438 if (! CPP->isNullValue())
439 assert(0 && "Cannot yet print non-null pointer constants to assembly");
441 toAsm << (void*) NULL << endl;
443 else if (ConstPoolPointerRef* CPRef = dyn_cast<ConstPoolPointerRef>(CV))
445 assert(0 && "Cannot yet initialize pointer refs in assembly");
449 assert(0 && "Cannot yet print non-primitive constants to assembly");
450 // toAsm << CV->getStrValue() << endl;
453 toAsm << "\t.type" << "\t" << valID << ",#object" << endl;
454 toAsm << "\t.size" << "\t" << valID << ","
455 << ConstantToSize(CV, Target) << endl;
460 SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
462 toAsm << "\t.global\t" << getID(GV) << endl;
464 if (GV->hasInitializer())
465 printConstant(GV->getInitializer(), getID(GV));
467 toAsm << "\t.align\t"
468 << TypeToAlignment(GV->getType()->getValueType(), Target) << endl;
469 toAsm << "\t.type\t" << getID(GV) << ",#object" << endl;
470 toAsm << "\t.reserve\t" << getID(GV) << ","
471 << TypeToSize(GV->getType()->getValueType(), Target)
478 FoldConstPools(const Module *M,
479 hash_set<const ConstPoolVal*>& moduleConstPool)
481 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
482 if (! (*I)->isExternal())
484 const hash_set<const ConstPoolVal*>& pool =
485 MachineCodeForMethod::get(*I).getConstantPoolValues();
486 moduleConstPool.insert(pool.begin(), pool.end());
492 SparcAsmPrinter::emitGlobalsAndConstants(const Module *M)
494 // First, get the constants there were marked by the code generator for
495 // inclusion in the assembly code data area and fold them all into a
496 // single constant pool since there may be lots of duplicates. Also,
497 // lets force these constants into the slot table so that we can get
498 // unique names for unnamed constants also.
500 hash_set<const ConstPoolVal*> moduleConstPool;
501 FoldConstPools(M, moduleConstPool);
503 // Now, emit the three data sections separately; the cost of I/O should
504 // make up for the cost of extra passes over the globals list!
506 // Read-only data section (implies initialized)
507 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
509 const GlobalVariable* GV = *GI;
510 if (GV->hasInitializer() && GV->isConstant())
512 if (GI == M->gbegin())
513 enterSection(ReadOnlyData);
514 printGlobalVariable(GV);
518 for (hash_set<const ConstPoolVal*>::const_iterator I=moduleConstPool.begin(),
519 E = moduleConstPool.end(); I != E; ++I)
522 // Initialized read-write data section
523 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
525 const GlobalVariable* GV = *GI;
526 if (GV->hasInitializer() && ! GV->isConstant())
528 if (GI == M->gbegin())
529 enterSection(InitRWData);
530 printGlobalVariable(GV);
534 // Uninitialized read-write data section
535 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
537 const GlobalVariable* GV = *GI;
538 if (! GV->hasInitializer())
540 if (GI == M->gbegin())
541 enterSection(UninitRWData);
542 printGlobalVariable(GV);
551 SparcAsmPrinter::emitModule(const Module *M)
553 // TODO: Look for a filename annotation on M to emit a .file directive
554 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
557 emitGlobalsAndConstants(M);
560 } // End anonymous namespace
564 // emitAssembly - Output assembly language code (a .s file) for the specified
565 // method. The specified method must have been compiled before this may be
569 UltraSparc::emitAssembly(const Module *M, ostream &toAsm) const
571 SparcAsmPrinter Print(toAsm, M, *this);