diff options
Diffstat (limited to 'lib/AsmParser')
-rw-r--r-- | lib/AsmParser/LLLexer.cpp | 59 | ||||
-rw-r--r-- | lib/AsmParser/LLLexer.h | 6 | ||||
-rw-r--r-- | lib/AsmParser/LLParser.cpp | 1334 | ||||
-rw-r--r-- | lib/AsmParser/LLParser.h | 16 | ||||
-rw-r--r-- | lib/AsmParser/LLToken.h | 16 | ||||
-rw-r--r-- | lib/AsmParser/Parser.cpp | 39 |
6 files changed, 914 insertions, 556 deletions
diff --git a/lib/AsmParser/LLLexer.cpp b/lib/AsmParser/LLLexer.cpp index 741c538..0e9f1a0 100644 --- a/lib/AsmParser/LLLexer.cpp +++ b/lib/AsmParser/LLLexer.cpp @@ -14,11 +14,14 @@ #include "LLLexer.h" #include "llvm/DerivedTypes.h" #include "llvm/Instruction.h" +#include "llvm/LLVMContext.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Assembly/Parser.h" +#include <cstdio> #include <cstdlib> #include <cstring> using namespace llvm; @@ -180,8 +183,9 @@ static const char *isLabelTail(const char *CurPtr) { // Lexer definition. //===----------------------------------------------------------------------===// -LLLexer::LLLexer(MemoryBuffer *StartBuf, SourceMgr &sm, SMDiagnostic &Err) - : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), APFloatVal(0.0) { +LLLexer::LLLexer(MemoryBuffer *StartBuf, SourceMgr &sm, SMDiagnostic &Err, + LLVMContext &C) + : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), Context(C), APFloatVal(0.0) { CurPtr = CurBuf->getBufferStart(); } @@ -250,7 +254,7 @@ lltok::Kind LLLexer::LexToken() { case ';': SkipLineComment(); return LexToken(); - case '!': return lltok::Metadata; + case '!': return LexMetadata(); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': @@ -418,7 +422,23 @@ static bool JustWhitespaceNewLine(const char *&Ptr) { return false; } +/// LexMetadata: +/// !{...} +/// !42 +/// !foo +lltok::Kind LLLexer::LexMetadata() { + if (isalpha(CurPtr[0])) { + ++CurPtr; + while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' || + CurPtr[0] == '.' || CurPtr[0] == '_') + ++CurPtr; + StrVal.assign(TokStart+1, CurPtr); // Skip ! + return lltok::NamedOrCustomMD; + } + return lltok::Metadata; +} + /// LexIdentifier: Handle several related productions: /// Label [-a-zA-Z$._0-9]+: /// IntegerType i[0-9]+ @@ -452,7 +472,7 @@ lltok::Kind LLLexer::LexIdentifier() { Error("bitwidth for integer type out of range!"); return lltok::Error; } - TyVal = IntegerType::get(NumBits); + TyVal = IntegerType::get(Context, NumBits); return lltok::Type; } @@ -471,6 +491,7 @@ lltok::Kind LLLexer::LexIdentifier() { KEYWORD(global); KEYWORD(constant); KEYWORD(private); + KEYWORD(linker_private); KEYWORD(internal); KEYWORD(available_externally); KEYWORD(linkonce); @@ -497,6 +518,10 @@ lltok::Kind LLLexer::LexIdentifier() { KEYWORD(deplibs); KEYWORD(datalayout); KEYWORD(volatile); + KEYWORD(nuw); + KEYWORD(nsw); + KEYWORD(exact); + KEYWORD(inbounds); KEYWORD(align); KEYWORD(addrspace); KEYWORD(section); @@ -504,6 +529,7 @@ lltok::Kind LLLexer::LexIdentifier() { KEYWORD(module); KEYWORD(asm); KEYWORD(sideeffect); + KEYWORD(msasm); KEYWORD(gc); KEYWORD(ccc); @@ -531,6 +557,7 @@ lltok::Kind LLLexer::LexIdentifier() { KEYWORD(readnone); KEYWORD(readonly); + KEYWORD(inlinehint); KEYWORD(noinline); KEYWORD(alwaysinline); KEYWORD(optsize); @@ -538,6 +565,7 @@ lltok::Kind LLLexer::LexIdentifier() { KEYWORD(sspreq); KEYWORD(noredzone); KEYWORD(noimplicitfloat); + KEYWORD(naked); KEYWORD(type); KEYWORD(opaque); @@ -554,14 +582,14 @@ lltok::Kind LLLexer::LexIdentifier() { #define TYPEKEYWORD(STR, LLVMTY) \ if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \ TyVal = LLVMTY; return lltok::Type; } - TYPEKEYWORD("void", Type::VoidTy); - TYPEKEYWORD("float", Type::FloatTy); - TYPEKEYWORD("double", Type::DoubleTy); - TYPEKEYWORD("x86_fp80", Type::X86_FP80Ty); - TYPEKEYWORD("fp128", Type::FP128Ty); - TYPEKEYWORD("ppc_fp128", Type::PPC_FP128Ty); - TYPEKEYWORD("label", Type::LabelTy); - TYPEKEYWORD("metadata", Type::MetadataTy); + TYPEKEYWORD("void", Type::getVoidTy(Context)); + TYPEKEYWORD("float", Type::getFloatTy(Context)); + TYPEKEYWORD("double", Type::getDoubleTy(Context)); + TYPEKEYWORD("x86_fp80", Type::getX86_FP80Ty(Context)); + TYPEKEYWORD("fp128", Type::getFP128Ty(Context)); + TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context)); + TYPEKEYWORD("label", Type::getLabelTy(Context)); + TYPEKEYWORD("metadata", Type::getMetadataTy(Context)); #undef TYPEKEYWORD // Handle special forms for autoupgrading. Drop these in LLVM 3.0. This is @@ -589,7 +617,6 @@ lltok::Kind LLLexer::LexIdentifier() { INSTKEYWORD(shl, Shl); INSTKEYWORD(lshr, LShr); INSTKEYWORD(ashr, AShr); INSTKEYWORD(and, And); INSTKEYWORD(or, Or); INSTKEYWORD(xor, Xor); INSTKEYWORD(icmp, ICmp); INSTKEYWORD(fcmp, FCmp); - INSTKEYWORD(vicmp, VICmp); INSTKEYWORD(vfcmp, VFCmp); INSTKEYWORD(phi, PHI); INSTKEYWORD(call, Call); @@ -635,7 +662,7 @@ lltok::Kind LLLexer::LexIdentifier() { TokStart[1] == '0' && TokStart[2] == 'x' && isxdigit(TokStart[3])) { int len = CurPtr-TokStart-3; uint32_t bits = len * 4; - APInt Tmp(bits, TokStart+3, len, 16); + APInt Tmp(bits, StringRef(TokStart+3, len), 16); uint32_t activeBits = Tmp.getActiveBits(); if (activeBits > 0 && activeBits < bits) Tmp.trunc(activeBits); @@ -698,7 +725,7 @@ lltok::Kind LLLexer::Lex0x() { uint64_t Pair[2]; switch (Kind) { - default: assert(0 && "Unknown kind!"); + default: llvm_unreachable("Unknown kind!"); case 'K': // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes) FP80HexToIntPair(TokStart+3, CurPtr, Pair); @@ -761,7 +788,7 @@ lltok::Kind LLLexer::LexDigitOrNegative() { return Lex0x(); unsigned Len = CurPtr-TokStart; uint32_t numBits = ((Len * 64) / 19) + 2; - APInt Tmp(numBits, TokStart, Len, 10); + APInt Tmp(numBits, StringRef(TokStart, Len), 10); if (TokStart[0] == '-') { uint32_t minBits = Tmp.getMinSignedBits(); if (minBits > 0 && minBits < numBits) diff --git a/lib/AsmParser/LLLexer.h b/lib/AsmParser/LLLexer.h index b5e58f1..de39272 100644 --- a/lib/AsmParser/LLLexer.h +++ b/lib/AsmParser/LLLexer.h @@ -24,12 +24,14 @@ namespace llvm { class MemoryBuffer; class Type; class SMDiagnostic; + class LLVMContext; class LLLexer { const char *CurPtr; MemoryBuffer *CurBuf; SMDiagnostic &ErrorInfo; SourceMgr &SM; + LLVMContext &Context; // Information about the current token. const char *TokStart; @@ -42,7 +44,8 @@ namespace llvm { std::string TheError; public: - explicit LLLexer(MemoryBuffer *StartBuf, SourceMgr &SM, SMDiagnostic &); + explicit LLLexer(MemoryBuffer *StartBuf, SourceMgr &SM, SMDiagnostic &, + LLVMContext &C); ~LLLexer() {} lltok::Kind Lex() { @@ -72,6 +75,7 @@ namespace llvm { lltok::Kind LexDigitOrNegative(); lltok::Kind LexPositive(); lltok::Kind LexAt(); + lltok::Kind LexMetadata(); lltok::Kind LexPercent(); lltok::Kind LexQuote(); lltok::Kind Lex0x(); diff --git a/lib/AsmParser/LLParser.cpp b/lib/AsmParser/LLParser.cpp index 3966ab3..09bc5f7 100644 --- a/lib/AsmParser/LLParser.cpp +++ b/lib/AsmParser/LLParser.cpp @@ -19,11 +19,13 @@ #include "llvm/InlineAsm.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" -#include "llvm/MDNode.h" +#include "llvm/Metadata.h" #include "llvm/Module.h" +#include "llvm/Operator.h" #include "llvm/ValueSymbolTable.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; @@ -40,15 +42,17 @@ namespace llvm { t_Null, t_Undef, t_Zero, // No value. t_EmptyArray, // No value: [] t_Constant, // Value in ConstantVal. - t_InlineAsm // Value in StrVal/StrVal2/UIntVal. + t_InlineAsm, // Value in StrVal/StrVal2/UIntVal. + t_Metadata // Value in MetadataVal. } Kind; - + LLParser::LocTy Loc; unsigned UIntVal; std::string StrVal, StrVal2; APSInt APSIntVal; APFloat APFloatVal; Constant *ConstantVal; + MetadataBase *MetadataVal; ValID() : APFloatVal(0.0) {} }; } @@ -73,21 +77,29 @@ bool LLParser::ValidateEndOfModule() { return Error(ForwardRefTypeIDs.begin()->second.second, "use of undefined type '%" + utostr(ForwardRefTypeIDs.begin()->first) + "'"); - + if (!ForwardRefVals.empty()) return Error(ForwardRefVals.begin()->second.second, "use of undefined value '@" + ForwardRefVals.begin()->first + "'"); - + if (!ForwardRefValIDs.empty()) return Error(ForwardRefValIDs.begin()->second.second, "use of undefined value '@" + utostr(ForwardRefValIDs.begin()->first) + "'"); - + + if (!ForwardRefMDNodes.empty()) + return Error(ForwardRefMDNodes.begin()->second.second, + "use of undefined metadata '!" + + utostr(ForwardRefMDNodes.begin()->first) + "'"); + + // Look for intrinsic functions and CallInst that need to be upgraded for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove - + + // Check debug info intrinsics. + CheckDebugInfoIntrinsics(M); return false; } @@ -107,27 +119,31 @@ bool LLParser::ParseTopLevelEntities() { case lltok::kw_target: if (ParseTargetDefinition()) return true; break; case lltok::kw_deplibs: if (ParseDepLibs()) return true; break; case lltok::kw_type: if (ParseUnnamedType()) return true; break; + case lltok::LocalVarID: if (ParseUnnamedType()) return true; break; case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0 case lltok::LocalVar: if (ParseNamedType()) return true; break; + case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break; case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break; + case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break; // The Global variable production with no name can have many different // optional leading prefixes, the production is: // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal // OptionalAddrSpace ('constant'|'global') ... - case lltok::kw_private: // OptionalLinkage - case lltok::kw_internal: // OptionalLinkage - case lltok::kw_weak: // OptionalLinkage - case lltok::kw_weak_odr: // OptionalLinkage - case lltok::kw_linkonce: // OptionalLinkage - case lltok::kw_linkonce_odr: // OptionalLinkage - case lltok::kw_appending: // OptionalLinkage - case lltok::kw_dllexport: // OptionalLinkage - case lltok::kw_common: // OptionalLinkage - case lltok::kw_dllimport: // OptionalLinkage - case lltok::kw_extern_weak: // OptionalLinkage - case lltok::kw_external: { // OptionalLinkage + case lltok::kw_private : // OptionalLinkage + case lltok::kw_linker_private: // OptionalLinkage + case lltok::kw_internal: // OptionalLinkage + case lltok::kw_weak: // OptionalLinkage + case lltok::kw_weak_odr: // OptionalLinkage + case lltok::kw_linkonce: // OptionalLinkage + case lltok::kw_linkonce_odr: // OptionalLinkage + case lltok::kw_appending: // OptionalLinkage + case lltok::kw_dllexport: // OptionalLinkage + case lltok::kw_common: // OptionalLinkage + case lltok::kw_dllimport: // OptionalLinkage + case lltok::kw_extern_weak: // OptionalLinkage + case lltok::kw_external: { // OptionalLinkage unsigned Linkage, Visibility; if (ParseOptionalLinkage(Linkage) || ParseOptionalVisibility(Visibility) || @@ -144,7 +160,7 @@ bool LLParser::ParseTopLevelEntities() { return true; break; } - + case lltok::kw_thread_local: // OptionalThreadLocal case lltok::kw_addrspace: // OptionalAddrSpace case lltok::kw_constant: // GlobalType @@ -161,11 +177,11 @@ bool LLParser::ParseTopLevelEntities() { bool LLParser::ParseModuleAsm() { assert(Lex.getKind() == lltok::kw_module); Lex.Lex(); - - std::string AsmStr; + + std::string AsmStr; if (ParseToken(lltok::kw_asm, "expected 'module asm'") || ParseStringConstant(AsmStr)) return true; - + const std::string &AsmSoFar = M->getModuleInlineAsm(); if (AsmSoFar.empty()) M->setModuleInlineAsm(AsmStr); @@ -211,7 +227,7 @@ bool LLParser::ParseDepLibs() { if (EatIfPresent(lltok::rsquare)) return false; - + std::string Str; if (ParseStringConstant(Str)) return true; M->addLibrary(Str); @@ -224,32 +240,44 @@ bool LLParser::ParseDepLibs() { return ParseToken(lltok::rsquare, "expected ']' at end of list"); } -/// toplevelentity +/// ParseUnnamedType: /// ::= 'type' type +/// ::= LocalVarID '=' 'type' type bool LLParser::ParseUnnamedType() { + unsigned TypeID = NumberedTypes.size(); + + // Handle the LocalVarID form. + if (Lex.getKind() == lltok::LocalVarID) { + if (Lex.getUIntVal() != TypeID) + return Error(Lex.getLoc(), "type expected to be numbered '%" + + utostr(TypeID) + "'"); + Lex.Lex(); // eat LocalVarID; + + if (ParseToken(lltok::equal, "expected '=' after name")) + return true; + } + assert(Lex.getKind() == lltok::kw_type); LocTy TypeLoc = Lex.getLoc(); Lex.Lex(); // eat kw_type - PATypeHolder Ty(Type::VoidTy); + PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseType(Ty)) return true; - - unsigned TypeID = NumberedTypes.size(); - + // See if this type was previously referenced. std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator FI = ForwardRefTypeIDs.find(TypeID); if (FI != ForwardRefTypeIDs.end()) { if (FI->second.first.get() == Ty) return Error(TypeLoc, "self referential type is invalid"); - + cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty); Ty = FI->second.first.get(); ForwardRefTypeIDs.erase(FI); } - + NumberedTypes.push_back(Ty); - + return false; } @@ -259,14 +287,14 @@ bool LLParser::ParseNamedType() { std::string Name = Lex.getStrVal(); LocTy NameLoc = Lex.getLoc(); Lex.Lex(); // eat LocalVar. - - PATypeHolder Ty(Type::VoidTy); - + + PATypeHolder Ty(Type::getVoidTy(Context)); + if (ParseToken(lltok::equal, "expected '=' after name") || ParseToken(lltok::kw_type, "expected 'type' after name") || ParseType(Ty)) return true; - + // Set the type name, checking for conflicts as we do so. bool AlreadyExists = M->addTypeName(Name, Ty); if (!AlreadyExists) return false; @@ -283,16 +311,16 @@ bool LLParser::ParseNamedType() { Ty = FI->second.first.get(); ForwardRefTypes.erase(FI); } - + // Inserting a name that is already defined, get the existing name. const Type *Existing = M->getTypeByName(Name); assert(Existing && "Conflict but no matching type?!"); - + // Otherwise, this is an attempt to redefine a type. That's okay if // the redefinition is identical to the original. // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0 if (Existing == Ty) return false; - + // Any other kind of (non-equivalent) redefinition is an error. return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" + Ty->getDescription() + "'"); @@ -304,7 +332,7 @@ bool LLParser::ParseNamedType() { bool LLParser::ParseDeclare() { assert(Lex.getKind() == lltok::kw_declare); Lex.Lex(); - + Function *F; return ParseFunctionHeader(F, false); } @@ -314,7 +342,7 @@ bool LLParser::ParseDeclare() { bool LLParser::ParseDefine() { assert(Lex.getKind() == lltok::kw_define); Lex.Lex(); - + Function *F; return ParseFunctionHeader(F, true) || ParseFunctionBody(*F); @@ -336,6 +364,38 @@ bool LLParser::ParseGlobalType(bool &IsConstant) { return false; } +/// ParseUnnamedGlobal: +/// OptionalVisibility ALIAS ... +/// OptionalLinkage OptionalVisibility ... -> global variable +/// GlobalID '=' OptionalVisibility ALIAS ... +/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable +bool LLParser::ParseUnnamedGlobal() { + unsigned VarID = NumberedVals.size(); + std::string Name; + LocTy NameLoc = Lex.getLoc(); + + // Handle the GlobalID form. + if (Lex.getKind() == lltok::GlobalID) { + if (Lex.getUIntVal() != VarID) + return Error(Lex.getLoc(), "variable expected to be numbered '%" + + utostr(VarID) + "'"); + Lex.Lex(); // eat GlobalID; + + if (ParseToken(lltok::equal, "expected '=' after name")) + return true; + } + + bool HasLinkage; + unsigned Linkage, Visibility; + if (ParseOptionalLinkage(Linkage, HasLinkage) || + ParseOptionalVisibility(Visibility)) + return true; + + if (HasLinkage || Lex.getKind() != lltok::kw_alias) + return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); + return ParseAlias(Name, NameLoc, Visibility); +} + /// ParseNamedGlobal: /// GlobalVar '=' OptionalVisibility ALIAS ... /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable @@ -344,21 +404,96 @@ bool LLParser::ParseNamedGlobal() { LocTy NameLoc = Lex.getLoc(); std::string Name = Lex.getStrVal(); Lex.Lex(); - + bool HasLinkage; unsigned Linkage, Visibility; if (ParseToken(lltok::equal, "expected '=' in global variable") || ParseOptionalLinkage(Linkage, HasLinkage) || ParseOptionalVisibility(Visibility)) return true; - + if (HasLinkage || Lex.getKind() != lltok::kw_alias) return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); return ParseAlias(Name, NameLoc, Visibility); } +// MDString: +// ::= '!' STRINGCONSTANT +bool LLParser::ParseMDString(MetadataBase *&MDS) { + std::string Str; + if (ParseStringConstant(Str)) return true; + MDS = MDString::get(Context, Str); + return false; +} + +// MDNode: +// ::= '!' MDNodeNumber +bool LLParser::ParseMDNode(MetadataBase *&Node) { + // !{ ..., !42, ... } + unsigned MID = 0; + if (ParseUInt32(MID)) return true; + + // Check existing MDNode. + std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID); + if (I != MetadataCache.end()) { + Node = I->second; + return false; + } + + // Check known forward references. + std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator + FI = ForwardRefMDNodes.find(MID); + if (FI != ForwardRefMDNodes.end()) { + Node = FI->second.first; + return false; + } + + // Create MDNode forward reference + SmallVector<Value *, 1> Elts; + std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID); + Elts.push_back(MDString::get(Context, FwdRefName)); + MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size()); + ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); + Node = FwdNode; + return false; +} + +///ParseNamedMetadata: +/// !foo = !{ !1, !2 } +bool LLParser::ParseNamedMetadata() { + assert(Lex.getKind() == lltok::NamedOrCustomMD); + Lex.Lex(); + std::string Name = Lex.getStrVal(); + + if (ParseToken(lltok::equal, "expected '=' here")) + return true; + + if (Lex.getKind() != lltok::Metadata) + return TokError("Expected '!' here"); + Lex.Lex(); + + if (Lex.getKind() != lltok::lbrace) + return TokError("Expected '{' here"); + Lex.Lex(); + SmallVector<MetadataBase *, 8> Elts; + do { + if (Lex.getKind() != lltok::Metadata) + return TokError("Expected '!' here"); + Lex.Lex(); + MetadataBase *N = 0; + if (ParseMDNode(N)) return true; + Elts.push_back(N); + } while (EatIfPresent(lltok::comma)); + + if (ParseToken(lltok::rbrace, "expected end of metadata node")) + return true; + + NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M); + return false; +} + /// ParseStandaloneMetadata: -/// !42 = !{...} +/// !42 = !{...} bool LLParser::ParseStandaloneMetadata() { assert(Lex.getKind() == lltok::Metadata); Lex.Lex(); @@ -371,17 +506,32 @@ bool LLParser::ParseStandaloneMetadata() { return true; LocTy TyLoc; - bool IsConstant; - PATypeHolder Ty(Type::VoidTy); - if (ParseGlobalType(IsConstant) || - ParseType(Ty, TyLoc)) + PATypeHolder Ty(Type::getVoidTy(Context)); + if (ParseType(Ty, TyLoc)) return true; - - Constant *Init = 0; - if (ParseGlobalValue(Ty, Init)) - return true; + if (Lex.getKind() != lltok::Metadata) + return TokError("Expected metadata here"); + + Lex.Lex(); + if (Lex.getKind() != lltok::lbrace) + return TokError("Expected '{' here"); + + SmallVector<Value *, 16> Elts; + if (ParseMDNodeVector(Elts) + || ParseToken(lltok::rbrace, "expected end of metadata node")) + return true; + + MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size()); MetadataCache[MetadataID] = Init; + std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator + FI = ForwardRefMDNodes.find(MetadataID); + if (FI != ForwardRefMDNodes.end()) { + MDNode *FwdNode = cast<MDNode>(FI->second.first); + FwdNode->replaceAllUsesWith(Init); + ForwardRefMDNodes.erase(FI); + } + return false; } @@ -390,7 +540,7 @@ bool LLParser::ParseStandaloneMetadata() { /// Aliasee /// ::= TypeAndValue /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')' -/// ::= 'getelementptr' '(' ... ')' +/// ::= 'getelementptr' 'inbounds'? '(' ... ')' /// /// Everything through visibility has already been parsed. /// @@ -407,9 +557,10 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, Linkage != GlobalValue::WeakAnyLinkage && Linkage != GlobalValue::WeakODRLinkage && Linkage != GlobalValue::InternalLinkage && - Linkage != GlobalValue::PrivateLinkage) + Linkage != GlobalValue::PrivateLinkage && + Linkage != GlobalValue::LinkerPrivateLinkage) return Error(LinkageLoc, "invalid linkage type for alias"); - + Constant *Aliasee; LocTy AliaseeLoc = Lex.getLoc(); if (Lex.getKind() != lltok::kw_bitcast && @@ -423,7 +574,7 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, return Error(AliaseeLoc, "invalid aliasee"); Aliasee = ID.ConstantVal; } - + if (!isa<PointerType>(Aliasee->getType())) return Error(AliaseeLoc, "alias must have pointer type"); @@ -432,7 +583,7 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, (GlobalValue::LinkageTypes)Linkage, Name, Aliasee); GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); - + // See if this value already exists in the symbol table. If so, it is either // a redefinition or a definition of a forward reference. if (GlobalValue *Val = @@ -449,18 +600,18 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, if (Val->getType() != GA->getType()) return Error(NameLoc, "forward reference and definition of alias have different types"); - + // If they agree, just RAUW the old value with the alias and remove the // forward ref info. Val->replaceAllUsesWith(GA); Val->eraseFromParent(); ForwardRefVals.erase(I); } - + // Insert into the module, we know its name won't collide now. M->getAliasList().push_back(GA); assert(GA->getNameStr() == Name && "Should not be a name conflict!"); - + return false; } @@ -478,14 +629,14 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, unsigned AddrSpace; bool ThreadLocal, IsConstant; LocTy TyLoc; - - PATypeHolder Ty(Type::VoidTy); + + PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) || ParseOptionalAddrSpace(AddrSpace) || ParseGlobalType(IsConstant) || ParseType(Ty, TyLoc)) return true; - + // If the linkage is specified and is external, then no initializer is // present. Constant *Init = 0; @@ -496,9 +647,9 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, return true; } - if (isa<FunctionType>(Ty) || Ty == Type::LabelTy) + if (isa<FunctionType>(Ty) || Ty->isLabelTy()) return Error(TyLoc, "invalid type for global variable"); - + GlobalVariable *GV = 0; // See if the global was forward referenced, if so, use the global. @@ -516,20 +667,20 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, } if (GV == 0) { - GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name, - M, false, AddrSpace); + GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, + Name, 0, false, AddrSpace); } else { if (GV->getType()->getElementType() != Ty) return Error(TyLoc, "forward reference and definition of global have different types"); - + // Move the forward-reference to the correct spot in the module. M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); } if (Name.empty()) NumberedVals.push_back(GV); - + // Set the parsed properties on the global. if (Init) GV->setInitializer(Init); @@ -537,11 +688,11 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, GV->setLinkage((GlobalValue::LinkageTypes)Linkage); GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); GV->setThreadLocal(ThreadLocal); - + // Parse attributes on the global. while (Lex.getKind() == lltok::comma) { Lex.Lex(); - + if (Lex.getKind() == lltok::kw_section) { Lex.Lex(); GV->setSection(Lex.getStrVal()); @@ -555,7 +706,7 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, TokError("unknown global variable property!"); } } - + return false; } @@ -574,11 +725,11 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, Error(Loc, "global variable reference must have pointer type"); return 0; } - + // Look this name up in the normal function symbol table. GlobalValue *Val = cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -587,7 +738,7 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, if (I != ForwardRefVals.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; @@ -595,7 +746,7 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, Val->getType()->getDescription() + "'"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. GlobalValue *FwdVal; if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) { @@ -604,13 +755,13 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, Error(Loc, "function may not return opaque type"); return 0; } - + FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); } else { - FwdVal = new GlobalVariable(PTy->getElementType(), false, - GlobalValue::ExternalWeakLinkage, 0, Name, M); + FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, + GlobalValue::ExternalWeakLinkage, 0, Name); } - + ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -621,9 +772,9 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { Error(Loc, "global variable reference must have pointer type"); return 0; } - + GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -632,7 +783,7 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { if (I != ForwardRefValIDs.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; @@ -640,7 +791,7 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { Val->getType()->getDescription() + "'"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. GlobalValue *FwdVal; if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) { @@ -651,10 +802,10 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { } FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M); } else { - FwdVal = new GlobalVariable(PTy->getElementType(), false, - GlobalValue::ExternalWeakLinkage, 0, "", M); + FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, + GlobalValue::ExternalWeakLinkage, 0, ""); } - + ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -707,7 +858,7 @@ bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { return ParseToken(lltok::lparen, "expected '(' in address space") || ParseUInt32(AddrSpace) || ParseToken(lltok::rparen, "expected ')' in address space"); -} +} /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind /// indicates what kind of attribute list this is: 0: function arg, 1: result, @@ -716,7 +867,7 @@ bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { Attrs = Attribute::None; LocTy AttrLoc = Lex.getLoc(); - + while (1) { switch (Lex.getKind()) { case lltok::kw_sext: @@ -737,10 +888,10 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { default: // End of attributes. if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly)) return Error(AttrLoc, "invalid use of function-only attribute"); - + if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly)) return Error(AttrLoc, "invalid use of parameter-only attribute"); - + return false; case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break; case lltok::kw_signext: Attrs |= Attribute::SExt; break; @@ -756,13 +907,15 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { case lltok::kw_noinline: Attrs |= Attribute::NoInline; break; case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break; case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break; + case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break; case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break; case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break; case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break; case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break; case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break; case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break; - + case lltok::kw_naked: Attrs |= Attribute::Naked; break; + case lltok::kw_align: { unsigned Alignment; if (ParseOptionalAlignment(Alignment)) @@ -778,6 +931,7 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { /// ParseOptionalLinkage /// ::= /*empty*/ /// ::= 'private' +/// ::= 'linker_private' /// ::= 'internal' /// ::= 'weak' /// ::= 'weak_odr' @@ -792,22 +946,23 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { HasLinkage = false; switch (Lex.getKind()) { - default: Res = GlobalValue::ExternalLinkage; return false; - case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; - case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; - case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break; - case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break; - case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break; - case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break; + default: Res=GlobalValue::ExternalLinkage; return false; + case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; + case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break; + case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; + case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break; + case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break; + case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break; + case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break; case lltok::kw_available_externally: Res = GlobalValue::AvailableExternallyLinkage; break; - case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; - case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break; - case lltok::kw_common: Res = GlobalValue::CommonLinkage; break; - case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break; - case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; - case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; + case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; + case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break; + case lltok::kw_common: Res = GlobalValue::CommonLinkage; break; + case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break; + case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; + case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; } Lex.Lex(); HasLinkage = true; @@ -819,7 +974,7 @@ bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { /// ::= 'default' /// ::= 'hidden' /// ::= 'protected' -/// +/// bool LLParser::ParseOptionalVisibility(unsigned &Res) { switch (Lex.getKind()) { default: Res = GlobalValue::DefaultVisibility; return false; @@ -843,7 +998,7 @@ bool LLParser::ParseOptionalVisibility(unsigned &Res) { /// ::= 'arm_aapcs_vfpcc' /// ::= 'cc' UINT /// -bool LLParser::ParseOptionalCallingConv(unsigned &CC) { +bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) { switch (Lex.getKind()) { default: CC = CallingConv::C; return false; case lltok::kw_ccc: CC = CallingConv::C; break; @@ -854,9 +1009,47 @@ bool LLParser::ParseOptionalCallingConv(unsigned &CC) { case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; - case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC); + case lltok::kw_cc: { + unsigned ArbitraryCC; + Lex.Lex(); + if (ParseUInt32(ArbitraryCC)) { + return true; + } else + CC = static_cast<CallingConv::ID>(ArbitraryCC); + return false; + } + break; } + + Lex.Lex(); + return false; +} + +/// ParseOptionalCustomMetadata +/// ::= /* empty */ +/// ::= !dbg !42 +bool LLParser::ParseOptionalCustomMetadata() { + + std::string Name; + if (Lex.getKind() == lltok::NamedOrCustomMD) { + Name = Lex.getStrVal(); + Lex.Lex(); + } else + return false; + + if (Lex.getKind() != lltok::Metadata) + return TokError("Expected '!' here"); Lex.Lex(); + + MetadataBase *Node; + if (ParseMDNode(Node)) return true; + + MetadataContext &TheMetadata = M->getContext().getMetadata(); + unsigned MDK = TheMetadata.getMDKind(Name.c_str()); + if (!MDK) + MDK = TheMetadata.RegisterMDKind(Name.c_str()); + MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node))); + return false; } @@ -874,29 +1067,36 @@ bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { return false; } -/// ParseOptionalCommaAlignment -/// ::= /* empty */ -/// ::= ',' 'align' 4 -bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) { - Alignment = 0; - if (!EatIfPresent(lltok::comma)) - return false; - return ParseToken(lltok::kw_align, "expected 'align'") || - ParseUInt32(Alignment); +/// ParseOptionalInfo +/// ::= OptionalInfo (',' OptionalInfo)+ +bool LLParser::ParseOptionalInfo(unsigned &Alignment) { + + // FIXME: Handle customized metadata info attached with an instruction. + do { + if (Lex.getKind() == lltok::NamedOrCustomMD) { + if (ParseOptionalCustomMetadata()) return true; + } else if (Lex.getKind() == lltok::kw_align) { + if (ParseOptionalAlignment(Alignment)) return true; + } else + return true; + } while (EatIfPresent(lltok::comma)); + + return false; } + /// ParseIndexList /// ::= (',' uint32)+ bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) { if (Lex.getKind() != lltok::comma) return TokError("expected ',' as start of index list"); - + while (EatIfPresent(lltok::comma)) { unsigned Idx; if (ParseUInt32(Idx)) return true; Indices.push_back(Idx); } - + return false; } @@ -908,14 +1108,14 @@ bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) { bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) { LocTy TypeLoc = Lex.getLoc(); if (ParseTypeRec(Result)) return true; - + // Verify no unresolved uprefs. if (!UpRefs.empty()) return Error(UpRefs.back().Loc, "invalid unresolved type up reference"); - - if (!AllowVoid && Result.get() == Type::VoidTy) + + if (!AllowVoid && Result.get()->isVoidTy()) return Error(TypeLoc, "void type only allowed for function results"); - + return false; } @@ -930,26 +1130,26 @@ PATypeHolder LLParser::HandleUpRefs(const Type *ty) { // If Ty isn't abstract, or if there are no up-references in it, then there is // nothing to resolve here. if (!ty->isAbstract() || UpRefs.empty()) return ty; - + PATypeHolder Ty(ty); #if 0 errs() << "Type '" << Ty->getDescription() << "' newly formed. Resolving upreferences.\n" << UpRefs.size() << " upreferences active!\n"; #endif - + // If we find any resolvable upreferences (i.e., those whose NestingLevel goes // to zero), we resolve them all together before we resolve them to Ty. At // the end of the loop, if there is anything to resolve to Ty, it will be in // this variable. OpaqueType *TypeToResolve = 0; - + for (unsigned i = 0; i != UpRefs.size(); ++i) { // Determine if 'Ty' directly contains this up-references 'LastContainedTy'. bool ContainsType = std::find(Ty->subtype_begin(), Ty->subtype_end(), UpRefs[i].LastContainedTy) != Ty->subtype_end(); - + #if 0 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " << UpRefs[i].LastContainedTy->getDescription() << ") = " @@ -958,15 +1158,15 @@ PATypeHolder LLParser::HandleUpRefs(const Type *ty) { #endif if (!ContainsType) continue; - + // Decrement level of upreference unsigned Level = --UpRefs[i].NestingLevel; UpRefs[i].LastContainedTy = Ty; - + // If the Up-reference has a non-zero level, it shouldn't be resolved yet. if (Level != 0) continue; - + #if 0 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n"; #endif @@ -977,10 +1177,10 @@ PATypeHolder LLParser::HandleUpRefs(const Type *ty) { UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list. --i; // Do not skip the next element. } - + if (TypeToResolve) TypeToResolve->refineAbstractTypeTo(Ty); - + return Ty; } @@ -994,11 +1194,11 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { case lltok::Type: // TypeRec ::= 'float' | 'void' (etc) Result = Lex.getTyVal(); - Lex.Lex(); + Lex.Lex(); break; case lltok::kw_opaque: // TypeRec ::= 'opaque' - Result = Context.getOpaqueType(); + Result = OpaqueType::get(Context); Lex.Lex(); break; case lltok::lbrace: @@ -1028,7 +1228,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { if (const Type *T = M->getTypeByName(Lex.getStrVal())) { Result = T; } else { - Result = Context.getOpaqueType(); + Result = OpaqueType::get(Context); ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(), std::make_pair(Result, Lex.getLoc()))); @@ -1036,7 +1236,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { } Lex.Lex(); break; - + case lltok::LocalVarID: // TypeRec ::= %4 if (Lex.getUIntVal() < NumberedTypes.size()) @@ -1047,7 +1247,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { if (I != ForwardRefTypeIDs.end()) Result = I->second.first; else { - Result = Context.getOpaqueType(); + Result = OpaqueType::get(Context); ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(), std::make_pair(Result, Lex.getLoc()))); @@ -1060,36 +1260,36 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { Lex.Lex(); unsigned Val; if (ParseUInt32(Val)) return true; - OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder. + OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder. UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT)); Result = OT; break; } } - - // Parse the type suffixes. + + // Parse the type suffixes. while (1) { switch (Lex.getKind()) { // End of type. - default: return false; + default: return false; // TypeRec ::= TypeRec '*' case lltok::star: - if (Result.get() == Type::LabelTy) + if (Result.get()->isLabelTy()) return TokError("basic block pointers are invalid"); - if (Result.get() == Type::VoidTy) + if (Result.get()->isVoidTy()) return TokError("pointers to void are invalid; use i8* instead"); if (!PointerType::isValidElementType(Result.get())) return TokError("pointer to this type is invalid"); - Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get())); + Result = HandleUpRefs(PointerType::getUnqual(Result.get())); Lex.Lex(); break; // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*' case lltok::kw_addrspace: { - if (Result.get() == Type::LabelTy) + if (Result.get()->isLabelTy()) return TokError("basic block pointers are invalid"); - if (Result.get() == Type::VoidTy) + if (Result.get()->isVoidTy()) return TokError("pointers to void are invalid; use i8* instead"); if (!PointerType::isValidElementType(Result.get())) return TokError("pointer to this type is invalid"); @@ -1098,10 +1298,10 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { ParseToken(lltok::star, "expected '*' in address space")) return true; - Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace)); + Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace)); break; } - + /// Types '(' ArgTypeListI ')' OptFuncAttrs case lltok::lparen: if (ParseFunctionType(Result)) @@ -1120,16 +1320,16 @@ bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, PerFunctionState &PFS) { if (ParseToken(lltok::lparen, "expected '(' in call")) return true; - + while (Lex.getKind() != lltok::rparen) { // If this isn't the first argument, we need a comma. if (!ArgList.empty() && ParseToken(lltok::comma, "expected ',' in argument list")) return true; - + // Parse the argument. LocTy ArgLoc; - PATypeHolder ArgTy(Type::VoidTy); + PATypeHolder ArgTy(Type::getVoidTy(Context)); unsigned ArgAttrs1, ArgAttrs2; Value *V; if (ParseType(ArgTy, ArgLoc) || @@ -1162,7 +1362,7 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList, isVarArg = false; assert(Lex.getKind() == lltok::lparen); Lex.Lex(); // eat the (. - + if (Lex.getKind() == lltok::rparen) { // empty } else if (Lex.getKind() == lltok::dotdotdot) { @@ -1170,19 +1370,19 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList, Lex.Lex(); } else { LocTy TypeLoc = Lex.getLoc(); - PATypeHolder ArgTy(Type::VoidTy); + PATypeHolder ArgTy(Type::getVoidTy(Context)); unsigned Attrs; std::string Name; - + // If we're parsing a type, use ParseTypeRec, because we allow recursive // types (such as a function returning a pointer to itself). If parsing a // function prototype, we require fully resolved types. if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || ParseOptionalAttrs(Attrs, 0)) return true; - - if (ArgTy == Type::VoidTy) + + if (ArgTy->isVoidTy()) return Error(TypeLoc, "argument can not have void type"); - + if (Lex.getKind() == lltok::LocalVar || Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0 Name = Lex.getStrVal(); @@ -1191,22 +1391,22 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList, if (!FunctionType::isValidArgumentType(ArgTy)) return Error(TypeLoc, "invalid type for function argument"); - + ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); - + while (EatIfPresent(lltok::comma)) { // Handle ... at end of arg list. if (EatIfPresent(lltok::dotdotdot)) { isVarArg = true; break; } - + // Otherwise must be an argument type. TypeLoc = Lex.getLoc(); if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || ParseOptionalAttrs(Attrs, 0)) return true; - if (ArgTy == Type::VoidTy) + if (ArgTy->isVoidTy()) return Error(TypeLoc, "argument can not have void type"); if (Lex.getKind() == lltok::LocalVar || @@ -1219,14 +1419,14 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList, if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) return Error(TypeLoc, "invalid type for function argument"); - + ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); } } - + return ParseToken(lltok::rparen, "expected ')' at end of argument list"); } - + /// ParseFunctionType /// ::= Type ArgumentList OptionalAttrs bool LLParser::ParseFunctionType(PATypeHolder &Result) { @@ -1234,7 +1434,7 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { if (!FunctionType::isValidReturnType(Result)) return TokError("invalid function return type"); - + std::vector<ArgInfo> ArgList; bool isVarArg; unsigned Attrs; @@ -1243,7 +1443,7 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { // FIXME: Remove in LLVM 3.0 ParseOptionalAttrs(Attrs, 2)) return true; - + // Reject names on the arguments lists. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { if (!ArgList[i].Name.empty()) @@ -1254,12 +1454,12 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0 } } - + std::vector<const Type*> ArgListTy; for (unsigned i = 0, e = ArgList.size(); i != e; ++i) ArgListTy.push_back(ArgList[i].Type); - - Result = HandleUpRefs(Context.getFunctionType(Result.get(), + + Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg)); return false; } @@ -1273,9 +1473,9 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { assert(Lex.getKind() == lltok::lbrace); Lex.Lex(); // Consume the '{' - + if (EatIfPresent(lltok::rbrace)) { - Result = Context.getStructType(Packed); + Result = StructType::get(Context, Packed); return false; } @@ -1283,62 +1483,62 @@ bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { LocTy EltTyLoc = Lex.getLoc(); if (ParseTypeRec(Result)) return true; ParamsList.push_back(Result); - - if (Result == Type::VoidTy) + + if (Result->isVoidTy()) return Error(EltTyLoc, "struct element can not have void type"); if (!StructType::isValidElementType(Result)) return Error(EltTyLoc, "invalid element type for struct"); - + while (EatIfPresent(lltok::comma)) { EltTyLoc = Lex.getLoc(); if (ParseTypeRec(Result)) return true; - - if (Result == Type::VoidTy) + + if (Result->isVoidTy()) return Error(EltTyLoc, "struct element can not have void type"); if (!StructType::isValidElementType(Result)) return Error(EltTyLoc, "invalid element type for struct"); - + ParamsList.push_back(Result); } - + if (ParseToken(lltok::rbrace, "expected '}' at end of struct")) return true; - + std::vector<const Type*> ParamsListTy; for (unsigned i = 0, e = ParamsList.size(); i != e; ++i) ParamsListTy.push_back(ParamsList[i].get()); - Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed)); + Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed)); return false; } /// ParseArrayVectorType - Parse an array or vector type, assuming the first /// token has already been consumed. -/// TypeRec +/// TypeRec /// ::= '[' APSINTVAL 'x' Types ']' /// ::= '<' APSINTVAL 'x' Types '>' bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) { if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || Lex.getAPSIntVal().getBitWidth() > 64) return TokError("expected number in address space"); - + LocTy SizeLoc = Lex.getLoc(); uint64_t Size = Lex.getAPSIntVal().getZExtValue(); Lex.Lex(); - + if (ParseToken(lltok::kw_x, "expected 'x' after element count")) return true; LocTy TypeLoc = Lex.getLoc(); - PATypeHolder EltTy(Type::VoidTy); + PATypeHolder EltTy(Type::getVoidTy(Context)); if (ParseTypeRec(EltTy)) return true; - - if (EltTy == Type::VoidTy) + + if (EltTy->isVoidTy()) return Error(TypeLoc, "array and vector element type cannot be void"); if (ParseToken(isVector ? lltok::greater : lltok::rsquare, "expected end of sequential type")) return true; - + if (isVector) { if (Size == 0) return Error(SizeLoc, "zero element vector is illegal"); @@ -1346,11 +1546,11 @@ bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) { return Error(SizeLoc, "size too large for vector"); if (!VectorType::isValidElementType(EltTy)) return Error(TypeLoc, "vector element type must be fp or integer"); - Result = Context.getVectorType(EltTy, unsigned(Size)); + Result = VectorType::get(EltTy, unsigned(Size)); } else { if (!ArrayType::isValidElementType(EltTy)) return Error(TypeLoc, "invalid array element type"); - Result = HandleUpRefs(Context.getArrayType(EltTy, Size)); + Result = HandleUpRefs(ArrayType::get(EltTy, Size)); } return false; } @@ -1375,16 +1575,16 @@ LLParser::PerFunctionState::~PerFunctionState() { I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I) if (!isa<BasicBlock>(I->second.first)) { I->second.first->replaceAllUsesWith( - P.getContext().getUndef(I->second.first->getType())); + UndefValue::get(I->second.first->getType())); delete I->second.first; I->second.first = 0; } - + for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) if (!isa<BasicBlock>(I->second.first)) { I->second.first->replaceAllUsesWith( - P.getContext().getUndef(I->second.first->getType())); + UndefValue::get(I->second.first->getType())); delete I->second.first; I->second.first = 0; } @@ -1410,7 +1610,7 @@ Value *LLParser::PerFunctionState::GetVal(const std::string &Name, const Type *Ty, LocTy Loc) { // Look this name up in the normal function symbol table. Value *Val = F.getValueSymbolTable().lookup(Name); - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -1419,31 +1619,32 @@ Value *LLParser::PerFunctionState::GetVal(const std::string &Name, if (I != ForwardRefVals.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; - if (Ty == Type::LabelTy) + if (Ty->isLabelTy()) P.Error(Loc, "'%" + Name + "' is not a basic block"); else P.Error(Loc, "'%" + Name + "' defined with type '" + Val->getType()->getDescription() + "'"); return 0; } - + // Don't make placeholders with invalid type. - if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) { + if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && + Ty != Type::getLabelTy(F.getContext())) { P.Error(Loc, "invalid use of a non-first-class type"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. Value *FwdVal; - if (Ty == Type::LabelTy) - FwdVal = BasicBlock::Create(Name, &F); + if (Ty->isLabelTy()) + FwdVal = BasicBlock::Create(F.getContext(), Name, &F); else FwdVal = new Argument(Ty, Name); - + ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -1452,7 +1653,7 @@ Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, LocTy Loc) { // Look this name up in the normal function symbol table. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -1461,30 +1662,31 @@ Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, if (I != ForwardRefValIDs.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; - if (Ty == Type::LabelTy) + if (Ty->isLabelTy()) P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block"); else P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" + Val->getType()->getDescription() + "'"); return 0; } - - if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) { + + if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && + Ty != Type::getLabelTy(F.getContext())) { P.Error(Loc, "invalid use of a non-first-class type"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. Value *FwdVal; - if (Ty == Type::LabelTy) - FwdVal = BasicBlock::Create("", &F); + if (Ty->isLabelTy()) + FwdVal = BasicBlock::Create(F.getContext(), "", &F); else FwdVal = new Argument(Ty); - + ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -1495,30 +1697,31 @@ bool LLParser::PerFunctionState::SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc, Instruction *Inst) { // If this instruction has void type, it cannot have a name or ID specified. - if (Inst->getType() == Type::VoidTy) { + if (Inst->getType()->isVoidTy()) { if (NameID != -1 || !NameStr.empty()) return P.Error(NameLoc, "instructions returning void cannot have a name"); return false; } - + // If this was a numbered instruction, verify that the instruction is the // expected value and resolve any forward references. if (NameStr.empty()) { // If neither a name nor an ID was specified, just use the next ID. if (NameID == -1) NameID = NumberedVals.size(); - + if (unsigned(NameID) != NumberedVals.size()) return P.Error(NameLoc, "instruction expected to be numbered '%" + utostr(NumberedVals.size()) + "'"); - + std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI = ForwardRefValIDs.find(NameID); if (FI != ForwardRefValIDs.end()) { if (FI->second.first->getType() != Inst->getType()) - return P.Error(NameLoc, "instruction forward referenced with type '" + + return P.Error(NameLoc, "instruction forward referenced with type '" + FI->second.first->getType()->getDescription() + "'"); FI->second.first->replaceAllUsesWith(Inst); + delete FI->second.first; ForwardRefValIDs.erase(FI); } @@ -1531,17 +1734,18 @@ bool LLParser::PerFunctionState::SetInstName(int NameID, FI = ForwardRefVals.find(NameStr); if (FI != ForwardRefVals.end()) { if (FI->second.first->getType() != Inst->getType()) - return P.Error(NameLoc, "instruction forward referenced with type '" + + return P.Error(NameLoc, "instruction forward referenced with type '" + FI->second.first->getType()->getDescription() + "'"); FI->second.first->replaceAllUsesWith(Inst); + delete FI->second.first; ForwardRefVals.erase(FI); } - + // Set the name on the instruction. Inst->setName(NameStr); - + if (Inst->getNameStr() != NameStr) - return P.Error(NameLoc, "multiple definition of local value named '" + + return P.Error(NameLoc, "multiple definition of local value named '" + NameStr + "'"); return false; } @@ -1550,11 +1754,13 @@ bool LLParser::PerFunctionState::SetInstName(int NameID, /// forward reference record if needed. BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, LocTy Loc) { - return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc)); + return cast_or_null<BasicBlock>(GetVal(Name, + Type::getLabelTy(F.getContext()), Loc)); } BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { - return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc)); + return cast_or_null<BasicBlock>(GetVal(ID, + Type::getLabelTy(F.getContext()), Loc)); } /// DefineBB - Define the specified basic block, which is either named or @@ -1568,11 +1774,11 @@ BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, else BB = GetBB(Name, Loc); if (BB == 0) return 0; // Already diagnosed error. - + // Move the block to the end of the function. Forward ref'd blocks are // inserted wherever they happen to be referenced. F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); - + // Remove the block from forward ref sets. if (Name.empty()) { ForwardRefValIDs.erase(NumberedVals.size()); @@ -1581,7 +1787,7 @@ BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, // BB forward references are already in the function symbol table. ForwardRefVals.erase(Name); } - + return BB; } @@ -1615,7 +1821,7 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_LocalName; break; case lltok::Metadata: { // !{...} MDNode, !"foo" MDString - ID.Kind = ValID::t_Constant; + ID.Kind = ValID::t_Metadata; Lex.Lex(); if (Lex.getKind() == lltok::lbrace) { SmallVector<Value*, 16> Elts; @@ -1623,31 +1829,23 @@ bool LLParser::ParseValID(ValID &ID) { ParseToken(lltok::rbrace, "expected end of metadata node")) return true; - ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size()); + ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size()); return false; } // Standalone metadata reference // !{ ..., !42, ... } - unsigned MID = 0; - if (!ParseUInt32(MID)) { - std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID); - if (I == MetadataCache.end()) - return TokError("Unknown metadata reference"); - ID.ConstantVal = I->second; + if (!ParseMDNode(ID.MetadataVal)) return false; - } - + // MDString: // ::= '!' STRINGCONSTANT - std::string Str; - if (ParseStringConstant(Str)) return true; - - ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size()); + if (ParseMDString(ID.MetadataVal)) return true; + ID.Kind = ValID::t_Metadata; return false; } case lltok::APSInt: - ID.APSIntVal = Lex.getAPSIntVal(); + ID.APSIntVal = Lex.getAPSIntVal(); ID.Kind = ValID::t_APSInt; break; case lltok::APFloat: @@ -1655,17 +1853,17 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_APFloat; break; case lltok::kw_true: - ID.ConstantVal = Context.getConstantIntTrue(); + ID.ConstantVal = ConstantInt::getTrue(Context); ID.Kind = ValID::t_Constant; break; case lltok::kw_false: - ID.ConstantVal = Context.getConstantIntFalse(); + ID.ConstantVal = ConstantInt::getFalse(Context); ID.Kind = ValID::t_Constant; break; case lltok::kw_null: ID.Kind = ValID::t_Null; break; case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; - + case lltok::lbrace: { // ValID ::= '{' ConstVector '}' Lex.Lex(); @@ -1673,8 +1871,9 @@ bool LLParser::ParseValID(ValID &ID) { if (ParseGlobalValueVector(Elts) || ParseToken(lltok::rbrace, "expected end of struct constant")) return true; - - ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false); + + ID.ConstantVal = ConstantStruct::get(Context, Elts.data(), + Elts.size(), false); ID.Kind = ValID::t_Constant; return false; } @@ -1683,7 +1882,7 @@ bool LLParser::ParseValID(ValID &ID) { // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. Lex.Lex(); bool isPackedStruct = EatIfPresent(lltok::lbrace); - + SmallVector<Constant*, 16> Elts; LocTy FirstEltLoc = Lex.getLoc(); if (ParseGlobalValueVector(Elts) || @@ -1691,14 +1890,14 @@ bool LLParser::ParseValID(ValID &ID) { ParseToken(lltok::rbrace, "expected end of packed struct")) || ParseToken(lltok::greater, "expected end of constant")) return true; - + if (isPackedStruct) { ID.ConstantVal = - Context.getConstantStruct(Elts.data(), Elts.size(), true); + ConstantStruct::get(Context, Elts.data(), Elts.size(), true); ID.Kind = ValID::t_Constant; return false; } - + if (Elts.empty()) return Error(ID.Loc, "constant vector must not be empty"); @@ -1706,15 +1905,15 @@ bool LLParser::ParseValID(ValID &ID) { !Elts[0]->getType()->isFloatingPoint()) return Error(FirstEltLoc, "vector elements must have integer or floating point type"); - + // Verify that all the vector elements have the same type. for (unsigned i = 1, e = Elts.size(); i != e; ++i) if (Elts[i]->getType() != Elts[0]->getType()) return Error(FirstEltLoc, "vector element #" + utostr(i) + " is not of type '" + Elts[0]->getType()->getDescription()); - - ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size()); + + ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size()); ID.Kind = ValID::t_Constant; return false; } @@ -1733,13 +1932,13 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_EmptyArray; return false; } - + if (!Elts[0]->getType()->isFirstClassType()) - return Error(FirstEltLoc, "invalid array element type: " + + return Error(FirstEltLoc, "invalid array element type: " + Elts[0]->getType()->getDescription()); - - ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size()); - + + ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); + // Verify all elements are correct type! for (unsigned i = 0, e = Elts.size(); i != e; ++i) { if (Elts[i]->getType() != Elts[0]->getType()) @@ -1747,33 +1946,34 @@ bool LLParser::ParseValID(ValID &ID) { "array element #" + utostr(i) + " is not of type '" +Elts[0]->getType()->getDescription()); } - - ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size()); + + ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size()); ID.Kind = ValID::t_Constant; return false; } case lltok::kw_c: // c "foo" Lex.Lex(); - ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false); + ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false); if (ParseToken(lltok::StringConstant, "expected string")) return true; ID.Kind = ValID::t_Constant; return false; case lltok::kw_asm: { - // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT - bool HasSideEffect; + // ValID ::= 'asm' SideEffect? MsAsm? STRINGCONSTANT ',' STRINGCONSTANT + bool HasSideEffect, MsAsm; Lex.Lex(); if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || + ParseOptionalToken(lltok::kw_msasm, MsAsm) || ParseStringConstant(ID.StrVal) || ParseToken(lltok::comma, "expected comma in inline asm expression") || ParseToken(lltok::StringConstant, "expected constraint string")) return true; ID.StrVal2 = Lex.getStrVal(); - ID.UIntVal = HasSideEffect; + ID.UIntVal = HasSideEffect | ((unsigned)MsAsm<<1); ID.Kind = ValID::t_InlineAsm; return false; } - + case lltok::kw_trunc: case lltok::kw_zext: case lltok::kw_sext: @@ -1783,11 +1983,11 @@ bool LLParser::ParseValID(ValID &ID) { case lltok::kw_uitofp: case lltok::kw_sitofp: case lltok::kw_fptoui: - case lltok::kw_fptosi: + case lltok::kw_fptosi: case lltok::kw_inttoptr: - case lltok::kw_ptrtoint: { + case lltok::kw_ptrtoint: { unsigned Opc = Lex.getUIntVal(); - PATypeHolder DestTy(Type::VoidTy); + PATypeHolder DestTy(Type::getVoidTy(Context)); Constant *SrcVal; Lex.Lex(); if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || @@ -1800,7 +2000,7 @@ bool LLParser::ParseValID(ValID &ID) { return Error(ID.Loc, "invalid cast opcode for cast from '" + SrcVal->getType()->getDescription() + "' to '" + DestTy->getDescription() + "'"); - ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc, + ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal, DestTy); ID.Kind = ValID::t_Constant; return false; @@ -1820,7 +2020,7 @@ bool LLParser::ParseValID(ValID &ID) { Indices.end())) return Error(ID.Loc, "invalid indices for extractvalue"); ID.ConstantVal = - Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size()); + ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size()); ID.Kind = ValID::t_Constant; return false; } @@ -1840,15 +2040,13 @@ bool LLParser::ParseValID(ValID &ID) { if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), Indices.end())) return Error(ID.Loc, "invalid indices for insertvalue"); - ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1, + ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices.data(), Indices.size()); ID.Kind = ValID::t_Constant; return false; } case lltok::kw_icmp: - case lltok::kw_fcmp: - case lltok::kw_vicmp: - case lltok::kw_vfcmp: { + case lltok::kw_fcmp: { unsigned PredVal, Opc = Lex.getUIntVal(); Constant *Val0, *Val1; Lex.Lex(); @@ -1859,38 +2057,27 @@ bool LLParser::ParseValID(ValID &ID) { ParseGlobalTypeAndValue(Val1) || ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) return true; - + if (Val0->getType() != Val1->getType()) return Error(ID.Loc, "compare operands must have the same type"); - + CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; - + if (Opc == Instruction::FCmp) { if (!Val0->getType()->isFPOrFPVector()) return Error(ID.Loc, "fcmp requires floating point operands"); - ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1); - } else if (Opc == Instruction::ICmp) { + ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); + } else { + assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); if (!Val0->getType()->isIntOrIntVector() && !isa<PointerType>(Val0->getType())) return Error(ID.Loc, "icmp requires pointer or integer operands"); - ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1); - } else if (Opc == Instruction::VFCmp) { - // FIXME: REMOVE VFCMP Support - if (!Val0->getType()->isFPOrFPVector() || - !isa<VectorType>(Val0->getType())) - return Error(ID.Loc, "vfcmp requires vector floating point operands"); - ID.ConstantVal = Context.getConstantExprVFCmp(Pred, Val0, Val1); - } else if (Opc == Instruction::VICmp) { - // FIXME: REMOVE VICMP Support - if (!Val0->getType()->isIntOrIntVector() || - !isa<VectorType>(Val0->getType())) - return Error(ID.Loc, "vicmp requires vector floating point operands"); - ID.ConstantVal = Context.getConstantExprVICmp(Pred, Val0, Val1); + ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); } ID.Kind = ValID::t_Constant; return false; } - + // Binary Operators. case lltok::kw_add: case lltok::kw_fadd: @@ -1904,9 +2091,27 @@ bool LLParser::ParseValID(ValID &ID) { case lltok::kw_urem: case lltok::kw_srem: case lltok::kw_frem: { + bool NUW = false; + bool NSW = false; + bool Exact = false; unsigned Opc = Lex.getUIntVal(); Constant *Val0, *Val1; Lex.Lex(); + LocTy ModifierLoc = Lex.getLoc(); + if (Opc == Instruction::Add || + Opc == Instruction::Sub || + Opc == Instruction::Mul) { + if (EatIfPresent(lltok::kw_nuw)) + NUW = true; + if (EatIfPresent(lltok::kw_nsw)) { + NSW = true; + if (EatIfPresent(lltok::kw_nuw)) + NUW = true; + } + } else if (Opc == Instruction::SDiv) { + if (EatIfPresent(lltok::kw_exact)) + Exact = true; + } if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || ParseGlobalTypeAndValue(Val0) || ParseToken(lltok::comma, "expected comma in binary constantexpr") || @@ -1915,14 +2120,27 @@ bool LLParser::ParseValID(ValID &ID) { return true; if (Val0->getType() != Val1->getType()) return Error(ID.Loc, "operands of constexpr must have same type"); + if (!Val0->getType()->isIntOrIntVector()) { + if (NUW) + return Error(ModifierLoc, "nuw only applies to integer operations"); + if (NSW) + return Error(ModifierLoc, "nsw only applies to integer operations"); + } + // API compatibility: Accept either integer or floating-point types with + // add, sub, and mul. if (!Val0->getType()->isIntOrIntVector() && !Val0->getType()->isFPOrFPVector()) return Error(ID.Loc,"constexpr requires integer, fp, or vector operands"); - ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1); + unsigned Flags = 0; + if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; + if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; + if (Exact) Flags |= SDivOperator::IsExact; + Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); + ID.ConstantVal = C; ID.Kind = ValID::t_Constant; return false; } - + // Logical Operations case lltok::kw_shl: case lltok::kw_lshr: @@ -1944,11 +2162,11 @@ bool LLParser::ParseValID(ValID &ID) { if (!Val0->getType()->isIntOrIntVector()) return Error(ID.Loc, "constexpr requires integer or integer vector operands"); - ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1); + ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); ID.Kind = ValID::t_Constant; return false; - } - + } + case lltok::kw_getelementptr: case lltok::kw_shufflevector: case lltok::kw_insertelement: @@ -1956,41 +2174,49 @@ bool LLParser::ParseValID(ValID &ID) { case lltok::kw_select: { unsigned Opc = Lex.getUIntVal(); SmallVector<Constant*, 16> Elts; + bool InBounds = false; Lex.Lex(); + if (Opc == Instruction::GetElementPtr) + InBounds = EatIfPresent(lltok::kw_inbounds); if (ParseToken(lltok::lparen, "expected '(' in constantexpr") || ParseGlobalValueVector(Elts) || ParseToken(lltok::rparen, "expected ')' in constantexpr")) return true; - + if (Opc == Instruction::GetElementPtr) { if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType())) return Error(ID.Loc, "getelementptr requires pointer operand"); - + if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), - (Value**)&Elts[1], Elts.size()-1)) + (Value**)(Elts.data() + 1), + Elts.size() - 1)) return Error(ID.Loc, "invalid indices for getelementptr"); - ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0], - &Elts[1], Elts.size()-1); + ID.ConstantVal = InBounds ? + ConstantExpr::getInBoundsGetElementPtr(Elts[0], + Elts.data() + 1, + Elts.size() - 1) : + ConstantExpr::getGetElementPtr(Elts[0], + Elts.data() + 1, Elts.size() - 1); } else if (Opc == Instruction::Select) { if (Elts.size() != 3) return Error(ID.Loc, "expected three operands to select"); if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], Elts[2])) return Error(ID.Loc, Reason); - ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]); + ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); } else if (Opc == Instruction::ShuffleVector) { if (Elts.size() != 3) return Error(ID.Loc, "expected three operands to shufflevector"); if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) return Error(ID.Loc, "invalid operands to shufflevector"); ID.ConstantVal = - Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]); + ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); } else if (Opc == Instruction::ExtractElement) { if (Elts.size() != 2) return Error(ID.Loc, "expected two operands to extractelement"); if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) return Error(ID.Loc, "invalid extractelement operands"); - ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]); + ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); } else { assert(Opc == Instruction::InsertElement && "Unknown opcode"); if (Elts.size() != 3) @@ -1998,14 +2224,14 @@ bool LLParser::ParseValID(ValID &ID) { if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) return Error(ID.Loc, "invalid insertelement operands"); ID.ConstantVal = - Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]); + ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); } - + ID.Kind = ValID::t_Constant; return false; } } - + Lex.Lex(); return false; } @@ -2024,9 +2250,11 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, Constant *&V) { if (isa<FunctionType>(Ty)) return Error(ID.Loc, "functions are not values, refer to them as pointers"); - + switch (ID.Kind) { - default: assert(0 && "Unknown ValID!"); + default: llvm_unreachable("Unknown ValID!"); + case ValID::t_Metadata: + return Error(ID.Loc, "invalid use of metadata"); case ValID::t_LocalID: case ValID::t_LocalName: return Error(ID.Loc, "invalid use of function-local name"); @@ -2042,50 +2270,50 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, if (!isa<IntegerType>(Ty)) return Error(ID.Loc, "integer constant must have integer type"); ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); - V = Context.getConstantInt(ID.APSIntVal); + V = ConstantInt::get(Context, ID.APSIntVal); return false; case ValID::t_APFloat: if (!Ty->isFloatingPoint() || !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) return Error(ID.Loc, "floating point constant invalid for type"); - + // The lexer has no type info, so builds all float and double FP constants // as double. Fix this here. Long double does not need this. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble && - Ty == Type::FloatTy) { + Ty->isFloatTy()) { bool Ignored; ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &Ignored); } - V = Context.getConstantFP(ID.APFloatVal); - + V = ConstantFP::get(Context, ID.APFloatVal); + if (V->getType() != Ty) return Error(ID.Loc, "floating point constant does not have type '" + Ty->getDescription() + "'"); - + return false; case ValID::t_Null: if (!isa<PointerType>(Ty)) return Error(ID.Loc, "null must be a pointer type"); - V = Context.getConstantPointerNull(cast<PointerType>(Ty)); + V = ConstantPointerNull::get(cast<PointerType>(Ty)); return false; case ValID::t_Undef: // FIXME: LabelTy should not be a first-class type. - if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) && + if ((!Ty->isFirstClassType() || Ty->isLabelTy()) && !isa<OpaqueType>(Ty)) return Error(ID.Loc, "invalid type for undef constant"); - V = Context.getUndef(Ty); + V = UndefValue::get(Ty); return false; case ValID::t_EmptyArray: if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0) return Error(ID.Loc, "invalid empty array initializer"); - V = Context.getUndef(Ty); + V = UndefValue::get(Ty); return false; case ValID::t_Zero: // FIXME: LabelTy should not be a first-class type. - if (!Ty->isFirstClassType() || Ty == Type::LabelTy) + if (!Ty->isFirstClassType() || Ty->isLabelTy()) return Error(ID.Loc, "invalid type for null constant"); - V = Context.getNullValue(Ty); + V = Constant::getNullValue(Ty); return false; case ValID::t_Constant: if (ID.ConstantVal->getType() != Ty) @@ -2094,12 +2322,12 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, return false; } } - + bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { - PATypeHolder Type(Type::VoidTy); + PATypeHolder Type(Type::getVoidTy(Context)); return ParseType(Type) || ParseGlobalValue(Type, V); -} +} /// ParseGlobalValueVector /// ::= /*empty*/ @@ -2111,16 +2339,16 @@ bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) { Lex.getKind() == lltok::greater || Lex.getKind() == lltok::rparen) return false; - + Constant *C; if (ParseGlobalTypeAndValue(C)) return true; Elts.push_back(C); - + while (EatIfPresent(lltok::comma)) { if (ParseGlobalTypeAndValue(C)) return true; Elts.push_back(C); } - + return false; } @@ -2141,8 +2369,10 @@ bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V, PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0; if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) return Error(ID.Loc, "invalid type for inline asm constraint string"); - V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal); + V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1); return false; + } else if (ID.Kind == ValID::t_Metadata) { + V = ID.MetadataVal; } else { Constant *C; if (ConvertGlobalValIDToValue(Ty, ID, C)) return true; @@ -2161,7 +2391,7 @@ bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) { } bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) { - PATypeHolder T(Type::VoidTy); + PATypeHolder T(Type::getVoidTy(Context)); return ParseType(T) || ParseValue(T, V, PFS); } @@ -2174,9 +2404,10 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { // Parse the linkage. LocTy LinkageLoc = Lex.getLoc(); unsigned Linkage; - - unsigned Visibility, CC, RetAttrs; - PATypeHolder RetType(Type::VoidTy); + + unsigned Visibility, RetAttrs; + CallingConv::ID CC; + PATypeHolder RetType(Type::getVoidTy(Context)); LocTy RetTypeLoc = Lex.getLoc(); if (ParseOptionalLinkage(Linkage) || ParseOptionalVisibility(Visibility) || @@ -2195,6 +2426,7 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { return Error(LinkageLoc, "invalid linkage for function definition"); break; case GlobalValue::PrivateLinkage: + case GlobalValue::LinkerPrivateLinkage: case GlobalValue::InternalLinkage: case GlobalValue::AvailableExternallyLinkage: case GlobalValue::LinkOnceAnyLinkage: @@ -2210,11 +2442,11 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { case GlobalValue::CommonLinkage: return Error(LinkageLoc, "invalid function linkage type"); } - + if (!FunctionType::isValidReturnType(RetType) || isa<OpaqueType>(RetType)) return Error(RetTypeLoc, "invalid function return type"); - + LocTy NameLoc = Lex.getLoc(); std::string FunctionName; @@ -2229,12 +2461,12 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { } else { return TokError("expected function name"); } - + Lex.Lex(); - + if (Lex.getKind() != lltok::lparen) return TokError("expected '(' in function argument list"); - + std::vector<ArgInfo> ArgList; bool isVarArg; unsigned FuncAttrs; @@ -2256,22 +2488,22 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs); FuncAttrs &= ~Attribute::Alignment; } - + // Okay, if we got here, the function is syntactically valid. Convert types // and do semantic checks. std::vector<const Type*> ParamTypeList; SmallVector<AttributeWithIndex, 8> Attrs; - // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function + // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function // attributes. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; if (FuncAttrs & ObsoleteFuncAttrs) { RetAttrs |= FuncAttrs & ObsoleteFuncAttrs; FuncAttrs &= ~ObsoleteFuncAttrs; } - + if (RetAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); - + for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { ParamTypeList.push_back(ArgList[i].Type); if (ArgList[i].Attrs != Attribute::None) @@ -2282,14 +2514,14 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs)); AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); - + if (PAL.paramHasAttr(1, Attribute::StructRet) && - RetType != Type::VoidTy) - return Error(RetTypeLoc, "functions with 'sret' argument must return void"); - + RetType != Type::getVoidTy(Context)) + return Error(RetTypeLoc, "functions with 'sret' argument must return void"); + const FunctionType *FT = - Context.getFunctionType(RetType, ParamTypeList, isVarArg); - const PointerType *PFT = Context.getPointerTypeUnqual(FT); + FunctionType::get(RetType, ParamTypeList, isVarArg); + const PointerType *PFT = PointerType::getUnqual(FT); Fn = 0; if (!FunctionName.empty()) { @@ -2317,8 +2549,8 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { AI->setName(""); } } - - } else if (FunctionName.empty()) { + + } else { // If this is a definition of a forward referenced function, make sure the // types agree. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I @@ -2339,7 +2571,7 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { if (FunctionName.empty()) NumberedVals.push_back(Fn); - + Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); Fn->setCallingConv(CC); @@ -2347,21 +2579,21 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { Fn->setAlignment(Alignment); Fn->setSection(Section); if (!GC.empty()) Fn->setGC(GC.c_str()); - + // Add all of the arguments we parsed to the function. Function::arg_iterator ArgIt = Fn->arg_begin(); for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { // If the argument has a name, insert it into the argument symbol table. if (ArgList[i].Name.empty()) continue; - + // Set the name, if it conflicted, it will be auto-renamed. ArgIt->setName(ArgList[i].Name); - + if (ArgIt->getNameStr() != ArgList[i].Name) return Error(ArgList[i].Loc, "redefinition of argument '%" + ArgList[i].Name + "'"); } - + return false; } @@ -2374,15 +2606,15 @@ bool LLParser::ParseFunctionBody(Function &Fn) { if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin) return TokError("expected '{' in function body"); Lex.Lex(); // eat the {. - + PerFunctionState PFS(*this, Fn); - + while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end) if (ParseBasicBlock(PFS)) return true; - + // Eat the }. Lex.Lex(); - + // Verify function is ok. return PFS.VerifyFunctionComplete(); } @@ -2397,12 +2629,12 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { Name = Lex.getStrVal(); Lex.Lex(); } - + BasicBlock *BB = PFS.DefineBB(Name, NameLoc); if (BB == 0) return true; - + std::string NameStr; - + // Parse the instructions in this block until we get a terminator. Instruction *Inst; do { @@ -2411,7 +2643,7 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { LocTy NameLoc = Lex.getLoc(); int NameID = -1; NameStr = ""; - + if (Lex.getKind() == lltok::LocalVarID) { NameID = Lex.getUIntVal(); Lex.Lex(); @@ -2425,15 +2657,24 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { if (ParseToken(lltok::equal, "expected '=' after instruction name")) return true; } - + if (ParseInstruction(Inst, BB, PFS)) return true; - + if (EatIfPresent(lltok::comma)) + ParseOptionalCustomMetadata(); + + // Set metadata attached with this instruction. + MetadataContext &TheMetadata = M->getContext().getMetadata(); + for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator + MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI) + TheMetadata.addMD(MDI->first, MDI->second, Inst); + MDsOnInst.clear(); + BB->getInstList().push_back(Inst); // Set the name on the instruction. if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; } while (!isa<TerminatorInst>(Inst)); - + return false; } @@ -2451,12 +2692,12 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, LocTy Loc = Lex.getLoc(); unsigned KeywordVal = Lex.getUIntVal(); Lex.Lex(); // Eat the keyword. - + switch (Token) { default: return Error(Loc, "expected instruction opcode"); // Terminator Instructions. - case lltok::kw_unwind: Inst = new UnwindInst(); return false; - case lltok::kw_unreachable: Inst = new UnreachableInst(); return false; + case lltok::kw_unwind: Inst = new UnwindInst(Context); return false; + case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; case lltok::kw_ret: return ParseRet(Inst, BB, PFS); case lltok::kw_br: return ParseBr(Inst, PFS); case lltok::kw_switch: return ParseSwitch(Inst, PFS); @@ -2464,15 +2705,49 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, // Binary Operators. case lltok::kw_add: case lltok::kw_sub: - case lltok::kw_mul: + case lltok::kw_mul: { + bool NUW = false; + bool NSW = false; + LocTy ModifierLoc = Lex.getLoc(); + if (EatIfPresent(lltok::kw_nuw)) + NUW = true; + if (EatIfPresent(lltok::kw_nsw)) { + NSW = true; + if (EatIfPresent(lltok::kw_nuw)) + NUW = true; + } // API compatibility: Accept either integer or floating-point types. - return ParseArithmetic(Inst, PFS, KeywordVal, 0); + bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0); + if (!Result) { + if (!Inst->getType()->isIntOrIntVector()) { + if (NUW) + return Error(ModifierLoc, "nuw only applies to integer operations"); + if (NSW) + return Error(ModifierLoc, "nsw only applies to integer operations"); + } + if (NUW) + cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); + if (NSW) + cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); + } + return Result; + } case lltok::kw_fadd: case lltok::kw_fsub: case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2); + case lltok::kw_sdiv: { + bool Exact = false; + if (EatIfPresent(lltok::kw_exact)) + Exact = true; + bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1); + if (!Result) + if (Exact) + cast<BinaryOperator>(Inst)->setIsExact(true); + return Result; + } + case lltok::kw_udiv: - case lltok::kw_sdiv: case lltok::kw_urem: case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1); case lltok::kw_fdiv: @@ -2484,9 +2759,7 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, case lltok::kw_or: case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); case lltok::kw_icmp: - case lltok::kw_fcmp: - case lltok::kw_vicmp: - case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal); + case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal); // Casts. case lltok::kw_trunc: case lltok::kw_zext: @@ -2497,7 +2770,7 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, case lltok::kw_uitofp: case lltok::kw_sitofp: case lltok::kw_fptoui: - case lltok::kw_fptosi: + case lltok::kw_fptosi: case lltok::kw_inttoptr: case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); // Other. @@ -2531,8 +2804,7 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { - // FIXME: REMOVE vicmp/vfcmp! - if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) { + if (Opc == Instruction::FCmp) { switch (Lex.getKind()) { default: TokError("expected fcmp predicate (e.g. 'oeq')"); case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; @@ -2576,42 +2848,57 @@ bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { //===----------------------------------------------------------------------===// /// ParseRet - Parse a return instruction. -/// ::= 'ret' void -/// ::= 'ret' TypeAndValue -/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]] +/// ::= 'ret' void (',' !dbg, !1) +/// ::= 'ret' TypeAndValue (',' !dbg, !1) +/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1) +/// [[obsolete: LLVM 3.0]] bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS) { - PATypeHolder Ty(Type::VoidTy); + PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseType(Ty, true /*void allowed*/)) return true; - - if (Ty == Type::VoidTy) { - Inst = ReturnInst::Create(); + + if (Ty->isVoidTy()) { + if (EatIfPresent(lltok::comma)) + if (ParseOptionalCustomMetadata()) return true; + Inst = ReturnInst::Create(Context); return false; } - + Value *RV; if (ParseValue(Ty, RV, PFS)) return true; - - // The normal case is one return value. - if (Lex.getKind() == lltok::comma) { - // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use - // of 'ret {i32,i32} {i32 1, i32 2}' - SmallVector<Value*, 8> RVs; - RVs.push_back(RV); - - while (EatIfPresent(lltok::comma)) { - if (ParseTypeAndValue(RV, PFS)) return true; + + if (EatIfPresent(lltok::comma)) { + // Parse optional custom metadata, e.g. !dbg + if (Lex.getKind() == lltok::NamedOrCustomMD) { + if (ParseOptionalCustomMetadata()) return true; + } else { + // The normal case is one return value. + // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use + // of 'ret {i32,i32} {i32 1, i32 2}' + SmallVector<Value*, 8> RVs; RVs.push_back(RV); - } - RV = Context.getUndef(PFS.getFunction().getReturnType()); - for (unsigned i = 0, e = RVs.size(); i != e; ++i) { - Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv"); - BB->getInstList().push_back(I); - RV = I; + do { + // If optional custom metadata, e.g. !dbg is seen then this is the + // end of MRV. + if (Lex.getKind() == lltok::NamedOrCustomMD) + break; + if (ParseTypeAndValue(RV, PFS)) return true; + RVs.push_back(RV); + } while (EatIfPresent(lltok::comma)); + + RV = UndefValue::get(PFS.getFunction().getReturnType()); + for (unsigned i = 0, e = RVs.size(); i != e; ++i) { + Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv"); + BB->getInstList().push_back(I); + RV = I; + } } } - Inst = ReturnInst::Create(RV); + if (EatIfPresent(lltok::comma)) + if (ParseOptionalCustomMetadata()) return true; + + Inst = ReturnInst::Create(Context, RV); return false; } @@ -2623,26 +2910,26 @@ bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { LocTy Loc, Loc2; Value *Op0, *Op1, *Op2; if (ParseTypeAndValue(Op0, Loc, PFS)) return true; - + if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { Inst = BranchInst::Create(BB); return false; } - - if (Op0->getType() != Type::Int1Ty) + + if (Op0->getType() != Type::getInt1Ty(Context)) return Error(Loc, "branch condition must have 'i1' type"); - + if (ParseToken(lltok::comma, "expected ',' after branch condition") || ParseTypeAndValue(Op1, Loc, PFS) || ParseToken(lltok::comma, "expected ',' after true destination") || ParseTypeAndValue(Op2, Loc2, PFS)) return true; - + if (!isa<BasicBlock>(Op1)) return Error(Loc, "true destination of branch must be a basic block"); if (!isa<BasicBlock>(Op2)) return Error(Loc2, "true destination of branch must be a basic block"); - + Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0); return false; } @@ -2665,13 +2952,13 @@ bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { return Error(CondLoc, "switch condition must have integer type"); if (!isa<BasicBlock>(DefaultBB)) return Error(BBLoc, "default destination must be a basic block"); - + // Parse the jump table pairs. SmallPtrSet<Value*, 32> SeenCases; SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; while (Lex.getKind() != lltok::rsquare) { Value *Constant, *DestBB; - + if (ParseTypeAndValue(Constant, CondLoc, PFS) || ParseToken(lltok::comma, "expected ',' after case value") || ParseTypeAndValue(DestBB, BBLoc, PFS)) @@ -2683,13 +2970,13 @@ bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { return Error(CondLoc, "case value is not a constant integer"); if (!isa<BasicBlock>(DestBB)) return Error(BBLoc, "case destination is not a basic block"); - + Table.push_back(std::make_pair(cast<ConstantInt>(Constant), cast<BasicBlock>(DestBB))); } - + Lex.Lex(); // Eat the ']'. - + SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB), Table.size()); for (unsigned i = 0, e = Table.size(); i != e; ++i) @@ -2703,8 +2990,9 @@ bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { LocTy CallLoc = Lex.getLoc(); - unsigned CC, RetAttrs, FnAttrs; - PATypeHolder RetType(Type::VoidTy); + unsigned RetAttrs, FnAttrs; + CallingConv::ID CC; + PATypeHolder RetType(Type::getVoidTy(Context)); LocTy RetTypeLoc; ValID CalleeID; SmallVector<ParamInfo, 16> ArgList; @@ -2721,12 +3009,12 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || ParseTypeAndValue(UnwindBB, PFS)) return true; - + if (!isa<BasicBlock>(NormalBB)) return Error(CallLoc, "normal destination is not a basic block"); if (!isa<BasicBlock>(UnwindBB)) return Error(CallLoc, "unwind destination is not a basic block"); - + // If RetType is a non-function pointer type, then this is the short syntax // for the call, which means that RetType is just the return type. Infer the // rest of the function argument types from the arguments that are present. @@ -2738,18 +3026,18 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { std::vector<const Type*> ParamTypes; for (unsigned i = 0, e = ArgList.size(); i != e; ++i) ParamTypes.push_back(ArgList[i].V->getType()); - + if (!FunctionType::isValidReturnType(RetType)) return Error(RetTypeLoc, "Invalid result type for LLVM function"); - - Ty = Context.getFunctionType(RetType, ParamTypes, false); - PFTy = Context.getPointerTypeUnqual(Ty); + + Ty = FunctionType::get(RetType, ParamTypes, false); + PFTy = PointerType::getUnqual(Ty); } - + // Look up the callee. Value *Callee; if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; - + // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional // function attributes. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; @@ -2757,14 +3045,14 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { RetAttrs |= FnAttrs & ObsoleteFuncAttrs; FnAttrs &= ~ObsoleteFuncAttrs; } - + // Set up the Attributes for the function. SmallVector<AttributeWithIndex, 8> Attrs; if (RetAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); - + SmallVector<Value*, 8> Args; - + // Loop through FunctionType's arguments and ensure they are specified // correctly. Also, gather any parameter attributes. FunctionType::param_iterator I = Ty->param_begin(); @@ -2776,7 +3064,7 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { } else if (!Ty->isVarArg()) { return Error(ArgList[i].Loc, "too many arguments specified"); } - + if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) return Error(ArgList[i].Loc, "argument is not of expected type '" + ExpectedTy->getDescription() + "'"); @@ -2784,16 +3072,16 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { if (ArgList[i].Attrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); } - + if (I != E) return Error(CallLoc, "not enough parameters specified for call"); - + if (FnAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); - + // Finish off the Attributes and check them AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); - + InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB), cast<BasicBlock>(UnwindBB), Args.begin(), Args.end()); @@ -2824,7 +3112,7 @@ bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, bool Valid; switch (OperandType) { - default: assert(0 && "Unknown operand type!"); + default: llvm_unreachable("Unknown operand type!"); case 0: // int or FP. Valid = LHS->getType()->isIntOrIntVector() || LHS->getType()->isFPOrFPVector(); @@ -2832,10 +3120,10 @@ bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, case 1: Valid = LHS->getType()->isIntOrIntVector(); break; case 2: Valid = LHS->getType()->isFPOrFPVector(); break; } - + if (!Valid) return Error(Loc, "invalid operand type for instruction"); - + Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); return false; } @@ -2861,8 +3149,6 @@ bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, /// ParseCompare /// ::= 'icmp' IPredicates TypeAndValue ',' Value /// ::= 'fcmp' FPredicates TypeAndValue ',' Value -/// ::= 'vicmp' IPredicates TypeAndValue ',' Value -/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc) { // Parse the integer/fp comparison predicate. @@ -2874,24 +3160,17 @@ bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, ParseToken(lltok::comma, "expected ',' after compare value") || ParseValue(LHS->getType(), RHS, PFS)) return true; - + if (Opc == Instruction::FCmp) { if (!LHS->getType()->isFPOrFPVector()) return Error(Loc, "fcmp requires floating point operands"); Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); - } else if (Opc == Instruction::ICmp) { + } else { + assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); if (!LHS->getType()->isIntOrIntVector() && !isa<PointerType>(LHS->getType())) return Error(Loc, "icmp requires integer operands"); Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); - } else if (Opc == Instruction::VFCmp) { - if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType())) - return Error(Loc, "vfcmp requires vector floating point operands"); - Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS); - } else if (Opc == Instruction::VICmp) { - if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType())) - return Error(Loc, "vicmp requires vector floating point operands"); - Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS); } return false; } @@ -2906,12 +3185,12 @@ bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc) { LocTy Loc; Value *Op; - PATypeHolder DestTy(Type::VoidTy); + PATypeHolder DestTy(Type::getVoidTy(Context)); if (ParseTypeAndValue(Op, Loc, PFS) || ParseToken(lltok::kw_to, "expected 'to' after cast value") || ParseType(DestTy)) return true; - + if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); return Error(Loc, "invalid cast opcode for cast from '" + @@ -2933,10 +3212,10 @@ bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after select value") || ParseTypeAndValue(Op2, PFS)) return true; - + if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) return Error(Loc, Reason); - + Inst = SelectInst::Create(Op0, Op1, Op2); return false; } @@ -2945,13 +3224,13 @@ bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { /// ::= 'va_arg' TypeAndValue ',' Type bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { Value *Op; - PATypeHolder EltTy(Type::VoidTy); + PATypeHolder EltTy(Type::getVoidTy(Context)); LocTy TypeLoc; if (ParseTypeAndValue(Op, PFS) || ParseToken(lltok::comma, "expected ',' after vaarg operand") || ParseType(EltTy, TypeLoc)) return true; - + if (!EltTy->isFirstClassType()) return Error(TypeLoc, "va_arg requires operand with first class type"); @@ -2968,11 +3247,11 @@ bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after extract value") || ParseTypeAndValue(Op1, PFS)) return true; - + if (!ExtractElementInst::isValidOperands(Op0, Op1)) return Error(Loc, "invalid extractelement operands"); - - Inst = new ExtractElementInst(Op0, Op1); + + Inst = ExtractElementInst::Create(Op0, Op1); return false; } @@ -2987,10 +3266,10 @@ bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after insertelement value") || ParseTypeAndValue(Op2, PFS)) return true; - + if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) - return Error(Loc, "invalid extractelement operands"); - + return Error(Loc, "invalid insertelement operands"); + Inst = InsertElementInst::Create(Op0, Op1, Op2); return false; } @@ -3006,10 +3285,10 @@ bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after shuffle value") || ParseTypeAndValue(Op2, PFS)) return true; - + if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) return Error(Loc, "invalid extractelement operands"); - + Inst = new ShuffleVectorInst(Op0, Op1, Op2); return false; } @@ -3017,33 +3296,33 @@ bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { /// ParsePHI /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')* bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { - PATypeHolder Ty(Type::VoidTy); + PATypeHolder Ty(Type::getVoidTy(Context)); Value *Op0, *Op1; LocTy TypeLoc = Lex.getLoc(); - + if (ParseType(Ty) || ParseToken(lltok::lsquare, "expected '[' in phi value list") || ParseValue(Ty, Op0, PFS) || ParseToken(lltok::comma, "expected ',' after insertelement value") || - ParseValue(Type::LabelTy, Op1, PFS) || + ParseValue(Type::getLabelTy(Context), Op1, PFS) || ParseToken(lltok::rsquare, "expected ']' in phi value list")) return true; - + SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; while (1) { PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); - + if (!EatIfPresent(lltok::comma)) break; if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || ParseValue(Ty, Op0, PFS) || ParseToken(lltok::comma, "expected ',' after insertelement value") || - ParseValue(Type::LabelTy, Op1, PFS) || + ParseValue(Type::getLabelTy(Context), Op1, PFS) || ParseToken(lltok::rsquare, "expected ']' in phi value list")) return true; } - + if (!Ty->isFirstClassType()) return Error(TypeLoc, "phi node must have first class type"); @@ -3060,13 +3339,14 @@ bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { /// ParameterList OptionalAttrs bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, bool isTail) { - unsigned CC, RetAttrs, FnAttrs; - PATypeHolder RetType(Type::VoidTy); + unsigned RetAttrs, FnAttrs; + CallingConv::ID CC; + PATypeHolder RetType(Type::getVoidTy(Context)); LocTy RetTypeLoc; ValID CalleeID; SmallVector<ParamInfo, 16> ArgList; LocTy CallLoc = Lex.getLoc(); - + if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) || ParseOptionalCallingConv(CC) || ParseOptionalAttrs(RetAttrs, 1) || @@ -3075,7 +3355,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, ParseParameterList(ArgList, PFS) || ParseOptionalAttrs(FnAttrs, 2)) return true; - + // If RetType is a non-function pointer type, then this is the short syntax // for the call, which means that RetType is just the return type. Infer the // rest of the function argument types from the arguments that are present. @@ -3087,18 +3367,18 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, std::vector<const Type*> ParamTypes; for (unsigned i = 0, e = ArgList.size(); i != e; ++i) ParamTypes.push_back(ArgList[i].V->getType()); - + if (!FunctionType::isValidReturnType(RetType)) return Error(RetTypeLoc, "Invalid result type for LLVM function"); - - Ty = Context.getFunctionType(RetType, ParamTypes, false); - PFTy = Context.getPointerTypeUnqual(Ty); + + Ty = FunctionType::get(RetType, ParamTypes, false); + PFTy = PointerType::getUnqual(Ty); } - + // Look up the callee. Value *Callee; if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; - + // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional // function attributes. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; @@ -3111,9 +3391,9 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, SmallVector<AttributeWithIndex, 8> Attrs; if (RetAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); - + SmallVector<Value*, 8> Args; - + // Loop through FunctionType's arguments and ensure they are specified // correctly. Also, gather any parameter attributes. FunctionType::param_iterator I = Ty->param_begin(); @@ -3125,7 +3405,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, } else if (!Ty->isVarArg()) { return Error(ArgList[i].Loc, "too many arguments specified"); } - + if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) return Error(ArgList[i].Loc, "argument is not of expected type '" + ExpectedTy->getDescription() + "'"); @@ -3133,7 +3413,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, if (ArgList[i].Attrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); } - + if (I != E) return Error(CallLoc, "not enough parameters specified for call"); @@ -3142,7 +3422,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, // Finish off the Attributes and check them AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); - + CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end()); CI->setTailCall(isTail); CI->setCallingConv(CC); @@ -3156,26 +3436,28 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, //===----------------------------------------------------------------------===// /// ParseAlloc -/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)? -/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)? +/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)? +/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)? bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc) { - PATypeHolder Ty(Type::VoidTy); + PATypeHolder Ty(Type::getVoidTy(Context)); Value *Size = 0; LocTy SizeLoc; unsigned Alignment = 0; if (ParseType(Ty)) return true; if (EatIfPresent(lltok::comma)) { - if (Lex.getKind() == lltok::kw_align) { - if (ParseOptionalAlignment(Alignment)) return true; - } else if (ParseTypeAndValue(Size, SizeLoc, PFS) || - ParseOptionalCommaAlignment(Alignment)) { - return true; + if (Lex.getKind() == lltok::kw_align + || Lex.getKind() == lltok::NamedOrCustomMD) { + if (ParseOptionalInfo(Alignment)) return true; + } else { + if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true; + if (EatIfPresent(lltok::comma)) + if (ParseOptionalInfo(Alignment)) return true; } } - if (Size && Size->getType() != Type::Int32Ty) + if (Size && Size->getType() != Type::getInt32Ty(Context)) return Error(SizeLoc, "element count must be i32"); if (Opc == Instruction::Malloc) @@ -3197,19 +3479,20 @@ bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) { } /// ParseLoad -/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)? +/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)? bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, bool isVolatile) { Value *Val; LocTy Loc; - unsigned Alignment; - if (ParseTypeAndValue(Val, Loc, PFS) || - ParseOptionalCommaAlignment(Alignment)) - return true; + unsigned Alignment = 0; + if (ParseTypeAndValue(Val, Loc, PFS)) return true; + + if (EatIfPresent(lltok::comma)) + if (ParseOptionalInfo(Alignment)) return true; if (!isa<PointerType>(Val->getType()) || !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType()) return Error(Loc, "load operand must be a pointer to a first class type"); - + Inst = new LoadInst(Val, "", isVolatile, Alignment); return false; } @@ -3219,20 +3502,22 @@ bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS, bool isVolatile) { Value *Val, *Ptr; LocTy Loc, PtrLoc; - unsigned Alignment; + unsigned Alignment = 0; if (ParseTypeAndValue(Val, Loc, PFS) || ParseToken(lltok::comma, "expected ',' after store operand") || - ParseTypeAndValue(Ptr, PtrLoc, PFS) || - ParseOptionalCommaAlignment(Alignment)) + ParseTypeAndValue(Ptr, PtrLoc, PFS)) return true; - + + if (EatIfPresent(lltok::comma)) + if (ParseOptionalInfo(Alignment)) return true; + if (!isa<PointerType>(Ptr->getType())) return Error(PtrLoc, "store operand must be a pointer"); if (!Val->getType()->isFirstClassType()) return Error(Loc, "store operand must be a first class value"); if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) return Error(Loc, "stored value and pointer type do not match"); - + Inst = new StoreInst(Val, Ptr, isVolatile, Alignment); return false; } @@ -3247,7 +3532,7 @@ bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after getresult operand") || ParseUInt32(Element, EltLoc)) return true; - + if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) return Error(ValLoc, "getresult inst requires an aggregate operand"); if (!ExtractValueInst::getIndexedType(Val->getType(), Element)) @@ -3257,26 +3542,35 @@ bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) { } /// ParseGetElementPtr -/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)* +/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { Value *Ptr, *Val; LocTy Loc, EltLoc; + + bool InBounds = EatIfPresent(lltok::kw_inbounds); + if (ParseTypeAndValue(Ptr, Loc, PFS)) return true; - + if (!isa<PointerType>(Ptr->getType())) return Error(Loc, "base of getelementptr must be a pointer"); - + SmallVector<Value*, 16> Indices; while (EatIfPresent(lltok::comma)) { + if (Lex.getKind() == lltok::NamedOrCustomMD) + break; if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; if (!isa<IntegerType>(Val->getType())) return Error(EltLoc, "getelementptr index must be an integer"); Indices.push_back(Val); } - + if (Lex.getKind() == lltok::NamedOrCustomMD) + if (ParseOptionalCustomMetadata()) return true; + if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices.begin(), Indices.end())) return Error(Loc, "invalid getelementptr indices"); Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end()); + if (InBounds) + cast<GetElementPtrInst>(Inst)->setIsInBounds(true); return false; } @@ -3309,10 +3603,10 @@ bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { ParseTypeAndValue(Val1, Loc1, PFS) || ParseIndexList(Indices)) return true; - + if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType())) return Error(Loc0, "extractvalue operand must be array or struct"); - + if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), Indices.end())) return Error(Loc0, "invalid indices for insertvalue"); @@ -3332,14 +3626,28 @@ bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) { assert(Lex.getKind() == lltok::lbrace); Lex.Lex(); do { - Value *V; + Value *V = 0; if (Lex.getKind() == lltok::kw_null) { Lex.Lex(); V = 0; } else { - Constant *C; - if (ParseGlobalTypeAndValue(C)) return true; - V = C; + PATypeHolder Ty(Type::getVoidTy(Context)); + if (ParseType(Ty)) return true; + if (Lex.getKind() == lltok::Metadata) { + Lex.Lex(); + MetadataBase *Node = 0; + if (!ParseMDNode(Node)) + V = Node; + else { + MetadataBase *MDS = 0; + if (ParseMDString(MDS)) return true; + V = MDS; + } + } else { + Constant *C; + if (ParseGlobalValue(Ty, C)) return true; + V = C; + } } Elts.push_back(V); } while (EatIfPresent(lltok::comma)); diff --git a/lib/AsmParser/LLParser.h b/lib/AsmParser/LLParser.h index 6659620..97bf2f3 100644 --- a/lib/AsmParser/LLParser.h +++ b/lib/AsmParser/LLParser.h @@ -28,6 +28,7 @@ namespace llvm { class Instruction; class Constant; class GlobalValue; + class MetadataBase; class MDString; class MDNode; struct ValID; @@ -45,7 +46,9 @@ namespace llvm { std::map<unsigned, std::pair<PATypeHolder, LocTy> > ForwardRefTypeIDs; std::vector<PATypeHolder> NumberedTypes; /// MetadataCache - This map keeps track of parsed metadata constants. - std::map<unsigned, Constant *> MetadataCache; + std::map<unsigned, MetadataBase *> MetadataCache; + std::map<unsigned, std::pair<MetadataBase *, LocTy> > ForwardRefMDNodes; + SmallVector<std::pair<unsigned, MDNode *>, 2> MDsOnInst; struct UpRefRecord { /// Loc - This is the location of the upref. LocTy Loc; @@ -74,7 +77,7 @@ namespace llvm { std::vector<GlobalValue*> NumberedVals; public: LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) : - Context(m->getContext()), Lex(F, SM, Err), M(m) {} + Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m) {} bool Run(); LLVMContext& getContext() { return Context; } @@ -123,9 +126,10 @@ namespace llvm { bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage); } bool ParseOptionalVisibility(unsigned &Visibility); - bool ParseOptionalCallingConv(unsigned &CC); + bool ParseOptionalCallingConv(CallingConv::ID &CC); bool ParseOptionalAlignment(unsigned &Alignment); - bool ParseOptionalCommaAlignment(unsigned &Alignment); + bool ParseOptionalCustomMetadata(); + bool ParseOptionalInfo(unsigned &Alignment); bool ParseIndexList(SmallVectorImpl<unsigned> &Indices); // Top-Level Entities @@ -140,11 +144,15 @@ namespace llvm { bool ParseDefine(); bool ParseGlobalType(bool &IsConstant); + bool ParseUnnamedGlobal(); bool ParseNamedGlobal(); bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage, bool HasLinkage, unsigned Visibility); bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility); bool ParseStandaloneMetadata(); + bool ParseNamedMetadata(); + bool ParseMDString(MetadataBase *&S); + bool ParseMDNode(MetadataBase *&N); // Type Parsing. bool ParseType(PATypeHolder &Result, bool AllowVoid = false); diff --git a/lib/AsmParser/LLToken.h b/lib/AsmParser/LLToken.h index cff89f8..b3c59ee 100644 --- a/lib/AsmParser/LLToken.h +++ b/lib/AsmParser/LLToken.h @@ -36,8 +36,9 @@ namespace lltok { kw_declare, kw_define, kw_global, kw_constant, - kw_private, kw_internal, kw_linkonce, kw_linkonce_odr, kw_weak, kw_weak_odr, - kw_appending, kw_dllimport, kw_dllexport, kw_common,kw_available_externally, + kw_private, kw_linker_private, kw_internal, kw_linkonce, kw_linkonce_odr, + kw_weak, kw_weak_odr, kw_appending, kw_dllimport, kw_dllexport, kw_common, + kw_available_externally, kw_default, kw_hidden, kw_protected, kw_extern_weak, kw_external, kw_thread_local, @@ -50,6 +51,10 @@ namespace lltok { kw_deplibs, kw_datalayout, kw_volatile, + kw_nuw, + kw_nsw, + kw_exact, + kw_inbounds, kw_align, kw_addrspace, kw_section, @@ -57,7 +62,9 @@ namespace lltok { kw_module, kw_asm, kw_sideeffect, + kw_msasm, kw_gc, + kw_dbg, kw_c, kw_cc, kw_ccc, kw_fastcc, kw_coldcc, @@ -77,6 +84,7 @@ namespace lltok { kw_readnone, kw_readonly, + kw_inlinehint, kw_noinline, kw_alwaysinline, kw_optsize, @@ -84,6 +92,7 @@ namespace lltok { kw_sspreq, kw_noredzone, kw_noimplicitfloat, + kw_naked, kw_type, kw_opaque, @@ -96,7 +105,7 @@ namespace lltok { kw_add, kw_fadd, kw_sub, kw_fsub, kw_mul, kw_fmul, kw_udiv, kw_sdiv, kw_fdiv, kw_urem, kw_srem, kw_frem, kw_shl, kw_lshr, kw_ashr, - kw_and, kw_or, kw_xor, kw_icmp, kw_fcmp, kw_vicmp, kw_vfcmp, + kw_and, kw_or, kw_xor, kw_icmp, kw_fcmp, kw_phi, kw_call, kw_trunc, kw_zext, kw_sext, kw_fptrunc, kw_fpext, kw_uitofp, kw_sitofp, @@ -119,6 +128,7 @@ namespace lltok { GlobalVar, // @foo @"foo" LocalVar, // %foo %"foo" StringConstant, // "foo" + NamedOrCustomMD, // !foo // Metadata valued tokens. Metadata, // !"foo" !{i8 42} diff --git a/lib/AsmParser/Parser.cpp b/lib/AsmParser/Parser.cpp index d66c13d..331a233 100644 --- a/lib/AsmParser/Parser.cpp +++ b/lib/AsmParser/Parser.cpp @@ -21,6 +21,24 @@ #include <cstring> using namespace llvm; +Module *llvm::ParseAssembly(MemoryBuffer *F, + Module *M, + SMDiagnostic &Err, + LLVMContext &Context) { + SourceMgr SM; + SM.AddNewSourceBuffer(F, SMLoc()); + + // If we are parsing into an existing module, do it. + if (M) + return LLParser(F, SM, Err, M).Run() ? 0 : M; + + // Otherwise create a new module. + OwningPtr<Module> M2(new Module(F->getBufferIdentifier(), Context)); + if (LLParser(F, SM, Err, M2.get()).Run()) + return 0; + return M2.take(); +} + Module *llvm::ParseAssemblyFile(const std::string &Filename, SMDiagnostic &Err, LLVMContext &Context) { std::string ErrorStr; @@ -31,13 +49,7 @@ Module *llvm::ParseAssemblyFile(const std::string &Filename, SMDiagnostic &Err, return 0; } - SourceMgr SM; - SM.AddNewSourceBuffer(F, SMLoc()); - - OwningPtr<Module> M(new Module(Filename, Context)); - if (LLParser(F, SM, Err, M.get()).Run()) - return 0; - return M.take(); + return ParseAssembly(F, 0, Err, Context); } Module *llvm::ParseAssemblyString(const char *AsmString, Module *M, @@ -45,17 +57,6 @@ Module *llvm::ParseAssemblyString(const char *AsmString, Module *M, MemoryBuffer *F = MemoryBuffer::getMemBuffer(AsmString, AsmString+strlen(AsmString), "<string>"); - - SourceMgr SM; - SM.AddNewSourceBuffer(F, SMLoc()); - // If we are parsing into an existing module, do it. - if (M) - return LLParser(F, SM, Err, M).Run() ? 0 : M; - - // Otherwise create a new module. - OwningPtr<Module> M2(new Module("<string>", Context)); - if (LLParser(F, SM, Err, M2.get()).Run()) - return 0; - return M2.take(); + return ParseAssembly(F, M, Err, Context); } |