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/DebugInfo.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Module.h"
29 #include "llvm/ValueSymbolTable.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/FormattedStream.h"
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast<Argument>(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
55 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
58 if (const Instruction *I = dyn_cast<Instruction>(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
63 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return GV->getParent();
68 // PrintEscapedString - Print each character of the specified string, escaping
69 // it if it is not printable or if it is an escape char.
70 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
71 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
72 unsigned char C = Name[i];
73 if (isprint(C) && C != '\\' && C != '"')
76 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
87 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
88 /// prefixed with % (if the string only contains simple characters) or is
89 /// surrounded with ""'s (if it has special chars in it). Print it out.
90 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
91 assert(!Name.empty() && "Cannot get empty name!");
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) {
103 // By making this unsigned, the value passed in to isalnum will always be
104 // in the range 0-255. This is important when building with MSVC because
105 // its implementation will assert. This situation can arise when dealing
106 // with UTF-8 multibyte characters.
107 unsigned char C = Name[i];
108 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
115 // If we didn't need any quotes, just write out the name in one blast.
121 // Okay, we need quotes. Output the quotes and escape any scary characters as
124 PrintEscapedString(Name, OS);
128 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
129 /// prefixed with % (if the string only contains simple characters) or is
130 /// surrounded with ""'s (if it has special chars in it). Print it out.
131 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
132 PrintLLVMName(OS, V->getName(),
133 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
136 //===----------------------------------------------------------------------===//
137 // TypePrinting Class: Type printing machinery
138 //===----------------------------------------------------------------------===//
140 /// TypePrinting - Type printing machinery.
143 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
144 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
147 /// NamedTypes - The named types that are used by the current module.
148 std::vector<StructType*> NamedTypes;
150 /// NumberedTypes - The numbered types, along with their value.
151 DenseMap<StructType*, unsigned> NumberedTypes;
157 void incorporateTypes(const Module &M);
159 void print(Type *Ty, raw_ostream &OS);
161 void printStructBody(StructType *Ty, raw_ostream &OS);
163 } // end anonymous namespace.
166 void TypePrinting::incorporateTypes(const Module &M) {
167 M.findUsedStructTypes(NamedTypes);
169 // The list of struct types we got back includes all the struct types, split
170 // the unnamed ones out to a numbering and remove the anonymous structs.
171 unsigned NextNumber = 0;
173 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
174 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
175 StructType *STy = *I;
177 // Ignore anonymous types.
178 if (STy->isLiteral())
181 if (STy->getName().empty())
182 NumberedTypes[STy] = NextNumber++;
187 NamedTypes.erase(NextToUse, NamedTypes.end());
191 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
192 /// use of type names or up references to shorten the type name where possible.
193 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
194 switch (Ty->getTypeID()) {
195 case Type::VoidTyID: OS << "void"; break;
196 case Type::HalfTyID: OS << "half"; break;
197 case Type::FloatTyID: OS << "float"; break;
198 case Type::DoubleTyID: OS << "double"; break;
199 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
200 case Type::FP128TyID: OS << "fp128"; break;
201 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
202 case Type::LabelTyID: OS << "label"; break;
203 case Type::MetadataTyID: OS << "metadata"; break;
204 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
205 case Type::IntegerTyID:
206 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
209 case Type::FunctionTyID: {
210 FunctionType *FTy = cast<FunctionType>(Ty);
211 print(FTy->getReturnType(), OS);
213 for (FunctionType::param_iterator I = FTy->param_begin(),
214 E = FTy->param_end(); I != E; ++I) {
215 if (I != FTy->param_begin())
219 if (FTy->isVarArg()) {
220 if (FTy->getNumParams()) OS << ", ";
226 case Type::StructTyID: {
227 StructType *STy = cast<StructType>(Ty);
229 if (STy->isLiteral())
230 return printStructBody(STy, OS);
232 if (!STy->getName().empty())
233 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
235 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
236 if (I != NumberedTypes.end())
237 OS << '%' << I->second;
238 else // Not enumerated, print the hex address.
239 OS << "%\"type " << STy << '\"';
242 case Type::PointerTyID: {
243 PointerType *PTy = cast<PointerType>(Ty);
244 print(PTy->getElementType(), OS);
245 if (unsigned AddressSpace = PTy->getAddressSpace())
246 OS << " addrspace(" << AddressSpace << ')';
250 case Type::ArrayTyID: {
251 ArrayType *ATy = cast<ArrayType>(Ty);
252 OS << '[' << ATy->getNumElements() << " x ";
253 print(ATy->getElementType(), OS);
257 case Type::VectorTyID: {
258 VectorType *PTy = cast<VectorType>(Ty);
259 OS << "<" << PTy->getNumElements() << " x ";
260 print(PTy->getElementType(), OS);
265 OS << "<unrecognized-type>";
270 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
271 if (STy->isOpaque()) {
279 if (STy->getNumElements() == 0) {
282 StructType::element_iterator I = STy->element_begin();
285 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
298 //===----------------------------------------------------------------------===//
299 // SlotTracker Class: Enumerate slot numbers for unnamed values
300 //===----------------------------------------------------------------------===//
304 /// This class provides computation of slot numbers for LLVM Assembly writing.
308 /// ValueMap - A mapping of Values to slot numbers.
309 typedef DenseMap<const Value*, unsigned> ValueMap;
312 /// TheModule - The module for which we are holding slot numbers.
313 const Module* TheModule;
315 /// TheFunction - The function for which we are holding slot numbers.
316 const Function* TheFunction;
317 bool FunctionProcessed;
319 /// mMap - The slot map for the module level data.
323 /// fMap - The slot map for the function level data.
327 /// mdnMap - Map for MDNodes.
328 DenseMap<const MDNode*, unsigned> mdnMap;
331 /// Construct from a module
332 explicit SlotTracker(const Module *M);
333 /// Construct from a function, starting out in incorp state.
334 explicit SlotTracker(const Function *F);
336 /// Return the slot number of the specified value in it's type
337 /// plane. If something is not in the SlotTracker, return -1.
338 int getLocalSlot(const Value *V);
339 int getGlobalSlot(const GlobalValue *V);
340 int getMetadataSlot(const MDNode *N);
342 /// If you'd like to deal with a function instead of just a module, use
343 /// this method to get its data into the SlotTracker.
344 void incorporateFunction(const Function *F) {
346 FunctionProcessed = false;
349 /// After calling incorporateFunction, use this method to remove the
350 /// most recently incorporated function from the SlotTracker. This
351 /// will reset the state of the machine back to just the module contents.
352 void purgeFunction();
354 /// MDNode map iterators.
355 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
356 mdn_iterator mdn_begin() { return mdnMap.begin(); }
357 mdn_iterator mdn_end() { return mdnMap.end(); }
358 unsigned mdn_size() const { return mdnMap.size(); }
359 bool mdn_empty() const { return mdnMap.empty(); }
361 /// This function does the actual initialization.
362 inline void initialize();
364 // Implementation Details
366 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
367 void CreateModuleSlot(const GlobalValue *V);
369 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
370 void CreateMetadataSlot(const MDNode *N);
372 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
373 void CreateFunctionSlot(const Value *V);
375 /// Add all of the module level global variables (and their initializers)
376 /// and function declarations, but not the contents of those functions.
377 void processModule();
379 /// Add all of the functions arguments, basic blocks, and instructions.
380 void processFunction();
382 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
383 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
386 } // end anonymous namespace
389 static SlotTracker *createSlotTracker(const Value *V) {
390 if (const Argument *FA = dyn_cast<Argument>(V))
391 return new SlotTracker(FA->getParent());
393 if (const Instruction *I = dyn_cast<Instruction>(V))
395 return new SlotTracker(I->getParent()->getParent());
397 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
398 return new SlotTracker(BB->getParent());
400 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
401 return new SlotTracker(GV->getParent());
403 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
404 return new SlotTracker(GA->getParent());
406 if (const Function *Func = dyn_cast<Function>(V))
407 return new SlotTracker(Func);
409 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
410 if (!MD->isFunctionLocal())
411 return new SlotTracker(MD->getFunction());
413 return new SlotTracker((Function *)0);
420 #define ST_DEBUG(X) dbgs() << X
425 // Module level constructor. Causes the contents of the Module (sans functions)
426 // to be added to the slot table.
427 SlotTracker::SlotTracker(const Module *M)
428 : TheModule(M), TheFunction(0), FunctionProcessed(false),
429 mNext(0), fNext(0), mdnNext(0) {
432 // Function level constructor. Causes the contents of the Module and the one
433 // function provided to be added to the slot table.
434 SlotTracker::SlotTracker(const Function *F)
435 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
436 mNext(0), fNext(0), mdnNext(0) {
439 inline void SlotTracker::initialize() {
442 TheModule = 0; ///< Prevent re-processing next time we're called.
445 if (TheFunction && !FunctionProcessed)
449 // Iterate through all the global variables, functions, and global
450 // variable initializers and create slots for them.
451 void SlotTracker::processModule() {
452 ST_DEBUG("begin processModule!\n");
454 // Add all of the unnamed global variables to the value table.
455 for (Module::const_global_iterator I = TheModule->global_begin(),
456 E = TheModule->global_end(); I != E; ++I) {
461 // Add metadata used by named metadata.
462 for (Module::const_named_metadata_iterator
463 I = TheModule->named_metadata_begin(),
464 E = TheModule->named_metadata_end(); I != E; ++I) {
465 const NamedMDNode *NMD = I;
466 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
467 CreateMetadataSlot(NMD->getOperand(i));
470 // Add all the unnamed functions to the table.
471 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
476 ST_DEBUG("end processModule!\n");
479 // Process the arguments, basic blocks, and instructions of a function.
480 void SlotTracker::processFunction() {
481 ST_DEBUG("begin processFunction!\n");
484 // Add all the function arguments with no names.
485 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
486 AE = TheFunction->arg_end(); AI != AE; ++AI)
488 CreateFunctionSlot(AI);
490 ST_DEBUG("Inserting Instructions:\n");
492 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
494 // Add all of the basic blocks and instructions with no names.
495 for (Function::const_iterator BB = TheFunction->begin(),
496 E = TheFunction->end(); BB != E; ++BB) {
498 CreateFunctionSlot(BB);
500 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
502 if (!I->getType()->isVoidTy() && !I->hasName())
503 CreateFunctionSlot(I);
505 // Intrinsics can directly use metadata. We allow direct calls to any
506 // llvm.foo function here, because the target may not be linked into the
508 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
509 if (Function *F = CI->getCalledFunction())
510 if (F->getName().startswith("llvm."))
511 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
512 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
513 CreateMetadataSlot(N);
516 // Process metadata attached with this instruction.
517 I->getAllMetadata(MDForInst);
518 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
519 CreateMetadataSlot(MDForInst[i].second);
524 FunctionProcessed = true;
526 ST_DEBUG("end processFunction!\n");
529 /// Clean up after incorporating a function. This is the only way to get out of
530 /// the function incorporation state that affects get*Slot/Create*Slot. Function
531 /// incorporation state is indicated by TheFunction != 0.
532 void SlotTracker::purgeFunction() {
533 ST_DEBUG("begin purgeFunction!\n");
534 fMap.clear(); // Simply discard the function level map
536 FunctionProcessed = false;
537 ST_DEBUG("end purgeFunction!\n");
540 /// getGlobalSlot - Get the slot number of a global value.
541 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
542 // Check for uninitialized state and do lazy initialization.
545 // Find the value in the module map
546 ValueMap::iterator MI = mMap.find(V);
547 return MI == mMap.end() ? -1 : (int)MI->second;
550 /// getMetadataSlot - Get the slot number of a MDNode.
551 int SlotTracker::getMetadataSlot(const MDNode *N) {
552 // Check for uninitialized state and do lazy initialization.
555 // Find the MDNode in the module map
556 mdn_iterator MI = mdnMap.find(N);
557 return MI == mdnMap.end() ? -1 : (int)MI->second;
561 /// getLocalSlot - Get the slot number for a value that is local to a function.
562 int SlotTracker::getLocalSlot(const Value *V) {
563 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
565 // Check for uninitialized state and do lazy initialization.
568 ValueMap::iterator FI = fMap.find(V);
569 return FI == fMap.end() ? -1 : (int)FI->second;
573 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
574 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
575 assert(V && "Can't insert a null Value into SlotTracker!");
576 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
577 assert(!V->hasName() && "Doesn't need a slot!");
579 unsigned DestSlot = mNext++;
582 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
584 // G = Global, F = Function, A = Alias, o = other
585 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
586 (isa<Function>(V) ? 'F' :
587 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
590 /// CreateSlot - Create a new slot for the specified value if it has no name.
591 void SlotTracker::CreateFunctionSlot(const Value *V) {
592 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
594 unsigned DestSlot = fNext++;
597 // G = Global, F = Function, o = other
598 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
599 DestSlot << " [o]\n");
602 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
603 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
604 assert(N && "Can't insert a null Value into SlotTracker!");
606 // Don't insert if N is a function-local metadata, these are always printed
608 if (!N->isFunctionLocal()) {
609 mdn_iterator I = mdnMap.find(N);
610 if (I != mdnMap.end())
613 unsigned DestSlot = mdnNext++;
614 mdnMap[N] = DestSlot;
617 // Recursively add any MDNodes referenced by operands.
618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
619 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
620 CreateMetadataSlot(Op);
623 //===----------------------------------------------------------------------===//
624 // AsmWriter Implementation
625 //===----------------------------------------------------------------------===//
627 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
628 TypePrinting *TypePrinter,
629 SlotTracker *Machine,
630 const Module *Context);
634 static const char *getPredicateText(unsigned predicate) {
635 const char * pred = "unknown";
637 case FCmpInst::FCMP_FALSE: pred = "false"; break;
638 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
639 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
640 case FCmpInst::FCMP_OGE: pred = "oge"; break;
641 case FCmpInst::FCMP_OLT: pred = "olt"; break;
642 case FCmpInst::FCMP_OLE: pred = "ole"; break;
643 case FCmpInst::FCMP_ONE: pred = "one"; break;
644 case FCmpInst::FCMP_ORD: pred = "ord"; break;
645 case FCmpInst::FCMP_UNO: pred = "uno"; break;
646 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
647 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
648 case FCmpInst::FCMP_UGE: pred = "uge"; break;
649 case FCmpInst::FCMP_ULT: pred = "ult"; break;
650 case FCmpInst::FCMP_ULE: pred = "ule"; break;
651 case FCmpInst::FCMP_UNE: pred = "une"; break;
652 case FCmpInst::FCMP_TRUE: pred = "true"; break;
653 case ICmpInst::ICMP_EQ: pred = "eq"; break;
654 case ICmpInst::ICMP_NE: pred = "ne"; break;
655 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
656 case ICmpInst::ICMP_SGE: pred = "sge"; break;
657 case ICmpInst::ICMP_SLT: pred = "slt"; break;
658 case ICmpInst::ICMP_SLE: pred = "sle"; break;
659 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
660 case ICmpInst::ICMP_UGE: pred = "uge"; break;
661 case ICmpInst::ICMP_ULT: pred = "ult"; break;
662 case ICmpInst::ICMP_ULE: pred = "ule"; break;
667 static void writeAtomicRMWOperation(raw_ostream &Out,
668 AtomicRMWInst::BinOp Op) {
670 default: Out << " <unknown operation " << Op << ">"; break;
671 case AtomicRMWInst::Xchg: Out << " xchg"; break;
672 case AtomicRMWInst::Add: Out << " add"; break;
673 case AtomicRMWInst::Sub: Out << " sub"; break;
674 case AtomicRMWInst::And: Out << " and"; break;
675 case AtomicRMWInst::Nand: Out << " nand"; break;
676 case AtomicRMWInst::Or: Out << " or"; break;
677 case AtomicRMWInst::Xor: Out << " xor"; break;
678 case AtomicRMWInst::Max: Out << " max"; break;
679 case AtomicRMWInst::Min: Out << " min"; break;
680 case AtomicRMWInst::UMax: Out << " umax"; break;
681 case AtomicRMWInst::UMin: Out << " umin"; break;
685 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
686 if (const OverflowingBinaryOperator *OBO =
687 dyn_cast<OverflowingBinaryOperator>(U)) {
688 if (OBO->hasNoUnsignedWrap())
690 if (OBO->hasNoSignedWrap())
692 } else if (const PossiblyExactOperator *Div =
693 dyn_cast<PossiblyExactOperator>(U)) {
696 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
697 if (GEP->isInBounds())
702 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
703 TypePrinting &TypePrinter,
704 SlotTracker *Machine,
705 const Module *Context) {
706 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
707 if (CI->getType()->isIntegerTy(1)) {
708 Out << (CI->getZExtValue() ? "true" : "false");
711 Out << CI->getValue();
715 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
716 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
717 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
718 // We would like to output the FP constant value in exponential notation,
719 // but we cannot do this if doing so will lose precision. Check here to
720 // make sure that we only output it in exponential format if we can parse
721 // the value back and get the same value.
724 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
725 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
726 bool isInf = CFP->getValueAPF().isInfinity();
727 bool isNaN = CFP->getValueAPF().isNaN();
728 if (!isHalf && !isInf && !isNaN) {
729 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
730 CFP->getValueAPF().convertToFloat();
731 SmallString<128> StrVal;
732 raw_svector_ostream(StrVal) << Val;
734 // Check to make sure that the stringized number is not some string like
735 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
736 // that the string matches the "[-+]?[0-9]" regex.
738 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
739 ((StrVal[0] == '-' || StrVal[0] == '+') &&
740 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
741 // Reparse stringized version!
742 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
748 // Otherwise we could not reparse it to exactly the same value, so we must
749 // output the string in hexadecimal format! Note that loading and storing
750 // floating point types changes the bits of NaNs on some hosts, notably
751 // x86, so we must not use these types.
752 assert(sizeof(double) == sizeof(uint64_t) &&
753 "assuming that double is 64 bits!");
755 APFloat apf = CFP->getValueAPF();
756 // Halves and floats are represented in ASCII IR as double, convert.
758 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
761 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
766 // Either half, or some form of long double.
767 // These appear as a magic letter identifying the type, then a
768 // fixed number of hex digits.
770 // Bit position, in the current word, of the next nibble to print.
773 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
775 // api needed to prevent premature destruction
776 APInt api = CFP->getValueAPF().bitcastToAPInt();
777 const uint64_t* p = api.getRawData();
778 uint64_t word = p[1];
780 int width = api.getBitWidth();
781 for (int j=0; j<width; j+=4, shiftcount-=4) {
782 unsigned int nibble = (word>>shiftcount) & 15;
784 Out << (unsigned char)(nibble + '0');
786 Out << (unsigned char)(nibble - 10 + 'A');
787 if (shiftcount == 0 && j+4 < width) {
791 shiftcount = width-j-4;
795 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
798 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
801 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
805 llvm_unreachable("Unsupported floating point type");
806 // api needed to prevent premature destruction
807 APInt api = CFP->getValueAPF().bitcastToAPInt();
808 const uint64_t* p = api.getRawData();
810 int width = api.getBitWidth();
811 for (int j=0; j<width; j+=4, shiftcount-=4) {
812 unsigned int nibble = (word>>shiftcount) & 15;
814 Out << (unsigned char)(nibble + '0');
816 Out << (unsigned char)(nibble - 10 + 'A');
817 if (shiftcount == 0 && j+4 < width) {
821 shiftcount = width-j-4;
827 if (isa<ConstantAggregateZero>(CV)) {
828 Out << "zeroinitializer";
832 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
833 Out << "blockaddress(";
834 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
837 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
843 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
844 Type *ETy = CA->getType()->getElementType();
846 TypePrinter.print(ETy, Out);
848 WriteAsOperandInternal(Out, CA->getOperand(0),
849 &TypePrinter, Machine,
851 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
853 TypePrinter.print(ETy, Out);
855 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
862 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
863 // As a special case, print the array as a string if it is an array of
864 // i8 with ConstantInt values.
865 if (CA->isString()) {
867 PrintEscapedString(CA->getAsString(), Out);
872 Type *ETy = CA->getType()->getElementType();
874 TypePrinter.print(ETy, Out);
876 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
877 &TypePrinter, Machine,
879 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
881 TypePrinter.print(ETy, Out);
883 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
891 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
892 if (CS->getType()->isPacked())
895 unsigned N = CS->getNumOperands();
898 TypePrinter.print(CS->getOperand(0)->getType(), Out);
901 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
904 for (unsigned i = 1; i < N; i++) {
906 TypePrinter.print(CS->getOperand(i)->getType(), Out);
909 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
916 if (CS->getType()->isPacked())
921 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
922 Type *ETy = CV->getType()->getVectorElementType();
924 TypePrinter.print(ETy, Out);
926 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
928 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
930 TypePrinter.print(ETy, Out);
932 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
939 if (isa<ConstantPointerNull>(CV)) {
944 if (isa<UndefValue>(CV)) {
949 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
950 Out << CE->getOpcodeName();
951 WriteOptimizationInfo(Out, CE);
953 Out << ' ' << getPredicateText(CE->getPredicate());
956 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
957 TypePrinter.print((*OI)->getType(), Out);
959 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
960 if (OI+1 != CE->op_end())
964 if (CE->hasIndices()) {
965 ArrayRef<unsigned> Indices = CE->getIndices();
966 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
967 Out << ", " << Indices[i];
972 TypePrinter.print(CE->getType(), Out);
979 Out << "<placeholder or erroneous Constant>";
982 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
983 TypePrinting *TypePrinter,
984 SlotTracker *Machine,
985 const Module *Context) {
987 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
988 const Value *V = Node->getOperand(mi);
992 TypePrinter->print(V->getType(), Out);
994 WriteAsOperandInternal(Out, Node->getOperand(mi),
995 TypePrinter, Machine, Context);
1005 /// WriteAsOperand - Write the name of the specified value out to the specified
1006 /// ostream. This can be useful when you just want to print int %reg126, not
1007 /// the whole instruction that generated it.
1009 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1010 TypePrinting *TypePrinter,
1011 SlotTracker *Machine,
1012 const Module *Context) {
1014 PrintLLVMName(Out, V);
1018 const Constant *CV = dyn_cast<Constant>(V);
1019 if (CV && !isa<GlobalValue>(CV)) {
1020 assert(TypePrinter && "Constants require TypePrinting!");
1021 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1025 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1027 if (IA->hasSideEffects())
1028 Out << "sideeffect ";
1029 if (IA->isAlignStack())
1030 Out << "alignstack ";
1032 PrintEscapedString(IA->getAsmString(), Out);
1034 PrintEscapedString(IA->getConstraintString(), Out);
1039 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1040 if (N->isFunctionLocal()) {
1041 // Print metadata inline, not via slot reference number.
1042 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1047 if (N->isFunctionLocal())
1048 Machine = new SlotTracker(N->getFunction());
1050 Machine = new SlotTracker(Context);
1052 int Slot = Machine->getMetadataSlot(N);
1060 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1062 PrintEscapedString(MDS->getString(), Out);
1067 if (V->getValueID() == Value::PseudoSourceValueVal ||
1068 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1075 // If we have a SlotTracker, use it.
1077 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1078 Slot = Machine->getGlobalSlot(GV);
1081 Slot = Machine->getLocalSlot(V);
1083 // If the local value didn't succeed, then we may be referring to a value
1084 // from a different function. Translate it, as this can happen when using
1085 // address of blocks.
1087 if ((Machine = createSlotTracker(V))) {
1088 Slot = Machine->getLocalSlot(V);
1092 } else if ((Machine = createSlotTracker(V))) {
1093 // Otherwise, create one to get the # and then destroy it.
1094 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1095 Slot = Machine->getGlobalSlot(GV);
1098 Slot = Machine->getLocalSlot(V);
1107 Out << Prefix << Slot;
1112 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1113 bool PrintType, const Module *Context) {
1115 // Fast path: Don't construct and populate a TypePrinting object if we
1116 // won't be needing any types printed.
1118 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1119 V->hasName() || isa<GlobalValue>(V))) {
1120 WriteAsOperandInternal(Out, V, 0, 0, Context);
1124 if (Context == 0) Context = getModuleFromVal(V);
1126 TypePrinting TypePrinter;
1128 TypePrinter.incorporateTypes(*Context);
1130 TypePrinter.print(V->getType(), Out);
1134 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1139 class AssemblyWriter {
1140 formatted_raw_ostream &Out;
1141 SlotTracker &Machine;
1142 const Module *TheModule;
1143 TypePrinting TypePrinter;
1144 AssemblyAnnotationWriter *AnnotationWriter;
1147 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1149 AssemblyAnnotationWriter *AAW)
1150 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1152 TypePrinter.incorporateTypes(*M);
1155 void printMDNodeBody(const MDNode *MD);
1156 void printNamedMDNode(const NamedMDNode *NMD);
1158 void printModule(const Module *M);
1160 void writeOperand(const Value *Op, bool PrintType);
1161 void writeParamOperand(const Value *Operand, Attributes Attrs);
1162 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1164 void writeAllMDNodes();
1166 void printTypeIdentities();
1167 void printGlobal(const GlobalVariable *GV);
1168 void printAlias(const GlobalAlias *GV);
1169 void printFunction(const Function *F);
1170 void printArgument(const Argument *FA, Attributes Attrs);
1171 void printBasicBlock(const BasicBlock *BB);
1172 void printInstruction(const Instruction &I);
1175 // printInfoComment - Print a little comment after the instruction indicating
1176 // which slot it occupies.
1177 void printInfoComment(const Value &V);
1179 } // end of anonymous namespace
1181 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1183 Out << "<null operand!>";
1187 TypePrinter.print(Operand->getType(), Out);
1190 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1193 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1194 SynchronizationScope SynchScope) {
1195 if (Ordering == NotAtomic)
1198 switch (SynchScope) {
1199 case SingleThread: Out << " singlethread"; break;
1200 case CrossThread: break;
1204 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1205 case Unordered: Out << " unordered"; break;
1206 case Monotonic: Out << " monotonic"; break;
1207 case Acquire: Out << " acquire"; break;
1208 case Release: Out << " release"; break;
1209 case AcquireRelease: Out << " acq_rel"; break;
1210 case SequentiallyConsistent: Out << " seq_cst"; break;
1214 void AssemblyWriter::writeParamOperand(const Value *Operand,
1217 Out << "<null operand!>";
1222 TypePrinter.print(Operand->getType(), Out);
1223 // Print parameter attributes list
1224 if (Attrs != Attribute::None)
1225 Out << ' ' << Attribute::getAsString(Attrs);
1227 // Print the operand
1228 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1231 void AssemblyWriter::printModule(const Module *M) {
1232 if (!M->getModuleIdentifier().empty() &&
1233 // Don't print the ID if it will start a new line (which would
1234 // require a comment char before it).
1235 M->getModuleIdentifier().find('\n') == std::string::npos)
1236 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1238 if (!M->getDataLayout().empty())
1239 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1240 if (!M->getTargetTriple().empty())
1241 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1243 if (!M->getModuleInlineAsm().empty()) {
1244 // Split the string into lines, to make it easier to read the .ll file.
1245 std::string Asm = M->getModuleInlineAsm();
1247 size_t NewLine = Asm.find_first_of('\n', CurPos);
1249 while (NewLine != std::string::npos) {
1250 // We found a newline, print the portion of the asm string from the
1251 // last newline up to this newline.
1252 Out << "module asm \"";
1253 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1257 NewLine = Asm.find_first_of('\n', CurPos);
1259 std::string rest(Asm.begin()+CurPos, Asm.end());
1260 if (!rest.empty()) {
1261 Out << "module asm \"";
1262 PrintEscapedString(rest, Out);
1267 // Loop over the dependent libraries and emit them.
1268 Module::lib_iterator LI = M->lib_begin();
1269 Module::lib_iterator LE = M->lib_end();
1272 Out << "deplibs = [ ";
1274 Out << '"' << *LI << '"';
1282 printTypeIdentities();
1284 // Output all globals.
1285 if (!M->global_empty()) Out << '\n';
1286 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1290 // Output all aliases.
1291 if (!M->alias_empty()) Out << "\n";
1292 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1296 // Output all of the functions.
1297 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1300 // Output named metadata.
1301 if (!M->named_metadata_empty()) Out << '\n';
1303 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1304 E = M->named_metadata_end(); I != E; ++I)
1305 printNamedMDNode(I);
1308 if (!Machine.mdn_empty()) {
1314 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1316 StringRef Name = NMD->getName();
1318 Out << "<empty name> ";
1320 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1321 Name[0] == '.' || Name[0] == '_')
1324 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1325 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1326 unsigned char C = Name[i];
1327 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1330 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1334 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1336 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1346 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1347 formatted_raw_ostream &Out) {
1349 case GlobalValue::ExternalLinkage: break;
1350 case GlobalValue::PrivateLinkage: Out << "private "; break;
1351 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1352 case GlobalValue::LinkerPrivateWeakLinkage:
1353 Out << "linker_private_weak ";
1355 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1356 Out << "linker_private_weak_def_auto ";
1358 case GlobalValue::InternalLinkage: Out << "internal "; break;
1359 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1360 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1361 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1362 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1363 case GlobalValue::CommonLinkage: Out << "common "; break;
1364 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1365 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1366 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1367 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1368 case GlobalValue::AvailableExternallyLinkage:
1369 Out << "available_externally ";
1375 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1376 formatted_raw_ostream &Out) {
1378 case GlobalValue::DefaultVisibility: break;
1379 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1380 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1384 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1385 formatted_raw_ostream &Out) {
1387 case GlobalVariable::NotThreadLocal:
1389 case GlobalVariable::GeneralDynamicTLSModel:
1390 Out << "thread_local ";
1392 case GlobalVariable::LocalDynamicTLSModel:
1393 Out << "thread_local(localdynamic) ";
1395 case GlobalVariable::InitialExecTLSModel:
1396 Out << "thread_local(initialexec) ";
1398 case GlobalVariable::LocalExecTLSModel:
1399 Out << "thread_local(localexec) ";
1404 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1405 if (GV->isMaterializable())
1406 Out << "; Materializable\n";
1408 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1411 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1414 PrintLinkage(GV->getLinkage(), Out);
1415 PrintVisibility(GV->getVisibility(), Out);
1416 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1418 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1419 Out << "addrspace(" << AddressSpace << ") ";
1420 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1421 Out << (GV->isConstant() ? "constant " : "global ");
1422 TypePrinter.print(GV->getType()->getElementType(), Out);
1424 if (GV->hasInitializer()) {
1426 writeOperand(GV->getInitializer(), false);
1429 if (GV->hasSection()) {
1430 Out << ", section \"";
1431 PrintEscapedString(GV->getSection(), Out);
1434 if (GV->getAlignment())
1435 Out << ", align " << GV->getAlignment();
1437 printInfoComment(*GV);
1441 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1442 if (GA->isMaterializable())
1443 Out << "; Materializable\n";
1445 // Don't crash when dumping partially built GA
1447 Out << "<<nameless>> = ";
1449 PrintLLVMName(Out, GA);
1452 PrintVisibility(GA->getVisibility(), Out);
1456 PrintLinkage(GA->getLinkage(), Out);
1458 const Constant *Aliasee = GA->getAliasee();
1461 TypePrinter.print(GA->getType(), Out);
1462 Out << " <<NULL ALIASEE>>";
1464 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1467 printInfoComment(*GA);
1471 void AssemblyWriter::printTypeIdentities() {
1472 if (TypePrinter.NumberedTypes.empty() &&
1473 TypePrinter.NamedTypes.empty())
1478 // We know all the numbers that each type is used and we know that it is a
1479 // dense assignment. Convert the map to an index table.
1480 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1481 for (DenseMap<StructType*, unsigned>::iterator I =
1482 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1484 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1485 NumberedTypes[I->second] = I->first;
1488 // Emit all numbered types.
1489 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1490 Out << '%' << i << " = type ";
1492 // Make sure we print out at least one level of the type structure, so
1493 // that we do not get %2 = type %2
1494 TypePrinter.printStructBody(NumberedTypes[i], Out);
1498 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1499 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1502 // Make sure we print out at least one level of the type structure, so
1503 // that we do not get %FILE = type %FILE
1504 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1509 /// printFunction - Print all aspects of a function.
1511 void AssemblyWriter::printFunction(const Function *F) {
1512 // Print out the return type and name.
1515 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1517 if (F->isMaterializable())
1518 Out << "; Materializable\n";
1520 if (F->isDeclaration())
1525 PrintLinkage(F->getLinkage(), Out);
1526 PrintVisibility(F->getVisibility(), Out);
1528 // Print the calling convention.
1529 switch (F->getCallingConv()) {
1530 case CallingConv::C: break; // default
1531 case CallingConv::Fast: Out << "fastcc "; break;
1532 case CallingConv::Cold: Out << "coldcc "; break;
1533 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1534 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1535 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1536 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1537 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1538 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1539 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1540 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1541 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1542 default: Out << "cc" << F->getCallingConv() << " "; break;
1545 FunctionType *FT = F->getFunctionType();
1546 const AttrListPtr &Attrs = F->getAttributes();
1547 Attributes RetAttrs = Attrs.getRetAttributes();
1548 if (RetAttrs != Attribute::None)
1549 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1550 TypePrinter.print(F->getReturnType(), Out);
1552 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1554 Machine.incorporateFunction(F);
1556 // Loop over the arguments, printing them...
1559 if (!F->isDeclaration()) {
1560 // If this isn't a declaration, print the argument names as well.
1561 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1563 // Insert commas as we go... the first arg doesn't get a comma
1564 if (I != F->arg_begin()) Out << ", ";
1565 printArgument(I, Attrs.getParamAttributes(Idx));
1569 // Otherwise, print the types from the function type.
1570 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1571 // Insert commas as we go... the first arg doesn't get a comma
1575 TypePrinter.print(FT->getParamType(i), Out);
1577 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1578 if (ArgAttrs != Attribute::None)
1579 Out << ' ' << Attribute::getAsString(ArgAttrs);
1583 // Finish printing arguments...
1584 if (FT->isVarArg()) {
1585 if (FT->getNumParams()) Out << ", ";
1586 Out << "..."; // Output varargs portion of signature!
1589 if (F->hasUnnamedAddr())
1590 Out << " unnamed_addr";
1591 Attributes FnAttrs = Attrs.getFnAttributes();
1592 if (FnAttrs != Attribute::None)
1593 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1594 if (F->hasSection()) {
1595 Out << " section \"";
1596 PrintEscapedString(F->getSection(), Out);
1599 if (F->getAlignment())
1600 Out << " align " << F->getAlignment();
1602 Out << " gc \"" << F->getGC() << '"';
1603 if (F->isDeclaration()) {
1607 // Output all of the function's basic blocks.
1608 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1614 Machine.purgeFunction();
1617 /// printArgument - This member is called for every argument that is passed into
1618 /// the function. Simply print it out
1620 void AssemblyWriter::printArgument(const Argument *Arg,
1623 TypePrinter.print(Arg->getType(), Out);
1625 // Output parameter attributes list
1626 if (Attrs != Attribute::None)
1627 Out << ' ' << Attribute::getAsString(Attrs);
1629 // Output name, if available...
1630 if (Arg->hasName()) {
1632 PrintLLVMName(Out, Arg);
1636 /// printBasicBlock - This member is called for each basic block in a method.
1638 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1639 if (BB->hasName()) { // Print out the label if it exists...
1641 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1643 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1644 Out << "\n; <label>:";
1645 int Slot = Machine.getLocalSlot(BB);
1652 if (BB->getParent() == 0) {
1653 Out.PadToColumn(50);
1654 Out << "; Error: Block without parent!";
1655 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1656 // Output predecessors for the block.
1657 Out.PadToColumn(50);
1659 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1662 Out << " No predecessors!";
1665 writeOperand(*PI, false);
1666 for (++PI; PI != PE; ++PI) {
1668 writeOperand(*PI, false);
1675 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1677 // Output all of the instructions in the basic block...
1678 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1679 printInstruction(*I);
1683 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1686 /// printInfoComment - Print a little comment after the instruction indicating
1687 /// which slot it occupies.
1689 void AssemblyWriter::printInfoComment(const Value &V) {
1690 if (AnnotationWriter) {
1691 AnnotationWriter->printInfoComment(V, Out);
1696 // This member is called for each Instruction in a function..
1697 void AssemblyWriter::printInstruction(const Instruction &I) {
1698 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1700 // Print out indentation for an instruction.
1703 // Print out name if it exists...
1705 PrintLLVMName(Out, &I);
1707 } else if (!I.getType()->isVoidTy()) {
1708 // Print out the def slot taken.
1709 int SlotNum = Machine.getLocalSlot(&I);
1711 Out << "<badref> = ";
1713 Out << '%' << SlotNum << " = ";
1716 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1719 // Print out the opcode...
1720 Out << I.getOpcodeName();
1722 // If this is an atomic load or store, print out the atomic marker.
1723 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1724 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1727 // If this is a volatile operation, print out the volatile marker.
1728 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1729 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1730 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1731 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1734 // Print out optimization information.
1735 WriteOptimizationInfo(Out, &I);
1737 // Print out the compare instruction predicates
1738 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1739 Out << ' ' << getPredicateText(CI->getPredicate());
1741 // Print out the atomicrmw operation
1742 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1743 writeAtomicRMWOperation(Out, RMWI->getOperation());
1745 // Print out the type of the operands...
1746 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1748 // Special case conditional branches to swizzle the condition out to the front
1749 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1750 BranchInst &BI(cast<BranchInst>(I));
1752 writeOperand(BI.getCondition(), true);
1754 writeOperand(BI.getSuccessor(0), true);
1756 writeOperand(BI.getSuccessor(1), true);
1758 } else if (isa<SwitchInst>(I)) {
1759 SwitchInst& SI(cast<SwitchInst>(I));
1760 // Special case switch instruction to get formatting nice and correct.
1762 writeOperand(SI.getCondition(), true);
1764 writeOperand(SI.getDefaultDest(), true);
1766 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1769 writeOperand(i.getCaseValue(), true);
1771 writeOperand(i.getCaseSuccessor(), true);
1774 } else if (isa<IndirectBrInst>(I)) {
1775 // Special case indirectbr instruction to get formatting nice and correct.
1777 writeOperand(Operand, true);
1780 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1783 writeOperand(I.getOperand(i), true);
1786 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1788 TypePrinter.print(I.getType(), Out);
1791 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1792 if (op) Out << ", ";
1794 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1795 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1797 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1799 writeOperand(I.getOperand(0), true);
1800 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1802 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1804 writeOperand(I.getOperand(0), true); Out << ", ";
1805 writeOperand(I.getOperand(1), true);
1806 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1808 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1810 TypePrinter.print(I.getType(), Out);
1811 Out << " personality ";
1812 writeOperand(I.getOperand(0), true); Out << '\n';
1814 if (LPI->isCleanup())
1817 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1818 if (i != 0 || LPI->isCleanup()) Out << "\n";
1819 if (LPI->isCatch(i))
1824 writeOperand(LPI->getClause(i), true);
1826 } else if (isa<ReturnInst>(I) && !Operand) {
1828 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1829 // Print the calling convention being used.
1830 switch (CI->getCallingConv()) {
1831 case CallingConv::C: break; // default
1832 case CallingConv::Fast: Out << " fastcc"; break;
1833 case CallingConv::Cold: Out << " coldcc"; break;
1834 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1835 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1836 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1837 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1838 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1839 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1840 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1841 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1842 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1843 default: Out << " cc" << CI->getCallingConv(); break;
1846 Operand = CI->getCalledValue();
1847 PointerType *PTy = cast<PointerType>(Operand->getType());
1848 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1849 Type *RetTy = FTy->getReturnType();
1850 const AttrListPtr &PAL = CI->getAttributes();
1852 if (PAL.getRetAttributes() != Attribute::None)
1853 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1855 // If possible, print out the short form of the call instruction. We can
1856 // only do this if the first argument is a pointer to a nonvararg function,
1857 // and if the return type is not a pointer to a function.
1860 if (!FTy->isVarArg() &&
1861 (!RetTy->isPointerTy() ||
1862 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1863 TypePrinter.print(RetTy, Out);
1865 writeOperand(Operand, false);
1867 writeOperand(Operand, true);
1870 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1873 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1876 if (PAL.getFnAttributes() != Attribute::None)
1877 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1878 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1879 Operand = II->getCalledValue();
1880 PointerType *PTy = cast<PointerType>(Operand->getType());
1881 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1882 Type *RetTy = FTy->getReturnType();
1883 const AttrListPtr &PAL = II->getAttributes();
1885 // Print the calling convention being used.
1886 switch (II->getCallingConv()) {
1887 case CallingConv::C: break; // default
1888 case CallingConv::Fast: Out << " fastcc"; break;
1889 case CallingConv::Cold: Out << " coldcc"; break;
1890 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1891 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1892 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1893 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1894 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1895 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1896 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1897 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1898 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1899 default: Out << " cc" << II->getCallingConv(); break;
1902 if (PAL.getRetAttributes() != Attribute::None)
1903 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1905 // If possible, print out the short form of the invoke instruction. We can
1906 // only do this if the first argument is a pointer to a nonvararg function,
1907 // and if the return type is not a pointer to a function.
1910 if (!FTy->isVarArg() &&
1911 (!RetTy->isPointerTy() ||
1912 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1913 TypePrinter.print(RetTy, Out);
1915 writeOperand(Operand, false);
1917 writeOperand(Operand, true);
1920 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1923 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1927 if (PAL.getFnAttributes() != Attribute::None)
1928 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1931 writeOperand(II->getNormalDest(), true);
1933 writeOperand(II->getUnwindDest(), true);
1935 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1937 TypePrinter.print(AI->getType()->getElementType(), Out);
1938 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1940 writeOperand(AI->getArraySize(), true);
1942 if (AI->getAlignment()) {
1943 Out << ", align " << AI->getAlignment();
1945 } else if (isa<CastInst>(I)) {
1948 writeOperand(Operand, true); // Work with broken code
1951 TypePrinter.print(I.getType(), Out);
1952 } else if (isa<VAArgInst>(I)) {
1955 writeOperand(Operand, true); // Work with broken code
1958 TypePrinter.print(I.getType(), Out);
1959 } else if (Operand) { // Print the normal way.
1961 // PrintAllTypes - Instructions who have operands of all the same type
1962 // omit the type from all but the first operand. If the instruction has
1963 // different type operands (for example br), then they are all printed.
1964 bool PrintAllTypes = false;
1965 Type *TheType = Operand->getType();
1967 // Select, Store and ShuffleVector always print all types.
1968 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1969 || isa<ReturnInst>(I)) {
1970 PrintAllTypes = true;
1972 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1973 Operand = I.getOperand(i);
1974 // note that Operand shouldn't be null, but the test helps make dump()
1975 // more tolerant of malformed IR
1976 if (Operand && Operand->getType() != TheType) {
1977 PrintAllTypes = true; // We have differing types! Print them all!
1983 if (!PrintAllTypes) {
1985 TypePrinter.print(TheType, Out);
1989 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1991 writeOperand(I.getOperand(i), PrintAllTypes);
1995 // Print atomic ordering/alignment for memory operations
1996 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1998 writeAtomic(LI->getOrdering(), LI->getSynchScope());
1999 if (LI->getAlignment())
2000 Out << ", align " << LI->getAlignment();
2001 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2003 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2004 if (SI->getAlignment())
2005 Out << ", align " << SI->getAlignment();
2006 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2007 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
2008 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2009 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2010 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2011 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2014 // Print Metadata info.
2015 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2016 I.getAllMetadata(InstMD);
2017 if (!InstMD.empty()) {
2018 SmallVector<StringRef, 8> MDNames;
2019 I.getType()->getContext().getMDKindNames(MDNames);
2020 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2021 unsigned Kind = InstMD[i].first;
2022 if (Kind < MDNames.size()) {
2023 Out << ", !" << MDNames[Kind];
2025 Out << ", !<unknown kind #" << Kind << ">";
2028 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2032 printInfoComment(I);
2035 static void WriteMDNodeComment(const MDNode *Node,
2036 formatted_raw_ostream &Out) {
2037 if (Node->getNumOperands() < 1)
2040 Value *Op = Node->getOperand(0);
2041 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2044 DIDescriptor Desc(Node);
2045 if (Desc.getVersion() < LLVMDebugVersion11)
2048 unsigned Tag = Desc.getTag();
2049 Out.PadToColumn(50);
2050 if (dwarf::TagString(Tag)) {
2053 } else if (Tag == dwarf::DW_TAG_user_base) {
2054 Out << "; [ DW_TAG_user_base ]";
2058 void AssemblyWriter::writeAllMDNodes() {
2059 SmallVector<const MDNode *, 16> Nodes;
2060 Nodes.resize(Machine.mdn_size());
2061 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2063 Nodes[I->second] = cast<MDNode>(I->first);
2065 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2066 Out << '!' << i << " = metadata ";
2067 printMDNodeBody(Nodes[i]);
2071 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2072 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2073 WriteMDNodeComment(Node, Out);
2077 //===----------------------------------------------------------------------===//
2078 // External Interface declarations
2079 //===----------------------------------------------------------------------===//
2081 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2082 SlotTracker SlotTable(this);
2083 formatted_raw_ostream OS(ROS);
2084 AssemblyWriter W(OS, SlotTable, this, AAW);
2085 W.printModule(this);
2088 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2089 SlotTracker SlotTable(getParent());
2090 formatted_raw_ostream OS(ROS);
2091 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2092 W.printNamedMDNode(this);
2095 void Type::print(raw_ostream &OS) const {
2097 OS << "<null Type>";
2101 TP.print(const_cast<Type*>(this), OS);
2103 // If the type is a named struct type, print the body as well.
2104 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2105 if (!STy->isLiteral()) {
2107 TP.printStructBody(STy, OS);
2111 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2113 ROS << "printing a <null> value\n";
2116 formatted_raw_ostream OS(ROS);
2117 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2118 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2119 SlotTracker SlotTable(F);
2120 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2121 W.printInstruction(*I);
2122 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2123 SlotTracker SlotTable(BB->getParent());
2124 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2125 W.printBasicBlock(BB);
2126 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2127 SlotTracker SlotTable(GV->getParent());
2128 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2129 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2131 else if (const Function *F = dyn_cast<Function>(GV))
2134 W.printAlias(cast<GlobalAlias>(GV));
2135 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2136 const Function *F = N->getFunction();
2137 SlotTracker SlotTable(F);
2138 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2139 W.printMDNodeBody(N);
2140 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2141 TypePrinting TypePrinter;
2142 TypePrinter.print(C->getType(), OS);
2144 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2145 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2146 isa<Argument>(this)) {
2147 WriteAsOperand(OS, this, true, 0);
2149 // Otherwise we don't know what it is. Call the virtual function to
2150 // allow a subclass to print itself.
2155 // Value::printCustom - subclasses should override this to implement printing.
2156 void Value::printCustom(raw_ostream &OS) const {
2157 llvm_unreachable("Unknown value to print out!");
2160 // Value::dump - allow easy printing of Values from the debugger.
2161 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2163 // Type::dump - allow easy printing of Types from the debugger.
2164 void Type::dump() const { print(dbgs()); }
2166 // Module::dump() - Allow printing of Modules from the debugger.
2167 void Module::dump() const { print(dbgs(), 0); }
2169 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2170 void NamedMDNode::dump() const { print(dbgs(), 0); }