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/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/SlotCalculator.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "Support/StringExtras.h"
32 #include "Support/Statistic.h"
33 #include "SparcInternals.h"
42 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
44 class GlobalIdTable: public Annotation {
45 static AnnotationID AnnotId;
46 friend class AsmPrinter; // give access to AnnotId
48 typedef hash_map<const Value*, int> ValIdMap;
49 typedef ValIdMap::const_iterator ValIdMapConstIterator;
50 typedef ValIdMap:: iterator ValIdMapIterator;
52 SlotCalculator Table; // map anonymous values to unique integer IDs
53 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
55 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
58 AnnotationID GlobalIdTable::AnnotId =
59 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
61 //===--------------------------------------------------------------------===//
64 /// Can we treat the specified array as a string? Only if it is an array of
65 /// ubytes or non-negative sbytes.
67 bool isStringCompatible(const ConstantArray *CVA) {
68 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
69 if (ETy == Type::UByteTy) return true;
70 if (ETy != Type::SByteTy) return false;
72 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
73 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
79 /// getAsCString - Return the specified array as a C compatible string, only
80 /// if the predicate isStringCompatible is true.
82 std::string getAsCString(const ConstantArray *CVA) {
83 assert(isStringCompatible(CVA) && "Array is not string compatible!");
86 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
88 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
89 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
93 } else if (C == '\\') {
95 } else if (isprint(C)) {
98 Result += '\\'; // print all other chars as octal value
99 // Convert C to octal representation
100 Result += ((C >> 6) & 7) + '0';
101 Result += ((C >> 3) & 7) + '0';
102 Result += ((C >> 0) & 7) + '0';
110 inline bool ArrayTypeIsString(const ArrayType* arrayType) {
111 return (arrayType->getElementType() == Type::UByteTy ||
112 arrayType->getElementType() == Type::SByteTy);
115 inline const std::string
116 TypeToDataDirective(const Type* type) {
117 switch(type->getPrimitiveID())
119 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
121 case Type::UShortTyID: case Type::ShortTyID:
123 case Type::UIntTyID: case Type::IntTyID:
125 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
127 case Type::FloatTyID:
129 case Type::DoubleTyID:
131 case Type::ArrayTyID:
132 if (ArrayTypeIsString((ArrayType*) type))
135 return "<InvaliDataTypeForPrinting>";
137 return "<InvaliDataTypeForPrinting>";
141 /// Get the size of the constant for the given target.
142 /// If this is an unsized array, return 0.
145 ConstantToSize(const Constant* CV, const TargetMachine& target) {
146 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV)) {
147 const ArrayType *aty = cast<ArrayType>(CVA->getType());
148 if (ArrayTypeIsString(aty))
149 return 1 + CVA->getNumOperands();
152 return target.findOptimalStorageSize(CV->getType());
155 /// Align data larger than one L1 cache line on L1 cache line boundaries.
156 /// Align all smaller data on the next higher 2^x boundary (4, 8, ...).
159 SizeToAlignment(unsigned int size, const TargetMachine& target) {
160 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
161 if (size > (unsigned) cacheLineSize / 2)
162 return cacheLineSize;
164 for (unsigned sz=1; /*no condition*/; sz *= 2)
169 /// Get the size of the type and then use SizeToAlignment.
172 TypeToAlignment(const Type* type, const TargetMachine& target) {
173 return SizeToAlignment(target.findOptimalStorageSize(type), target);
176 /// Get the size of the constant and then use SizeToAlignment.
177 /// Handles strings as a special case;
179 ConstantToAlignment(const Constant* CV, const TargetMachine& target) {
180 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
181 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
182 return SizeToAlignment(1 + CVA->getNumOperands(), target);
184 return TypeToAlignment(CV->getType(), target);
187 } // End anonymous namespace
189 } // End namespace llvm
193 //===---------------------------------------------------------------------===//
194 // Code abstracted away from the AsmPrinter
195 //===---------------------------------------------------------------------===//
202 GlobalIdTable* idTable;
205 const TargetMachine &Target;
215 AsmPrinter(std::ostream &os, const TargetMachine &T)
216 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
218 // (start|end)(Module|Function) - Callback methods invoked by subclasses
219 void startModule(Module &M) {
220 // Create the global id table if it does not already exist
221 idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
222 if (idTable == NULL) {
223 idTable = new GlobalIdTable(&M);
224 M.addAnnotation(idTable);
228 void PrintZeroBytesToPad(int numBytes) {
229 for (/* no init */; numBytes >= 8; numBytes -= 8)
230 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
233 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
238 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
241 /// Print a single constant value.
243 void printSingleConstantValue(const Constant* CV);
245 /// Print a constant value or values (it may be an aggregate).
246 /// Uses printSingleConstantValue() to print each individual value.
248 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
250 // Print a constant (which may be an aggregate) prefixed by all the
251 // appropriate directives. Uses printConstantValueOnly() to print the
253 void printConstant(const Constant* CV, std::string valID = "") {
254 if (valID.length() == 0)
257 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
259 // Print .size and .type only if it is not a string.
260 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
261 if (CVA && isStringCompatible(CVA)) {
262 // print it as a string and return
263 toAsm << valID << ":\n";
264 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
268 toAsm << "\t.type" << "\t" << valID << ",#object\n";
270 unsigned int constSize = ConstantToSize(CV, Target);
272 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
274 toAsm << valID << ":\n";
276 printConstantValueOnly(CV);
279 void startFunction(Function &F) {
280 // Make sure the slot table has information about this function...
281 idTable->Table.incorporateFunction(&F);
283 void endFunction(Function &) {
284 idTable->Table.purgeFunction(); // Forget all about F
287 // Check if a value is external or accessible from external code.
288 bool isExternal(const Value* V) {
289 const GlobalValue *GV = dyn_cast<GlobalValue>(V);
290 return GV && GV->hasExternalLinkage();
293 // enterSection - Use this method to enter a different section of the output
294 // executable. This is used to only output necessary section transitions.
296 void enterSection(enum Sections S) {
297 if (S == CurSection) return; // Only switch section if necessary
300 toAsm << "\n\t.section ";
303 default: assert(0 && "Bad section name!");
304 case Text: toAsm << "\".text\""; break;
305 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
306 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
307 case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
312 static std::string getValidSymbolName(const std::string &S) {
315 // Symbol names in Sparc assembly language have these rules:
316 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
317 // (b) A name beginning in "." is treated as a local name.
322 for (unsigned i = 0; i < S.size(); ++i) {
324 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
328 Result += char('0' + ((unsigned char)C >> 4));
329 Result += char('0' + (C & 0xF));
335 // getID - Return a valid identifier for the specified value. Base it on
336 // the name of the identifier if possible (qualified by the type), and
337 // use a numbered value based on prefix otherwise.
338 // FPrefix is always prepended to the output identifier.
340 std::string getID(const Value *V, const char *Prefix,
341 const char *FPrefix = 0)
343 std::string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
345 Result += V->hasName() ? V->getName() : std::string(Prefix);
347 // Qualify all internal names with a unique id.
348 if (!isExternal(V)) {
349 int valId = idTable->Table.getSlot(V);
351 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
352 if (I == idTable->valToIdMap.end())
353 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
357 Result = Result + "_" + itostr(valId);
359 // Replace or prefix problem characters in the name
360 Result = getValidSymbolName(Result);
366 // getID Wrappers - Ensure consistent usage...
367 std::string getID(const Function *F) {
368 return getID(F, "LLVMFunction_");
370 std::string getID(const BasicBlock *BB) {
371 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
373 std::string getID(const GlobalVariable *GV) {
374 return getID(GV, "LLVMGlobal_");
376 std::string getID(const Constant *CV) {
377 return getID(CV, "LLVMConst_", ".C_");
379 std::string getID(const GlobalValue *GV) {
380 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
382 else if (const Function *F = dyn_cast<Function>(GV))
384 assert(0 && "Unexpected type of GlobalValue!");
388 // Combines expressions
389 inline std::string ConstantArithExprToString(const ConstantExpr* CE,
390 const TargetMachine &TM,
391 const std::string &op) {
392 return "(" + valToExprString(CE->getOperand(0), TM) + op
393 + valToExprString(CE->getOperand(1), TM) + ")";
396 /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
397 /// and return this as a string.
399 std::string ConstantExprToString(const ConstantExpr* CE,
400 const TargetMachine& target);
402 /// valToExprString - Helper function for ConstantExprToString().
403 /// Appends result to argument string S.
405 std::string valToExprString(const Value* V, const TargetMachine& target);
408 } // End anonymous namespace
410 } // End namespace llvm
412 /// Print a single constant value.
414 void AsmPrinter::printSingleConstantValue(const Constant* CV) {
415 assert(CV->getType() != Type::VoidTy &&
416 CV->getType() != Type::TypeTy &&
417 CV->getType() != Type::LabelTy &&
418 "Unexpected type for Constant");
420 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
421 && "Aggregate types should be handled outside this function");
423 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
425 if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV)) {
426 // This is a constant address for a global variable or method.
427 // Use the name of the variable or method as the address value.
428 assert(isa<GlobalValue>(CPR->getValue()) && "Unexpected non-global");
429 toAsm << getID(CPR->getValue()) << "\n";
430 } else if (isa<ConstantPointerNull>(CV)) {
431 // Null pointer value
433 } else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
434 // Constant expression built from operators, constants, and symbolic addrs
435 toAsm << ConstantExprToString(CE, Target) << "\n";
436 } else if (CV->getType()->isPrimitiveType()) {
437 // Check primitive types last
438 if (CV->getType()->isFloatingPoint()) {
439 // FP Constants are printed as integer constants to avoid losing
441 double Val = cast<ConstantFP>(CV)->getValue();
442 if (CV->getType() == Type::FloatTy) {
443 float FVal = (float)Val;
444 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
445 toAsm << *(unsigned int*)ProxyPtr;
446 } else if (CV->getType() == Type::DoubleTy) {
447 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
448 toAsm << *(uint64_t*)ProxyPtr;
450 assert(0 && "Unknown floating point type!");
453 toAsm << "\t! " << CV->getType()->getDescription()
454 << " value: " << Val << "\n";
456 WriteAsOperand(toAsm, CV, false, false) << "\n";
459 assert(0 && "Unknown elementary type for constant");
463 /// Print a constant value or values (it may be an aggregate).
464 /// Uses printSingleConstantValue() to print each individual value.
466 void AsmPrinter::printConstantValueOnly(const Constant* CV,
467 int numPadBytesAfter)
469 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
471 if (CVA && isStringCompatible(CVA)) {
472 // print the string alone and return
473 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
475 // Not a string. Print the values in successive locations
476 const std::vector<Use> &constValues = CVA->getValues();
477 for (unsigned i=0; i < constValues.size(); i++)
478 printConstantValueOnly(cast<Constant>(constValues[i].get()));
479 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
480 // Print the fields in successive locations. Pad to align if needed!
481 const StructLayout *cvsLayout =
482 Target.getTargetData().getStructLayout(CVS->getType());
483 const std::vector<Use>& constValues = CVS->getValues();
484 unsigned sizeSoFar = 0;
485 for (unsigned i=0, N = constValues.size(); i < N; i++) {
486 const Constant* field = cast<Constant>(constValues[i].get());
488 // Check if padding is needed and insert one or more 0s.
490 Target.getTargetData().getTypeSize(field->getType());
491 int padSize = ((i == N-1? cvsLayout->StructSize
492 : cvsLayout->MemberOffsets[i+1])
493 - cvsLayout->MemberOffsets[i]) - fieldSize;
494 sizeSoFar += (fieldSize + padSize);
496 // Now print the actual field value
497 printConstantValueOnly(field, padSize);
499 assert(sizeSoFar == cvsLayout->StructSize &&
500 "Layout of constant struct may be incorrect!");
503 printSingleConstantValue(CV);
505 if (numPadBytesAfter)
506 PrintZeroBytesToPad(numPadBytesAfter);
509 /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
510 /// and return this as a string.
512 std::string AsmPrinter::ConstantExprToString(const ConstantExpr* CE,
513 const TargetMachine& target) {
515 switch(CE->getOpcode()) {
516 case Instruction::GetElementPtr:
517 { // generate a symbolic expression for the byte address
518 const Value* ptrVal = CE->getOperand(0);
519 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
520 const TargetData &TD = target.getTargetData();
521 S += "(" + valToExprString(ptrVal, target) + ") + ("
522 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
526 case Instruction::Cast:
527 // Support only non-converting casts for now, i.e., a no-op.
528 // This assertion is not a complete check.
529 assert(target.getTargetData().getTypeSize(CE->getType()) ==
530 target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
531 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
534 case Instruction::Add:
535 S += ConstantArithExprToString(CE, target, ") + (");
538 case Instruction::Sub:
539 S += ConstantArithExprToString(CE, target, ") - (");
542 case Instruction::Mul:
543 S += ConstantArithExprToString(CE, target, ") * (");
546 case Instruction::Div:
547 S += ConstantArithExprToString(CE, target, ") / (");
550 case Instruction::Rem:
551 S += ConstantArithExprToString(CE, target, ") % (");
554 case Instruction::And:
555 // Logical && for booleans; bitwise & otherwise
556 S += ConstantArithExprToString(CE, target,
557 ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
560 case Instruction::Or:
561 // Logical || for booleans; bitwise | otherwise
562 S += ConstantArithExprToString(CE, target,
563 ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
566 case Instruction::Xor:
567 // Bitwise ^ for all types
568 S += ConstantArithExprToString(CE, target, ") ^ (");
572 assert(0 && "Unsupported operator in ConstantExprToString()");
579 /// valToExprString - Helper function for ConstantExprToString().
580 /// Appends result to argument string S.
582 std::string AsmPrinter::valToExprString(const Value* V,
583 const TargetMachine& target) {
586 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
587 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
588 S += std::string(CB == ConstantBool::True ? "1" : "0");
589 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
590 S += itostr(CI->getValue());
591 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
592 S += utostr(CI->getValue());
593 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
594 S += ftostr(CFP->getValue());
595 else if (isa<ConstantPointerNull>(CV))
597 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
598 S += valToExprString(CPR->getValue(), target);
599 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
600 S += ConstantExprToString(CE, target);
603 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
609 assert(0 && "Cannot convert value to string");
610 S += "<illegal-value>";
616 //===----------------------------------------------------------------------===//
617 // SparcAsmPrinter Code
618 //===----------------------------------------------------------------------===//
624 struct SparcAsmPrinter : public FunctionPass, public AsmPrinter {
625 inline SparcAsmPrinter(std::ostream &os, const TargetMachine &t)
626 : AsmPrinter(os, t) {}
628 const Function *currFunction;
630 const char *getPassName() const {
631 return "Output Sparc Assembly for Functions";
634 virtual bool doInitialization(Module &M) {
639 virtual bool runOnFunction(Function &F) {
647 virtual bool doFinalization(Module &M) {
652 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
653 AU.setPreservesAll();
656 void emitFunction(const Function &F);
658 void emitBasicBlock(const MachineBasicBlock &MBB);
659 void emitMachineInst(const MachineInstr *MI);
661 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
662 void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
664 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
665 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
667 unsigned getOperandMask(unsigned Opcode) {
670 case V9::SUBcci: return 1 << 3; // Remove CC argument
671 default: return 0; // By default, don't hack operands...
675 void emitGlobals(const Module &M);
676 void printGlobalVariable(const GlobalVariable *GV);
679 } // End anonymous namespace
682 SparcAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
683 unsigned int opNum) {
684 switch (MI->getOpCode()) {
696 SparcAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
697 unsigned int opNum) {
698 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
700 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
707 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
708 printOneOperand(mop1, opCode); \
710 printOneOperand(mop2, opCode);
713 SparcAsmPrinter::printOperands(const MachineInstr *MI,
716 const MachineOperand& mop = MI->getOperand(opNum);
718 if (OpIsBranchTargetLabel(MI, opNum)) {
719 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
721 } else if (OpIsMemoryAddressBase(MI, opNum)) {
723 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
727 printOneOperand(mop, MI->getOpCode());
733 SparcAsmPrinter::printOneOperand(const MachineOperand &mop,
734 MachineOpCode opCode)
736 bool needBitsFlag = true;
738 if (mop.isHiBits32())
740 else if (mop.isLoBits32())
742 else if (mop.isHiBits64())
744 else if (mop.isLoBits64())
747 needBitsFlag = false;
749 switch (mop.getType())
751 case MachineOperand::MO_VirtualRegister:
752 case MachineOperand::MO_CCRegister:
753 case MachineOperand::MO_MachineRegister:
755 int regNum = (int)mop.getAllocatedRegNum();
757 if (regNum == Target.getRegInfo().getInvalidRegNum()) {
758 // better to print code with NULL registers than to die
759 toAsm << "<NULL VALUE>";
761 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
766 case MachineOperand::MO_ConstantPoolIndex:
768 toAsm << ".CPI_" << currFunction->getName()
769 << "_" << mop.getConstantPoolIndex();
773 case MachineOperand::MO_PCRelativeDisp:
775 const Value *Val = mop.getVRegValue();
776 assert(Val && "\tNULL Value in SparcAsmPrinter");
778 if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
780 else if (const Function *M = dyn_cast<Function>(Val))
782 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
784 else if (const Constant *CV = dyn_cast<Constant>(Val))
787 assert(0 && "Unrecognized value in SparcAsmPrinter");
791 case MachineOperand::MO_SignExtendedImmed:
792 toAsm << mop.getImmedValue();
795 case MachineOperand::MO_UnextendedImmed:
796 toAsm << (uint64_t) mop.getImmedValue();
800 toAsm << mop; // use dump field
808 void SparcAsmPrinter::emitMachineInst(const MachineInstr *MI) {
809 unsigned Opcode = MI->getOpCode();
811 if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
812 return; // IGNORE PHI NODES
814 toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
816 unsigned Mask = getOperandMask(Opcode);
818 bool NeedComma = false;
820 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
821 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
822 if (NeedComma) toAsm << ", "; // Handle comma outputting
824 N = printOperands(MI, OpNum);
832 void SparcAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB) {
833 // Emit a label for the basic block
834 toAsm << getID(MBB.getBasicBlock()) << ":\n";
836 // Loop over all of the instructions in the basic block...
837 for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
839 emitMachineInst(*MII);
840 toAsm << "\n"; // Separate BB's with newlines
843 void SparcAsmPrinter::emitFunction(const Function &F) {
844 std::string methName = getID(&F);
845 toAsm << "!****** Outputing Function: " << methName << " ******\n";
847 // Emit constant pool for this function
848 const MachineConstantPool *MCP = MachineFunction::get(&F).getConstantPool();
849 const std::vector<Constant*> &CP = MCP->getConstants();
851 enterSection(AsmPrinter::ReadOnlyData);
852 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
853 std::string cpiName = ".CPI_" + F.getName() + "_" + utostr(i);
854 printConstant(CP[i], cpiName);
857 enterSection(AsmPrinter::Text);
858 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
859 //toAsm << "\t.type\t" << methName << ",#function\n";
860 toAsm << "\t.type\t" << methName << ", 2\n";
861 toAsm << methName << ":\n";
863 // Output code for all of the basic blocks in the function...
864 MachineFunction &MF = MachineFunction::get(&F);
865 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
868 // Output a .size directive so the debugger knows the extents of the function
869 toAsm << ".EndOf_" << methName << ":\n\t.size "
870 << methName << ", .EndOf_"
871 << methName << "-" << methName << "\n";
873 // Put some spaces between the functions
877 void SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV) {
878 if (GV->hasExternalLinkage())
879 toAsm << "\t.global\t" << getID(GV) << "\n";
881 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue()) {
882 printConstant(GV->getInitializer(), getID(GV));
884 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
886 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
887 toAsm << "\t.reserve\t" << getID(GV) << ","
888 << Target.findOptimalStorageSize(GV->getType()->getElementType())
893 void SparcAsmPrinter::emitGlobals(const Module &M) {
894 // Output global variables...
895 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
896 if (! GI->isExternal()) {
897 assert(GI->hasInitializer());
898 if (GI->isConstant())
899 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
900 else if (GI->getInitializer()->isNullValue())
901 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
903 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
905 printGlobalVariable(GI);
911 FunctionPass *createAsmPrinterPass(std::ostream &Out, const TargetMachine &TM) {
912 return new SparcAsmPrinter(Out, TM);
915 } // End llvm namespace