1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
32 /// ValID - Represents a reference of a definition of some sort with no type.
33 /// There are several cases where we have to parse the value but where the
34 /// type can depend on later context. This may either be a numeric reference
35 /// or a symbolic (%var) reference. This is just a discriminated union.
38 t_LocalID, t_GlobalID, // ID in UIntVal.
39 t_LocalName, t_GlobalName, // Name in StrVal.
40 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
41 t_Null, t_Undef, t_Zero, // No value.
42 t_EmptyArray, // No value: []
43 t_Constant, // Value in ConstantVal.
44 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
49 std::string StrVal, StrVal2;
52 Constant *ConstantVal;
53 ValID() : APFloatVal(0.0) {}
57 /// Run: module ::= toplevelentity*
58 bool LLParser::Run() {
62 return ParseTopLevelEntities() ||
63 ValidateEndOfModule();
66 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
68 bool LLParser::ValidateEndOfModule() {
69 if (!ForwardRefTypes.empty())
70 return Error(ForwardRefTypes.begin()->second.second,
71 "use of undefined type named '" +
72 ForwardRefTypes.begin()->first + "'");
73 if (!ForwardRefTypeIDs.empty())
74 return Error(ForwardRefTypeIDs.begin()->second.second,
75 "use of undefined type '%" +
76 utostr(ForwardRefTypeIDs.begin()->first) + "'");
78 if (!ForwardRefVals.empty())
79 return Error(ForwardRefVals.begin()->second.second,
80 "use of undefined value '@" + ForwardRefVals.begin()->first +
83 if (!ForwardRefValIDs.empty())
84 return Error(ForwardRefValIDs.begin()->second.second,
85 "use of undefined value '@" +
86 utostr(ForwardRefValIDs.begin()->first) + "'");
88 if (!ForwardRefMDNodes.empty())
89 return Error(ForwardRefMDNodes.begin()->second.second,
90 "use of undefined metadata '!" +
91 utostr(ForwardRefMDNodes.begin()->first) + "'");
94 // Look for intrinsic functions and CallInst that need to be upgraded
95 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
96 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
101 //===----------------------------------------------------------------------===//
102 // Top-Level Entities
103 //===----------------------------------------------------------------------===//
105 bool LLParser::ParseTopLevelEntities() {
107 switch (Lex.getKind()) {
108 default: return TokError("expected top-level entity");
109 case lltok::Eof: return false;
110 //case lltok::kw_define:
111 case lltok::kw_declare: if (ParseDeclare()) return true; break;
112 case lltok::kw_define: if (ParseDefine()) return true; break;
113 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
114 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
115 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
116 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
117 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
118 case lltok::LocalVar: if (ParseNamedType()) return true; break;
119 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
120 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
122 // The Global variable production with no name can have many different
123 // optional leading prefixes, the production is:
124 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
125 // OptionalAddrSpace ('constant'|'global') ...
126 case lltok::kw_private : // OptionalLinkage
127 case lltok::kw_linker_private: // OptionalLinkage
128 case lltok::kw_internal: // OptionalLinkage
129 case lltok::kw_weak: // OptionalLinkage
130 case lltok::kw_weak_odr: // OptionalLinkage
131 case lltok::kw_linkonce: // OptionalLinkage
132 case lltok::kw_linkonce_odr: // OptionalLinkage
133 case lltok::kw_appending: // OptionalLinkage
134 case lltok::kw_dllexport: // OptionalLinkage
135 case lltok::kw_common: // OptionalLinkage
136 case lltok::kw_dllimport: // OptionalLinkage
137 case lltok::kw_extern_weak: // OptionalLinkage
138 case lltok::kw_external: { // OptionalLinkage
139 unsigned Linkage, Visibility;
140 if (ParseOptionalLinkage(Linkage) ||
141 ParseOptionalVisibility(Visibility) ||
142 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
146 case lltok::kw_default: // OptionalVisibility
147 case lltok::kw_hidden: // OptionalVisibility
148 case lltok::kw_protected: { // OptionalVisibility
150 if (ParseOptionalVisibility(Visibility) ||
151 ParseGlobal("", SMLoc(), 0, false, Visibility))
156 case lltok::kw_thread_local: // OptionalThreadLocal
157 case lltok::kw_addrspace: // OptionalAddrSpace
158 case lltok::kw_constant: // GlobalType
159 case lltok::kw_global: // GlobalType
160 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
168 /// ::= 'module' 'asm' STRINGCONSTANT
169 bool LLParser::ParseModuleAsm() {
170 assert(Lex.getKind() == lltok::kw_module);
174 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
175 ParseStringConstant(AsmStr)) return true;
177 const std::string &AsmSoFar = M->getModuleInlineAsm();
178 if (AsmSoFar.empty())
179 M->setModuleInlineAsm(AsmStr);
181 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
186 /// ::= 'target' 'triple' '=' STRINGCONSTANT
187 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
188 bool LLParser::ParseTargetDefinition() {
189 assert(Lex.getKind() == lltok::kw_target);
192 default: return TokError("unknown target property");
193 case lltok::kw_triple:
195 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
196 ParseStringConstant(Str))
198 M->setTargetTriple(Str);
200 case lltok::kw_datalayout:
202 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
203 ParseStringConstant(Str))
205 M->setDataLayout(Str);
211 /// ::= 'deplibs' '=' '[' ']'
212 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
213 bool LLParser::ParseDepLibs() {
214 assert(Lex.getKind() == lltok::kw_deplibs);
216 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
217 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
220 if (EatIfPresent(lltok::rsquare))
224 if (ParseStringConstant(Str)) return true;
227 while (EatIfPresent(lltok::comma)) {
228 if (ParseStringConstant(Str)) return true;
232 return ParseToken(lltok::rsquare, "expected ']' at end of list");
237 bool LLParser::ParseUnnamedType() {
238 assert(Lex.getKind() == lltok::kw_type);
239 LocTy TypeLoc = Lex.getLoc();
240 Lex.Lex(); // eat kw_type
242 PATypeHolder Ty(Type::VoidTy);
243 if (ParseType(Ty)) return true;
245 unsigned TypeID = NumberedTypes.size();
247 // See if this type was previously referenced.
248 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
249 FI = ForwardRefTypeIDs.find(TypeID);
250 if (FI != ForwardRefTypeIDs.end()) {
251 if (FI->second.first.get() == Ty)
252 return Error(TypeLoc, "self referential type is invalid");
254 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
255 Ty = FI->second.first.get();
256 ForwardRefTypeIDs.erase(FI);
259 NumberedTypes.push_back(Ty);
265 /// ::= LocalVar '=' 'type' type
266 bool LLParser::ParseNamedType() {
267 std::string Name = Lex.getStrVal();
268 LocTy NameLoc = Lex.getLoc();
269 Lex.Lex(); // eat LocalVar.
271 PATypeHolder Ty(Type::VoidTy);
273 if (ParseToken(lltok::equal, "expected '=' after name") ||
274 ParseToken(lltok::kw_type, "expected 'type' after name") ||
278 // Set the type name, checking for conflicts as we do so.
279 bool AlreadyExists = M->addTypeName(Name, Ty);
280 if (!AlreadyExists) return false;
282 // See if this type is a forward reference. We need to eagerly resolve
283 // types to allow recursive type redefinitions below.
284 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
285 FI = ForwardRefTypes.find(Name);
286 if (FI != ForwardRefTypes.end()) {
287 if (FI->second.first.get() == Ty)
288 return Error(NameLoc, "self referential type is invalid");
290 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
291 Ty = FI->second.first.get();
292 ForwardRefTypes.erase(FI);
295 // Inserting a name that is already defined, get the existing name.
296 const Type *Existing = M->getTypeByName(Name);
297 assert(Existing && "Conflict but no matching type?!");
299 // Otherwise, this is an attempt to redefine a type. That's okay if
300 // the redefinition is identical to the original.
301 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
302 if (Existing == Ty) return false;
304 // Any other kind of (non-equivalent) redefinition is an error.
305 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
306 Ty->getDescription() + "'");
311 /// ::= 'declare' FunctionHeader
312 bool LLParser::ParseDeclare() {
313 assert(Lex.getKind() == lltok::kw_declare);
317 return ParseFunctionHeader(F, false);
321 /// ::= 'define' FunctionHeader '{' ...
322 bool LLParser::ParseDefine() {
323 assert(Lex.getKind() == lltok::kw_define);
327 return ParseFunctionHeader(F, true) ||
328 ParseFunctionBody(*F);
334 bool LLParser::ParseGlobalType(bool &IsConstant) {
335 if (Lex.getKind() == lltok::kw_constant)
337 else if (Lex.getKind() == lltok::kw_global)
341 return TokError("expected 'global' or 'constant'");
347 /// ParseNamedGlobal:
348 /// GlobalVar '=' OptionalVisibility ALIAS ...
349 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
350 bool LLParser::ParseNamedGlobal() {
351 assert(Lex.getKind() == lltok::GlobalVar);
352 LocTy NameLoc = Lex.getLoc();
353 std::string Name = Lex.getStrVal();
357 unsigned Linkage, Visibility;
358 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
359 ParseOptionalLinkage(Linkage, HasLinkage) ||
360 ParseOptionalVisibility(Visibility))
363 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
364 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
365 return ParseAlias(Name, NameLoc, Visibility);
369 // ::= '!' STRINGCONSTANT
370 bool LLParser::ParseMDString(Constant *&MDS) {
372 if (ParseStringConstant(Str)) return true;
373 MDS = Context.getMDString(Str.data(), Str.data() + Str.size());
378 // ::= '!' MDNodeNumber
379 bool LLParser::ParseMDNode(Constant *&Node) {
380 // !{ ..., !42, ... }
382 if (ParseUInt32(MID)) return true;
384 // Check existing MDNode.
385 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
386 if (I != MetadataCache.end()) {
391 // Check known forward references.
392 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
393 FI = ForwardRefMDNodes.find(MID);
394 if (FI != ForwardRefMDNodes.end()) {
395 Node = FI->second.first;
399 // Create MDNode forward reference
400 SmallVector<Value *, 1> Elts;
401 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
402 Elts.push_back(Context.getMDString(FwdRefName));
403 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
404 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
409 /// ParseStandaloneMetadata:
411 bool LLParser::ParseStandaloneMetadata() {
412 assert(Lex.getKind() == lltok::Metadata);
414 unsigned MetadataID = 0;
415 if (ParseUInt32(MetadataID))
417 if (MetadataCache.find(MetadataID) != MetadataCache.end())
418 return TokError("Metadata id is already used");
419 if (ParseToken(lltok::equal, "expected '=' here"))
423 PATypeHolder Ty(Type::VoidTy);
424 if (ParseType(Ty, TyLoc))
428 if (ParseGlobalValue(Ty, Init))
431 MetadataCache[MetadataID] = Init;
432 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
433 FI = ForwardRefMDNodes.find(MetadataID);
434 if (FI != ForwardRefMDNodes.end()) {
435 Constant *FwdNode = FI->second.first;
436 FwdNode->replaceAllUsesWith(Init);
437 ForwardRefMDNodes.erase(FI);
444 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
447 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
448 /// ::= 'getelementptr' '(' ... ')'
450 /// Everything through visibility has already been parsed.
452 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
453 unsigned Visibility) {
454 assert(Lex.getKind() == lltok::kw_alias);
457 LocTy LinkageLoc = Lex.getLoc();
458 if (ParseOptionalLinkage(Linkage))
461 if (Linkage != GlobalValue::ExternalLinkage &&
462 Linkage != GlobalValue::WeakAnyLinkage &&
463 Linkage != GlobalValue::WeakODRLinkage &&
464 Linkage != GlobalValue::InternalLinkage &&
465 Linkage != GlobalValue::PrivateLinkage &&
466 Linkage != GlobalValue::LinkerPrivateLinkage)
467 return Error(LinkageLoc, "invalid linkage type for alias");
470 LocTy AliaseeLoc = Lex.getLoc();
471 if (Lex.getKind() != lltok::kw_bitcast &&
472 Lex.getKind() != lltok::kw_getelementptr) {
473 if (ParseGlobalTypeAndValue(Aliasee)) return true;
475 // The bitcast dest type is not present, it is implied by the dest type.
477 if (ParseValID(ID)) return true;
478 if (ID.Kind != ValID::t_Constant)
479 return Error(AliaseeLoc, "invalid aliasee");
480 Aliasee = ID.ConstantVal;
483 if (!isa<PointerType>(Aliasee->getType()))
484 return Error(AliaseeLoc, "alias must have pointer type");
486 // Okay, create the alias but do not insert it into the module yet.
487 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
488 (GlobalValue::LinkageTypes)Linkage, Name,
490 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
492 // See if this value already exists in the symbol table. If so, it is either
493 // a redefinition or a definition of a forward reference.
494 if (GlobalValue *Val =
495 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
496 // See if this was a redefinition. If so, there is no entry in
498 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
499 I = ForwardRefVals.find(Name);
500 if (I == ForwardRefVals.end())
501 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
503 // Otherwise, this was a definition of forward ref. Verify that types
505 if (Val->getType() != GA->getType())
506 return Error(NameLoc,
507 "forward reference and definition of alias have different types");
509 // If they agree, just RAUW the old value with the alias and remove the
511 Val->replaceAllUsesWith(GA);
512 Val->eraseFromParent();
513 ForwardRefVals.erase(I);
516 // Insert into the module, we know its name won't collide now.
517 M->getAliasList().push_back(GA);
518 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
524 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
525 /// OptionalAddrSpace GlobalType Type Const
526 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
527 /// OptionalAddrSpace GlobalType Type Const
529 /// Everything through visibility has been parsed already.
531 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
532 unsigned Linkage, bool HasLinkage,
533 unsigned Visibility) {
535 bool ThreadLocal, IsConstant;
538 PATypeHolder Ty(Type::VoidTy);
539 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
540 ParseOptionalAddrSpace(AddrSpace) ||
541 ParseGlobalType(IsConstant) ||
542 ParseType(Ty, TyLoc))
545 // If the linkage is specified and is external, then no initializer is
548 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
549 Linkage != GlobalValue::ExternalWeakLinkage &&
550 Linkage != GlobalValue::ExternalLinkage)) {
551 if (ParseGlobalValue(Ty, Init))
555 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
556 return Error(TyLoc, "invalid type for global variable");
558 GlobalVariable *GV = 0;
560 // See if the global was forward referenced, if so, use the global.
562 if ((GV = M->getGlobalVariable(Name, true)) &&
563 !ForwardRefVals.erase(Name))
564 return Error(NameLoc, "redefinition of global '@" + Name + "'");
566 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
567 I = ForwardRefValIDs.find(NumberedVals.size());
568 if (I != ForwardRefValIDs.end()) {
569 GV = cast<GlobalVariable>(I->second.first);
570 ForwardRefValIDs.erase(I);
575 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
576 Name, 0, false, AddrSpace);
578 if (GV->getType()->getElementType() != Ty)
580 "forward reference and definition of global have different types");
582 // Move the forward-reference to the correct spot in the module.
583 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
587 NumberedVals.push_back(GV);
589 // Set the parsed properties on the global.
591 GV->setInitializer(Init);
592 GV->setConstant(IsConstant);
593 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
594 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
595 GV->setThreadLocal(ThreadLocal);
597 // Parse attributes on the global.
598 while (Lex.getKind() == lltok::comma) {
601 if (Lex.getKind() == lltok::kw_section) {
603 GV->setSection(Lex.getStrVal());
604 if (ParseToken(lltok::StringConstant, "expected global section string"))
606 } else if (Lex.getKind() == lltok::kw_align) {
608 if (ParseOptionalAlignment(Alignment)) return true;
609 GV->setAlignment(Alignment);
611 TokError("unknown global variable property!");
619 //===----------------------------------------------------------------------===//
620 // GlobalValue Reference/Resolution Routines.
621 //===----------------------------------------------------------------------===//
623 /// GetGlobalVal - Get a value with the specified name or ID, creating a
624 /// forward reference record if needed. This can return null if the value
625 /// exists but does not have the right type.
626 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
628 const PointerType *PTy = dyn_cast<PointerType>(Ty);
630 Error(Loc, "global variable reference must have pointer type");
634 // Look this name up in the normal function symbol table.
636 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
638 // If this is a forward reference for the value, see if we already created a
639 // forward ref record.
641 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
642 I = ForwardRefVals.find(Name);
643 if (I != ForwardRefVals.end())
644 Val = I->second.first;
647 // If we have the value in the symbol table or fwd-ref table, return it.
649 if (Val->getType() == Ty) return Val;
650 Error(Loc, "'@" + Name + "' defined with type '" +
651 Val->getType()->getDescription() + "'");
655 // Otherwise, create a new forward reference for this value and remember it.
657 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
658 // Function types can return opaque but functions can't.
659 if (isa<OpaqueType>(FT->getReturnType())) {
660 Error(Loc, "function may not return opaque type");
664 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
666 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
667 GlobalValue::ExternalWeakLinkage, 0, Name);
670 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
674 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
675 const PointerType *PTy = dyn_cast<PointerType>(Ty);
677 Error(Loc, "global variable reference must have pointer type");
681 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
683 // If this is a forward reference for the value, see if we already created a
684 // forward ref record.
686 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefValIDs.find(ID);
688 if (I != ForwardRefValIDs.end())
689 Val = I->second.first;
692 // If we have the value in the symbol table or fwd-ref table, return it.
694 if (Val->getType() == Ty) return Val;
695 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
696 Val->getType()->getDescription() + "'");
700 // Otherwise, create a new forward reference for this value and remember it.
702 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
703 // Function types can return opaque but functions can't.
704 if (isa<OpaqueType>(FT->getReturnType())) {
705 Error(Loc, "function may not return opaque type");
708 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
710 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
711 GlobalValue::ExternalWeakLinkage, 0, "");
714 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
719 //===----------------------------------------------------------------------===//
721 //===----------------------------------------------------------------------===//
723 /// ParseToken - If the current token has the specified kind, eat it and return
724 /// success. Otherwise, emit the specified error and return failure.
725 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
726 if (Lex.getKind() != T)
727 return TokError(ErrMsg);
732 /// ParseStringConstant
733 /// ::= StringConstant
734 bool LLParser::ParseStringConstant(std::string &Result) {
735 if (Lex.getKind() != lltok::StringConstant)
736 return TokError("expected string constant");
737 Result = Lex.getStrVal();
744 bool LLParser::ParseUInt32(unsigned &Val) {
745 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
746 return TokError("expected integer");
747 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
748 if (Val64 != unsigned(Val64))
749 return TokError("expected 32-bit integer (too large)");
756 /// ParseOptionalAddrSpace
758 /// := 'addrspace' '(' uint32 ')'
759 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
761 if (!EatIfPresent(lltok::kw_addrspace))
763 return ParseToken(lltok::lparen, "expected '(' in address space") ||
764 ParseUInt32(AddrSpace) ||
765 ParseToken(lltok::rparen, "expected ')' in address space");
768 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
769 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
770 /// 2: function attr.
771 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
772 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
773 Attrs = Attribute::None;
774 LocTy AttrLoc = Lex.getLoc();
777 switch (Lex.getKind()) {
780 // Treat these as signext/zeroext if they occur in the argument list after
781 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
782 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
784 // FIXME: REMOVE THIS IN LLVM 3.0
786 if (Lex.getKind() == lltok::kw_sext)
787 Attrs |= Attribute::SExt;
789 Attrs |= Attribute::ZExt;
793 default: // End of attributes.
794 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
795 return Error(AttrLoc, "invalid use of function-only attribute");
797 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
798 return Error(AttrLoc, "invalid use of parameter-only attribute");
801 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
802 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
803 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
804 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
805 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
806 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
807 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
808 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
810 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
811 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
812 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
813 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
814 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
815 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
816 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
817 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
818 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
819 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
820 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
821 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
823 case lltok::kw_align: {
825 if (ParseOptionalAlignment(Alignment))
827 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
835 /// ParseOptionalLinkage
838 /// ::= 'linker_private'
843 /// ::= 'linkonce_odr'
848 /// ::= 'extern_weak'
850 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
852 switch (Lex.getKind()) {
853 default: Res=GlobalValue::ExternalLinkage; return false;
854 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
855 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
856 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
857 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
858 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
859 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
860 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
861 case lltok::kw_available_externally:
862 Res = GlobalValue::AvailableExternallyLinkage;
864 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
865 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
866 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
867 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
868 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
869 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
876 /// ParseOptionalVisibility
882 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
883 switch (Lex.getKind()) {
884 default: Res = GlobalValue::DefaultVisibility; return false;
885 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
886 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
887 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
893 /// ParseOptionalCallingConv
898 /// ::= 'x86_stdcallcc'
899 /// ::= 'x86_fastcallcc'
901 /// ::= 'arm_aapcscc'
902 /// ::= 'arm_aapcs_vfpcc'
905 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
906 switch (Lex.getKind()) {
907 default: CC = CallingConv::C; return false;
908 case lltok::kw_ccc: CC = CallingConv::C; break;
909 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
910 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
911 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
912 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
913 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
914 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
915 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
916 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
922 /// ParseOptionalAlignment
925 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
927 if (!EatIfPresent(lltok::kw_align))
929 LocTy AlignLoc = Lex.getLoc();
930 if (ParseUInt32(Alignment)) return true;
931 if (!isPowerOf2_32(Alignment))
932 return Error(AlignLoc, "alignment is not a power of two");
936 /// ParseOptionalCommaAlignment
938 /// ::= ',' 'align' 4
939 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
941 if (!EatIfPresent(lltok::comma))
943 return ParseToken(lltok::kw_align, "expected 'align'") ||
944 ParseUInt32(Alignment);
948 /// ::= (',' uint32)+
949 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
950 if (Lex.getKind() != lltok::comma)
951 return TokError("expected ',' as start of index list");
953 while (EatIfPresent(lltok::comma)) {
955 if (ParseUInt32(Idx)) return true;
956 Indices.push_back(Idx);
962 //===----------------------------------------------------------------------===//
964 //===----------------------------------------------------------------------===//
966 /// ParseType - Parse and resolve a full type.
967 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
968 LocTy TypeLoc = Lex.getLoc();
969 if (ParseTypeRec(Result)) return true;
971 // Verify no unresolved uprefs.
973 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
975 if (!AllowVoid && Result.get() == Type::VoidTy)
976 return Error(TypeLoc, "void type only allowed for function results");
981 /// HandleUpRefs - Every time we finish a new layer of types, this function is
982 /// called. It loops through the UpRefs vector, which is a list of the
983 /// currently active types. For each type, if the up-reference is contained in
984 /// the newly completed type, we decrement the level count. When the level
985 /// count reaches zero, the up-referenced type is the type that is passed in:
986 /// thus we can complete the cycle.
988 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
989 // If Ty isn't abstract, or if there are no up-references in it, then there is
990 // nothing to resolve here.
991 if (!ty->isAbstract() || UpRefs.empty()) return ty;
995 errs() << "Type '" << Ty->getDescription()
996 << "' newly formed. Resolving upreferences.\n"
997 << UpRefs.size() << " upreferences active!\n";
1000 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1001 // to zero), we resolve them all together before we resolve them to Ty. At
1002 // the end of the loop, if there is anything to resolve to Ty, it will be in
1004 OpaqueType *TypeToResolve = 0;
1006 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1007 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1009 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1010 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1013 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1014 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1015 << (ContainsType ? "true" : "false")
1016 << " level=" << UpRefs[i].NestingLevel << "\n";
1021 // Decrement level of upreference
1022 unsigned Level = --UpRefs[i].NestingLevel;
1023 UpRefs[i].LastContainedTy = Ty;
1025 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1030 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1033 TypeToResolve = UpRefs[i].UpRefTy;
1035 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1036 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1037 --i; // Do not skip the next element.
1041 TypeToResolve->refineAbstractTypeTo(Ty);
1047 /// ParseTypeRec - The recursive function used to process the internal
1048 /// implementation details of types.
1049 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1050 switch (Lex.getKind()) {
1052 return TokError("expected type");
1054 // TypeRec ::= 'float' | 'void' (etc)
1055 Result = Lex.getTyVal();
1058 case lltok::kw_opaque:
1059 // TypeRec ::= 'opaque'
1060 Result = Context.getOpaqueType();
1064 // TypeRec ::= '{' ... '}'
1065 if (ParseStructType(Result, false))
1068 case lltok::lsquare:
1069 // TypeRec ::= '[' ... ']'
1070 Lex.Lex(); // eat the lsquare.
1071 if (ParseArrayVectorType(Result, false))
1074 case lltok::less: // Either vector or packed struct.
1075 // TypeRec ::= '<' ... '>'
1077 if (Lex.getKind() == lltok::lbrace) {
1078 if (ParseStructType(Result, true) ||
1079 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1081 } else if (ParseArrayVectorType(Result, true))
1084 case lltok::LocalVar:
1085 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1087 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1090 Result = Context.getOpaqueType();
1091 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1092 std::make_pair(Result,
1094 M->addTypeName(Lex.getStrVal(), Result.get());
1099 case lltok::LocalVarID:
1101 if (Lex.getUIntVal() < NumberedTypes.size())
1102 Result = NumberedTypes[Lex.getUIntVal()];
1104 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1105 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1106 if (I != ForwardRefTypeIDs.end())
1107 Result = I->second.first;
1109 Result = Context.getOpaqueType();
1110 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1111 std::make_pair(Result,
1117 case lltok::backslash: {
1118 // TypeRec ::= '\' 4
1121 if (ParseUInt32(Val)) return true;
1122 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1123 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1129 // Parse the type suffixes.
1131 switch (Lex.getKind()) {
1133 default: return false;
1135 // TypeRec ::= TypeRec '*'
1137 if (Result.get() == Type::LabelTy)
1138 return TokError("basic block pointers are invalid");
1139 if (Result.get() == Type::VoidTy)
1140 return TokError("pointers to void are invalid; use i8* instead");
1141 if (!PointerType::isValidElementType(Result.get()))
1142 return TokError("pointer to this type is invalid");
1143 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1147 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1148 case lltok::kw_addrspace: {
1149 if (Result.get() == Type::LabelTy)
1150 return TokError("basic block pointers are invalid");
1151 if (Result.get() == Type::VoidTy)
1152 return TokError("pointers to void are invalid; use i8* instead");
1153 if (!PointerType::isValidElementType(Result.get()))
1154 return TokError("pointer to this type is invalid");
1156 if (ParseOptionalAddrSpace(AddrSpace) ||
1157 ParseToken(lltok::star, "expected '*' in address space"))
1160 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1164 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1166 if (ParseFunctionType(Result))
1173 /// ParseParameterList
1175 /// ::= '(' Arg (',' Arg)* ')'
1177 /// ::= Type OptionalAttributes Value OptionalAttributes
1178 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1179 PerFunctionState &PFS) {
1180 if (ParseToken(lltok::lparen, "expected '(' in call"))
1183 while (Lex.getKind() != lltok::rparen) {
1184 // If this isn't the first argument, we need a comma.
1185 if (!ArgList.empty() &&
1186 ParseToken(lltok::comma, "expected ',' in argument list"))
1189 // Parse the argument.
1191 PATypeHolder ArgTy(Type::VoidTy);
1192 unsigned ArgAttrs1, ArgAttrs2;
1194 if (ParseType(ArgTy, ArgLoc) ||
1195 ParseOptionalAttrs(ArgAttrs1, 0) ||
1196 ParseValue(ArgTy, V, PFS) ||
1197 // FIXME: Should not allow attributes after the argument, remove this in
1199 ParseOptionalAttrs(ArgAttrs2, 3))
1201 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1204 Lex.Lex(); // Lex the ')'.
1210 /// ParseArgumentList - Parse the argument list for a function type or function
1211 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1212 /// ::= '(' ArgTypeListI ')'
1216 /// ::= ArgTypeList ',' '...'
1217 /// ::= ArgType (',' ArgType)*
1219 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1220 bool &isVarArg, bool inType) {
1222 assert(Lex.getKind() == lltok::lparen);
1223 Lex.Lex(); // eat the (.
1225 if (Lex.getKind() == lltok::rparen) {
1227 } else if (Lex.getKind() == lltok::dotdotdot) {
1231 LocTy TypeLoc = Lex.getLoc();
1232 PATypeHolder ArgTy(Type::VoidTy);
1236 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1237 // types (such as a function returning a pointer to itself). If parsing a
1238 // function prototype, we require fully resolved types.
1239 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1240 ParseOptionalAttrs(Attrs, 0)) return true;
1242 if (ArgTy == Type::VoidTy)
1243 return Error(TypeLoc, "argument can not have void type");
1245 if (Lex.getKind() == lltok::LocalVar ||
1246 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1247 Name = Lex.getStrVal();
1251 if (!FunctionType::isValidArgumentType(ArgTy))
1252 return Error(TypeLoc, "invalid type for function argument");
1254 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1256 while (EatIfPresent(lltok::comma)) {
1257 // Handle ... at end of arg list.
1258 if (EatIfPresent(lltok::dotdotdot)) {
1263 // Otherwise must be an argument type.
1264 TypeLoc = Lex.getLoc();
1265 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1266 ParseOptionalAttrs(Attrs, 0)) return true;
1268 if (ArgTy == Type::VoidTy)
1269 return Error(TypeLoc, "argument can not have void type");
1271 if (Lex.getKind() == lltok::LocalVar ||
1272 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1273 Name = Lex.getStrVal();
1279 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1280 return Error(TypeLoc, "invalid type for function argument");
1282 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1286 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1289 /// ParseFunctionType
1290 /// ::= Type ArgumentList OptionalAttrs
1291 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1292 assert(Lex.getKind() == lltok::lparen);
1294 if (!FunctionType::isValidReturnType(Result))
1295 return TokError("invalid function return type");
1297 std::vector<ArgInfo> ArgList;
1300 if (ParseArgumentList(ArgList, isVarArg, true) ||
1301 // FIXME: Allow, but ignore attributes on function types!
1302 // FIXME: Remove in LLVM 3.0
1303 ParseOptionalAttrs(Attrs, 2))
1306 // Reject names on the arguments lists.
1307 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1308 if (!ArgList[i].Name.empty())
1309 return Error(ArgList[i].Loc, "argument name invalid in function type");
1310 if (!ArgList[i].Attrs != 0) {
1311 // Allow but ignore attributes on function types; this permits
1313 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1317 std::vector<const Type*> ArgListTy;
1318 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1319 ArgListTy.push_back(ArgList[i].Type);
1321 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1322 ArgListTy, isVarArg));
1326 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1329 /// ::= '{' TypeRec (',' TypeRec)* '}'
1330 /// ::= '<' '{' '}' '>'
1331 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1332 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1333 assert(Lex.getKind() == lltok::lbrace);
1334 Lex.Lex(); // Consume the '{'
1336 if (EatIfPresent(lltok::rbrace)) {
1337 Result = Context.getStructType(Packed);
1341 std::vector<PATypeHolder> ParamsList;
1342 LocTy EltTyLoc = Lex.getLoc();
1343 if (ParseTypeRec(Result)) return true;
1344 ParamsList.push_back(Result);
1346 if (Result == Type::VoidTy)
1347 return Error(EltTyLoc, "struct element can not have void type");
1348 if (!StructType::isValidElementType(Result))
1349 return Error(EltTyLoc, "invalid element type for struct");
1351 while (EatIfPresent(lltok::comma)) {
1352 EltTyLoc = Lex.getLoc();
1353 if (ParseTypeRec(Result)) return true;
1355 if (Result == Type::VoidTy)
1356 return Error(EltTyLoc, "struct element can not have void type");
1357 if (!StructType::isValidElementType(Result))
1358 return Error(EltTyLoc, "invalid element type for struct");
1360 ParamsList.push_back(Result);
1363 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1366 std::vector<const Type*> ParamsListTy;
1367 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1368 ParamsListTy.push_back(ParamsList[i].get());
1369 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1373 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1374 /// token has already been consumed.
1376 /// ::= '[' APSINTVAL 'x' Types ']'
1377 /// ::= '<' APSINTVAL 'x' Types '>'
1378 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1379 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1380 Lex.getAPSIntVal().getBitWidth() > 64)
1381 return TokError("expected number in address space");
1383 LocTy SizeLoc = Lex.getLoc();
1384 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1387 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1390 LocTy TypeLoc = Lex.getLoc();
1391 PATypeHolder EltTy(Type::VoidTy);
1392 if (ParseTypeRec(EltTy)) return true;
1394 if (EltTy == Type::VoidTy)
1395 return Error(TypeLoc, "array and vector element type cannot be void");
1397 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1398 "expected end of sequential type"))
1403 return Error(SizeLoc, "zero element vector is illegal");
1404 if ((unsigned)Size != Size)
1405 return Error(SizeLoc, "size too large for vector");
1406 if (!VectorType::isValidElementType(EltTy))
1407 return Error(TypeLoc, "vector element type must be fp or integer");
1408 Result = Context.getVectorType(EltTy, unsigned(Size));
1410 if (!ArrayType::isValidElementType(EltTy))
1411 return Error(TypeLoc, "invalid array element type");
1412 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1417 //===----------------------------------------------------------------------===//
1418 // Function Semantic Analysis.
1419 //===----------------------------------------------------------------------===//
1421 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1424 // Insert unnamed arguments into the NumberedVals list.
1425 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1428 NumberedVals.push_back(AI);
1431 LLParser::PerFunctionState::~PerFunctionState() {
1432 // If there were any forward referenced non-basicblock values, delete them.
1433 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1434 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1435 if (!isa<BasicBlock>(I->second.first)) {
1436 I->second.first->replaceAllUsesWith(
1437 P.getContext().getUndef(I->second.first->getType()));
1438 delete I->second.first;
1439 I->second.first = 0;
1442 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1443 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1444 if (!isa<BasicBlock>(I->second.first)) {
1445 I->second.first->replaceAllUsesWith(
1446 P.getContext().getUndef(I->second.first->getType()));
1447 delete I->second.first;
1448 I->second.first = 0;
1452 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1453 if (!ForwardRefVals.empty())
1454 return P.Error(ForwardRefVals.begin()->second.second,
1455 "use of undefined value '%" + ForwardRefVals.begin()->first +
1457 if (!ForwardRefValIDs.empty())
1458 return P.Error(ForwardRefValIDs.begin()->second.second,
1459 "use of undefined value '%" +
1460 utostr(ForwardRefValIDs.begin()->first) + "'");
1465 /// GetVal - Get a value with the specified name or ID, creating a
1466 /// forward reference record if needed. This can return null if the value
1467 /// exists but does not have the right type.
1468 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1469 const Type *Ty, LocTy Loc) {
1470 // Look this name up in the normal function symbol table.
1471 Value *Val = F.getValueSymbolTable().lookup(Name);
1473 // If this is a forward reference for the value, see if we already created a
1474 // forward ref record.
1476 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1477 I = ForwardRefVals.find(Name);
1478 if (I != ForwardRefVals.end())
1479 Val = I->second.first;
1482 // If we have the value in the symbol table or fwd-ref table, return it.
1484 if (Val->getType() == Ty) return Val;
1485 if (Ty == Type::LabelTy)
1486 P.Error(Loc, "'%" + Name + "' is not a basic block");
1488 P.Error(Loc, "'%" + Name + "' defined with type '" +
1489 Val->getType()->getDescription() + "'");
1493 // Don't make placeholders with invalid type.
1494 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1495 P.Error(Loc, "invalid use of a non-first-class type");
1499 // Otherwise, create a new forward reference for this value and remember it.
1501 if (Ty == Type::LabelTy)
1502 FwdVal = BasicBlock::Create(Name, &F);
1504 FwdVal = new Argument(Ty, Name);
1506 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1510 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1512 // Look this name up in the normal function symbol table.
1513 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1515 // If this is a forward reference for the value, see if we already created a
1516 // forward ref record.
1518 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1519 I = ForwardRefValIDs.find(ID);
1520 if (I != ForwardRefValIDs.end())
1521 Val = I->second.first;
1524 // If we have the value in the symbol table or fwd-ref table, return it.
1526 if (Val->getType() == Ty) return Val;
1527 if (Ty == Type::LabelTy)
1528 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1530 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1531 Val->getType()->getDescription() + "'");
1535 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1536 P.Error(Loc, "invalid use of a non-first-class type");
1540 // Otherwise, create a new forward reference for this value and remember it.
1542 if (Ty == Type::LabelTy)
1543 FwdVal = BasicBlock::Create("", &F);
1545 FwdVal = new Argument(Ty);
1547 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1551 /// SetInstName - After an instruction is parsed and inserted into its
1552 /// basic block, this installs its name.
1553 bool LLParser::PerFunctionState::SetInstName(int NameID,
1554 const std::string &NameStr,
1555 LocTy NameLoc, Instruction *Inst) {
1556 // If this instruction has void type, it cannot have a name or ID specified.
1557 if (Inst->getType() == Type::VoidTy) {
1558 if (NameID != -1 || !NameStr.empty())
1559 return P.Error(NameLoc, "instructions returning void cannot have a name");
1563 // If this was a numbered instruction, verify that the instruction is the
1564 // expected value and resolve any forward references.
1565 if (NameStr.empty()) {
1566 // If neither a name nor an ID was specified, just use the next ID.
1568 NameID = NumberedVals.size();
1570 if (unsigned(NameID) != NumberedVals.size())
1571 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1572 utostr(NumberedVals.size()) + "'");
1574 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1575 ForwardRefValIDs.find(NameID);
1576 if (FI != ForwardRefValIDs.end()) {
1577 if (FI->second.first->getType() != Inst->getType())
1578 return P.Error(NameLoc, "instruction forward referenced with type '" +
1579 FI->second.first->getType()->getDescription() + "'");
1580 FI->second.first->replaceAllUsesWith(Inst);
1581 ForwardRefValIDs.erase(FI);
1584 NumberedVals.push_back(Inst);
1588 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1589 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1590 FI = ForwardRefVals.find(NameStr);
1591 if (FI != ForwardRefVals.end()) {
1592 if (FI->second.first->getType() != Inst->getType())
1593 return P.Error(NameLoc, "instruction forward referenced with type '" +
1594 FI->second.first->getType()->getDescription() + "'");
1595 FI->second.first->replaceAllUsesWith(Inst);
1596 ForwardRefVals.erase(FI);
1599 // Set the name on the instruction.
1600 Inst->setName(NameStr);
1602 if (Inst->getNameStr() != NameStr)
1603 return P.Error(NameLoc, "multiple definition of local value named '" +
1608 /// GetBB - Get a basic block with the specified name or ID, creating a
1609 /// forward reference record if needed.
1610 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1612 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1615 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1616 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1619 /// DefineBB - Define the specified basic block, which is either named or
1620 /// unnamed. If there is an error, this returns null otherwise it returns
1621 /// the block being defined.
1622 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1626 BB = GetBB(NumberedVals.size(), Loc);
1628 BB = GetBB(Name, Loc);
1629 if (BB == 0) return 0; // Already diagnosed error.
1631 // Move the block to the end of the function. Forward ref'd blocks are
1632 // inserted wherever they happen to be referenced.
1633 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1635 // Remove the block from forward ref sets.
1637 ForwardRefValIDs.erase(NumberedVals.size());
1638 NumberedVals.push_back(BB);
1640 // BB forward references are already in the function symbol table.
1641 ForwardRefVals.erase(Name);
1647 //===----------------------------------------------------------------------===//
1649 //===----------------------------------------------------------------------===//
1651 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1652 /// type implied. For example, if we parse "4" we don't know what integer type
1653 /// it has. The value will later be combined with its type and checked for
1655 bool LLParser::ParseValID(ValID &ID) {
1656 ID.Loc = Lex.getLoc();
1657 switch (Lex.getKind()) {
1658 default: return TokError("expected value token");
1659 case lltok::GlobalID: // @42
1660 ID.UIntVal = Lex.getUIntVal();
1661 ID.Kind = ValID::t_GlobalID;
1663 case lltok::GlobalVar: // @foo
1664 ID.StrVal = Lex.getStrVal();
1665 ID.Kind = ValID::t_GlobalName;
1667 case lltok::LocalVarID: // %42
1668 ID.UIntVal = Lex.getUIntVal();
1669 ID.Kind = ValID::t_LocalID;
1671 case lltok::LocalVar: // %foo
1672 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1673 ID.StrVal = Lex.getStrVal();
1674 ID.Kind = ValID::t_LocalName;
1676 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1677 ID.Kind = ValID::t_Constant;
1679 if (Lex.getKind() == lltok::lbrace) {
1680 SmallVector<Value*, 16> Elts;
1681 if (ParseMDNodeVector(Elts) ||
1682 ParseToken(lltok::rbrace, "expected end of metadata node"))
1685 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1689 // Standalone metadata reference
1690 // !{ ..., !42, ... }
1691 if (!ParseMDNode(ID.ConstantVal))
1695 // ::= '!' STRINGCONSTANT
1696 if (ParseMDString(ID.ConstantVal)) return true;
1700 ID.APSIntVal = Lex.getAPSIntVal();
1701 ID.Kind = ValID::t_APSInt;
1703 case lltok::APFloat:
1704 ID.APFloatVal = Lex.getAPFloatVal();
1705 ID.Kind = ValID::t_APFloat;
1707 case lltok::kw_true:
1708 ID.ConstantVal = Context.getConstantIntTrue();
1709 ID.Kind = ValID::t_Constant;
1711 case lltok::kw_false:
1712 ID.ConstantVal = Context.getConstantIntFalse();
1713 ID.Kind = ValID::t_Constant;
1715 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1716 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1717 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1719 case lltok::lbrace: {
1720 // ValID ::= '{' ConstVector '}'
1722 SmallVector<Constant*, 16> Elts;
1723 if (ParseGlobalValueVector(Elts) ||
1724 ParseToken(lltok::rbrace, "expected end of struct constant"))
1727 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1728 ID.Kind = ValID::t_Constant;
1732 // ValID ::= '<' ConstVector '>' --> Vector.
1733 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1735 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1737 SmallVector<Constant*, 16> Elts;
1738 LocTy FirstEltLoc = Lex.getLoc();
1739 if (ParseGlobalValueVector(Elts) ||
1741 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1742 ParseToken(lltok::greater, "expected end of constant"))
1745 if (isPackedStruct) {
1747 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1748 ID.Kind = ValID::t_Constant;
1753 return Error(ID.Loc, "constant vector must not be empty");
1755 if (!Elts[0]->getType()->isInteger() &&
1756 !Elts[0]->getType()->isFloatingPoint())
1757 return Error(FirstEltLoc,
1758 "vector elements must have integer or floating point type");
1760 // Verify that all the vector elements have the same type.
1761 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1762 if (Elts[i]->getType() != Elts[0]->getType())
1763 return Error(FirstEltLoc,
1764 "vector element #" + utostr(i) +
1765 " is not of type '" + Elts[0]->getType()->getDescription());
1767 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1768 ID.Kind = ValID::t_Constant;
1771 case lltok::lsquare: { // Array Constant
1773 SmallVector<Constant*, 16> Elts;
1774 LocTy FirstEltLoc = Lex.getLoc();
1775 if (ParseGlobalValueVector(Elts) ||
1776 ParseToken(lltok::rsquare, "expected end of array constant"))
1779 // Handle empty element.
1781 // Use undef instead of an array because it's inconvenient to determine
1782 // the element type at this point, there being no elements to examine.
1783 ID.Kind = ValID::t_EmptyArray;
1787 if (!Elts[0]->getType()->isFirstClassType())
1788 return Error(FirstEltLoc, "invalid array element type: " +
1789 Elts[0]->getType()->getDescription());
1791 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1793 // Verify all elements are correct type!
1794 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1795 if (Elts[i]->getType() != Elts[0]->getType())
1796 return Error(FirstEltLoc,
1797 "array element #" + utostr(i) +
1798 " is not of type '" +Elts[0]->getType()->getDescription());
1801 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1802 ID.Kind = ValID::t_Constant;
1805 case lltok::kw_c: // c "foo"
1807 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1808 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1809 ID.Kind = ValID::t_Constant;
1812 case lltok::kw_asm: {
1813 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1816 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1817 ParseStringConstant(ID.StrVal) ||
1818 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1819 ParseToken(lltok::StringConstant, "expected constraint string"))
1821 ID.StrVal2 = Lex.getStrVal();
1822 ID.UIntVal = HasSideEffect;
1823 ID.Kind = ValID::t_InlineAsm;
1827 case lltok::kw_trunc:
1828 case lltok::kw_zext:
1829 case lltok::kw_sext:
1830 case lltok::kw_fptrunc:
1831 case lltok::kw_fpext:
1832 case lltok::kw_bitcast:
1833 case lltok::kw_uitofp:
1834 case lltok::kw_sitofp:
1835 case lltok::kw_fptoui:
1836 case lltok::kw_fptosi:
1837 case lltok::kw_inttoptr:
1838 case lltok::kw_ptrtoint: {
1839 unsigned Opc = Lex.getUIntVal();
1840 PATypeHolder DestTy(Type::VoidTy);
1843 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1844 ParseGlobalTypeAndValue(SrcVal) ||
1845 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1846 ParseType(DestTy) ||
1847 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1849 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1850 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1851 SrcVal->getType()->getDescription() + "' to '" +
1852 DestTy->getDescription() + "'");
1853 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1855 ID.Kind = ValID::t_Constant;
1858 case lltok::kw_extractvalue: {
1861 SmallVector<unsigned, 4> Indices;
1862 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1863 ParseGlobalTypeAndValue(Val) ||
1864 ParseIndexList(Indices) ||
1865 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1867 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1868 return Error(ID.Loc, "extractvalue operand must be array or struct");
1869 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1871 return Error(ID.Loc, "invalid indices for extractvalue");
1873 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1874 ID.Kind = ValID::t_Constant;
1877 case lltok::kw_insertvalue: {
1879 Constant *Val0, *Val1;
1880 SmallVector<unsigned, 4> Indices;
1881 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1882 ParseGlobalTypeAndValue(Val0) ||
1883 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1884 ParseGlobalTypeAndValue(Val1) ||
1885 ParseIndexList(Indices) ||
1886 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1888 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1889 return Error(ID.Loc, "extractvalue operand must be array or struct");
1890 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1892 return Error(ID.Loc, "invalid indices for insertvalue");
1893 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1894 Indices.data(), Indices.size());
1895 ID.Kind = ValID::t_Constant;
1898 case lltok::kw_icmp:
1899 case lltok::kw_fcmp: {
1900 unsigned PredVal, Opc = Lex.getUIntVal();
1901 Constant *Val0, *Val1;
1903 if (ParseCmpPredicate(PredVal, Opc) ||
1904 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1905 ParseGlobalTypeAndValue(Val0) ||
1906 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1907 ParseGlobalTypeAndValue(Val1) ||
1908 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1911 if (Val0->getType() != Val1->getType())
1912 return Error(ID.Loc, "compare operands must have the same type");
1914 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1916 if (Opc == Instruction::FCmp) {
1917 if (!Val0->getType()->isFPOrFPVector())
1918 return Error(ID.Loc, "fcmp requires floating point operands");
1919 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1921 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1922 if (!Val0->getType()->isIntOrIntVector() &&
1923 !isa<PointerType>(Val0->getType()))
1924 return Error(ID.Loc, "icmp requires pointer or integer operands");
1925 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1927 ID.Kind = ValID::t_Constant;
1931 // Binary Operators.
1933 case lltok::kw_fadd:
1935 case lltok::kw_fsub:
1937 case lltok::kw_fmul:
1938 case lltok::kw_udiv:
1939 case lltok::kw_sdiv:
1940 case lltok::kw_fdiv:
1941 case lltok::kw_urem:
1942 case lltok::kw_srem:
1943 case lltok::kw_frem: {
1944 unsigned Opc = Lex.getUIntVal();
1945 Constant *Val0, *Val1;
1947 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1948 ParseGlobalTypeAndValue(Val0) ||
1949 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1950 ParseGlobalTypeAndValue(Val1) ||
1951 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1953 if (Val0->getType() != Val1->getType())
1954 return Error(ID.Loc, "operands of constexpr must have same type");
1955 if (!Val0->getType()->isIntOrIntVector() &&
1956 !Val0->getType()->isFPOrFPVector())
1957 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1958 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1959 ID.Kind = ValID::t_Constant;
1963 // Logical Operations
1965 case lltok::kw_lshr:
1966 case lltok::kw_ashr:
1969 case lltok::kw_xor: {
1970 unsigned Opc = Lex.getUIntVal();
1971 Constant *Val0, *Val1;
1973 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1974 ParseGlobalTypeAndValue(Val0) ||
1975 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1976 ParseGlobalTypeAndValue(Val1) ||
1977 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1979 if (Val0->getType() != Val1->getType())
1980 return Error(ID.Loc, "operands of constexpr must have same type");
1981 if (!Val0->getType()->isIntOrIntVector())
1982 return Error(ID.Loc,
1983 "constexpr requires integer or integer vector operands");
1984 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1985 ID.Kind = ValID::t_Constant;
1989 case lltok::kw_getelementptr:
1990 case lltok::kw_shufflevector:
1991 case lltok::kw_insertelement:
1992 case lltok::kw_extractelement:
1993 case lltok::kw_select: {
1994 unsigned Opc = Lex.getUIntVal();
1995 SmallVector<Constant*, 16> Elts;
1997 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1998 ParseGlobalValueVector(Elts) ||
1999 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2002 if (Opc == Instruction::GetElementPtr) {
2003 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2004 return Error(ID.Loc, "getelementptr requires pointer operand");
2006 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2007 (Value**)&Elts[1], Elts.size()-1))
2008 return Error(ID.Loc, "invalid indices for getelementptr");
2009 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
2010 &Elts[1], Elts.size()-1);
2011 } else if (Opc == Instruction::Select) {
2012 if (Elts.size() != 3)
2013 return Error(ID.Loc, "expected three operands to select");
2014 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2016 return Error(ID.Loc, Reason);
2017 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
2018 } else if (Opc == Instruction::ShuffleVector) {
2019 if (Elts.size() != 3)
2020 return Error(ID.Loc, "expected three operands to shufflevector");
2021 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2022 return Error(ID.Loc, "invalid operands to shufflevector");
2024 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2025 } else if (Opc == Instruction::ExtractElement) {
2026 if (Elts.size() != 2)
2027 return Error(ID.Loc, "expected two operands to extractelement");
2028 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2029 return Error(ID.Loc, "invalid extractelement operands");
2030 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2032 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2033 if (Elts.size() != 3)
2034 return Error(ID.Loc, "expected three operands to insertelement");
2035 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2036 return Error(ID.Loc, "invalid insertelement operands");
2038 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2041 ID.Kind = ValID::t_Constant;
2050 /// ParseGlobalValue - Parse a global value with the specified type.
2051 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2054 return ParseValID(ID) ||
2055 ConvertGlobalValIDToValue(Ty, ID, V);
2058 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2060 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2062 if (isa<FunctionType>(Ty))
2063 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2066 default: llvm_unreachable("Unknown ValID!");
2067 case ValID::t_LocalID:
2068 case ValID::t_LocalName:
2069 return Error(ID.Loc, "invalid use of function-local name");
2070 case ValID::t_InlineAsm:
2071 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2072 case ValID::t_GlobalName:
2073 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2075 case ValID::t_GlobalID:
2076 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2078 case ValID::t_APSInt:
2079 if (!isa<IntegerType>(Ty))
2080 return Error(ID.Loc, "integer constant must have integer type");
2081 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2082 V = Context.getConstantInt(ID.APSIntVal);
2084 case ValID::t_APFloat:
2085 if (!Ty->isFloatingPoint() ||
2086 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2087 return Error(ID.Loc, "floating point constant invalid for type");
2089 // The lexer has no type info, so builds all float and double FP constants
2090 // as double. Fix this here. Long double does not need this.
2091 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2092 Ty == Type::FloatTy) {
2094 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2097 V = Context.getConstantFP(ID.APFloatVal);
2099 if (V->getType() != Ty)
2100 return Error(ID.Loc, "floating point constant does not have type '" +
2101 Ty->getDescription() + "'");
2105 if (!isa<PointerType>(Ty))
2106 return Error(ID.Loc, "null must be a pointer type");
2107 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2109 case ValID::t_Undef:
2110 // FIXME: LabelTy should not be a first-class type.
2111 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2112 !isa<OpaqueType>(Ty))
2113 return Error(ID.Loc, "invalid type for undef constant");
2114 V = Context.getUndef(Ty);
2116 case ValID::t_EmptyArray:
2117 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2118 return Error(ID.Loc, "invalid empty array initializer");
2119 V = Context.getUndef(Ty);
2122 // FIXME: LabelTy should not be a first-class type.
2123 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2124 return Error(ID.Loc, "invalid type for null constant");
2125 V = Context.getNullValue(Ty);
2127 case ValID::t_Constant:
2128 if (ID.ConstantVal->getType() != Ty)
2129 return Error(ID.Loc, "constant expression type mismatch");
2135 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2136 PATypeHolder Type(Type::VoidTy);
2137 return ParseType(Type) ||
2138 ParseGlobalValue(Type, V);
2141 /// ParseGlobalValueVector
2143 /// ::= TypeAndValue (',' TypeAndValue)*
2144 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2146 if (Lex.getKind() == lltok::rbrace ||
2147 Lex.getKind() == lltok::rsquare ||
2148 Lex.getKind() == lltok::greater ||
2149 Lex.getKind() == lltok::rparen)
2153 if (ParseGlobalTypeAndValue(C)) return true;
2156 while (EatIfPresent(lltok::comma)) {
2157 if (ParseGlobalTypeAndValue(C)) return true;
2165 //===----------------------------------------------------------------------===//
2166 // Function Parsing.
2167 //===----------------------------------------------------------------------===//
2169 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2170 PerFunctionState &PFS) {
2171 if (ID.Kind == ValID::t_LocalID)
2172 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2173 else if (ID.Kind == ValID::t_LocalName)
2174 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2175 else if (ID.Kind == ValID::t_InlineAsm) {
2176 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2177 const FunctionType *FTy =
2178 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2179 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2180 return Error(ID.Loc, "invalid type for inline asm constraint string");
2181 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2185 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2193 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2196 return ParseValID(ID) ||
2197 ConvertValIDToValue(Ty, ID, V, PFS);
2200 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2201 PATypeHolder T(Type::VoidTy);
2202 return ParseType(T) ||
2203 ParseValue(T, V, PFS);
2207 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2208 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2209 /// OptionalAlign OptGC
2210 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2211 // Parse the linkage.
2212 LocTy LinkageLoc = Lex.getLoc();
2215 unsigned Visibility, CC, RetAttrs;
2216 PATypeHolder RetType(Type::VoidTy);
2217 LocTy RetTypeLoc = Lex.getLoc();
2218 if (ParseOptionalLinkage(Linkage) ||
2219 ParseOptionalVisibility(Visibility) ||
2220 ParseOptionalCallingConv(CC) ||
2221 ParseOptionalAttrs(RetAttrs, 1) ||
2222 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2225 // Verify that the linkage is ok.
2226 switch ((GlobalValue::LinkageTypes)Linkage) {
2227 case GlobalValue::ExternalLinkage:
2228 break; // always ok.
2229 case GlobalValue::DLLImportLinkage:
2230 case GlobalValue::ExternalWeakLinkage:
2232 return Error(LinkageLoc, "invalid linkage for function definition");
2234 case GlobalValue::PrivateLinkage:
2235 case GlobalValue::LinkerPrivateLinkage:
2236 case GlobalValue::InternalLinkage:
2237 case GlobalValue::AvailableExternallyLinkage:
2238 case GlobalValue::LinkOnceAnyLinkage:
2239 case GlobalValue::LinkOnceODRLinkage:
2240 case GlobalValue::WeakAnyLinkage:
2241 case GlobalValue::WeakODRLinkage:
2242 case GlobalValue::DLLExportLinkage:
2244 return Error(LinkageLoc, "invalid linkage for function declaration");
2246 case GlobalValue::AppendingLinkage:
2247 case GlobalValue::GhostLinkage:
2248 case GlobalValue::CommonLinkage:
2249 return Error(LinkageLoc, "invalid function linkage type");
2252 if (!FunctionType::isValidReturnType(RetType) ||
2253 isa<OpaqueType>(RetType))
2254 return Error(RetTypeLoc, "invalid function return type");
2256 LocTy NameLoc = Lex.getLoc();
2258 std::string FunctionName;
2259 if (Lex.getKind() == lltok::GlobalVar) {
2260 FunctionName = Lex.getStrVal();
2261 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2262 unsigned NameID = Lex.getUIntVal();
2264 if (NameID != NumberedVals.size())
2265 return TokError("function expected to be numbered '%" +
2266 utostr(NumberedVals.size()) + "'");
2268 return TokError("expected function name");
2273 if (Lex.getKind() != lltok::lparen)
2274 return TokError("expected '(' in function argument list");
2276 std::vector<ArgInfo> ArgList;
2279 std::string Section;
2283 if (ParseArgumentList(ArgList, isVarArg, false) ||
2284 ParseOptionalAttrs(FuncAttrs, 2) ||
2285 (EatIfPresent(lltok::kw_section) &&
2286 ParseStringConstant(Section)) ||
2287 ParseOptionalAlignment(Alignment) ||
2288 (EatIfPresent(lltok::kw_gc) &&
2289 ParseStringConstant(GC)))
2292 // If the alignment was parsed as an attribute, move to the alignment field.
2293 if (FuncAttrs & Attribute::Alignment) {
2294 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2295 FuncAttrs &= ~Attribute::Alignment;
2298 // Okay, if we got here, the function is syntactically valid. Convert types
2299 // and do semantic checks.
2300 std::vector<const Type*> ParamTypeList;
2301 SmallVector<AttributeWithIndex, 8> Attrs;
2302 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2304 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2305 if (FuncAttrs & ObsoleteFuncAttrs) {
2306 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2307 FuncAttrs &= ~ObsoleteFuncAttrs;
2310 if (RetAttrs != Attribute::None)
2311 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2313 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2314 ParamTypeList.push_back(ArgList[i].Type);
2315 if (ArgList[i].Attrs != Attribute::None)
2316 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2319 if (FuncAttrs != Attribute::None)
2320 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2322 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2324 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2325 RetType != Type::VoidTy)
2326 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2328 const FunctionType *FT =
2329 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2330 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2333 if (!FunctionName.empty()) {
2334 // If this was a definition of a forward reference, remove the definition
2335 // from the forward reference table and fill in the forward ref.
2336 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2337 ForwardRefVals.find(FunctionName);
2338 if (FRVI != ForwardRefVals.end()) {
2339 Fn = M->getFunction(FunctionName);
2340 ForwardRefVals.erase(FRVI);
2341 } else if ((Fn = M->getFunction(FunctionName))) {
2342 // If this function already exists in the symbol table, then it is
2343 // multiply defined. We accept a few cases for old backwards compat.
2344 // FIXME: Remove this stuff for LLVM 3.0.
2345 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2346 (!Fn->isDeclaration() && isDefine)) {
2347 // If the redefinition has different type or different attributes,
2348 // reject it. If both have bodies, reject it.
2349 return Error(NameLoc, "invalid redefinition of function '" +
2350 FunctionName + "'");
2351 } else if (Fn->isDeclaration()) {
2352 // Make sure to strip off any argument names so we can't get conflicts.
2353 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2359 } else if (FunctionName.empty()) {
2360 // If this is a definition of a forward referenced function, make sure the
2362 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2363 = ForwardRefValIDs.find(NumberedVals.size());
2364 if (I != ForwardRefValIDs.end()) {
2365 Fn = cast<Function>(I->second.first);
2366 if (Fn->getType() != PFT)
2367 return Error(NameLoc, "type of definition and forward reference of '@" +
2368 utostr(NumberedVals.size()) +"' disagree");
2369 ForwardRefValIDs.erase(I);
2374 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2375 else // Move the forward-reference to the correct spot in the module.
2376 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2378 if (FunctionName.empty())
2379 NumberedVals.push_back(Fn);
2381 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2382 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2383 Fn->setCallingConv(CC);
2384 Fn->setAttributes(PAL);
2385 Fn->setAlignment(Alignment);
2386 Fn->setSection(Section);
2387 if (!GC.empty()) Fn->setGC(GC.c_str());
2389 // Add all of the arguments we parsed to the function.
2390 Function::arg_iterator ArgIt = Fn->arg_begin();
2391 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2392 // If the argument has a name, insert it into the argument symbol table.
2393 if (ArgList[i].Name.empty()) continue;
2395 // Set the name, if it conflicted, it will be auto-renamed.
2396 ArgIt->setName(ArgList[i].Name);
2398 if (ArgIt->getNameStr() != ArgList[i].Name)
2399 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2400 ArgList[i].Name + "'");
2407 /// ParseFunctionBody
2408 /// ::= '{' BasicBlock+ '}'
2409 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2411 bool LLParser::ParseFunctionBody(Function &Fn) {
2412 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2413 return TokError("expected '{' in function body");
2414 Lex.Lex(); // eat the {.
2416 PerFunctionState PFS(*this, Fn);
2418 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2419 if (ParseBasicBlock(PFS)) return true;
2424 // Verify function is ok.
2425 return PFS.VerifyFunctionComplete();
2429 /// ::= LabelStr? Instruction*
2430 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2431 // If this basic block starts out with a name, remember it.
2433 LocTy NameLoc = Lex.getLoc();
2434 if (Lex.getKind() == lltok::LabelStr) {
2435 Name = Lex.getStrVal();
2439 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2440 if (BB == 0) return true;
2442 std::string NameStr;
2444 // Parse the instructions in this block until we get a terminator.
2447 // This instruction may have three possibilities for a name: a) none
2448 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2449 LocTy NameLoc = Lex.getLoc();
2453 if (Lex.getKind() == lltok::LocalVarID) {
2454 NameID = Lex.getUIntVal();
2456 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2458 } else if (Lex.getKind() == lltok::LocalVar ||
2459 // FIXME: REMOVE IN LLVM 3.0
2460 Lex.getKind() == lltok::StringConstant) {
2461 NameStr = Lex.getStrVal();
2463 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2467 if (ParseInstruction(Inst, BB, PFS)) return true;
2469 BB->getInstList().push_back(Inst);
2471 // Set the name on the instruction.
2472 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2473 } while (!isa<TerminatorInst>(Inst));
2478 //===----------------------------------------------------------------------===//
2479 // Instruction Parsing.
2480 //===----------------------------------------------------------------------===//
2482 /// ParseInstruction - Parse one of the many different instructions.
2484 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2485 PerFunctionState &PFS) {
2486 lltok::Kind Token = Lex.getKind();
2487 if (Token == lltok::Eof)
2488 return TokError("found end of file when expecting more instructions");
2489 LocTy Loc = Lex.getLoc();
2490 unsigned KeywordVal = Lex.getUIntVal();
2491 Lex.Lex(); // Eat the keyword.
2494 default: return Error(Loc, "expected instruction opcode");
2495 // Terminator Instructions.
2496 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2497 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2498 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2499 case lltok::kw_br: return ParseBr(Inst, PFS);
2500 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2501 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2502 // Binary Operators.
2506 // API compatibility: Accept either integer or floating-point types.
2507 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2508 case lltok::kw_fadd:
2509 case lltok::kw_fsub:
2510 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2512 case lltok::kw_udiv:
2513 case lltok::kw_sdiv:
2514 case lltok::kw_urem:
2515 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2516 case lltok::kw_fdiv:
2517 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2519 case lltok::kw_lshr:
2520 case lltok::kw_ashr:
2523 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2524 case lltok::kw_icmp:
2525 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2527 case lltok::kw_trunc:
2528 case lltok::kw_zext:
2529 case lltok::kw_sext:
2530 case lltok::kw_fptrunc:
2531 case lltok::kw_fpext:
2532 case lltok::kw_bitcast:
2533 case lltok::kw_uitofp:
2534 case lltok::kw_sitofp:
2535 case lltok::kw_fptoui:
2536 case lltok::kw_fptosi:
2537 case lltok::kw_inttoptr:
2538 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2540 case lltok::kw_select: return ParseSelect(Inst, PFS);
2541 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2542 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2543 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2544 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2545 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2546 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2547 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2549 case lltok::kw_alloca:
2550 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2551 case lltok::kw_free: return ParseFree(Inst, PFS);
2552 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2553 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2554 case lltok::kw_volatile:
2555 if (EatIfPresent(lltok::kw_load))
2556 return ParseLoad(Inst, PFS, true);
2557 else if (EatIfPresent(lltok::kw_store))
2558 return ParseStore(Inst, PFS, true);
2560 return TokError("expected 'load' or 'store'");
2561 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2562 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2563 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2564 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2568 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2569 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2570 if (Opc == Instruction::FCmp) {
2571 switch (Lex.getKind()) {
2572 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2573 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2574 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2575 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2576 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2577 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2578 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2579 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2580 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2581 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2582 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2583 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2584 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2585 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2586 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2587 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2588 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2591 switch (Lex.getKind()) {
2592 default: TokError("expected icmp predicate (e.g. 'eq')");
2593 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2594 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2595 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2596 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2597 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2598 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2599 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2600 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2601 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2602 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2609 //===----------------------------------------------------------------------===//
2610 // Terminator Instructions.
2611 //===----------------------------------------------------------------------===//
2613 /// ParseRet - Parse a return instruction.
2615 /// ::= 'ret' TypeAndValue
2616 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2617 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2618 PerFunctionState &PFS) {
2619 PATypeHolder Ty(Type::VoidTy);
2620 if (ParseType(Ty, true /*void allowed*/)) return true;
2622 if (Ty == Type::VoidTy) {
2623 Inst = ReturnInst::Create();
2628 if (ParseValue(Ty, RV, PFS)) return true;
2630 // The normal case is one return value.
2631 if (Lex.getKind() == lltok::comma) {
2632 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2633 // of 'ret {i32,i32} {i32 1, i32 2}'
2634 SmallVector<Value*, 8> RVs;
2637 while (EatIfPresent(lltok::comma)) {
2638 if (ParseTypeAndValue(RV, PFS)) return true;
2642 RV = Context.getUndef(PFS.getFunction().getReturnType());
2643 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2644 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2645 BB->getInstList().push_back(I);
2649 Inst = ReturnInst::Create(RV);
2655 /// ::= 'br' TypeAndValue
2656 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2657 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2659 Value *Op0, *Op1, *Op2;
2660 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2662 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2663 Inst = BranchInst::Create(BB);
2667 if (Op0->getType() != Type::Int1Ty)
2668 return Error(Loc, "branch condition must have 'i1' type");
2670 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2671 ParseTypeAndValue(Op1, Loc, PFS) ||
2672 ParseToken(lltok::comma, "expected ',' after true destination") ||
2673 ParseTypeAndValue(Op2, Loc2, PFS))
2676 if (!isa<BasicBlock>(Op1))
2677 return Error(Loc, "true destination of branch must be a basic block");
2678 if (!isa<BasicBlock>(Op2))
2679 return Error(Loc2, "true destination of branch must be a basic block");
2681 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2687 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2689 /// ::= (TypeAndValue ',' TypeAndValue)*
2690 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2691 LocTy CondLoc, BBLoc;
2692 Value *Cond, *DefaultBB;
2693 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2694 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2695 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2696 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2699 if (!isa<IntegerType>(Cond->getType()))
2700 return Error(CondLoc, "switch condition must have integer type");
2701 if (!isa<BasicBlock>(DefaultBB))
2702 return Error(BBLoc, "default destination must be a basic block");
2704 // Parse the jump table pairs.
2705 SmallPtrSet<Value*, 32> SeenCases;
2706 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2707 while (Lex.getKind() != lltok::rsquare) {
2708 Value *Constant, *DestBB;
2710 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2711 ParseToken(lltok::comma, "expected ',' after case value") ||
2712 ParseTypeAndValue(DestBB, BBLoc, PFS))
2715 if (!SeenCases.insert(Constant))
2716 return Error(CondLoc, "duplicate case value in switch");
2717 if (!isa<ConstantInt>(Constant))
2718 return Error(CondLoc, "case value is not a constant integer");
2719 if (!isa<BasicBlock>(DestBB))
2720 return Error(BBLoc, "case destination is not a basic block");
2722 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2723 cast<BasicBlock>(DestBB)));
2726 Lex.Lex(); // Eat the ']'.
2728 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2730 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2731 SI->addCase(Table[i].first, Table[i].second);
2737 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2738 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2739 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2740 LocTy CallLoc = Lex.getLoc();
2741 unsigned CC, RetAttrs, FnAttrs;
2742 PATypeHolder RetType(Type::VoidTy);
2745 SmallVector<ParamInfo, 16> ArgList;
2747 Value *NormalBB, *UnwindBB;
2748 if (ParseOptionalCallingConv(CC) ||
2749 ParseOptionalAttrs(RetAttrs, 1) ||
2750 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2751 ParseValID(CalleeID) ||
2752 ParseParameterList(ArgList, PFS) ||
2753 ParseOptionalAttrs(FnAttrs, 2) ||
2754 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2755 ParseTypeAndValue(NormalBB, PFS) ||
2756 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2757 ParseTypeAndValue(UnwindBB, PFS))
2760 if (!isa<BasicBlock>(NormalBB))
2761 return Error(CallLoc, "normal destination is not a basic block");
2762 if (!isa<BasicBlock>(UnwindBB))
2763 return Error(CallLoc, "unwind destination is not a basic block");
2765 // If RetType is a non-function pointer type, then this is the short syntax
2766 // for the call, which means that RetType is just the return type. Infer the
2767 // rest of the function argument types from the arguments that are present.
2768 const PointerType *PFTy = 0;
2769 const FunctionType *Ty = 0;
2770 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2771 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2772 // Pull out the types of all of the arguments...
2773 std::vector<const Type*> ParamTypes;
2774 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2775 ParamTypes.push_back(ArgList[i].V->getType());
2777 if (!FunctionType::isValidReturnType(RetType))
2778 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2780 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2781 PFTy = Context.getPointerTypeUnqual(Ty);
2784 // Look up the callee.
2786 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2788 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2789 // function attributes.
2790 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2791 if (FnAttrs & ObsoleteFuncAttrs) {
2792 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2793 FnAttrs &= ~ObsoleteFuncAttrs;
2796 // Set up the Attributes for the function.
2797 SmallVector<AttributeWithIndex, 8> Attrs;
2798 if (RetAttrs != Attribute::None)
2799 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2801 SmallVector<Value*, 8> Args;
2803 // Loop through FunctionType's arguments and ensure they are specified
2804 // correctly. Also, gather any parameter attributes.
2805 FunctionType::param_iterator I = Ty->param_begin();
2806 FunctionType::param_iterator E = Ty->param_end();
2807 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2808 const Type *ExpectedTy = 0;
2811 } else if (!Ty->isVarArg()) {
2812 return Error(ArgList[i].Loc, "too many arguments specified");
2815 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2816 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2817 ExpectedTy->getDescription() + "'");
2818 Args.push_back(ArgList[i].V);
2819 if (ArgList[i].Attrs != Attribute::None)
2820 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2824 return Error(CallLoc, "not enough parameters specified for call");
2826 if (FnAttrs != Attribute::None)
2827 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2829 // Finish off the Attributes and check them
2830 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2832 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2833 cast<BasicBlock>(UnwindBB),
2834 Args.begin(), Args.end());
2835 II->setCallingConv(CC);
2836 II->setAttributes(PAL);
2843 //===----------------------------------------------------------------------===//
2844 // Binary Operators.
2845 //===----------------------------------------------------------------------===//
2848 /// ::= ArithmeticOps TypeAndValue ',' Value
2850 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2851 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2852 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2853 unsigned Opc, unsigned OperandType) {
2854 LocTy Loc; Value *LHS, *RHS;
2855 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2856 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2857 ParseValue(LHS->getType(), RHS, PFS))
2861 switch (OperandType) {
2862 default: llvm_unreachable("Unknown operand type!");
2863 case 0: // int or FP.
2864 Valid = LHS->getType()->isIntOrIntVector() ||
2865 LHS->getType()->isFPOrFPVector();
2867 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2868 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2872 return Error(Loc, "invalid operand type for instruction");
2874 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2879 /// ::= ArithmeticOps TypeAndValue ',' Value {
2880 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2882 LocTy Loc; Value *LHS, *RHS;
2883 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2884 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2885 ParseValue(LHS->getType(), RHS, PFS))
2888 if (!LHS->getType()->isIntOrIntVector())
2889 return Error(Loc,"instruction requires integer or integer vector operands");
2891 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2897 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2898 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2899 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2901 // Parse the integer/fp comparison predicate.
2905 if (ParseCmpPredicate(Pred, Opc) ||
2906 ParseTypeAndValue(LHS, Loc, PFS) ||
2907 ParseToken(lltok::comma, "expected ',' after compare value") ||
2908 ParseValue(LHS->getType(), RHS, PFS))
2911 if (Opc == Instruction::FCmp) {
2912 if (!LHS->getType()->isFPOrFPVector())
2913 return Error(Loc, "fcmp requires floating point operands");
2914 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2916 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
2917 if (!LHS->getType()->isIntOrIntVector() &&
2918 !isa<PointerType>(LHS->getType()))
2919 return Error(Loc, "icmp requires integer operands");
2920 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2925 //===----------------------------------------------------------------------===//
2926 // Other Instructions.
2927 //===----------------------------------------------------------------------===//
2931 /// ::= CastOpc TypeAndValue 'to' Type
2932 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2934 LocTy Loc; Value *Op;
2935 PATypeHolder DestTy(Type::VoidTy);
2936 if (ParseTypeAndValue(Op, Loc, PFS) ||
2937 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2941 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2942 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2943 return Error(Loc, "invalid cast opcode for cast from '" +
2944 Op->getType()->getDescription() + "' to '" +
2945 DestTy->getDescription() + "'");
2947 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2952 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2953 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2955 Value *Op0, *Op1, *Op2;
2956 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2957 ParseToken(lltok::comma, "expected ',' after select condition") ||
2958 ParseTypeAndValue(Op1, PFS) ||
2959 ParseToken(lltok::comma, "expected ',' after select value") ||
2960 ParseTypeAndValue(Op2, PFS))
2963 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2964 return Error(Loc, Reason);
2966 Inst = SelectInst::Create(Op0, Op1, Op2);
2971 /// ::= 'va_arg' TypeAndValue ',' Type
2972 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2974 PATypeHolder EltTy(Type::VoidTy);
2976 if (ParseTypeAndValue(Op, PFS) ||
2977 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2978 ParseType(EltTy, TypeLoc))
2981 if (!EltTy->isFirstClassType())
2982 return Error(TypeLoc, "va_arg requires operand with first class type");
2984 Inst = new VAArgInst(Op, EltTy);
2988 /// ParseExtractElement
2989 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2990 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2993 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2994 ParseToken(lltok::comma, "expected ',' after extract value") ||
2995 ParseTypeAndValue(Op1, PFS))
2998 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2999 return Error(Loc, "invalid extractelement operands");
3001 Inst = new ExtractElementInst(Op0, Op1);
3005 /// ParseInsertElement
3006 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3007 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3009 Value *Op0, *Op1, *Op2;
3010 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3011 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3012 ParseTypeAndValue(Op1, PFS) ||
3013 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3014 ParseTypeAndValue(Op2, PFS))
3017 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3018 return Error(Loc, "invalid extractelement operands");
3020 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3024 /// ParseShuffleVector
3025 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3026 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3028 Value *Op0, *Op1, *Op2;
3029 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3030 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3031 ParseTypeAndValue(Op1, PFS) ||
3032 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3033 ParseTypeAndValue(Op2, PFS))
3036 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3037 return Error(Loc, "invalid extractelement operands");
3039 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3044 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3045 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3046 PATypeHolder Ty(Type::VoidTy);
3048 LocTy TypeLoc = Lex.getLoc();
3050 if (ParseType(Ty) ||
3051 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3052 ParseValue(Ty, Op0, PFS) ||
3053 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3054 ParseValue(Type::LabelTy, Op1, PFS) ||
3055 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3058 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3060 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3062 if (!EatIfPresent(lltok::comma))
3065 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3066 ParseValue(Ty, Op0, PFS) ||
3067 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3068 ParseValue(Type::LabelTy, Op1, PFS) ||
3069 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3073 if (!Ty->isFirstClassType())
3074 return Error(TypeLoc, "phi node must have first class type");
3076 PHINode *PN = PHINode::Create(Ty);
3077 PN->reserveOperandSpace(PHIVals.size());
3078 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3079 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3085 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3086 /// ParameterList OptionalAttrs
3087 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3089 unsigned CC, RetAttrs, FnAttrs;
3090 PATypeHolder RetType(Type::VoidTy);
3093 SmallVector<ParamInfo, 16> ArgList;
3094 LocTy CallLoc = Lex.getLoc();
3096 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3097 ParseOptionalCallingConv(CC) ||
3098 ParseOptionalAttrs(RetAttrs, 1) ||
3099 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3100 ParseValID(CalleeID) ||
3101 ParseParameterList(ArgList, PFS) ||
3102 ParseOptionalAttrs(FnAttrs, 2))
3105 // If RetType is a non-function pointer type, then this is the short syntax
3106 // for the call, which means that RetType is just the return type. Infer the
3107 // rest of the function argument types from the arguments that are present.
3108 const PointerType *PFTy = 0;
3109 const FunctionType *Ty = 0;
3110 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3111 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3112 // Pull out the types of all of the arguments...
3113 std::vector<const Type*> ParamTypes;
3114 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3115 ParamTypes.push_back(ArgList[i].V->getType());
3117 if (!FunctionType::isValidReturnType(RetType))
3118 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3120 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3121 PFTy = Context.getPointerTypeUnqual(Ty);
3124 // Look up the callee.
3126 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3128 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3129 // function attributes.
3130 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3131 if (FnAttrs & ObsoleteFuncAttrs) {
3132 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3133 FnAttrs &= ~ObsoleteFuncAttrs;
3136 // Set up the Attributes for the function.
3137 SmallVector<AttributeWithIndex, 8> Attrs;
3138 if (RetAttrs != Attribute::None)
3139 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3141 SmallVector<Value*, 8> Args;
3143 // Loop through FunctionType's arguments and ensure they are specified
3144 // correctly. Also, gather any parameter attributes.
3145 FunctionType::param_iterator I = Ty->param_begin();
3146 FunctionType::param_iterator E = Ty->param_end();
3147 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3148 const Type *ExpectedTy = 0;
3151 } else if (!Ty->isVarArg()) {
3152 return Error(ArgList[i].Loc, "too many arguments specified");
3155 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3156 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3157 ExpectedTy->getDescription() + "'");
3158 Args.push_back(ArgList[i].V);
3159 if (ArgList[i].Attrs != Attribute::None)
3160 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3164 return Error(CallLoc, "not enough parameters specified for call");
3166 if (FnAttrs != Attribute::None)
3167 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3169 // Finish off the Attributes and check them
3170 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3172 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3173 CI->setTailCall(isTail);
3174 CI->setCallingConv(CC);
3175 CI->setAttributes(PAL);
3180 //===----------------------------------------------------------------------===//
3181 // Memory Instructions.
3182 //===----------------------------------------------------------------------===//
3185 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3186 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3187 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3189 PATypeHolder Ty(Type::VoidTy);
3192 unsigned Alignment = 0;
3193 if (ParseType(Ty)) return true;
3195 if (EatIfPresent(lltok::comma)) {
3196 if (Lex.getKind() == lltok::kw_align) {
3197 if (ParseOptionalAlignment(Alignment)) return true;
3198 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3199 ParseOptionalCommaAlignment(Alignment)) {
3204 if (Size && Size->getType() != Type::Int32Ty)
3205 return Error(SizeLoc, "element count must be i32");
3207 if (Opc == Instruction::Malloc)
3208 Inst = new MallocInst(Ty, Size, Alignment);
3210 Inst = new AllocaInst(Ty, Size, Alignment);
3215 /// ::= 'free' TypeAndValue
3216 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3217 Value *Val; LocTy Loc;
3218 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3219 if (!isa<PointerType>(Val->getType()))
3220 return Error(Loc, "operand to free must be a pointer");
3221 Inst = new FreeInst(Val);
3226 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3227 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3229 Value *Val; LocTy Loc;
3231 if (ParseTypeAndValue(Val, Loc, PFS) ||
3232 ParseOptionalCommaAlignment(Alignment))
3235 if (!isa<PointerType>(Val->getType()) ||
3236 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3237 return Error(Loc, "load operand must be a pointer to a first class type");
3239 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3244 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3245 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3247 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3249 if (ParseTypeAndValue(Val, Loc, PFS) ||
3250 ParseToken(lltok::comma, "expected ',' after store operand") ||
3251 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3252 ParseOptionalCommaAlignment(Alignment))
3255 if (!isa<PointerType>(Ptr->getType()))
3256 return Error(PtrLoc, "store operand must be a pointer");
3257 if (!Val->getType()->isFirstClassType())
3258 return Error(Loc, "store operand must be a first class value");
3259 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3260 return Error(Loc, "stored value and pointer type do not match");
3262 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3267 /// ::= 'getresult' TypeAndValue ',' i32
3268 /// FIXME: Remove support for getresult in LLVM 3.0
3269 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3270 Value *Val; LocTy ValLoc, EltLoc;
3272 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3273 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3274 ParseUInt32(Element, EltLoc))
3277 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3278 return Error(ValLoc, "getresult inst requires an aggregate operand");
3279 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3280 return Error(EltLoc, "invalid getresult index for value");
3281 Inst = ExtractValueInst::Create(Val, Element);
3285 /// ParseGetElementPtr
3286 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3287 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3288 Value *Ptr, *Val; LocTy Loc, EltLoc;
3289 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3291 if (!isa<PointerType>(Ptr->getType()))
3292 return Error(Loc, "base of getelementptr must be a pointer");
3294 SmallVector<Value*, 16> Indices;
3295 while (EatIfPresent(lltok::comma)) {
3296 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3297 if (!isa<IntegerType>(Val->getType()))
3298 return Error(EltLoc, "getelementptr index must be an integer");
3299 Indices.push_back(Val);
3302 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3303 Indices.begin(), Indices.end()))
3304 return Error(Loc, "invalid getelementptr indices");
3305 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3309 /// ParseExtractValue
3310 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3311 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3312 Value *Val; LocTy Loc;
3313 SmallVector<unsigned, 4> Indices;
3314 if (ParseTypeAndValue(Val, Loc, PFS) ||
3315 ParseIndexList(Indices))
3318 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3319 return Error(Loc, "extractvalue operand must be array or struct");
3321 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3323 return Error(Loc, "invalid indices for extractvalue");
3324 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3328 /// ParseInsertValue
3329 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3330 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3331 Value *Val0, *Val1; LocTy Loc0, Loc1;
3332 SmallVector<unsigned, 4> Indices;
3333 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3334 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3335 ParseTypeAndValue(Val1, Loc1, PFS) ||
3336 ParseIndexList(Indices))
3339 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3340 return Error(Loc0, "extractvalue operand must be array or struct");
3342 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3344 return Error(Loc0, "invalid indices for insertvalue");
3345 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3349 //===----------------------------------------------------------------------===//
3350 // Embedded metadata.
3351 //===----------------------------------------------------------------------===//
3353 /// ParseMDNodeVector
3354 /// ::= Element (',' Element)*
3356 /// ::= 'null' | TypeAndValue
3357 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3358 assert(Lex.getKind() == lltok::lbrace);
3362 if (Lex.getKind() == lltok::kw_null) {
3367 if (ParseGlobalTypeAndValue(C)) return true;
3371 } while (EatIfPresent(lltok::comma));