1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/FormattedStream.h"
43 // Make virtual table appear in this compilation unit.
44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 static const Module *getModuleFromVal(const Value *V) {
51 if (const Argument *MA = dyn_cast<Argument>(V))
52 return MA->getParent() ? MA->getParent()->getParent() : 0;
54 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55 return BB->getParent() ? BB->getParent()->getParent() : 0;
57 if (const Instruction *I = dyn_cast<Instruction>(V)) {
58 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59 return M ? M->getParent() : 0;
62 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63 return GV->getParent();
67 // PrintEscapedString - Print each character of the specified string, escaping
68 // it if it is not printable or if it is an escape char.
69 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
70 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71 unsigned char C = Name[i];
72 if (isprint(C) && C != '\\' && C != '"')
75 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
86 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87 /// prefixed with % (if the string only contains simple characters) or is
88 /// surrounded with ""'s (if it has special chars in it). Print it out.
89 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
90 assert(!Name.empty() && "Cannot get empty name!");
92 default: llvm_unreachable("Bad prefix!");
94 case GlobalPrefix: OS << '@'; break;
95 case LabelPrefix: break;
96 case LocalPrefix: OS << '%'; break;
99 // Scan the name to see if it needs quotes first.
100 bool NeedsQuotes = isdigit(Name[0]);
102 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
104 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
111 // If we didn't need any quotes, just write out the name in one blast.
117 // Okay, we need quotes. Output the quotes and escape any scary characters as
120 PrintEscapedString(Name, OS);
124 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
125 /// prefixed with % (if the string only contains simple characters) or is
126 /// surrounded with ""'s (if it has special chars in it). Print it out.
127 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
128 PrintLLVMName(OS, V->getName(),
129 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
132 //===----------------------------------------------------------------------===//
133 // TypePrinting Class: Type printing machinery
134 //===----------------------------------------------------------------------===//
136 /// TypePrinting - Type printing machinery.
139 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
140 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
143 /// NamedTypes - The named types that are used by the current module.
144 std::vector<StructType*> NamedTypes;
146 /// NumberedTypes - The numbered types, along with their value.
147 DenseMap<StructType*, unsigned> NumberedTypes;
153 void incorporateTypes(const Module &M);
155 void print(Type *Ty, raw_ostream &OS);
157 void printStructBody(StructType *Ty, raw_ostream &OS);
159 } // end anonymous namespace.
162 void TypePrinting::incorporateTypes(const Module &M) {
163 M.findUsedStructTypes(NamedTypes);
165 // The list of struct types we got back includes all the struct types, split
166 // the unnamed ones out to a numbering and remove the anonymous structs.
167 unsigned NextNumber = 0;
169 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
170 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
171 StructType *STy = *I;
173 // Ignore anonymous types.
174 if (STy->isAnonymous())
177 if (STy->getName().empty())
178 NumberedTypes[STy] = NextNumber++;
183 NamedTypes.erase(NextToUse, NamedTypes.end());
187 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
188 /// use of type names or up references to shorten the type name where possible.
189 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
190 switch (Ty->getTypeID()) {
191 case Type::VoidTyID: OS << "void"; break;
192 case Type::FloatTyID: OS << "float"; break;
193 case Type::DoubleTyID: OS << "double"; break;
194 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
195 case Type::FP128TyID: OS << "fp128"; break;
196 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
197 case Type::LabelTyID: OS << "label"; break;
198 case Type::MetadataTyID: OS << "metadata"; break;
199 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
200 case Type::IntegerTyID:
201 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
204 case Type::FunctionTyID: {
205 FunctionType *FTy = cast<FunctionType>(Ty);
206 print(FTy->getReturnType(), OS);
208 for (FunctionType::param_iterator I = FTy->param_begin(),
209 E = FTy->param_end(); I != E; ++I) {
210 if (I != FTy->param_begin())
214 if (FTy->isVarArg()) {
215 if (FTy->getNumParams()) OS << ", ";
221 case Type::StructTyID: {
222 StructType *STy = cast<StructType>(Ty);
224 if (STy->isAnonymous())
225 return printStructBody(STy, OS);
227 if (!STy->getName().empty())
228 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
230 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
231 if (I != NumberedTypes.end())
232 OS << '%' << I->second;
233 else // Not enumerated, print the hex address.
234 OS << "%\"type 0x" << STy << '\"';
237 case Type::PointerTyID: {
238 PointerType *PTy = cast<PointerType>(Ty);
239 print(PTy->getElementType(), OS);
240 if (unsigned AddressSpace = PTy->getAddressSpace())
241 OS << " addrspace(" << AddressSpace << ')';
245 case Type::ArrayTyID: {
246 ArrayType *ATy = cast<ArrayType>(Ty);
247 OS << '[' << ATy->getNumElements() << " x ";
248 print(ATy->getElementType(), OS);
252 case Type::VectorTyID: {
253 VectorType *PTy = cast<VectorType>(Ty);
254 OS << "<" << PTy->getNumElements() << " x ";
255 print(PTy->getElementType(), OS);
260 OS << "<unrecognized-type>";
265 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
266 if (STy->isOpaque()) {
274 if (STy->getNumElements() == 0) {
277 StructType::element_iterator I = STy->element_begin();
280 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
293 //===----------------------------------------------------------------------===//
294 // SlotTracker Class: Enumerate slot numbers for unnamed values
295 //===----------------------------------------------------------------------===//
299 /// This class provides computation of slot numbers for LLVM Assembly writing.
303 /// ValueMap - A mapping of Values to slot numbers.
304 typedef DenseMap<const Value*, unsigned> ValueMap;
307 /// TheModule - The module for which we are holding slot numbers.
308 const Module* TheModule;
310 /// TheFunction - The function for which we are holding slot numbers.
311 const Function* TheFunction;
312 bool FunctionProcessed;
314 /// mMap - The slot map for the module level data.
318 /// fMap - The slot map for the function level data.
322 /// mdnMap - Map for MDNodes.
323 DenseMap<const MDNode*, unsigned> mdnMap;
326 /// Construct from a module
327 explicit SlotTracker(const Module *M);
328 /// Construct from a function, starting out in incorp state.
329 explicit SlotTracker(const Function *F);
331 /// Return the slot number of the specified value in it's type
332 /// plane. If something is not in the SlotTracker, return -1.
333 int getLocalSlot(const Value *V);
334 int getGlobalSlot(const GlobalValue *V);
335 int getMetadataSlot(const MDNode *N);
337 /// If you'd like to deal with a function instead of just a module, use
338 /// this method to get its data into the SlotTracker.
339 void incorporateFunction(const Function *F) {
341 FunctionProcessed = false;
344 /// After calling incorporateFunction, use this method to remove the
345 /// most recently incorporated function from the SlotTracker. This
346 /// will reset the state of the machine back to just the module contents.
347 void purgeFunction();
349 /// MDNode map iterators.
350 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
351 mdn_iterator mdn_begin() { return mdnMap.begin(); }
352 mdn_iterator mdn_end() { return mdnMap.end(); }
353 unsigned mdn_size() const { return mdnMap.size(); }
354 bool mdn_empty() const { return mdnMap.empty(); }
356 /// This function does the actual initialization.
357 inline void initialize();
359 // Implementation Details
361 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
362 void CreateModuleSlot(const GlobalValue *V);
364 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
365 void CreateMetadataSlot(const MDNode *N);
367 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
368 void CreateFunctionSlot(const Value *V);
370 /// Add all of the module level global variables (and their initializers)
371 /// and function declarations, but not the contents of those functions.
372 void processModule();
374 /// Add all of the functions arguments, basic blocks, and instructions.
375 void processFunction();
377 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
378 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
381 } // end anonymous namespace
384 static SlotTracker *createSlotTracker(const Value *V) {
385 if (const Argument *FA = dyn_cast<Argument>(V))
386 return new SlotTracker(FA->getParent());
388 if (const Instruction *I = dyn_cast<Instruction>(V))
389 return new SlotTracker(I->getParent()->getParent());
391 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
392 return new SlotTracker(BB->getParent());
394 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
395 return new SlotTracker(GV->getParent());
397 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
398 return new SlotTracker(GA->getParent());
400 if (const Function *Func = dyn_cast<Function>(V))
401 return new SlotTracker(Func);
403 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
404 if (!MD->isFunctionLocal())
405 return new SlotTracker(MD->getFunction());
407 return new SlotTracker((Function *)0);
414 #define ST_DEBUG(X) dbgs() << X
419 // Module level constructor. Causes the contents of the Module (sans functions)
420 // to be added to the slot table.
421 SlotTracker::SlotTracker(const Module *M)
422 : TheModule(M), TheFunction(0), FunctionProcessed(false),
423 mNext(0), fNext(0), mdnNext(0) {
426 // Function level constructor. Causes the contents of the Module and the one
427 // function provided to be added to the slot table.
428 SlotTracker::SlotTracker(const Function *F)
429 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
430 mNext(0), fNext(0), mdnNext(0) {
433 inline void SlotTracker::initialize() {
436 TheModule = 0; ///< Prevent re-processing next time we're called.
439 if (TheFunction && !FunctionProcessed)
443 // Iterate through all the global variables, functions, and global
444 // variable initializers and create slots for them.
445 void SlotTracker::processModule() {
446 ST_DEBUG("begin processModule!\n");
448 // Add all of the unnamed global variables to the value table.
449 for (Module::const_global_iterator I = TheModule->global_begin(),
450 E = TheModule->global_end(); I != E; ++I) {
455 // Add metadata used by named metadata.
456 for (Module::const_named_metadata_iterator
457 I = TheModule->named_metadata_begin(),
458 E = TheModule->named_metadata_end(); I != E; ++I) {
459 const NamedMDNode *NMD = I;
460 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
461 CreateMetadataSlot(NMD->getOperand(i));
464 // Add all the unnamed functions to the table.
465 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
470 ST_DEBUG("end processModule!\n");
473 // Process the arguments, basic blocks, and instructions of a function.
474 void SlotTracker::processFunction() {
475 ST_DEBUG("begin processFunction!\n");
478 // Add all the function arguments with no names.
479 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
480 AE = TheFunction->arg_end(); AI != AE; ++AI)
482 CreateFunctionSlot(AI);
484 ST_DEBUG("Inserting Instructions:\n");
486 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
488 // Add all of the basic blocks and instructions with no names.
489 for (Function::const_iterator BB = TheFunction->begin(),
490 E = TheFunction->end(); BB != E; ++BB) {
492 CreateFunctionSlot(BB);
494 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
496 if (!I->getType()->isVoidTy() && !I->hasName())
497 CreateFunctionSlot(I);
499 // Intrinsics can directly use metadata. We allow direct calls to any
500 // llvm.foo function here, because the target may not be linked into the
502 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
503 if (Function *F = CI->getCalledFunction())
504 if (F->getName().startswith("llvm."))
505 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
506 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
507 CreateMetadataSlot(N);
510 // Process metadata attached with this instruction.
511 I->getAllMetadata(MDForInst);
512 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
513 CreateMetadataSlot(MDForInst[i].second);
518 FunctionProcessed = true;
520 ST_DEBUG("end processFunction!\n");
523 /// Clean up after incorporating a function. This is the only way to get out of
524 /// the function incorporation state that affects get*Slot/Create*Slot. Function
525 /// incorporation state is indicated by TheFunction != 0.
526 void SlotTracker::purgeFunction() {
527 ST_DEBUG("begin purgeFunction!\n");
528 fMap.clear(); // Simply discard the function level map
530 FunctionProcessed = false;
531 ST_DEBUG("end purgeFunction!\n");
534 /// getGlobalSlot - Get the slot number of a global value.
535 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
536 // Check for uninitialized state and do lazy initialization.
539 // Find the value in the module map
540 ValueMap::iterator MI = mMap.find(V);
541 return MI == mMap.end() ? -1 : (int)MI->second;
544 /// getMetadataSlot - Get the slot number of a MDNode.
545 int SlotTracker::getMetadataSlot(const MDNode *N) {
546 // Check for uninitialized state and do lazy initialization.
549 // Find the MDNode in the module map
550 mdn_iterator MI = mdnMap.find(N);
551 return MI == mdnMap.end() ? -1 : (int)MI->second;
555 /// getLocalSlot - Get the slot number for a value that is local to a function.
556 int SlotTracker::getLocalSlot(const Value *V) {
557 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
559 // Check for uninitialized state and do lazy initialization.
562 ValueMap::iterator FI = fMap.find(V);
563 return FI == fMap.end() ? -1 : (int)FI->second;
567 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
568 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
569 assert(V && "Can't insert a null Value into SlotTracker!");
570 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
571 assert(!V->hasName() && "Doesn't need a slot!");
573 unsigned DestSlot = mNext++;
576 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
578 // G = Global, F = Function, A = Alias, o = other
579 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
580 (isa<Function>(V) ? 'F' :
581 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
584 /// CreateSlot - Create a new slot for the specified value if it has no name.
585 void SlotTracker::CreateFunctionSlot(const Value *V) {
586 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
588 unsigned DestSlot = fNext++;
591 // G = Global, F = Function, o = other
592 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
593 DestSlot << " [o]\n");
596 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
597 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
598 assert(N && "Can't insert a null Value into SlotTracker!");
600 // Don't insert if N is a function-local metadata, these are always printed
602 if (!N->isFunctionLocal()) {
603 mdn_iterator I = mdnMap.find(N);
604 if (I != mdnMap.end())
607 unsigned DestSlot = mdnNext++;
608 mdnMap[N] = DestSlot;
611 // Recursively add any MDNodes referenced by operands.
612 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
613 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
614 CreateMetadataSlot(Op);
617 //===----------------------------------------------------------------------===//
618 // AsmWriter Implementation
619 //===----------------------------------------------------------------------===//
621 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
622 TypePrinting *TypePrinter,
623 SlotTracker *Machine,
624 const Module *Context);
628 static const char *getPredicateText(unsigned predicate) {
629 const char * pred = "unknown";
631 case FCmpInst::FCMP_FALSE: pred = "false"; break;
632 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
633 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
634 case FCmpInst::FCMP_OGE: pred = "oge"; break;
635 case FCmpInst::FCMP_OLT: pred = "olt"; break;
636 case FCmpInst::FCMP_OLE: pred = "ole"; break;
637 case FCmpInst::FCMP_ONE: pred = "one"; break;
638 case FCmpInst::FCMP_ORD: pred = "ord"; break;
639 case FCmpInst::FCMP_UNO: pred = "uno"; break;
640 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
641 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
642 case FCmpInst::FCMP_UGE: pred = "uge"; break;
643 case FCmpInst::FCMP_ULT: pred = "ult"; break;
644 case FCmpInst::FCMP_ULE: pred = "ule"; break;
645 case FCmpInst::FCMP_UNE: pred = "une"; break;
646 case FCmpInst::FCMP_TRUE: pred = "true"; break;
647 case ICmpInst::ICMP_EQ: pred = "eq"; break;
648 case ICmpInst::ICMP_NE: pred = "ne"; break;
649 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
650 case ICmpInst::ICMP_SGE: pred = "sge"; break;
651 case ICmpInst::ICMP_SLT: pred = "slt"; break;
652 case ICmpInst::ICMP_SLE: pred = "sle"; break;
653 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
654 case ICmpInst::ICMP_UGE: pred = "uge"; break;
655 case ICmpInst::ICMP_ULT: pred = "ult"; break;
656 case ICmpInst::ICMP_ULE: pred = "ule"; break;
661 static void writeAtomicRMWOperation(raw_ostream &Out,
662 AtomicRMWInst::BinOp Op) {
664 default: Out << " <unknown operation " << Op << ">"; break;
665 case AtomicRMWInst::Xchg: Out << " xchg"; break;
666 case AtomicRMWInst::Add: Out << " add"; break;
667 case AtomicRMWInst::Sub: Out << " sub"; break;
668 case AtomicRMWInst::And: Out << " and"; break;
669 case AtomicRMWInst::Nand: Out << " nand"; break;
670 case AtomicRMWInst::Or: Out << " or"; break;
671 case AtomicRMWInst::Xor: Out << " xor"; break;
672 case AtomicRMWInst::Max: Out << " max"; break;
673 case AtomicRMWInst::Min: Out << " min"; break;
674 case AtomicRMWInst::UMax: Out << " umax"; break;
675 case AtomicRMWInst::UMin: Out << " umin"; break;
679 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
680 if (const OverflowingBinaryOperator *OBO =
681 dyn_cast<OverflowingBinaryOperator>(U)) {
682 if (OBO->hasNoUnsignedWrap())
684 if (OBO->hasNoSignedWrap())
686 } else if (const PossiblyExactOperator *Div =
687 dyn_cast<PossiblyExactOperator>(U)) {
690 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
691 if (GEP->isInBounds())
696 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
697 TypePrinting &TypePrinter,
698 SlotTracker *Machine,
699 const Module *Context) {
700 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
701 if (CI->getType()->isIntegerTy(1)) {
702 Out << (CI->getZExtValue() ? "true" : "false");
705 Out << CI->getValue();
709 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
710 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
711 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
712 // We would like to output the FP constant value in exponential notation,
713 // but we cannot do this if doing so will lose precision. Check here to
714 // make sure that we only output it in exponential format if we can parse
715 // the value back and get the same value.
718 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
719 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
720 CFP->getValueAPF().convertToFloat();
721 SmallString<128> StrVal;
722 raw_svector_ostream(StrVal) << Val;
724 // Check to make sure that the stringized number is not some string like
725 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
726 // that the string matches the "[-+]?[0-9]" regex.
728 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
729 ((StrVal[0] == '-' || StrVal[0] == '+') &&
730 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
731 // Reparse stringized version!
732 if (atof(StrVal.c_str()) == Val) {
737 // Otherwise we could not reparse it to exactly the same value, so we must
738 // output the string in hexadecimal format! Note that loading and storing
739 // floating point types changes the bits of NaNs on some hosts, notably
740 // x86, so we must not use these types.
741 assert(sizeof(double) == sizeof(uint64_t) &&
742 "assuming that double is 64 bits!");
744 APFloat apf = CFP->getValueAPF();
745 // Floats are represented in ASCII IR as double, convert.
747 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
750 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
755 // Some form of long double. These appear as a magic letter identifying
756 // the type, then a fixed number of hex digits.
758 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
760 // api needed to prevent premature destruction
761 APInt api = CFP->getValueAPF().bitcastToAPInt();
762 const uint64_t* p = api.getRawData();
763 uint64_t word = p[1];
765 int width = api.getBitWidth();
766 for (int j=0; j<width; j+=4, shiftcount-=4) {
767 unsigned int nibble = (word>>shiftcount) & 15;
769 Out << (unsigned char)(nibble + '0');
771 Out << (unsigned char)(nibble - 10 + 'A');
772 if (shiftcount == 0 && j+4 < width) {
776 shiftcount = width-j-4;
780 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
782 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
785 llvm_unreachable("Unsupported floating point type");
786 // api needed to prevent premature destruction
787 APInt api = CFP->getValueAPF().bitcastToAPInt();
788 const uint64_t* p = api.getRawData();
791 int width = api.getBitWidth();
792 for (int j=0; j<width; j+=4, shiftcount-=4) {
793 unsigned int nibble = (word>>shiftcount) & 15;
795 Out << (unsigned char)(nibble + '0');
797 Out << (unsigned char)(nibble - 10 + 'A');
798 if (shiftcount == 0 && j+4 < width) {
802 shiftcount = width-j-4;
808 if (isa<ConstantAggregateZero>(CV)) {
809 Out << "zeroinitializer";
813 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
814 Out << "blockaddress(";
815 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
818 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
824 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
825 // As a special case, print the array as a string if it is an array of
826 // i8 with ConstantInt values.
828 Type *ETy = CA->getType()->getElementType();
829 if (CA->isString()) {
831 PrintEscapedString(CA->getAsString(), Out);
833 } else { // Cannot output in string format...
835 if (CA->getNumOperands()) {
836 TypePrinter.print(ETy, Out);
838 WriteAsOperandInternal(Out, CA->getOperand(0),
839 &TypePrinter, Machine,
841 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
843 TypePrinter.print(ETy, Out);
845 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
854 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
855 if (CS->getType()->isPacked())
858 unsigned N = CS->getNumOperands();
861 TypePrinter.print(CS->getOperand(0)->getType(), Out);
864 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
867 for (unsigned i = 1; i < N; i++) {
869 TypePrinter.print(CS->getOperand(i)->getType(), Out);
872 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
879 if (CS->getType()->isPacked())
884 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
885 Type *ETy = CP->getType()->getElementType();
886 assert(CP->getNumOperands() > 0 &&
887 "Number of operands for a PackedConst must be > 0");
889 TypePrinter.print(ETy, Out);
891 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
893 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
895 TypePrinter.print(ETy, Out);
897 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
904 if (isa<ConstantPointerNull>(CV)) {
909 if (isa<UndefValue>(CV)) {
914 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
915 Out << CE->getOpcodeName();
916 WriteOptimizationInfo(Out, CE);
918 Out << ' ' << getPredicateText(CE->getPredicate());
921 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
922 TypePrinter.print((*OI)->getType(), Out);
924 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
925 if (OI+1 != CE->op_end())
929 if (CE->hasIndices()) {
930 ArrayRef<unsigned> Indices = CE->getIndices();
931 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
932 Out << ", " << Indices[i];
937 TypePrinter.print(CE->getType(), Out);
944 Out << "<placeholder or erroneous Constant>";
947 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
948 TypePrinting *TypePrinter,
949 SlotTracker *Machine,
950 const Module *Context) {
952 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
953 const Value *V = Node->getOperand(mi);
957 TypePrinter->print(V->getType(), Out);
959 WriteAsOperandInternal(Out, Node->getOperand(mi),
960 TypePrinter, Machine, Context);
970 /// WriteAsOperand - Write the name of the specified value out to the specified
971 /// ostream. This can be useful when you just want to print int %reg126, not
972 /// the whole instruction that generated it.
974 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
975 TypePrinting *TypePrinter,
976 SlotTracker *Machine,
977 const Module *Context) {
979 PrintLLVMName(Out, V);
983 const Constant *CV = dyn_cast<Constant>(V);
984 if (CV && !isa<GlobalValue>(CV)) {
985 assert(TypePrinter && "Constants require TypePrinting!");
986 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
990 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
992 if (IA->hasSideEffects())
993 Out << "sideeffect ";
994 if (IA->isAlignStack())
995 Out << "alignstack ";
997 PrintEscapedString(IA->getAsmString(), Out);
999 PrintEscapedString(IA->getConstraintString(), Out);
1004 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1005 if (N->isFunctionLocal()) {
1006 // Print metadata inline, not via slot reference number.
1007 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1012 if (N->isFunctionLocal())
1013 Machine = new SlotTracker(N->getFunction());
1015 Machine = new SlotTracker(Context);
1017 int Slot = Machine->getMetadataSlot(N);
1025 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1027 PrintEscapedString(MDS->getString(), Out);
1032 if (V->getValueID() == Value::PseudoSourceValueVal ||
1033 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1041 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1042 Slot = Machine->getGlobalSlot(GV);
1045 Slot = Machine->getLocalSlot(V);
1048 Machine = createSlotTracker(V);
1050 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1051 Slot = Machine->getGlobalSlot(GV);
1054 Slot = Machine->getLocalSlot(V);
1063 Out << Prefix << Slot;
1068 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1069 bool PrintType, const Module *Context) {
1071 // Fast path: Don't construct and populate a TypePrinting object if we
1072 // won't be needing any types printed.
1074 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1075 V->hasName() || isa<GlobalValue>(V))) {
1076 WriteAsOperandInternal(Out, V, 0, 0, Context);
1080 if (Context == 0) Context = getModuleFromVal(V);
1082 TypePrinting TypePrinter;
1084 TypePrinter.incorporateTypes(*Context);
1086 TypePrinter.print(V->getType(), Out);
1090 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1095 class AssemblyWriter {
1096 formatted_raw_ostream &Out;
1097 SlotTracker &Machine;
1098 const Module *TheModule;
1099 TypePrinting TypePrinter;
1100 AssemblyAnnotationWriter *AnnotationWriter;
1103 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1105 AssemblyAnnotationWriter *AAW)
1106 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1108 TypePrinter.incorporateTypes(*M);
1111 void printMDNodeBody(const MDNode *MD);
1112 void printNamedMDNode(const NamedMDNode *NMD);
1114 void printModule(const Module *M);
1116 void writeOperand(const Value *Op, bool PrintType);
1117 void writeParamOperand(const Value *Operand, Attributes Attrs);
1118 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1120 void writeAllMDNodes();
1122 void printTypeIdentities();
1123 void printGlobal(const GlobalVariable *GV);
1124 void printAlias(const GlobalAlias *GV);
1125 void printFunction(const Function *F);
1126 void printArgument(const Argument *FA, Attributes Attrs);
1127 void printBasicBlock(const BasicBlock *BB);
1128 void printInstruction(const Instruction &I);
1131 // printInfoComment - Print a little comment after the instruction indicating
1132 // which slot it occupies.
1133 void printInfoComment(const Value &V);
1135 } // end of anonymous namespace
1137 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1139 Out << "<null operand!>";
1143 TypePrinter.print(Operand->getType(), Out);
1146 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1149 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1150 SynchronizationScope SynchScope) {
1151 if (Ordering == NotAtomic)
1154 switch (SynchScope) {
1155 default: Out << " <bad scope " << int(SynchScope) << ">"; break;
1156 case SingleThread: Out << " singlethread"; break;
1157 case CrossThread: break;
1161 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1162 case Unordered: Out << " unordered"; break;
1163 case Monotonic: Out << " monotonic"; break;
1164 case Acquire: Out << " acquire"; break;
1165 case Release: Out << " release"; break;
1166 case AcquireRelease: Out << " acq_rel"; break;
1167 case SequentiallyConsistent: Out << " seq_cst"; break;
1171 void AssemblyWriter::writeParamOperand(const Value *Operand,
1174 Out << "<null operand!>";
1179 TypePrinter.print(Operand->getType(), Out);
1180 // Print parameter attributes list
1181 if (Attrs != Attribute::None)
1182 Out << ' ' << Attribute::getAsString(Attrs);
1184 // Print the operand
1185 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1188 void AssemblyWriter::printModule(const Module *M) {
1189 if (!M->getModuleIdentifier().empty() &&
1190 // Don't print the ID if it will start a new line (which would
1191 // require a comment char before it).
1192 M->getModuleIdentifier().find('\n') == std::string::npos)
1193 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1195 if (!M->getDataLayout().empty())
1196 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1197 if (!M->getTargetTriple().empty())
1198 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1200 if (!M->getModuleInlineAsm().empty()) {
1201 // Split the string into lines, to make it easier to read the .ll file.
1202 std::string Asm = M->getModuleInlineAsm();
1204 size_t NewLine = Asm.find_first_of('\n', CurPos);
1206 while (NewLine != std::string::npos) {
1207 // We found a newline, print the portion of the asm string from the
1208 // last newline up to this newline.
1209 Out << "module asm \"";
1210 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1214 NewLine = Asm.find_first_of('\n', CurPos);
1216 std::string rest(Asm.begin()+CurPos, Asm.end());
1217 if (!rest.empty()) {
1218 Out << "module asm \"";
1219 PrintEscapedString(rest, Out);
1224 // Loop over the dependent libraries and emit them.
1225 Module::lib_iterator LI = M->lib_begin();
1226 Module::lib_iterator LE = M->lib_end();
1229 Out << "deplibs = [ ";
1231 Out << '"' << *LI << '"';
1239 printTypeIdentities();
1241 // Output all globals.
1242 if (!M->global_empty()) Out << '\n';
1243 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1247 // Output all aliases.
1248 if (!M->alias_empty()) Out << "\n";
1249 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1253 // Output all of the functions.
1254 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1257 // Output named metadata.
1258 if (!M->named_metadata_empty()) Out << '\n';
1260 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1261 E = M->named_metadata_end(); I != E; ++I)
1262 printNamedMDNode(I);
1265 if (!Machine.mdn_empty()) {
1271 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1273 StringRef Name = NMD->getName();
1275 Out << "<empty name> ";
1277 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1278 Name[0] == '.' || Name[0] == '_')
1281 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1282 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1283 unsigned char C = Name[i];
1284 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1287 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1291 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1293 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1303 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1304 formatted_raw_ostream &Out) {
1306 case GlobalValue::ExternalLinkage: break;
1307 case GlobalValue::PrivateLinkage: Out << "private "; break;
1308 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1309 case GlobalValue::LinkerPrivateWeakLinkage:
1310 Out << "linker_private_weak ";
1312 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1313 Out << "linker_private_weak_def_auto ";
1315 case GlobalValue::InternalLinkage: Out << "internal "; break;
1316 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1317 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1318 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1319 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1320 case GlobalValue::CommonLinkage: Out << "common "; break;
1321 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1322 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1323 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1324 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1325 case GlobalValue::AvailableExternallyLinkage:
1326 Out << "available_externally ";
1332 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1333 formatted_raw_ostream &Out) {
1335 case GlobalValue::DefaultVisibility: break;
1336 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1337 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1341 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1342 if (GV->isMaterializable())
1343 Out << "; Materializable\n";
1345 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1348 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1351 PrintLinkage(GV->getLinkage(), Out);
1352 PrintVisibility(GV->getVisibility(), Out);
1354 if (GV->isThreadLocal()) Out << "thread_local ";
1355 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1356 Out << "addrspace(" << AddressSpace << ") ";
1357 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1358 Out << (GV->isConstant() ? "constant " : "global ");
1359 TypePrinter.print(GV->getType()->getElementType(), Out);
1361 if (GV->hasInitializer()) {
1363 writeOperand(GV->getInitializer(), false);
1366 if (GV->hasSection()) {
1367 Out << ", section \"";
1368 PrintEscapedString(GV->getSection(), Out);
1371 if (GV->getAlignment())
1372 Out << ", align " << GV->getAlignment();
1374 printInfoComment(*GV);
1378 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1379 if (GA->isMaterializable())
1380 Out << "; Materializable\n";
1382 // Don't crash when dumping partially built GA
1384 Out << "<<nameless>> = ";
1386 PrintLLVMName(Out, GA);
1389 PrintVisibility(GA->getVisibility(), Out);
1393 PrintLinkage(GA->getLinkage(), Out);
1395 const Constant *Aliasee = GA->getAliasee();
1398 TypePrinter.print(GA->getType(), Out);
1399 Out << " <<NULL ALIASEE>>";
1401 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1404 printInfoComment(*GA);
1408 void AssemblyWriter::printTypeIdentities() {
1409 if (TypePrinter.NumberedTypes.empty() &&
1410 TypePrinter.NamedTypes.empty())
1415 // We know all the numbers that each type is used and we know that it is a
1416 // dense assignment. Convert the map to an index table.
1417 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1418 for (DenseMap<StructType*, unsigned>::iterator I =
1419 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1421 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1422 NumberedTypes[I->second] = I->first;
1425 // Emit all numbered types.
1426 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1427 Out << '%' << i << " = type ";
1429 // Make sure we print out at least one level of the type structure, so
1430 // that we do not get %2 = type %2
1431 TypePrinter.printStructBody(NumberedTypes[i], Out);
1435 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1436 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1439 // Make sure we print out at least one level of the type structure, so
1440 // that we do not get %FILE = type %FILE
1441 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1446 /// printFunction - Print all aspects of a function.
1448 void AssemblyWriter::printFunction(const Function *F) {
1449 // Print out the return type and name.
1452 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1454 if (F->isMaterializable())
1455 Out << "; Materializable\n";
1457 if (F->isDeclaration())
1462 PrintLinkage(F->getLinkage(), Out);
1463 PrintVisibility(F->getVisibility(), Out);
1465 // Print the calling convention.
1466 switch (F->getCallingConv()) {
1467 case CallingConv::C: break; // default
1468 case CallingConv::Fast: Out << "fastcc "; break;
1469 case CallingConv::Cold: Out << "coldcc "; break;
1470 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1471 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1472 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1473 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1474 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1475 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1476 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1477 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1478 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1479 default: Out << "cc" << F->getCallingConv() << " "; break;
1482 FunctionType *FT = F->getFunctionType();
1483 const AttrListPtr &Attrs = F->getAttributes();
1484 Attributes RetAttrs = Attrs.getRetAttributes();
1485 if (RetAttrs != Attribute::None)
1486 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1487 TypePrinter.print(F->getReturnType(), Out);
1489 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1491 Machine.incorporateFunction(F);
1493 // Loop over the arguments, printing them...
1496 if (!F->isDeclaration()) {
1497 // If this isn't a declaration, print the argument names as well.
1498 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1500 // Insert commas as we go... the first arg doesn't get a comma
1501 if (I != F->arg_begin()) Out << ", ";
1502 printArgument(I, Attrs.getParamAttributes(Idx));
1506 // Otherwise, print the types from the function type.
1507 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1508 // Insert commas as we go... the first arg doesn't get a comma
1512 TypePrinter.print(FT->getParamType(i), Out);
1514 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1515 if (ArgAttrs != Attribute::None)
1516 Out << ' ' << Attribute::getAsString(ArgAttrs);
1520 // Finish printing arguments...
1521 if (FT->isVarArg()) {
1522 if (FT->getNumParams()) Out << ", ";
1523 Out << "..."; // Output varargs portion of signature!
1526 if (F->hasUnnamedAddr())
1527 Out << " unnamed_addr";
1528 Attributes FnAttrs = Attrs.getFnAttributes();
1529 if (FnAttrs != Attribute::None)
1530 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1531 if (F->hasSection()) {
1532 Out << " section \"";
1533 PrintEscapedString(F->getSection(), Out);
1536 if (F->getAlignment())
1537 Out << " align " << F->getAlignment();
1539 Out << " gc \"" << F->getGC() << '"';
1540 if (F->isDeclaration()) {
1544 // Output all of the function's basic blocks.
1545 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1551 Machine.purgeFunction();
1554 /// printArgument - This member is called for every argument that is passed into
1555 /// the function. Simply print it out
1557 void AssemblyWriter::printArgument(const Argument *Arg,
1560 TypePrinter.print(Arg->getType(), Out);
1562 // Output parameter attributes list
1563 if (Attrs != Attribute::None)
1564 Out << ' ' << Attribute::getAsString(Attrs);
1566 // Output name, if available...
1567 if (Arg->hasName()) {
1569 PrintLLVMName(Out, Arg);
1573 /// printBasicBlock - This member is called for each basic block in a method.
1575 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1576 if (BB->hasName()) { // Print out the label if it exists...
1578 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1580 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1581 Out << "\n; <label>:";
1582 int Slot = Machine.getLocalSlot(BB);
1589 if (BB->getParent() == 0) {
1590 Out.PadToColumn(50);
1591 Out << "; Error: Block without parent!";
1592 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1593 // Output predecessors for the block.
1594 Out.PadToColumn(50);
1596 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1599 Out << " No predecessors!";
1602 writeOperand(*PI, false);
1603 for (++PI; PI != PE; ++PI) {
1605 writeOperand(*PI, false);
1612 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1614 // Output all of the instructions in the basic block...
1615 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1616 printInstruction(*I);
1620 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1623 /// printInfoComment - Print a little comment after the instruction indicating
1624 /// which slot it occupies.
1626 void AssemblyWriter::printInfoComment(const Value &V) {
1627 if (AnnotationWriter) {
1628 AnnotationWriter->printInfoComment(V, Out);
1633 // This member is called for each Instruction in a function..
1634 void AssemblyWriter::printInstruction(const Instruction &I) {
1635 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1637 // Print out indentation for an instruction.
1640 // Print out name if it exists...
1642 PrintLLVMName(Out, &I);
1644 } else if (!I.getType()->isVoidTy()) {
1645 // Print out the def slot taken.
1646 int SlotNum = Machine.getLocalSlot(&I);
1648 Out << "<badref> = ";
1650 Out << '%' << SlotNum << " = ";
1653 // If this is a volatile load or store, print out the volatile marker.
1654 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1655 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1657 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1658 // If this is a call, check if it's a tail call.
1662 // Print out the opcode...
1663 Out << I.getOpcodeName();
1665 // Print out optimization information.
1666 WriteOptimizationInfo(Out, &I);
1668 // Print out the compare instruction predicates
1669 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1670 Out << ' ' << getPredicateText(CI->getPredicate());
1672 // Print out the atomicrmw operation
1673 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1674 writeAtomicRMWOperation(Out, RMWI->getOperation());
1676 // Print out the type of the operands...
1677 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1679 // Special case conditional branches to swizzle the condition out to the front
1680 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1681 BranchInst &BI(cast<BranchInst>(I));
1683 writeOperand(BI.getCondition(), true);
1685 writeOperand(BI.getSuccessor(0), true);
1687 writeOperand(BI.getSuccessor(1), true);
1689 } else if (isa<SwitchInst>(I)) {
1690 // Special case switch instruction to get formatting nice and correct.
1692 writeOperand(Operand , true);
1694 writeOperand(I.getOperand(1), true);
1697 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1699 writeOperand(I.getOperand(op ), true);
1701 writeOperand(I.getOperand(op+1), true);
1704 } else if (isa<IndirectBrInst>(I)) {
1705 // Special case indirectbr instruction to get formatting nice and correct.
1707 writeOperand(Operand, true);
1710 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1713 writeOperand(I.getOperand(i), true);
1716 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1718 TypePrinter.print(I.getType(), Out);
1721 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1722 if (op) Out << ", ";
1724 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1725 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1727 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1729 writeOperand(I.getOperand(0), true);
1730 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1732 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1734 writeOperand(I.getOperand(0), true); Out << ", ";
1735 writeOperand(I.getOperand(1), true);
1736 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1738 } else if (isa<ReturnInst>(I) && !Operand) {
1740 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1741 // Print the calling convention being used.
1742 switch (CI->getCallingConv()) {
1743 case CallingConv::C: break; // default
1744 case CallingConv::Fast: Out << " fastcc"; break;
1745 case CallingConv::Cold: Out << " coldcc"; break;
1746 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1747 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1748 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1749 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1750 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1751 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1752 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1753 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1754 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1755 default: Out << " cc" << CI->getCallingConv(); break;
1758 Operand = CI->getCalledValue();
1759 PointerType *PTy = cast<PointerType>(Operand->getType());
1760 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1761 Type *RetTy = FTy->getReturnType();
1762 const AttrListPtr &PAL = CI->getAttributes();
1764 if (PAL.getRetAttributes() != Attribute::None)
1765 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1767 // If possible, print out the short form of the call instruction. We can
1768 // only do this if the first argument is a pointer to a nonvararg function,
1769 // and if the return type is not a pointer to a function.
1772 if (!FTy->isVarArg() &&
1773 (!RetTy->isPointerTy() ||
1774 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1775 TypePrinter.print(RetTy, Out);
1777 writeOperand(Operand, false);
1779 writeOperand(Operand, true);
1782 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1785 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1788 if (PAL.getFnAttributes() != Attribute::None)
1789 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1790 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1791 Operand = II->getCalledValue();
1792 PointerType *PTy = cast<PointerType>(Operand->getType());
1793 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1794 Type *RetTy = FTy->getReturnType();
1795 const AttrListPtr &PAL = II->getAttributes();
1797 // Print the calling convention being used.
1798 switch (II->getCallingConv()) {
1799 case CallingConv::C: break; // default
1800 case CallingConv::Fast: Out << " fastcc"; break;
1801 case CallingConv::Cold: Out << " coldcc"; break;
1802 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1803 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1804 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1805 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1806 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1807 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1808 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1809 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1810 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1811 default: Out << " cc" << II->getCallingConv(); break;
1814 if (PAL.getRetAttributes() != Attribute::None)
1815 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1817 // If possible, print out the short form of the invoke instruction. We can
1818 // only do this if the first argument is a pointer to a nonvararg function,
1819 // and if the return type is not a pointer to a function.
1822 if (!FTy->isVarArg() &&
1823 (!RetTy->isPointerTy() ||
1824 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1825 TypePrinter.print(RetTy, Out);
1827 writeOperand(Operand, false);
1829 writeOperand(Operand, true);
1832 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1835 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1839 if (PAL.getFnAttributes() != Attribute::None)
1840 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1843 writeOperand(II->getNormalDest(), true);
1845 writeOperand(II->getUnwindDest(), true);
1847 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1849 TypePrinter.print(AI->getType()->getElementType(), Out);
1850 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1852 writeOperand(AI->getArraySize(), true);
1854 if (AI->getAlignment()) {
1855 Out << ", align " << AI->getAlignment();
1857 } else if (isa<CastInst>(I)) {
1860 writeOperand(Operand, true); // Work with broken code
1863 TypePrinter.print(I.getType(), Out);
1864 } else if (isa<VAArgInst>(I)) {
1867 writeOperand(Operand, true); // Work with broken code
1870 TypePrinter.print(I.getType(), Out);
1871 } else if (Operand) { // Print the normal way.
1873 // PrintAllTypes - Instructions who have operands of all the same type
1874 // omit the type from all but the first operand. If the instruction has
1875 // different type operands (for example br), then they are all printed.
1876 bool PrintAllTypes = false;
1877 Type *TheType = Operand->getType();
1879 // Select, Store and ShuffleVector always print all types.
1880 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1881 || isa<ReturnInst>(I)) {
1882 PrintAllTypes = true;
1884 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1885 Operand = I.getOperand(i);
1886 // note that Operand shouldn't be null, but the test helps make dump()
1887 // more tolerant of malformed IR
1888 if (Operand && Operand->getType() != TheType) {
1889 PrintAllTypes = true; // We have differing types! Print them all!
1895 if (!PrintAllTypes) {
1897 TypePrinter.print(TheType, Out);
1901 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1903 writeOperand(I.getOperand(i), PrintAllTypes);
1907 // Print post operand alignment for load/store.
1908 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1909 Out << ", align " << cast<LoadInst>(I).getAlignment();
1910 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1911 Out << ", align " << cast<StoreInst>(I).getAlignment();
1912 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
1913 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
1914 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
1915 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
1916 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
1917 writeAtomic(FI->getOrdering(), FI->getSynchScope());
1920 // Print Metadata info.
1921 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1922 I.getAllMetadata(InstMD);
1923 if (!InstMD.empty()) {
1924 SmallVector<StringRef, 8> MDNames;
1925 I.getType()->getContext().getMDKindNames(MDNames);
1926 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1927 unsigned Kind = InstMD[i].first;
1928 if (Kind < MDNames.size()) {
1929 Out << ", !" << MDNames[Kind];
1931 Out << ", !<unknown kind #" << Kind << ">";
1934 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
1938 printInfoComment(I);
1941 static void WriteMDNodeComment(const MDNode *Node,
1942 formatted_raw_ostream &Out) {
1943 if (Node->getNumOperands() < 1)
1945 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1947 APInt Val = CI->getValue();
1948 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
1949 if (Val.ult(LLVMDebugVersion))
1952 Out.PadToColumn(50);
1953 if (Tag == dwarf::DW_TAG_user_base)
1954 Out << "; [ DW_TAG_user_base ]";
1955 else if (Tag.isIntN(32)) {
1956 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
1957 Out << "; [ " << TagName << " ]";
1961 void AssemblyWriter::writeAllMDNodes() {
1962 SmallVector<const MDNode *, 16> Nodes;
1963 Nodes.resize(Machine.mdn_size());
1964 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
1966 Nodes[I->second] = cast<MDNode>(I->first);
1968 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1969 Out << '!' << i << " = metadata ";
1970 printMDNodeBody(Nodes[i]);
1974 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
1975 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
1976 WriteMDNodeComment(Node, Out);
1980 //===----------------------------------------------------------------------===//
1981 // External Interface declarations
1982 //===----------------------------------------------------------------------===//
1984 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
1985 SlotTracker SlotTable(this);
1986 formatted_raw_ostream OS(ROS);
1987 AssemblyWriter W(OS, SlotTable, this, AAW);
1988 W.printModule(this);
1991 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
1992 SlotTracker SlotTable(getParent());
1993 formatted_raw_ostream OS(ROS);
1994 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
1995 W.printNamedMDNode(this);
1998 void Type::print(raw_ostream &OS) const {
2000 OS << "<null Type>";
2004 TP.print(const_cast<Type*>(this), OS);
2006 // If the type is a named struct type, print the body as well.
2007 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2008 if (!STy->isAnonymous()) {
2010 TP.printStructBody(STy, OS);
2014 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2016 ROS << "printing a <null> value\n";
2019 formatted_raw_ostream OS(ROS);
2020 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2021 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2022 SlotTracker SlotTable(F);
2023 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2024 W.printInstruction(*I);
2025 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2026 SlotTracker SlotTable(BB->getParent());
2027 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2028 W.printBasicBlock(BB);
2029 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2030 SlotTracker SlotTable(GV->getParent());
2031 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2032 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2034 else if (const Function *F = dyn_cast<Function>(GV))
2037 W.printAlias(cast<GlobalAlias>(GV));
2038 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2039 const Function *F = N->getFunction();
2040 SlotTracker SlotTable(F);
2041 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2042 W.printMDNodeBody(N);
2043 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2044 TypePrinting TypePrinter;
2045 TypePrinter.print(C->getType(), OS);
2047 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2048 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2049 isa<Argument>(this)) {
2050 WriteAsOperand(OS, this, true, 0);
2052 // Otherwise we don't know what it is. Call the virtual function to
2053 // allow a subclass to print itself.
2058 // Value::printCustom - subclasses should override this to implement printing.
2059 void Value::printCustom(raw_ostream &OS) const {
2060 llvm_unreachable("Unknown value to print out!");
2063 // Value::dump - allow easy printing of Values from the debugger.
2064 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2066 // Type::dump - allow easy printing of Types from the debugger.
2067 void Type::dump() const { print(dbgs()); }
2069 // Module::dump() - Allow printing of Modules from the debugger.
2070 void Module::dump() const { print(dbgs(), 0); }