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/TypeSymbolTable.h"
30
#include "llvm/ADT/DenseSet.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"
45
// Make virtual table appear in this compilation unit.
46
AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48
//===----------------------------------------------------------------------===//
50
//===----------------------------------------------------------------------===//
52
static const Module *getModuleFromVal(const Value *V) {
53
if (const Argument *MA = dyn_cast<Argument>(V))
54
return MA->getParent() ? MA->getParent()->getParent() : 0;
56
if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57
return BB->getParent() ? BB->getParent()->getParent() : 0;
59
if (const Instruction *I = dyn_cast<Instruction>(V)) {
60
const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61
return M ? M->getParent() : 0;
64
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65
return GV->getParent();
69
// PrintEscapedString - Print each character of the specified string, escaping
70
// it if it is not printable or if it is an escape char.
71
static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
72
for (unsigned i = 0, e = Name.size(); i != e; ++i) {
73
unsigned char C = Name[i];
74
if (isprint(C) && C != '\\' && C != '"')
77
Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
88
/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
89
/// prefixed with % (if the string only contains simple characters) or is
90
/// surrounded with ""'s (if it has special chars in it). Print it out.
91
static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
92
assert(Name.data() && "Cannot get empty name!");
94
default: llvm_unreachable("Bad prefix!");
96
case GlobalPrefix: OS << '@'; break;
97
case LabelPrefix: break;
98
case LocalPrefix: OS << '%'; break;
101
// Scan the name to see if it needs quotes first.
102
bool NeedsQuotes = isdigit(Name[0]);
104
for (unsigned i = 0, e = Name.size(); i != e; ++i) {
106
if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
113
// If we didn't need any quotes, just write out the name in one blast.
119
// Okay, we need quotes. Output the quotes and escape any scary characters as
122
PrintEscapedString(Name, OS);
126
/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
127
/// prefixed with % (if the string only contains simple characters) or is
128
/// surrounded with ""'s (if it has special chars in it). Print it out.
129
static void PrintLLVMName(raw_ostream &OS, const Value *V) {
130
PrintLLVMName(OS, V->getName(),
131
isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
134
//===----------------------------------------------------------------------===//
135
// TypePrinting Class: Type printing machinery
136
//===----------------------------------------------------------------------===//
138
static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
139
return *static_cast<DenseMap<const Type *, std::string>*>(M);
142
void TypePrinting::clear() {
143
getTypeNamesMap(TypeNames).clear();
146
bool TypePrinting::hasTypeName(const Type *Ty) const {
147
return getTypeNamesMap(TypeNames).count(Ty);
150
void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
151
getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
155
TypePrinting::TypePrinting() {
156
TypeNames = new DenseMap<const Type *, std::string>();
159
TypePrinting::~TypePrinting() {
160
delete &getTypeNamesMap(TypeNames);
163
/// CalcTypeName - Write the specified type to the specified raw_ostream, making
164
/// use of type names or up references to shorten the type name where possible.
165
void TypePrinting::CalcTypeName(const Type *Ty,
166
SmallVectorImpl<const Type *> &TypeStack,
167
raw_ostream &OS, bool IgnoreTopLevelName) {
168
// Check to see if the type is named.
169
if (!IgnoreTopLevelName) {
170
DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
171
DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
178
// Check to see if the Type is already on the stack...
179
unsigned Slot = 0, CurSize = TypeStack.size();
180
while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
182
// This is another base case for the recursion. In this case, we know
183
// that we have looped back to a type that we have previously visited.
184
// Generate the appropriate upreference to handle this.
185
if (Slot < CurSize) {
186
OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
190
TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
192
switch (Ty->getTypeID()) {
193
case Type::VoidTyID: OS << "void"; break;
194
case Type::FloatTyID: OS << "float"; break;
195
case Type::DoubleTyID: OS << "double"; break;
196
case Type::X86_FP80TyID: OS << "x86_fp80"; break;
197
case Type::FP128TyID: OS << "fp128"; break;
198
case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
199
case Type::LabelTyID: OS << "label"; break;
200
case Type::MetadataTyID: OS << "metadata"; break;
201
case Type::IntegerTyID:
202
OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
205
case Type::FunctionTyID: {
206
const FunctionType *FTy = cast<FunctionType>(Ty);
207
CalcTypeName(FTy->getReturnType(), TypeStack, OS);
209
for (FunctionType::param_iterator I = FTy->param_begin(),
210
E = FTy->param_end(); I != E; ++I) {
211
if (I != FTy->param_begin())
213
CalcTypeName(*I, TypeStack, OS);
215
if (FTy->isVarArg()) {
216
if (FTy->getNumParams()) OS << ", ";
222
case Type::StructTyID: {
223
const StructType *STy = cast<StructType>(Ty);
227
for (StructType::element_iterator I = STy->element_begin(),
228
E = STy->element_end(); I != E; ++I) {
230
CalcTypeName(*I, TypeStack, OS);
231
if (llvm::next(I) == STy->element_end())
241
case Type::PointerTyID: {
242
const PointerType *PTy = cast<PointerType>(Ty);
243
CalcTypeName(PTy->getElementType(), TypeStack, OS);
244
if (unsigned AddressSpace = PTy->getAddressSpace())
245
OS << " addrspace(" << AddressSpace << ')';
249
case Type::ArrayTyID: {
250
const ArrayType *ATy = cast<ArrayType>(Ty);
251
OS << '[' << ATy->getNumElements() << " x ";
252
CalcTypeName(ATy->getElementType(), TypeStack, OS);
256
case Type::VectorTyID: {
257
const VectorType *PTy = cast<VectorType>(Ty);
258
OS << "<" << PTy->getNumElements() << " x ";
259
CalcTypeName(PTy->getElementType(), TypeStack, OS);
263
case Type::OpaqueTyID:
267
OS << "<unrecognized-type>";
271
TypeStack.pop_back(); // Remove self from stack.
274
/// printTypeInt - The internal guts of printing out a type that has a
275
/// potentially named portion.
277
void TypePrinting::print(const Type *Ty, raw_ostream &OS,
278
bool IgnoreTopLevelName) {
279
// Check to see if the type is named.
280
DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
281
if (!IgnoreTopLevelName) {
282
DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
289
// Otherwise we have a type that has not been named but is a derived type.
290
// Carefully recurse the type hierarchy to print out any contained symbolic
292
SmallVector<const Type *, 16> TypeStack;
293
std::string TypeName;
295
raw_string_ostream TypeOS(TypeName);
296
CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
299
// Cache type name for later use.
300
if (!IgnoreTopLevelName)
301
TM.insert(std::make_pair(Ty, TypeOS.str()));
306
// To avoid walking constant expressions multiple times and other IR
307
// objects, we keep several helper maps.
308
DenseSet<const Value*> VisitedConstants;
309
DenseSet<const Type*> VisitedTypes;
312
std::vector<const Type*> &NumberedTypes;
314
TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
315
: TP(tp), NumberedTypes(numberedTypes) {}
317
void Run(const Module &M) {
318
// Get types from the type symbol table. This gets opaque types referened
319
// only through derived named types.
320
const TypeSymbolTable &ST = M.getTypeSymbolTable();
321
for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
323
IncorporateType(TI->second);
325
// Get types from global variables.
326
for (Module::const_global_iterator I = M.global_begin(),
327
E = M.global_end(); I != E; ++I) {
328
IncorporateType(I->getType());
329
if (I->hasInitializer())
330
IncorporateValue(I->getInitializer());
333
// Get types from aliases.
334
for (Module::const_alias_iterator I = M.alias_begin(),
335
E = M.alias_end(); I != E; ++I) {
336
IncorporateType(I->getType());
337
IncorporateValue(I->getAliasee());
340
// Get types from functions.
341
for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
342
IncorporateType(FI->getType());
344
for (Function::const_iterator BB = FI->begin(), E = FI->end();
346
for (BasicBlock::const_iterator II = BB->begin(),
347
E = BB->end(); II != E; ++II) {
348
const Instruction &I = *II;
349
// Incorporate the type of the instruction and all its operands.
350
IncorporateType(I.getType());
351
for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
353
IncorporateValue(*OI);
359
void IncorporateType(const Type *Ty) {
360
// Check to see if we're already visited this type.
361
if (!VisitedTypes.insert(Ty).second)
364
// If this is a structure or opaque type, add a name for the type.
365
if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
366
|| Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
367
TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
368
NumberedTypes.push_back(Ty);
371
// Recursively walk all contained types.
372
for (Type::subtype_iterator I = Ty->subtype_begin(),
373
E = Ty->subtype_end(); I != E; ++I)
377
/// IncorporateValue - This method is used to walk operand lists finding
378
/// types hiding in constant expressions and other operands that won't be
379
/// walked in other ways. GlobalValues, basic blocks, instructions, and
380
/// inst operands are all explicitly enumerated.
381
void IncorporateValue(const Value *V) {
382
if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
385
if (!VisitedConstants.insert(V).second)
389
IncorporateType(V->getType());
391
// Look in operands for types.
392
const Constant *C = cast<Constant>(V);
393
for (Constant::const_op_iterator I = C->op_begin(),
394
E = C->op_end(); I != E;++I)
395
IncorporateValue(*I);
398
} // end anonymous namespace
401
/// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
402
/// the specified module to the TypePrinter and all numbered types to it and the
403
/// NumberedTypes table.
404
static void AddModuleTypesToPrinter(TypePrinting &TP,
405
std::vector<const Type*> &NumberedTypes,
409
// If the module has a symbol table, take all global types and stuff their
410
// names into the TypeNames map.
411
const TypeSymbolTable &ST = M->getTypeSymbolTable();
412
for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
414
const Type *Ty = cast<Type>(TI->second);
416
// As a heuristic, don't insert pointer to primitive types, because
417
// they are used too often to have a single useful name.
418
if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
419
const Type *PETy = PTy->getElementType();
420
if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
425
// Likewise don't insert primitives either.
426
if (Ty->isIntegerTy() || Ty->isPrimitiveType())
429
// Get the name as a string and insert it into TypeNames.
431
raw_string_ostream NameROS(NameStr);
432
formatted_raw_ostream NameOS(NameROS);
433
PrintLLVMName(NameOS, TI->first, LocalPrefix);
435
TP.addTypeName(Ty, NameStr);
438
// Walk the entire module to find references to unnamed structure and opaque
439
// types. This is required for correctness by opaque types (because multiple
440
// uses of an unnamed opaque type needs to be referred to by the same ID) and
441
// it shrinks complex recursive structure types substantially in some cases.
442
TypeFinder(TP, NumberedTypes).Run(*M);
446
/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
447
/// type, iff there is an entry in the modules symbol table for the specified
448
/// type or one of it's component types.
450
void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
451
TypePrinting Printer;
452
std::vector<const Type*> NumberedTypes;
453
AddModuleTypesToPrinter(Printer, NumberedTypes, M);
454
Printer.print(Ty, OS);
457
//===----------------------------------------------------------------------===//
458
// SlotTracker Class: Enumerate slot numbers for unnamed values
459
//===----------------------------------------------------------------------===//
463
/// This class provides computation of slot numbers for LLVM Assembly writing.
467
/// ValueMap - A mapping of Values to slot numbers.
468
typedef DenseMap<const Value*, unsigned> ValueMap;
471
/// TheModule - The module for which we are holding slot numbers.
472
const Module* TheModule;
474
/// TheFunction - The function for which we are holding slot numbers.
475
const Function* TheFunction;
476
bool FunctionProcessed;
478
/// mMap - The TypePlanes map for the module level data.
482
/// fMap - The TypePlanes map for the function level data.
486
/// mdnMap - Map for MDNodes.
487
DenseMap<const MDNode*, unsigned> mdnMap;
490
/// Construct from a module
491
explicit SlotTracker(const Module *M);
492
/// Construct from a function, starting out in incorp state.
493
explicit SlotTracker(const Function *F);
495
/// Return the slot number of the specified value in it's type
496
/// plane. If something is not in the SlotTracker, return -1.
497
int getLocalSlot(const Value *V);
498
int getGlobalSlot(const GlobalValue *V);
499
int getMetadataSlot(const MDNode *N);
501
/// If you'd like to deal with a function instead of just a module, use
502
/// this method to get its data into the SlotTracker.
503
void incorporateFunction(const Function *F) {
505
FunctionProcessed = false;
508
/// After calling incorporateFunction, use this method to remove the
509
/// most recently incorporated function from the SlotTracker. This
510
/// will reset the state of the machine back to just the module contents.
511
void purgeFunction();
513
/// MDNode map iterators.
514
typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
515
mdn_iterator mdn_begin() { return mdnMap.begin(); }
516
mdn_iterator mdn_end() { return mdnMap.end(); }
517
unsigned mdn_size() const { return mdnMap.size(); }
518
bool mdn_empty() const { return mdnMap.empty(); }
520
/// This function does the actual initialization.
521
inline void initialize();
523
// Implementation Details
525
/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
526
void CreateModuleSlot(const GlobalValue *V);
528
/// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
529
void CreateMetadataSlot(const MDNode *N);
531
/// CreateFunctionSlot - Insert the specified Value* into the slot table.
532
void CreateFunctionSlot(const Value *V);
534
/// Add all of the module level global variables (and their initializers)
535
/// and function declarations, but not the contents of those functions.
536
void processModule();
538
/// Add all of the functions arguments, basic blocks, and instructions.
539
void processFunction();
541
SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
542
void operator=(const SlotTracker &); // DO NOT IMPLEMENT
545
} // end anonymous namespace
548
static SlotTracker *createSlotTracker(const Value *V) {
549
if (const Argument *FA = dyn_cast<Argument>(V))
550
return new SlotTracker(FA->getParent());
552
if (const Instruction *I = dyn_cast<Instruction>(V))
553
return new SlotTracker(I->getParent()->getParent());
555
if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
556
return new SlotTracker(BB->getParent());
558
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
559
return new SlotTracker(GV->getParent());
561
if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
562
return new SlotTracker(GA->getParent());
564
if (const Function *Func = dyn_cast<Function>(V))
565
return new SlotTracker(Func);
567
if (const MDNode *MD = dyn_cast<MDNode>(V)) {
568
if (!MD->isFunctionLocal())
569
return new SlotTracker(MD->getFunction());
571
return new SlotTracker((Function *)0);
578
#define ST_DEBUG(X) dbgs() << X
583
// Module level constructor. Causes the contents of the Module (sans functions)
584
// to be added to the slot table.
585
SlotTracker::SlotTracker(const Module *M)
586
: TheModule(M), TheFunction(0), FunctionProcessed(false),
587
mNext(0), fNext(0), mdnNext(0) {
590
// Function level constructor. Causes the contents of the Module and the one
591
// function provided to be added to the slot table.
592
SlotTracker::SlotTracker(const Function *F)
593
: TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
594
mNext(0), fNext(0), mdnNext(0) {
597
inline void SlotTracker::initialize() {
600
TheModule = 0; ///< Prevent re-processing next time we're called.
603
if (TheFunction && !FunctionProcessed)
607
// Iterate through all the global variables, functions, and global
608
// variable initializers and create slots for them.
609
void SlotTracker::processModule() {
610
ST_DEBUG("begin processModule!\n");
612
// Add all of the unnamed global variables to the value table.
613
for (Module::const_global_iterator I = TheModule->global_begin(),
614
E = TheModule->global_end(); I != E; ++I) {
619
// Add metadata used by named metadata.
620
for (Module::const_named_metadata_iterator
621
I = TheModule->named_metadata_begin(),
622
E = TheModule->named_metadata_end(); I != E; ++I) {
623
const NamedMDNode *NMD = I;
624
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
625
CreateMetadataSlot(NMD->getOperand(i));
628
// Add all the unnamed functions to the table.
629
for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
634
ST_DEBUG("end processModule!\n");
637
// Process the arguments, basic blocks, and instructions of a function.
638
void SlotTracker::processFunction() {
639
ST_DEBUG("begin processFunction!\n");
642
// Add all the function arguments with no names.
643
for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
644
AE = TheFunction->arg_end(); AI != AE; ++AI)
646
CreateFunctionSlot(AI);
648
ST_DEBUG("Inserting Instructions:\n");
650
SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
652
// Add all of the basic blocks and instructions with no names.
653
for (Function::const_iterator BB = TheFunction->begin(),
654
E = TheFunction->end(); BB != E; ++BB) {
656
CreateFunctionSlot(BB);
658
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
660
if (!I->getType()->isVoidTy() && !I->hasName())
661
CreateFunctionSlot(I);
663
// Intrinsics can directly use metadata. We allow direct calls to any
664
// llvm.foo function here, because the target may not be linked into the
666
if (const CallInst *CI = dyn_cast<CallInst>(I)) {
667
if (Function *F = CI->getCalledFunction())
668
if (F->getName().startswith("llvm."))
669
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
670
if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
671
CreateMetadataSlot(N);
674
// Process metadata attached with this instruction.
675
I->getAllMetadata(MDForInst);
676
for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
677
CreateMetadataSlot(MDForInst[i].second);
682
FunctionProcessed = true;
684
ST_DEBUG("end processFunction!\n");
687
/// Clean up after incorporating a function. This is the only way to get out of
688
/// the function incorporation state that affects get*Slot/Create*Slot. Function
689
/// incorporation state is indicated by TheFunction != 0.
690
void SlotTracker::purgeFunction() {
691
ST_DEBUG("begin purgeFunction!\n");
692
fMap.clear(); // Simply discard the function level map
694
FunctionProcessed = false;
695
ST_DEBUG("end purgeFunction!\n");
698
/// getGlobalSlot - Get the slot number of a global value.
699
int SlotTracker::getGlobalSlot(const GlobalValue *V) {
700
// Check for uninitialized state and do lazy initialization.
703
// Find the type plane in the module map
704
ValueMap::iterator MI = mMap.find(V);
705
return MI == mMap.end() ? -1 : (int)MI->second;
708
/// getMetadataSlot - Get the slot number of a MDNode.
709
int SlotTracker::getMetadataSlot(const MDNode *N) {
710
// Check for uninitialized state and do lazy initialization.
713
// Find the type plane in the module map
714
mdn_iterator MI = mdnMap.find(N);
715
return MI == mdnMap.end() ? -1 : (int)MI->second;
719
/// getLocalSlot - Get the slot number for a value that is local to a function.
720
int SlotTracker::getLocalSlot(const Value *V) {
721
assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
723
// Check for uninitialized state and do lazy initialization.
726
ValueMap::iterator FI = fMap.find(V);
727
return FI == fMap.end() ? -1 : (int)FI->second;
731
/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
732
void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
733
assert(V && "Can't insert a null Value into SlotTracker!");
734
assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
735
assert(!V->hasName() && "Doesn't need a slot!");
737
unsigned DestSlot = mNext++;
740
ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
742
// G = Global, F = Function, A = Alias, o = other
743
ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
744
(isa<Function>(V) ? 'F' :
745
(isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
748
/// CreateSlot - Create a new slot for the specified value if it has no name.
749
void SlotTracker::CreateFunctionSlot(const Value *V) {
750
assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
752
unsigned DestSlot = fNext++;
755
// G = Global, F = Function, o = other
756
ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
757
DestSlot << " [o]\n");
760
/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
761
void SlotTracker::CreateMetadataSlot(const MDNode *N) {
762
assert(N && "Can't insert a null Value into SlotTracker!");
764
// Don't insert if N is a function-local metadata, these are always printed
766
if (!N->isFunctionLocal()) {
767
mdn_iterator I = mdnMap.find(N);
768
if (I != mdnMap.end())
771
unsigned DestSlot = mdnNext++;
772
mdnMap[N] = DestSlot;
775
// Recursively add any MDNodes referenced by operands.
776
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
777
if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
778
CreateMetadataSlot(Op);
781
//===----------------------------------------------------------------------===//
782
// AsmWriter Implementation
783
//===----------------------------------------------------------------------===//
785
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
786
TypePrinting *TypePrinter,
787
SlotTracker *Machine,
788
const Module *Context);
792
static const char *getPredicateText(unsigned predicate) {
793
const char * pred = "unknown";
795
case FCmpInst::FCMP_FALSE: pred = "false"; break;
796
case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
797
case FCmpInst::FCMP_OGT: pred = "ogt"; break;
798
case FCmpInst::FCMP_OGE: pred = "oge"; break;
799
case FCmpInst::FCMP_OLT: pred = "olt"; break;
800
case FCmpInst::FCMP_OLE: pred = "ole"; break;
801
case FCmpInst::FCMP_ONE: pred = "one"; break;
802
case FCmpInst::FCMP_ORD: pred = "ord"; break;
803
case FCmpInst::FCMP_UNO: pred = "uno"; break;
804
case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
805
case FCmpInst::FCMP_UGT: pred = "ugt"; break;
806
case FCmpInst::FCMP_UGE: pred = "uge"; break;
807
case FCmpInst::FCMP_ULT: pred = "ult"; break;
808
case FCmpInst::FCMP_ULE: pred = "ule"; break;
809
case FCmpInst::FCMP_UNE: pred = "une"; break;
810
case FCmpInst::FCMP_TRUE: pred = "true"; break;
811
case ICmpInst::ICMP_EQ: pred = "eq"; break;
812
case ICmpInst::ICMP_NE: pred = "ne"; break;
813
case ICmpInst::ICMP_SGT: pred = "sgt"; break;
814
case ICmpInst::ICMP_SGE: pred = "sge"; break;
815
case ICmpInst::ICMP_SLT: pred = "slt"; break;
816
case ICmpInst::ICMP_SLE: pred = "sle"; break;
817
case ICmpInst::ICMP_UGT: pred = "ugt"; break;
818
case ICmpInst::ICMP_UGE: pred = "uge"; break;
819
case ICmpInst::ICMP_ULT: pred = "ult"; break;
820
case ICmpInst::ICMP_ULE: pred = "ule"; break;
826
static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
827
if (const OverflowingBinaryOperator *OBO =
828
dyn_cast<OverflowingBinaryOperator>(U)) {
829
if (OBO->hasNoUnsignedWrap())
831
if (OBO->hasNoSignedWrap())
833
} else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
836
} else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
837
if (GEP->isInBounds())
842
static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
843
TypePrinting &TypePrinter,
844
SlotTracker *Machine,
845
const Module *Context) {
846
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
847
if (CI->getType()->isIntegerTy(1)) {
848
Out << (CI->getZExtValue() ? "true" : "false");
851
Out << CI->getValue();
855
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
856
if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
857
&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
858
// We would like to output the FP constant value in exponential notation,
859
// but we cannot do this if doing so will lose precision. Check here to
860
// make sure that we only output it in exponential format if we can parse
861
// the value back and get the same value.
864
bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
865
double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
866
CFP->getValueAPF().convertToFloat();
867
SmallString<128> StrVal;
868
raw_svector_ostream(StrVal) << Val;
870
// Check to make sure that the stringized number is not some string like
871
// "Inf" or NaN, that atof will accept, but the lexer will not. Check
872
// that the string matches the "[-+]?[0-9]" regex.
874
if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
875
((StrVal[0] == '-' || StrVal[0] == '+') &&
876
(StrVal[1] >= '0' && StrVal[1] <= '9'))) {
877
// Reparse stringized version!
878
if (atof(StrVal.c_str()) == Val) {
883
// Otherwise we could not reparse it to exactly the same value, so we must
884
// output the string in hexadecimal format! Note that loading and storing
885
// floating point types changes the bits of NaNs on some hosts, notably
886
// x86, so we must not use these types.
887
assert(sizeof(double) == sizeof(uint64_t) &&
888
"assuming that double is 64 bits!");
890
APFloat apf = CFP->getValueAPF();
891
// Floats are represented in ASCII IR as double, convert.
893
apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
896
utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
901
// Some form of long double. These appear as a magic letter identifying
902
// the type, then a fixed number of hex digits.
904
if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
906
// api needed to prevent premature destruction
907
APInt api = CFP->getValueAPF().bitcastToAPInt();
908
const uint64_t* p = api.getRawData();
909
uint64_t word = p[1];
911
int width = api.getBitWidth();
912
for (int j=0; j<width; j+=4, shiftcount-=4) {
913
unsigned int nibble = (word>>shiftcount) & 15;
915
Out << (unsigned char)(nibble + '0');
917
Out << (unsigned char)(nibble - 10 + 'A');
918
if (shiftcount == 0 && j+4 < width) {
922
shiftcount = width-j-4;
926
} else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
928
else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
931
llvm_unreachable("Unsupported floating point type");
932
// api needed to prevent premature destruction
933
APInt api = CFP->getValueAPF().bitcastToAPInt();
934
const uint64_t* p = api.getRawData();
937
int width = api.getBitWidth();
938
for (int j=0; j<width; j+=4, shiftcount-=4) {
939
unsigned int nibble = (word>>shiftcount) & 15;
941
Out << (unsigned char)(nibble + '0');
943
Out << (unsigned char)(nibble - 10 + 'A');
944
if (shiftcount == 0 && j+4 < width) {
948
shiftcount = width-j-4;
954
if (isa<ConstantAggregateZero>(CV)) {
955
Out << "zeroinitializer";
959
if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
960
Out << "blockaddress(";
961
WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
964
WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
970
if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
971
// As a special case, print the array as a string if it is an array of
972
// i8 with ConstantInt values.
974
const Type *ETy = CA->getType()->getElementType();
975
if (CA->isString()) {
977
PrintEscapedString(CA->getAsString(), Out);
979
} else { // Cannot output in string format...
981
if (CA->getNumOperands()) {
982
TypePrinter.print(ETy, Out);
984
WriteAsOperandInternal(Out, CA->getOperand(0),
985
&TypePrinter, Machine,
987
for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
989
TypePrinter.print(ETy, Out);
991
WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1000
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1001
if (CS->getType()->isPacked())
1004
unsigned N = CS->getNumOperands();
1007
TypePrinter.print(CS->getOperand(0)->getType(), Out);
1010
WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1013
for (unsigned i = 1; i < N; i++) {
1015
TypePrinter.print(CS->getOperand(i)->getType(), Out);
1018
WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1025
if (CS->getType()->isPacked())
1030
if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1031
const Type *ETy = CP->getType()->getElementType();
1032
assert(CP->getNumOperands() > 0 &&
1033
"Number of operands for a PackedConst must be > 0");
1035
TypePrinter.print(ETy, Out);
1037
WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
1039
for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1041
TypePrinter.print(ETy, Out);
1043
WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
1050
if (isa<ConstantPointerNull>(CV)) {
1055
if (isa<UndefValue>(CV)) {
1060
if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1061
Out << "!" << Machine->getMetadataSlot(Node);
1065
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1066
Out << CE->getOpcodeName();
1067
WriteOptimizationInfo(Out, CE);
1068
if (CE->isCompare())
1069
Out << ' ' << getPredicateText(CE->getPredicate());
1072
for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1073
TypePrinter.print((*OI)->getType(), Out);
1075
WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1076
if (OI+1 != CE->op_end())
1080
if (CE->hasIndices()) {
1081
const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1082
for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1083
Out << ", " << Indices[i];
1088
TypePrinter.print(CE->getType(), Out);
1095
Out << "<placeholder or erroneous Constant>";
1098
static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1099
TypePrinting *TypePrinter,
1100
SlotTracker *Machine,
1101
const Module *Context) {
1103
for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1104
const Value *V = Node->getOperand(mi);
1108
TypePrinter->print(V->getType(), Out);
1110
WriteAsOperandInternal(Out, Node->getOperand(mi),
1111
TypePrinter, Machine, Context);
1121
/// WriteAsOperand - Write the name of the specified value out to the specified
1122
/// ostream. This can be useful when you just want to print int %reg126, not
1123
/// the whole instruction that generated it.
1125
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1126
TypePrinting *TypePrinter,
1127
SlotTracker *Machine,
1128
const Module *Context) {
1130
PrintLLVMName(Out, V);
1134
const Constant *CV = dyn_cast<Constant>(V);
1135
if (CV && !isa<GlobalValue>(CV)) {
1136
assert(TypePrinter && "Constants require TypePrinting!");
1137
WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1141
if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1143
if (IA->hasSideEffects())
1144
Out << "sideeffect ";
1145
if (IA->isAlignStack())
1146
Out << "alignstack ";
1148
PrintEscapedString(IA->getAsmString(), Out);
1150
PrintEscapedString(IA->getConstraintString(), Out);
1155
if (const MDNode *N = dyn_cast<MDNode>(V)) {
1156
if (N->isFunctionLocal()) {
1157
// Print metadata inline, not via slot reference number.
1158
WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1163
if (N->isFunctionLocal())
1164
Machine = new SlotTracker(N->getFunction());
1166
Machine = new SlotTracker(Context);
1168
Out << '!' << Machine->getMetadataSlot(N);
1172
if (const MDString *MDS = dyn_cast<MDString>(V)) {
1174
PrintEscapedString(MDS->getString(), Out);
1179
if (V->getValueID() == Value::PseudoSourceValueVal ||
1180
V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1188
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1189
Slot = Machine->getGlobalSlot(GV);
1192
Slot = Machine->getLocalSlot(V);
1195
Machine = createSlotTracker(V);
1197
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1198
Slot = Machine->getGlobalSlot(GV);
1201
Slot = Machine->getLocalSlot(V);
1210
Out << Prefix << Slot;
1215
void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1216
bool PrintType, const Module *Context) {
1218
// Fast path: Don't construct and populate a TypePrinting object if we
1219
// won't be needing any types printed.
1221
((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1222
V->hasName() || isa<GlobalValue>(V))) {
1223
WriteAsOperandInternal(Out, V, 0, 0, Context);
1227
if (Context == 0) Context = getModuleFromVal(V);
1229
TypePrinting TypePrinter;
1230
std::vector<const Type*> NumberedTypes;
1231
AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1233
TypePrinter.print(V->getType(), Out);
1237
WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1242
class AssemblyWriter {
1243
formatted_raw_ostream &Out;
1244
SlotTracker &Machine;
1245
const Module *TheModule;
1246
TypePrinting TypePrinter;
1247
AssemblyAnnotationWriter *AnnotationWriter;
1248
std::vector<const Type*> NumberedTypes;
1251
inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1253
AssemblyAnnotationWriter *AAW)
1254
: Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1255
AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1258
void printMDNodeBody(const MDNode *MD);
1259
void printNamedMDNode(const NamedMDNode *NMD);
1261
void printModule(const Module *M);
1263
void writeOperand(const Value *Op, bool PrintType);
1264
void writeParamOperand(const Value *Operand, Attributes Attrs);
1266
void writeAllMDNodes();
1268
void printTypeSymbolTable(const TypeSymbolTable &ST);
1269
void printGlobal(const GlobalVariable *GV);
1270
void printAlias(const GlobalAlias *GV);
1271
void printFunction(const Function *F);
1272
void printArgument(const Argument *FA, Attributes Attrs);
1273
void printBasicBlock(const BasicBlock *BB);
1274
void printInstruction(const Instruction &I);
1277
// printInfoComment - Print a little comment after the instruction indicating
1278
// which slot it occupies.
1279
void printInfoComment(const Value &V);
1281
} // end of anonymous namespace
1283
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1285
Out << "<null operand!>";
1289
TypePrinter.print(Operand->getType(), Out);
1292
WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1295
void AssemblyWriter::writeParamOperand(const Value *Operand,
1298
Out << "<null operand!>";
1303
TypePrinter.print(Operand->getType(), Out);
1304
// Print parameter attributes list
1305
if (Attrs != Attribute::None)
1306
Out << ' ' << Attribute::getAsString(Attrs);
1308
// Print the operand
1309
WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1312
void AssemblyWriter::printModule(const Module *M) {
1313
if (!M->getModuleIdentifier().empty() &&
1314
// Don't print the ID if it will start a new line (which would
1315
// require a comment char before it).
1316
M->getModuleIdentifier().find('\n') == std::string::npos)
1317
Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1319
if (!M->getDataLayout().empty())
1320
Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1321
if (!M->getTargetTriple().empty())
1322
Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1324
if (!M->getModuleInlineAsm().empty()) {
1325
// Split the string into lines, to make it easier to read the .ll file.
1326
std::string Asm = M->getModuleInlineAsm();
1328
size_t NewLine = Asm.find_first_of('\n', CurPos);
1330
while (NewLine != std::string::npos) {
1331
// We found a newline, print the portion of the asm string from the
1332
// last newline up to this newline.
1333
Out << "module asm \"";
1334
PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1338
NewLine = Asm.find_first_of('\n', CurPos);
1340
Out << "module asm \"";
1341
PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1345
// Loop over the dependent libraries and emit them.
1346
Module::lib_iterator LI = M->lib_begin();
1347
Module::lib_iterator LE = M->lib_end();
1350
Out << "deplibs = [ ";
1352
Out << '"' << *LI << '"';
1360
// Loop over the symbol table, emitting all id'd types.
1361
if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1362
printTypeSymbolTable(M->getTypeSymbolTable());
1364
// Output all globals.
1365
if (!M->global_empty()) Out << '\n';
1366
for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1370
// Output all aliases.
1371
if (!M->alias_empty()) Out << "\n";
1372
for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1376
// Output all of the functions.
1377
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1380
// Output named metadata.
1381
if (!M->named_metadata_empty()) Out << '\n';
1383
for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1384
E = M->named_metadata_end(); I != E; ++I)
1385
printNamedMDNode(I);
1388
if (!Machine.mdn_empty()) {
1394
void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1395
Out << "!" << NMD->getName() << " = !{";
1396
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1398
Out << '!' << Machine.getMetadataSlot(NMD->getOperand(i));
1404
static void PrintLinkage(GlobalValue::LinkageTypes LT,
1405
formatted_raw_ostream &Out) {
1407
case GlobalValue::ExternalLinkage: break;
1408
case GlobalValue::PrivateLinkage: Out << "private "; break;
1409
case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1410
case GlobalValue::LinkerPrivateWeakLinkage:
1411
Out << "linker_private_weak ";
1413
case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1414
Out << "linker_private_weak_def_auto ";
1416
case GlobalValue::InternalLinkage: Out << "internal "; break;
1417
case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1418
case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1419
case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1420
case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1421
case GlobalValue::CommonLinkage: Out << "common "; break;
1422
case GlobalValue::AppendingLinkage: Out << "appending "; break;
1423
case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1424
case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1425
case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1426
case GlobalValue::AvailableExternallyLinkage:
1427
Out << "available_externally ";
1433
static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1434
formatted_raw_ostream &Out) {
1436
case GlobalValue::DefaultVisibility: break;
1437
case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1438
case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1442
void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1443
if (GV->isMaterializable())
1444
Out << "; Materializable\n";
1446
WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1449
if (!GV->hasInitializer() && GV->hasExternalLinkage())
1452
PrintLinkage(GV->getLinkage(), Out);
1453
PrintVisibility(GV->getVisibility(), Out);
1455
if (GV->isThreadLocal()) Out << "thread_local ";
1456
if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1457
Out << "addrspace(" << AddressSpace << ") ";
1458
Out << (GV->isConstant() ? "constant " : "global ");
1459
TypePrinter.print(GV->getType()->getElementType(), Out);
1461
if (GV->hasInitializer()) {
1463
writeOperand(GV->getInitializer(), false);
1466
if (GV->hasSection()) {
1467
Out << ", section \"";
1468
PrintEscapedString(GV->getSection(), Out);
1471
if (GV->getAlignment())
1472
Out << ", align " << GV->getAlignment();
1474
printInfoComment(*GV);
1478
void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1479
if (GA->isMaterializable())
1480
Out << "; Materializable\n";
1482
// Don't crash when dumping partially built GA
1484
Out << "<<nameless>> = ";
1486
PrintLLVMName(Out, GA);
1489
PrintVisibility(GA->getVisibility(), Out);
1493
PrintLinkage(GA->getLinkage(), Out);
1495
const Constant *Aliasee = GA->getAliasee();
1497
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1498
TypePrinter.print(GV->getType(), Out);
1500
PrintLLVMName(Out, GV);
1501
} else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1502
TypePrinter.print(F->getFunctionType(), Out);
1505
WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1506
} else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1507
TypePrinter.print(GA->getType(), Out);
1509
PrintLLVMName(Out, GA);
1511
const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1512
// The only valid GEP is an all zero GEP.
1513
assert((CE->getOpcode() == Instruction::BitCast ||
1514
CE->getOpcode() == Instruction::GetElementPtr) &&
1515
"Unsupported aliasee");
1516
writeOperand(CE, false);
1519
printInfoComment(*GA);
1523
void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1524
// Emit all numbered types.
1525
for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1526
Out << '%' << i << " = type ";
1528
// Make sure we print out at least one level of the type structure, so
1529
// that we do not get %2 = type %2
1530
TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1534
// Print the named types.
1535
for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1537
PrintLLVMName(Out, TI->first, LocalPrefix);
1540
// Make sure we print out at least one level of the type structure, so
1541
// that we do not get %FILE = type %FILE
1542
TypePrinter.printAtLeastOneLevel(TI->second, Out);
1547
/// printFunction - Print all aspects of a function.
1549
void AssemblyWriter::printFunction(const Function *F) {
1550
// Print out the return type and name.
1553
if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1555
if (F->isMaterializable())
1556
Out << "; Materializable\n";
1558
if (F->isDeclaration())
1563
PrintLinkage(F->getLinkage(), Out);
1564
PrintVisibility(F->getVisibility(), Out);
1566
// Print the calling convention.
1567
switch (F->getCallingConv()) {
1568
case CallingConv::C: break; // default
1569
case CallingConv::Fast: Out << "fastcc "; break;
1570
case CallingConv::Cold: Out << "coldcc "; break;
1571
case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1572
case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1573
case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1574
case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1575
case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1576
case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1577
case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1578
default: Out << "cc" << F->getCallingConv() << " "; break;
1581
const FunctionType *FT = F->getFunctionType();
1582
const AttrListPtr &Attrs = F->getAttributes();
1583
Attributes RetAttrs = Attrs.getRetAttributes();
1584
if (RetAttrs != Attribute::None)
1585
Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1586
TypePrinter.print(F->getReturnType(), Out);
1588
WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1590
Machine.incorporateFunction(F);
1592
// Loop over the arguments, printing them...
1595
if (!F->isDeclaration()) {
1596
// If this isn't a declaration, print the argument names as well.
1597
for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1599
// Insert commas as we go... the first arg doesn't get a comma
1600
if (I != F->arg_begin()) Out << ", ";
1601
printArgument(I, Attrs.getParamAttributes(Idx));
1605
// Otherwise, print the types from the function type.
1606
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1607
// Insert commas as we go... the first arg doesn't get a comma
1611
TypePrinter.print(FT->getParamType(i), Out);
1613
Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1614
if (ArgAttrs != Attribute::None)
1615
Out << ' ' << Attribute::getAsString(ArgAttrs);
1619
// Finish printing arguments...
1620
if (FT->isVarArg()) {
1621
if (FT->getNumParams()) Out << ", ";
1622
Out << "..."; // Output varargs portion of signature!
1625
Attributes FnAttrs = Attrs.getFnAttributes();
1626
if (FnAttrs != Attribute::None)
1627
Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1628
if (F->hasSection()) {
1629
Out << " section \"";
1630
PrintEscapedString(F->getSection(), Out);
1633
if (F->getAlignment())
1634
Out << " align " << F->getAlignment();
1636
Out << " gc \"" << F->getGC() << '"';
1637
if (F->isDeclaration()) {
1641
// Output all of the function's basic blocks.
1642
for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1648
Machine.purgeFunction();
1651
/// printArgument - This member is called for every argument that is passed into
1652
/// the function. Simply print it out
1654
void AssemblyWriter::printArgument(const Argument *Arg,
1657
TypePrinter.print(Arg->getType(), Out);
1659
// Output parameter attributes list
1660
if (Attrs != Attribute::None)
1661
Out << ' ' << Attribute::getAsString(Attrs);
1663
// Output name, if available...
1664
if (Arg->hasName()) {
1666
PrintLLVMName(Out, Arg);
1670
/// printBasicBlock - This member is called for each basic block in a method.
1672
void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1673
if (BB->hasName()) { // Print out the label if it exists...
1675
PrintLLVMName(Out, BB->getName(), LabelPrefix);
1677
} else if (!BB->use_empty()) { // Don't print block # of no uses...
1678
Out << "\n; <label>:";
1679
int Slot = Machine.getLocalSlot(BB);
1686
if (BB->getParent() == 0) {
1687
Out.PadToColumn(50);
1688
Out << "; Error: Block without parent!";
1689
} else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1690
// Output predecessors for the block.
1691
Out.PadToColumn(50);
1693
const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1696
Out << " No predecessors!";
1699
writeOperand(*PI, false);
1700
for (++PI; PI != PE; ++PI) {
1702
writeOperand(*PI, false);
1709
if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1711
// Output all of the instructions in the basic block...
1712
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1713
printInstruction(*I);
1717
if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1720
/// printInfoComment - Print a little comment after the instruction indicating
1721
/// which slot it occupies.
1723
void AssemblyWriter::printInfoComment(const Value &V) {
1724
if (AnnotationWriter) {
1725
AnnotationWriter->printInfoComment(V, Out);
1730
// This member is called for each Instruction in a function..
1731
void AssemblyWriter::printInstruction(const Instruction &I) {
1732
if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1734
// Print out indentation for an instruction.
1737
// Print out name if it exists...
1739
PrintLLVMName(Out, &I);
1741
} else if (!I.getType()->isVoidTy()) {
1742
// Print out the def slot taken.
1743
int SlotNum = Machine.getLocalSlot(&I);
1745
Out << "<badref> = ";
1747
Out << '%' << SlotNum << " = ";
1750
// If this is a volatile load or store, print out the volatile marker.
1751
if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1752
(isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1754
} else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1755
// If this is a call, check if it's a tail call.
1759
// Print out the opcode...
1760
Out << I.getOpcodeName();
1762
// Print out optimization information.
1763
WriteOptimizationInfo(Out, &I);
1765
// Print out the compare instruction predicates
1766
if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1767
Out << ' ' << getPredicateText(CI->getPredicate());
1769
// Print out the type of the operands...
1770
const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1772
// Special case conditional branches to swizzle the condition out to the front
1773
if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1774
BranchInst &BI(cast<BranchInst>(I));
1776
writeOperand(BI.getCondition(), true);
1778
writeOperand(BI.getSuccessor(0), true);
1780
writeOperand(BI.getSuccessor(1), true);
1782
} else if (isa<SwitchInst>(I)) {
1783
// Special case switch instruction to get formatting nice and correct.
1785
writeOperand(Operand , true);
1787
writeOperand(I.getOperand(1), true);
1790
for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1792
writeOperand(I.getOperand(op ), true);
1794
writeOperand(I.getOperand(op+1), true);
1797
} else if (isa<IndirectBrInst>(I)) {
1798
// Special case indirectbr instruction to get formatting nice and correct.
1800
writeOperand(Operand, true);
1803
for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1806
writeOperand(I.getOperand(i), true);
1809
} else if (isa<PHINode>(I)) {
1811
TypePrinter.print(I.getType(), Out);
1814
for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1815
if (op) Out << ", ";
1817
writeOperand(I.getOperand(op ), false); Out << ", ";
1818
writeOperand(I.getOperand(op+1), false); Out << " ]";
1820
} else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1822
writeOperand(I.getOperand(0), true);
1823
for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1825
} else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1827
writeOperand(I.getOperand(0), true); Out << ", ";
1828
writeOperand(I.getOperand(1), true);
1829
for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1831
} else if (isa<ReturnInst>(I) && !Operand) {
1833
} else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1834
// Print the calling convention being used.
1835
switch (CI->getCallingConv()) {
1836
case CallingConv::C: break; // default
1837
case CallingConv::Fast: Out << " fastcc"; break;
1838
case CallingConv::Cold: Out << " coldcc"; break;
1839
case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1840
case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1841
case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1842
case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1843
case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1844
case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1845
case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1846
default: Out << " cc" << CI->getCallingConv(); break;
1849
Operand = CI->getCalledValue();
1850
const PointerType *PTy = cast<PointerType>(Operand->getType());
1851
const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1852
const Type *RetTy = FTy->getReturnType();
1853
const AttrListPtr &PAL = CI->getAttributes();
1855
if (PAL.getRetAttributes() != Attribute::None)
1856
Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1858
// If possible, print out the short form of the call instruction. We can
1859
// only do this if the first argument is a pointer to a nonvararg function,
1860
// and if the return type is not a pointer to a function.
1863
if (!FTy->isVarArg() &&
1864
(!RetTy->isPointerTy() ||
1865
!cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1866
TypePrinter.print(RetTy, Out);
1868
writeOperand(Operand, false);
1870
writeOperand(Operand, true);
1873
for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1876
writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1879
if (PAL.getFnAttributes() != Attribute::None)
1880
Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1881
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1882
Operand = II->getCalledValue();
1883
const PointerType *PTy = cast<PointerType>(Operand->getType());
1884
const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1885
const Type *RetTy = FTy->getReturnType();
1886
const AttrListPtr &PAL = II->getAttributes();
1888
// Print the calling convention being used.
1889
switch (II->getCallingConv()) {
1890
case CallingConv::C: break; // default
1891
case CallingConv::Fast: Out << " fastcc"; break;
1892
case CallingConv::Cold: Out << " coldcc"; break;
1893
case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1894
case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1895
case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1896
case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1897
case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1898
case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1899
case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1900
default: Out << " cc" << II->getCallingConv(); break;
1903
if (PAL.getRetAttributes() != Attribute::None)
1904
Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1906
// If possible, print out the short form of the invoke instruction. We can
1907
// only do this if the first argument is a pointer to a nonvararg function,
1908
// and if the return type is not a pointer to a function.
1911
if (!FTy->isVarArg() &&
1912
(!RetTy->isPointerTy() ||
1913
!cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1914
TypePrinter.print(RetTy, Out);
1916
writeOperand(Operand, false);
1918
writeOperand(Operand, true);
1921
for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1924
writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1928
if (PAL.getFnAttributes() != Attribute::None)
1929
Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1932
writeOperand(II->getNormalDest(), true);
1934
writeOperand(II->getUnwindDest(), true);
1936
} else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1938
TypePrinter.print(AI->getType()->getElementType(), Out);
1939
if (!AI->getArraySize() || AI->isArrayAllocation()) {
1941
writeOperand(AI->getArraySize(), true);
1943
if (AI->getAlignment()) {
1944
Out << ", align " << AI->getAlignment();
1946
} else if (isa<CastInst>(I)) {
1949
writeOperand(Operand, true); // Work with broken code
1952
TypePrinter.print(I.getType(), Out);
1953
} else if (isa<VAArgInst>(I)) {
1956
writeOperand(Operand, true); // Work with broken code
1959
TypePrinter.print(I.getType(), Out);
1960
} else if (Operand) { // Print the normal way.
1962
// PrintAllTypes - Instructions who have operands of all the same type
1963
// omit the type from all but the first operand. If the instruction has
1964
// different type operands (for example br), then they are all printed.
1965
bool PrintAllTypes = false;
1966
const Type *TheType = Operand->getType();
1968
// Select, Store and ShuffleVector always print all types.
1969
if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1970
|| isa<ReturnInst>(I)) {
1971
PrintAllTypes = true;
1973
for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1974
Operand = I.getOperand(i);
1975
// note that Operand shouldn't be null, but the test helps make dump()
1976
// more tolerant of malformed IR
1977
if (Operand && Operand->getType() != TheType) {
1978
PrintAllTypes = true; // We have differing types! Print them all!
1984
if (!PrintAllTypes) {
1986
TypePrinter.print(TheType, Out);
1990
for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1992
writeOperand(I.getOperand(i), PrintAllTypes);
1996
// Print post operand alignment for load/store.
1997
if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1998
Out << ", align " << cast<LoadInst>(I).getAlignment();
1999
} else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2000
Out << ", align " << cast<StoreInst>(I).getAlignment();
2003
// Print Metadata info.
2004
SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2005
I.getAllMetadata(InstMD);
2006
if (!InstMD.empty()) {
2007
SmallVector<StringRef, 8> MDNames;
2008
I.getType()->getContext().getMDKindNames(MDNames);
2009
for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2010
unsigned Kind = InstMD[i].first;
2011
if (Kind < MDNames.size()) {
2012
Out << ", !" << MDNames[Kind];
2014
Out << ", !<unknown kind #" << Kind << ">";
2017
WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2021
printInfoComment(I);
2024
static void WriteMDNodeComment(const MDNode *Node,
2025
formatted_raw_ostream &Out) {
2026
if (Node->getNumOperands() < 1)
2028
ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2030
APInt Val = CI->getValue();
2031
APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2032
if (Val.ult(LLVMDebugVersion))
2035
Out.PadToColumn(50);
2036
if (Tag == dwarf::DW_TAG_auto_variable)
2037
Out << "; [ DW_TAG_auto_variable ]";
2038
else if (Tag == dwarf::DW_TAG_arg_variable)
2039
Out << "; [ DW_TAG_arg_variable ]";
2040
else if (Tag == dwarf::DW_TAG_return_variable)
2041
Out << "; [ DW_TAG_return_variable ]";
2042
else if (Tag == dwarf::DW_TAG_vector_type)
2043
Out << "; [ DW_TAG_vector_type ]";
2044
else if (Tag == dwarf::DW_TAG_user_base)
2045
Out << "; [ DW_TAG_user_base ]";
2046
else if (Tag.isIntN(32)) {
2047
if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2048
Out << "; [ " << TagName << " ]";
2052
void AssemblyWriter::writeAllMDNodes() {
2053
SmallVector<const MDNode *, 16> Nodes;
2054
Nodes.resize(Machine.mdn_size());
2055
for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2057
Nodes[I->second] = cast<MDNode>(I->first);
2059
for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2060
Out << '!' << i << " = metadata ";
2061
printMDNodeBody(Nodes[i]);
2065
void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2066
WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2067
WriteMDNodeComment(Node, Out);
2071
//===----------------------------------------------------------------------===//
2072
// External Interface declarations
2073
//===----------------------------------------------------------------------===//
2075
void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2076
SlotTracker SlotTable(this);
2077
formatted_raw_ostream OS(ROS);
2078
AssemblyWriter W(OS, SlotTable, this, AAW);
2079
W.printModule(this);
2082
void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2083
SlotTracker SlotTable(getParent());
2084
formatted_raw_ostream OS(ROS);
2085
AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2086
W.printNamedMDNode(this);
2089
void Type::print(raw_ostream &OS) const {
2091
OS << "<null Type>";
2094
TypePrinting().print(this, OS);
2097
void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2099
ROS << "printing a <null> value\n";
2102
formatted_raw_ostream OS(ROS);
2103
if (const Instruction *I = dyn_cast<Instruction>(this)) {
2104
const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2105
SlotTracker SlotTable(F);
2106
AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2107
W.printInstruction(*I);
2108
} else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2109
SlotTracker SlotTable(BB->getParent());
2110
AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2111
W.printBasicBlock(BB);
2112
} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2113
SlotTracker SlotTable(GV->getParent());
2114
AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2115
if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2117
else if (const Function *F = dyn_cast<Function>(GV))
2120
W.printAlias(cast<GlobalAlias>(GV));
2121
} else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2122
const Function *F = N->getFunction();
2123
SlotTracker SlotTable(F);
2124
AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2125
W.printMDNodeBody(N);
2126
} else if (const Constant *C = dyn_cast<Constant>(this)) {
2127
TypePrinting TypePrinter;
2128
TypePrinter.print(C->getType(), OS);
2130
WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2131
} else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2132
isa<Argument>(this)) {
2133
WriteAsOperand(OS, this, true, 0);
2135
// Otherwise we don't know what it is. Call the virtual function to
2136
// allow a subclass to print itself.
2141
// Value::printCustom - subclasses should override this to implement printing.
2142
void Value::printCustom(raw_ostream &OS) const {
2143
llvm_unreachable("Unknown value to print out!");
2146
// Value::dump - allow easy printing of Values from the debugger.
2147
void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2149
// Type::dump - allow easy printing of Types from the debugger.
2150
// This one uses type names from the given context module
2151
void Type::dump(const Module *Context) const {
2152
WriteTypeSymbolic(dbgs(), this, Context);
2156
// Type::dump - allow easy printing of Types from the debugger.
2157
void Type::dump() const { dump(0); }
2159
// Module::dump() - Allow printing of Modules from the debugger.
2160
void Module::dump() const { print(dbgs(), 0); }