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_internal: // OptionalLinkage
128 case lltok::kw_weak: // OptionalLinkage
129 case lltok::kw_weak_odr: // OptionalLinkage
130 case lltok::kw_linkonce: // OptionalLinkage
131 case lltok::kw_linkonce_odr: // OptionalLinkage
132 case lltok::kw_appending: // OptionalLinkage
133 case lltok::kw_dllexport: // OptionalLinkage
134 case lltok::kw_common: // OptionalLinkage
135 case lltok::kw_dllimport: // OptionalLinkage
136 case lltok::kw_extern_weak: // OptionalLinkage
137 case lltok::kw_external: { // OptionalLinkage
138 unsigned Linkage, Visibility;
139 if (ParseOptionalLinkage(Linkage) ||
140 ParseOptionalVisibility(Visibility) ||
141 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
145 case lltok::kw_default: // OptionalVisibility
146 case lltok::kw_hidden: // OptionalVisibility
147 case lltok::kw_protected: { // OptionalVisibility
149 if (ParseOptionalVisibility(Visibility) ||
150 ParseGlobal("", SMLoc(), 0, false, Visibility))
155 case lltok::kw_thread_local: // OptionalThreadLocal
156 case lltok::kw_addrspace: // OptionalAddrSpace
157 case lltok::kw_constant: // GlobalType
158 case lltok::kw_global: // GlobalType
159 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
167 /// ::= 'module' 'asm' STRINGCONSTANT
168 bool LLParser::ParseModuleAsm() {
169 assert(Lex.getKind() == lltok::kw_module);
173 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
174 ParseStringConstant(AsmStr)) return true;
176 const std::string &AsmSoFar = M->getModuleInlineAsm();
177 if (AsmSoFar.empty())
178 M->setModuleInlineAsm(AsmStr);
180 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
185 /// ::= 'target' 'triple' '=' STRINGCONSTANT
186 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
187 bool LLParser::ParseTargetDefinition() {
188 assert(Lex.getKind() == lltok::kw_target);
191 default: return TokError("unknown target property");
192 case lltok::kw_triple:
194 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
195 ParseStringConstant(Str))
197 M->setTargetTriple(Str);
199 case lltok::kw_datalayout:
201 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
202 ParseStringConstant(Str))
204 M->setDataLayout(Str);
210 /// ::= 'deplibs' '=' '[' ']'
211 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
212 bool LLParser::ParseDepLibs() {
213 assert(Lex.getKind() == lltok::kw_deplibs);
215 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
216 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
219 if (EatIfPresent(lltok::rsquare))
223 if (ParseStringConstant(Str)) return true;
226 while (EatIfPresent(lltok::comma)) {
227 if (ParseStringConstant(Str)) return true;
231 return ParseToken(lltok::rsquare, "expected ']' at end of list");
236 bool LLParser::ParseUnnamedType() {
237 assert(Lex.getKind() == lltok::kw_type);
238 LocTy TypeLoc = Lex.getLoc();
239 Lex.Lex(); // eat kw_type
241 PATypeHolder Ty(Type::VoidTy);
242 if (ParseType(Ty)) return true;
244 unsigned TypeID = NumberedTypes.size();
246 // See if this type was previously referenced.
247 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
248 FI = ForwardRefTypeIDs.find(TypeID);
249 if (FI != ForwardRefTypeIDs.end()) {
250 if (FI->second.first.get() == Ty)
251 return Error(TypeLoc, "self referential type is invalid");
253 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
254 Ty = FI->second.first.get();
255 ForwardRefTypeIDs.erase(FI);
258 NumberedTypes.push_back(Ty);
264 /// ::= LocalVar '=' 'type' type
265 bool LLParser::ParseNamedType() {
266 std::string Name = Lex.getStrVal();
267 LocTy NameLoc = Lex.getLoc();
268 Lex.Lex(); // eat LocalVar.
270 PATypeHolder Ty(Type::VoidTy);
272 if (ParseToken(lltok::equal, "expected '=' after name") ||
273 ParseToken(lltok::kw_type, "expected 'type' after name") ||
277 // Set the type name, checking for conflicts as we do so.
278 bool AlreadyExists = M->addTypeName(Name, Ty);
279 if (!AlreadyExists) return false;
281 // See if this type is a forward reference. We need to eagerly resolve
282 // types to allow recursive type redefinitions below.
283 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
284 FI = ForwardRefTypes.find(Name);
285 if (FI != ForwardRefTypes.end()) {
286 if (FI->second.first.get() == Ty)
287 return Error(NameLoc, "self referential type is invalid");
289 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
290 Ty = FI->second.first.get();
291 ForwardRefTypes.erase(FI);
294 // Inserting a name that is already defined, get the existing name.
295 const Type *Existing = M->getTypeByName(Name);
296 assert(Existing && "Conflict but no matching type?!");
298 // Otherwise, this is an attempt to redefine a type. That's okay if
299 // the redefinition is identical to the original.
300 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
301 if (Existing == Ty) return false;
303 // Any other kind of (non-equivalent) redefinition is an error.
304 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
305 Ty->getDescription() + "'");
310 /// ::= 'declare' FunctionHeader
311 bool LLParser::ParseDeclare() {
312 assert(Lex.getKind() == lltok::kw_declare);
316 return ParseFunctionHeader(F, false);
320 /// ::= 'define' FunctionHeader '{' ...
321 bool LLParser::ParseDefine() {
322 assert(Lex.getKind() == lltok::kw_define);
326 return ParseFunctionHeader(F, true) ||
327 ParseFunctionBody(*F);
333 bool LLParser::ParseGlobalType(bool &IsConstant) {
334 if (Lex.getKind() == lltok::kw_constant)
336 else if (Lex.getKind() == lltok::kw_global)
340 return TokError("expected 'global' or 'constant'");
346 /// ParseNamedGlobal:
347 /// GlobalVar '=' OptionalVisibility ALIAS ...
348 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
349 bool LLParser::ParseNamedGlobal() {
350 assert(Lex.getKind() == lltok::GlobalVar);
351 LocTy NameLoc = Lex.getLoc();
352 std::string Name = Lex.getStrVal();
356 unsigned Linkage, Visibility;
357 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
358 ParseOptionalLinkage(Linkage, HasLinkage) ||
359 ParseOptionalVisibility(Visibility))
362 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
363 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
364 return ParseAlias(Name, NameLoc, Visibility);
367 /// ParseStandaloneMetadata:
369 bool LLParser::ParseStandaloneMetadata() {
370 assert(Lex.getKind() == lltok::Metadata);
372 unsigned MetadataID = 0;
373 if (ParseUInt32(MetadataID))
375 if (MetadataCache.find(MetadataID) != MetadataCache.end())
376 return TokError("Metadata id is already used");
377 if (ParseToken(lltok::equal, "expected '=' here"))
381 PATypeHolder Ty(Type::VoidTy);
382 if (ParseType(Ty, TyLoc))
386 if (ParseGlobalValue(Ty, Init))
389 MetadataCache[MetadataID] = Init;
390 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
391 FI = ForwardRefMDNodes.find(MetadataID);
392 if (FI != ForwardRefMDNodes.end()) {
393 Constant *FwdNode = FI->second.first;
394 FwdNode->replaceAllUsesWith(Init);
395 ForwardRefMDNodes.erase(FI);
402 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
405 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
406 /// ::= 'getelementptr' '(' ... ')'
408 /// Everything through visibility has already been parsed.
410 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
411 unsigned Visibility) {
412 assert(Lex.getKind() == lltok::kw_alias);
415 LocTy LinkageLoc = Lex.getLoc();
416 if (ParseOptionalLinkage(Linkage))
419 if (Linkage != GlobalValue::ExternalLinkage &&
420 Linkage != GlobalValue::WeakAnyLinkage &&
421 Linkage != GlobalValue::WeakODRLinkage &&
422 Linkage != GlobalValue::InternalLinkage &&
423 Linkage != GlobalValue::PrivateLinkage)
424 return Error(LinkageLoc, "invalid linkage type for alias");
427 LocTy AliaseeLoc = Lex.getLoc();
428 if (Lex.getKind() != lltok::kw_bitcast &&
429 Lex.getKind() != lltok::kw_getelementptr) {
430 if (ParseGlobalTypeAndValue(Aliasee)) return true;
432 // The bitcast dest type is not present, it is implied by the dest type.
434 if (ParseValID(ID)) return true;
435 if (ID.Kind != ValID::t_Constant)
436 return Error(AliaseeLoc, "invalid aliasee");
437 Aliasee = ID.ConstantVal;
440 if (!isa<PointerType>(Aliasee->getType()))
441 return Error(AliaseeLoc, "alias must have pointer type");
443 // Okay, create the alias but do not insert it into the module yet.
444 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
445 (GlobalValue::LinkageTypes)Linkage, Name,
447 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
449 // See if this value already exists in the symbol table. If so, it is either
450 // a redefinition or a definition of a forward reference.
451 if (GlobalValue *Val =
452 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
453 // See if this was a redefinition. If so, there is no entry in
455 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
456 I = ForwardRefVals.find(Name);
457 if (I == ForwardRefVals.end())
458 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
460 // Otherwise, this was a definition of forward ref. Verify that types
462 if (Val->getType() != GA->getType())
463 return Error(NameLoc,
464 "forward reference and definition of alias have different types");
466 // If they agree, just RAUW the old value with the alias and remove the
468 Val->replaceAllUsesWith(GA);
469 Val->eraseFromParent();
470 ForwardRefVals.erase(I);
473 // Insert into the module, we know its name won't collide now.
474 M->getAliasList().push_back(GA);
475 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
481 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
482 /// OptionalAddrSpace GlobalType Type Const
483 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
484 /// OptionalAddrSpace GlobalType Type Const
486 /// Everything through visibility has been parsed already.
488 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
489 unsigned Linkage, bool HasLinkage,
490 unsigned Visibility) {
492 bool ThreadLocal, IsConstant;
495 PATypeHolder Ty(Type::VoidTy);
496 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
497 ParseOptionalAddrSpace(AddrSpace) ||
498 ParseGlobalType(IsConstant) ||
499 ParseType(Ty, TyLoc))
502 // If the linkage is specified and is external, then no initializer is
505 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
506 Linkage != GlobalValue::ExternalWeakLinkage &&
507 Linkage != GlobalValue::ExternalLinkage)) {
508 if (ParseGlobalValue(Ty, Init))
512 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
513 return Error(TyLoc, "invalid type for global variable");
515 GlobalVariable *GV = 0;
517 // See if the global was forward referenced, if so, use the global.
519 if ((GV = M->getGlobalVariable(Name, true)) &&
520 !ForwardRefVals.erase(Name))
521 return Error(NameLoc, "redefinition of global '@" + Name + "'");
523 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
524 I = ForwardRefValIDs.find(NumberedVals.size());
525 if (I != ForwardRefValIDs.end()) {
526 GV = cast<GlobalVariable>(I->second.first);
527 ForwardRefValIDs.erase(I);
532 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
533 Name, 0, false, AddrSpace);
535 if (GV->getType()->getElementType() != Ty)
537 "forward reference and definition of global have different types");
539 // Move the forward-reference to the correct spot in the module.
540 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
544 NumberedVals.push_back(GV);
546 // Set the parsed properties on the global.
548 GV->setInitializer(Init);
549 GV->setConstant(IsConstant);
550 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
551 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
552 GV->setThreadLocal(ThreadLocal);
554 // Parse attributes on the global.
555 while (Lex.getKind() == lltok::comma) {
558 if (Lex.getKind() == lltok::kw_section) {
560 GV->setSection(Lex.getStrVal());
561 if (ParseToken(lltok::StringConstant, "expected global section string"))
563 } else if (Lex.getKind() == lltok::kw_align) {
565 if (ParseOptionalAlignment(Alignment)) return true;
566 GV->setAlignment(Alignment);
568 TokError("unknown global variable property!");
576 //===----------------------------------------------------------------------===//
577 // GlobalValue Reference/Resolution Routines.
578 //===----------------------------------------------------------------------===//
580 /// GetGlobalVal - Get a value with the specified name or ID, creating a
581 /// forward reference record if needed. This can return null if the value
582 /// exists but does not have the right type.
583 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
587 Error(Loc, "global variable reference must have pointer type");
591 // Look this name up in the normal function symbol table.
593 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
595 // If this is a forward reference for the value, see if we already created a
596 // forward ref record.
598 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
599 I = ForwardRefVals.find(Name);
600 if (I != ForwardRefVals.end())
601 Val = I->second.first;
604 // If we have the value in the symbol table or fwd-ref table, return it.
606 if (Val->getType() == Ty) return Val;
607 Error(Loc, "'@" + Name + "' defined with type '" +
608 Val->getType()->getDescription() + "'");
612 // Otherwise, create a new forward reference for this value and remember it.
614 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
615 // Function types can return opaque but functions can't.
616 if (isa<OpaqueType>(FT->getReturnType())) {
617 Error(Loc, "function may not return opaque type");
621 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
623 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
624 GlobalValue::ExternalWeakLinkage, 0, Name);
627 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
631 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
632 const PointerType *PTy = dyn_cast<PointerType>(Ty);
634 Error(Loc, "global variable reference must have pointer type");
638 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
640 // If this is a forward reference for the value, see if we already created a
641 // forward ref record.
643 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
644 I = ForwardRefValIDs.find(ID);
645 if (I != ForwardRefValIDs.end())
646 Val = I->second.first;
649 // If we have the value in the symbol table or fwd-ref table, return it.
651 if (Val->getType() == Ty) return Val;
652 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
653 Val->getType()->getDescription() + "'");
657 // Otherwise, create a new forward reference for this value and remember it.
659 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
660 // Function types can return opaque but functions can't.
661 if (isa<OpaqueType>(FT->getReturnType())) {
662 Error(Loc, "function may not return opaque type");
665 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
667 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
668 GlobalValue::ExternalWeakLinkage, 0, "");
671 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
676 //===----------------------------------------------------------------------===//
678 //===----------------------------------------------------------------------===//
680 /// ParseToken - If the current token has the specified kind, eat it and return
681 /// success. Otherwise, emit the specified error and return failure.
682 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
683 if (Lex.getKind() != T)
684 return TokError(ErrMsg);
689 /// ParseStringConstant
690 /// ::= StringConstant
691 bool LLParser::ParseStringConstant(std::string &Result) {
692 if (Lex.getKind() != lltok::StringConstant)
693 return TokError("expected string constant");
694 Result = Lex.getStrVal();
701 bool LLParser::ParseUInt32(unsigned &Val) {
702 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
703 return TokError("expected integer");
704 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
705 if (Val64 != unsigned(Val64))
706 return TokError("expected 32-bit integer (too large)");
713 /// ParseOptionalAddrSpace
715 /// := 'addrspace' '(' uint32 ')'
716 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
718 if (!EatIfPresent(lltok::kw_addrspace))
720 return ParseToken(lltok::lparen, "expected '(' in address space") ||
721 ParseUInt32(AddrSpace) ||
722 ParseToken(lltok::rparen, "expected ')' in address space");
725 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
726 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
727 /// 2: function attr.
728 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
729 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
730 Attrs = Attribute::None;
731 LocTy AttrLoc = Lex.getLoc();
734 switch (Lex.getKind()) {
737 // Treat these as signext/zeroext if they occur in the argument list after
738 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
739 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
741 // FIXME: REMOVE THIS IN LLVM 3.0
743 if (Lex.getKind() == lltok::kw_sext)
744 Attrs |= Attribute::SExt;
746 Attrs |= Attribute::ZExt;
750 default: // End of attributes.
751 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
752 return Error(AttrLoc, "invalid use of function-only attribute");
754 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
755 return Error(AttrLoc, "invalid use of parameter-only attribute");
758 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
759 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
760 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
761 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
762 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
763 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
764 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
765 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
767 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
768 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
769 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
770 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
771 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
772 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
773 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
774 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
775 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
776 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
777 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
779 case lltok::kw_align: {
781 if (ParseOptionalAlignment(Alignment))
783 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
791 /// ParseOptionalLinkage
798 /// ::= 'linkonce_odr'
803 /// ::= 'extern_weak'
805 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
807 switch (Lex.getKind()) {
808 default: Res = GlobalValue::ExternalLinkage; return false;
809 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
810 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
811 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
812 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
813 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
814 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
815 case lltok::kw_available_externally:
816 Res = GlobalValue::AvailableExternallyLinkage;
818 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
819 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
820 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
821 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
822 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
823 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
830 /// ParseOptionalVisibility
836 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
837 switch (Lex.getKind()) {
838 default: Res = GlobalValue::DefaultVisibility; return false;
839 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
840 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
841 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
847 /// ParseOptionalCallingConv
852 /// ::= 'x86_stdcallcc'
853 /// ::= 'x86_fastcallcc'
855 /// ::= 'arm_aapcscc'
856 /// ::= 'arm_aapcs_vfpcc'
859 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
860 switch (Lex.getKind()) {
861 default: CC = CallingConv::C; return false;
862 case lltok::kw_ccc: CC = CallingConv::C; break;
863 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
864 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
865 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
866 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
867 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
868 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
869 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
870 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
876 /// ParseOptionalAlignment
879 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
881 if (!EatIfPresent(lltok::kw_align))
883 LocTy AlignLoc = Lex.getLoc();
884 if (ParseUInt32(Alignment)) return true;
885 if (!isPowerOf2_32(Alignment))
886 return Error(AlignLoc, "alignment is not a power of two");
890 /// ParseOptionalCommaAlignment
892 /// ::= ',' 'align' 4
893 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
895 if (!EatIfPresent(lltok::comma))
897 return ParseToken(lltok::kw_align, "expected 'align'") ||
898 ParseUInt32(Alignment);
902 /// ::= (',' uint32)+
903 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
904 if (Lex.getKind() != lltok::comma)
905 return TokError("expected ',' as start of index list");
907 while (EatIfPresent(lltok::comma)) {
909 if (ParseUInt32(Idx)) return true;
910 Indices.push_back(Idx);
916 //===----------------------------------------------------------------------===//
918 //===----------------------------------------------------------------------===//
920 /// ParseType - Parse and resolve a full type.
921 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
922 LocTy TypeLoc = Lex.getLoc();
923 if (ParseTypeRec(Result)) return true;
925 // Verify no unresolved uprefs.
927 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
929 if (!AllowVoid && Result.get() == Type::VoidTy)
930 return Error(TypeLoc, "void type only allowed for function results");
935 /// HandleUpRefs - Every time we finish a new layer of types, this function is
936 /// called. It loops through the UpRefs vector, which is a list of the
937 /// currently active types. For each type, if the up-reference is contained in
938 /// the newly completed type, we decrement the level count. When the level
939 /// count reaches zero, the up-referenced type is the type that is passed in:
940 /// thus we can complete the cycle.
942 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
943 // If Ty isn't abstract, or if there are no up-references in it, then there is
944 // nothing to resolve here.
945 if (!ty->isAbstract() || UpRefs.empty()) return ty;
949 errs() << "Type '" << Ty->getDescription()
950 << "' newly formed. Resolving upreferences.\n"
951 << UpRefs.size() << " upreferences active!\n";
954 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
955 // to zero), we resolve them all together before we resolve them to Ty. At
956 // the end of the loop, if there is anything to resolve to Ty, it will be in
958 OpaqueType *TypeToResolve = 0;
960 for (unsigned i = 0; i != UpRefs.size(); ++i) {
961 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
963 std::find(Ty->subtype_begin(), Ty->subtype_end(),
964 UpRefs[i].LastContainedTy) != Ty->subtype_end();
967 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
968 << UpRefs[i].LastContainedTy->getDescription() << ") = "
969 << (ContainsType ? "true" : "false")
970 << " level=" << UpRefs[i].NestingLevel << "\n";
975 // Decrement level of upreference
976 unsigned Level = --UpRefs[i].NestingLevel;
977 UpRefs[i].LastContainedTy = Ty;
979 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
984 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
987 TypeToResolve = UpRefs[i].UpRefTy;
989 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
990 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
991 --i; // Do not skip the next element.
995 TypeToResolve->refineAbstractTypeTo(Ty);
1001 /// ParseTypeRec - The recursive function used to process the internal
1002 /// implementation details of types.
1003 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1004 switch (Lex.getKind()) {
1006 return TokError("expected type");
1008 // TypeRec ::= 'float' | 'void' (etc)
1009 Result = Lex.getTyVal();
1012 case lltok::kw_opaque:
1013 // TypeRec ::= 'opaque'
1014 Result = Context.getOpaqueType();
1018 // TypeRec ::= '{' ... '}'
1019 if (ParseStructType(Result, false))
1022 case lltok::lsquare:
1023 // TypeRec ::= '[' ... ']'
1024 Lex.Lex(); // eat the lsquare.
1025 if (ParseArrayVectorType(Result, false))
1028 case lltok::less: // Either vector or packed struct.
1029 // TypeRec ::= '<' ... '>'
1031 if (Lex.getKind() == lltok::lbrace) {
1032 if (ParseStructType(Result, true) ||
1033 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1035 } else if (ParseArrayVectorType(Result, true))
1038 case lltok::LocalVar:
1039 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1041 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1044 Result = Context.getOpaqueType();
1045 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1046 std::make_pair(Result,
1048 M->addTypeName(Lex.getStrVal(), Result.get());
1053 case lltok::LocalVarID:
1055 if (Lex.getUIntVal() < NumberedTypes.size())
1056 Result = NumberedTypes[Lex.getUIntVal()];
1058 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1059 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1060 if (I != ForwardRefTypeIDs.end())
1061 Result = I->second.first;
1063 Result = Context.getOpaqueType();
1064 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1065 std::make_pair(Result,
1071 case lltok::backslash: {
1072 // TypeRec ::= '\' 4
1075 if (ParseUInt32(Val)) return true;
1076 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1077 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1083 // Parse the type suffixes.
1085 switch (Lex.getKind()) {
1087 default: return false;
1089 // TypeRec ::= TypeRec '*'
1091 if (Result.get() == Type::LabelTy)
1092 return TokError("basic block pointers are invalid");
1093 if (Result.get() == Type::VoidTy)
1094 return TokError("pointers to void are invalid; use i8* instead");
1095 if (!PointerType::isValidElementType(Result.get()))
1096 return TokError("pointer to this type is invalid");
1097 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1101 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1102 case lltok::kw_addrspace: {
1103 if (Result.get() == Type::LabelTy)
1104 return TokError("basic block pointers are invalid");
1105 if (Result.get() == Type::VoidTy)
1106 return TokError("pointers to void are invalid; use i8* instead");
1107 if (!PointerType::isValidElementType(Result.get()))
1108 return TokError("pointer to this type is invalid");
1110 if (ParseOptionalAddrSpace(AddrSpace) ||
1111 ParseToken(lltok::star, "expected '*' in address space"))
1114 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1118 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1120 if (ParseFunctionType(Result))
1127 /// ParseParameterList
1129 /// ::= '(' Arg (',' Arg)* ')'
1131 /// ::= Type OptionalAttributes Value OptionalAttributes
1132 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1133 PerFunctionState &PFS) {
1134 if (ParseToken(lltok::lparen, "expected '(' in call"))
1137 while (Lex.getKind() != lltok::rparen) {
1138 // If this isn't the first argument, we need a comma.
1139 if (!ArgList.empty() &&
1140 ParseToken(lltok::comma, "expected ',' in argument list"))
1143 // Parse the argument.
1145 PATypeHolder ArgTy(Type::VoidTy);
1146 unsigned ArgAttrs1, ArgAttrs2;
1148 if (ParseType(ArgTy, ArgLoc) ||
1149 ParseOptionalAttrs(ArgAttrs1, 0) ||
1150 ParseValue(ArgTy, V, PFS) ||
1151 // FIXME: Should not allow attributes after the argument, remove this in
1153 ParseOptionalAttrs(ArgAttrs2, 3))
1155 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1158 Lex.Lex(); // Lex the ')'.
1164 /// ParseArgumentList - Parse the argument list for a function type or function
1165 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1166 /// ::= '(' ArgTypeListI ')'
1170 /// ::= ArgTypeList ',' '...'
1171 /// ::= ArgType (',' ArgType)*
1173 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1174 bool &isVarArg, bool inType) {
1176 assert(Lex.getKind() == lltok::lparen);
1177 Lex.Lex(); // eat the (.
1179 if (Lex.getKind() == lltok::rparen) {
1181 } else if (Lex.getKind() == lltok::dotdotdot) {
1185 LocTy TypeLoc = Lex.getLoc();
1186 PATypeHolder ArgTy(Type::VoidTy);
1190 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1191 // types (such as a function returning a pointer to itself). If parsing a
1192 // function prototype, we require fully resolved types.
1193 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1194 ParseOptionalAttrs(Attrs, 0)) return true;
1196 if (ArgTy == Type::VoidTy)
1197 return Error(TypeLoc, "argument can not have void type");
1199 if (Lex.getKind() == lltok::LocalVar ||
1200 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1201 Name = Lex.getStrVal();
1205 if (!FunctionType::isValidArgumentType(ArgTy))
1206 return Error(TypeLoc, "invalid type for function argument");
1208 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1210 while (EatIfPresent(lltok::comma)) {
1211 // Handle ... at end of arg list.
1212 if (EatIfPresent(lltok::dotdotdot)) {
1217 // Otherwise must be an argument type.
1218 TypeLoc = Lex.getLoc();
1219 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1220 ParseOptionalAttrs(Attrs, 0)) return true;
1222 if (ArgTy == Type::VoidTy)
1223 return Error(TypeLoc, "argument can not have void type");
1225 if (Lex.getKind() == lltok::LocalVar ||
1226 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1227 Name = Lex.getStrVal();
1233 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1234 return Error(TypeLoc, "invalid type for function argument");
1236 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1240 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1243 /// ParseFunctionType
1244 /// ::= Type ArgumentList OptionalAttrs
1245 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1246 assert(Lex.getKind() == lltok::lparen);
1248 if (!FunctionType::isValidReturnType(Result))
1249 return TokError("invalid function return type");
1251 std::vector<ArgInfo> ArgList;
1254 if (ParseArgumentList(ArgList, isVarArg, true) ||
1255 // FIXME: Allow, but ignore attributes on function types!
1256 // FIXME: Remove in LLVM 3.0
1257 ParseOptionalAttrs(Attrs, 2))
1260 // Reject names on the arguments lists.
1261 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1262 if (!ArgList[i].Name.empty())
1263 return Error(ArgList[i].Loc, "argument name invalid in function type");
1264 if (!ArgList[i].Attrs != 0) {
1265 // Allow but ignore attributes on function types; this permits
1267 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1271 std::vector<const Type*> ArgListTy;
1272 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1273 ArgListTy.push_back(ArgList[i].Type);
1275 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1276 ArgListTy, isVarArg));
1280 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1283 /// ::= '{' TypeRec (',' TypeRec)* '}'
1284 /// ::= '<' '{' '}' '>'
1285 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1286 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1287 assert(Lex.getKind() == lltok::lbrace);
1288 Lex.Lex(); // Consume the '{'
1290 if (EatIfPresent(lltok::rbrace)) {
1291 Result = Context.getStructType(Packed);
1295 std::vector<PATypeHolder> ParamsList;
1296 LocTy EltTyLoc = Lex.getLoc();
1297 if (ParseTypeRec(Result)) return true;
1298 ParamsList.push_back(Result);
1300 if (Result == Type::VoidTy)
1301 return Error(EltTyLoc, "struct element can not have void type");
1302 if (!StructType::isValidElementType(Result))
1303 return Error(EltTyLoc, "invalid element type for struct");
1305 while (EatIfPresent(lltok::comma)) {
1306 EltTyLoc = Lex.getLoc();
1307 if (ParseTypeRec(Result)) return true;
1309 if (Result == Type::VoidTy)
1310 return Error(EltTyLoc, "struct element can not have void type");
1311 if (!StructType::isValidElementType(Result))
1312 return Error(EltTyLoc, "invalid element type for struct");
1314 ParamsList.push_back(Result);
1317 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1320 std::vector<const Type*> ParamsListTy;
1321 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1322 ParamsListTy.push_back(ParamsList[i].get());
1323 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1327 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1328 /// token has already been consumed.
1330 /// ::= '[' APSINTVAL 'x' Types ']'
1331 /// ::= '<' APSINTVAL 'x' Types '>'
1332 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1333 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1334 Lex.getAPSIntVal().getBitWidth() > 64)
1335 return TokError("expected number in address space");
1337 LocTy SizeLoc = Lex.getLoc();
1338 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1341 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1344 LocTy TypeLoc = Lex.getLoc();
1345 PATypeHolder EltTy(Type::VoidTy);
1346 if (ParseTypeRec(EltTy)) return true;
1348 if (EltTy == Type::VoidTy)
1349 return Error(TypeLoc, "array and vector element type cannot be void");
1351 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1352 "expected end of sequential type"))
1357 return Error(SizeLoc, "zero element vector is illegal");
1358 if ((unsigned)Size != Size)
1359 return Error(SizeLoc, "size too large for vector");
1360 if (!VectorType::isValidElementType(EltTy))
1361 return Error(TypeLoc, "vector element type must be fp or integer");
1362 Result = Context.getVectorType(EltTy, unsigned(Size));
1364 if (!ArrayType::isValidElementType(EltTy))
1365 return Error(TypeLoc, "invalid array element type");
1366 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1371 //===----------------------------------------------------------------------===//
1372 // Function Semantic Analysis.
1373 //===----------------------------------------------------------------------===//
1375 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1378 // Insert unnamed arguments into the NumberedVals list.
1379 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1382 NumberedVals.push_back(AI);
1385 LLParser::PerFunctionState::~PerFunctionState() {
1386 // If there were any forward referenced non-basicblock values, delete them.
1387 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1388 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1389 if (!isa<BasicBlock>(I->second.first)) {
1390 I->second.first->replaceAllUsesWith(
1391 P.getContext().getUndef(I->second.first->getType()));
1392 delete I->second.first;
1393 I->second.first = 0;
1396 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1397 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1398 if (!isa<BasicBlock>(I->second.first)) {
1399 I->second.first->replaceAllUsesWith(
1400 P.getContext().getUndef(I->second.first->getType()));
1401 delete I->second.first;
1402 I->second.first = 0;
1406 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1407 if (!ForwardRefVals.empty())
1408 return P.Error(ForwardRefVals.begin()->second.second,
1409 "use of undefined value '%" + ForwardRefVals.begin()->first +
1411 if (!ForwardRefValIDs.empty())
1412 return P.Error(ForwardRefValIDs.begin()->second.second,
1413 "use of undefined value '%" +
1414 utostr(ForwardRefValIDs.begin()->first) + "'");
1419 /// GetVal - Get a value with the specified name or ID, creating a
1420 /// forward reference record if needed. This can return null if the value
1421 /// exists but does not have the right type.
1422 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1423 const Type *Ty, LocTy Loc) {
1424 // Look this name up in the normal function symbol table.
1425 Value *Val = F.getValueSymbolTable().lookup(Name);
1427 // If this is a forward reference for the value, see if we already created a
1428 // forward ref record.
1430 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1431 I = ForwardRefVals.find(Name);
1432 if (I != ForwardRefVals.end())
1433 Val = I->second.first;
1436 // If we have the value in the symbol table or fwd-ref table, return it.
1438 if (Val->getType() == Ty) return Val;
1439 if (Ty == Type::LabelTy)
1440 P.Error(Loc, "'%" + Name + "' is not a basic block");
1442 P.Error(Loc, "'%" + Name + "' defined with type '" +
1443 Val->getType()->getDescription() + "'");
1447 // Don't make placeholders with invalid type.
1448 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1449 P.Error(Loc, "invalid use of a non-first-class type");
1453 // Otherwise, create a new forward reference for this value and remember it.
1455 if (Ty == Type::LabelTy)
1456 FwdVal = BasicBlock::Create(Name, &F);
1458 FwdVal = new Argument(Ty, Name);
1460 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1464 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1466 // Look this name up in the normal function symbol table.
1467 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1469 // If this is a forward reference for the value, see if we already created a
1470 // forward ref record.
1472 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1473 I = ForwardRefValIDs.find(ID);
1474 if (I != ForwardRefValIDs.end())
1475 Val = I->second.first;
1478 // If we have the value in the symbol table or fwd-ref table, return it.
1480 if (Val->getType() == Ty) return Val;
1481 if (Ty == Type::LabelTy)
1482 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1484 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1485 Val->getType()->getDescription() + "'");
1489 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1490 P.Error(Loc, "invalid use of a non-first-class type");
1494 // Otherwise, create a new forward reference for this value and remember it.
1496 if (Ty == Type::LabelTy)
1497 FwdVal = BasicBlock::Create("", &F);
1499 FwdVal = new Argument(Ty);
1501 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1505 /// SetInstName - After an instruction is parsed and inserted into its
1506 /// basic block, this installs its name.
1507 bool LLParser::PerFunctionState::SetInstName(int NameID,
1508 const std::string &NameStr,
1509 LocTy NameLoc, Instruction *Inst) {
1510 // If this instruction has void type, it cannot have a name or ID specified.
1511 if (Inst->getType() == Type::VoidTy) {
1512 if (NameID != -1 || !NameStr.empty())
1513 return P.Error(NameLoc, "instructions returning void cannot have a name");
1517 // If this was a numbered instruction, verify that the instruction is the
1518 // expected value and resolve any forward references.
1519 if (NameStr.empty()) {
1520 // If neither a name nor an ID was specified, just use the next ID.
1522 NameID = NumberedVals.size();
1524 if (unsigned(NameID) != NumberedVals.size())
1525 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1526 utostr(NumberedVals.size()) + "'");
1528 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1529 ForwardRefValIDs.find(NameID);
1530 if (FI != ForwardRefValIDs.end()) {
1531 if (FI->second.first->getType() != Inst->getType())
1532 return P.Error(NameLoc, "instruction forward referenced with type '" +
1533 FI->second.first->getType()->getDescription() + "'");
1534 FI->second.first->replaceAllUsesWith(Inst);
1535 ForwardRefValIDs.erase(FI);
1538 NumberedVals.push_back(Inst);
1542 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1543 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1544 FI = ForwardRefVals.find(NameStr);
1545 if (FI != ForwardRefVals.end()) {
1546 if (FI->second.first->getType() != Inst->getType())
1547 return P.Error(NameLoc, "instruction forward referenced with type '" +
1548 FI->second.first->getType()->getDescription() + "'");
1549 FI->second.first->replaceAllUsesWith(Inst);
1550 ForwardRefVals.erase(FI);
1553 // Set the name on the instruction.
1554 Inst->setName(NameStr);
1556 if (Inst->getNameStr() != NameStr)
1557 return P.Error(NameLoc, "multiple definition of local value named '" +
1562 /// GetBB - Get a basic block with the specified name or ID, creating a
1563 /// forward reference record if needed.
1564 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1566 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1569 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1570 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1573 /// DefineBB - Define the specified basic block, which is either named or
1574 /// unnamed. If there is an error, this returns null otherwise it returns
1575 /// the block being defined.
1576 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1580 BB = GetBB(NumberedVals.size(), Loc);
1582 BB = GetBB(Name, Loc);
1583 if (BB == 0) return 0; // Already diagnosed error.
1585 // Move the block to the end of the function. Forward ref'd blocks are
1586 // inserted wherever they happen to be referenced.
1587 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1589 // Remove the block from forward ref sets.
1591 ForwardRefValIDs.erase(NumberedVals.size());
1592 NumberedVals.push_back(BB);
1594 // BB forward references are already in the function symbol table.
1595 ForwardRefVals.erase(Name);
1601 //===----------------------------------------------------------------------===//
1603 //===----------------------------------------------------------------------===//
1605 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1606 /// type implied. For example, if we parse "4" we don't know what integer type
1607 /// it has. The value will later be combined with its type and checked for
1609 bool LLParser::ParseValID(ValID &ID) {
1610 ID.Loc = Lex.getLoc();
1611 switch (Lex.getKind()) {
1612 default: return TokError("expected value token");
1613 case lltok::GlobalID: // @42
1614 ID.UIntVal = Lex.getUIntVal();
1615 ID.Kind = ValID::t_GlobalID;
1617 case lltok::GlobalVar: // @foo
1618 ID.StrVal = Lex.getStrVal();
1619 ID.Kind = ValID::t_GlobalName;
1621 case lltok::LocalVarID: // %42
1622 ID.UIntVal = Lex.getUIntVal();
1623 ID.Kind = ValID::t_LocalID;
1625 case lltok::LocalVar: // %foo
1626 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1627 ID.StrVal = Lex.getStrVal();
1628 ID.Kind = ValID::t_LocalName;
1630 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1631 ID.Kind = ValID::t_Constant;
1633 if (Lex.getKind() == lltok::lbrace) {
1634 SmallVector<Value*, 16> Elts;
1635 if (ParseMDNodeVector(Elts) ||
1636 ParseToken(lltok::rbrace, "expected end of metadata node"))
1639 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1643 // Standalone metadata reference
1644 // !{ ..., !42, ... }
1646 if (!ParseUInt32(MID)) {
1647 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1648 if (I != MetadataCache.end())
1649 ID.ConstantVal = I->second;
1651 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1652 FI = ForwardRefMDNodes.find(MID);
1653 if (FI != ForwardRefMDNodes.end())
1654 ID.ConstantVal = FI->second.first;
1656 // Create MDNode forward reference
1657 SmallVector<Value *, 1> Elts;
1658 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
1659 Elts.push_back(Context.getMDString(FwdRefName));
1660 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1661 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1662 ID.ConstantVal = FwdNode;
1670 // ::= '!' STRINGCONSTANT
1672 if (ParseStringConstant(Str)) return true;
1674 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
1678 ID.APSIntVal = Lex.getAPSIntVal();
1679 ID.Kind = ValID::t_APSInt;
1681 case lltok::APFloat:
1682 ID.APFloatVal = Lex.getAPFloatVal();
1683 ID.Kind = ValID::t_APFloat;
1685 case lltok::kw_true:
1686 ID.ConstantVal = Context.getConstantIntTrue();
1687 ID.Kind = ValID::t_Constant;
1689 case lltok::kw_false:
1690 ID.ConstantVal = Context.getConstantIntFalse();
1691 ID.Kind = ValID::t_Constant;
1693 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1694 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1695 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1697 case lltok::lbrace: {
1698 // ValID ::= '{' ConstVector '}'
1700 SmallVector<Constant*, 16> Elts;
1701 if (ParseGlobalValueVector(Elts) ||
1702 ParseToken(lltok::rbrace, "expected end of struct constant"))
1705 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1706 ID.Kind = ValID::t_Constant;
1710 // ValID ::= '<' ConstVector '>' --> Vector.
1711 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1713 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1715 SmallVector<Constant*, 16> Elts;
1716 LocTy FirstEltLoc = Lex.getLoc();
1717 if (ParseGlobalValueVector(Elts) ||
1719 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1720 ParseToken(lltok::greater, "expected end of constant"))
1723 if (isPackedStruct) {
1725 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1726 ID.Kind = ValID::t_Constant;
1731 return Error(ID.Loc, "constant vector must not be empty");
1733 if (!Elts[0]->getType()->isInteger() &&
1734 !Elts[0]->getType()->isFloatingPoint())
1735 return Error(FirstEltLoc,
1736 "vector elements must have integer or floating point type");
1738 // Verify that all the vector elements have the same type.
1739 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1740 if (Elts[i]->getType() != Elts[0]->getType())
1741 return Error(FirstEltLoc,
1742 "vector element #" + utostr(i) +
1743 " is not of type '" + Elts[0]->getType()->getDescription());
1745 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1746 ID.Kind = ValID::t_Constant;
1749 case lltok::lsquare: { // Array Constant
1751 SmallVector<Constant*, 16> Elts;
1752 LocTy FirstEltLoc = Lex.getLoc();
1753 if (ParseGlobalValueVector(Elts) ||
1754 ParseToken(lltok::rsquare, "expected end of array constant"))
1757 // Handle empty element.
1759 // Use undef instead of an array because it's inconvenient to determine
1760 // the element type at this point, there being no elements to examine.
1761 ID.Kind = ValID::t_EmptyArray;
1765 if (!Elts[0]->getType()->isFirstClassType())
1766 return Error(FirstEltLoc, "invalid array element type: " +
1767 Elts[0]->getType()->getDescription());
1769 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1771 // Verify all elements are correct type!
1772 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1773 if (Elts[i]->getType() != Elts[0]->getType())
1774 return Error(FirstEltLoc,
1775 "array element #" + utostr(i) +
1776 " is not of type '" +Elts[0]->getType()->getDescription());
1779 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1780 ID.Kind = ValID::t_Constant;
1783 case lltok::kw_c: // c "foo"
1785 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1786 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1787 ID.Kind = ValID::t_Constant;
1790 case lltok::kw_asm: {
1791 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1794 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1795 ParseStringConstant(ID.StrVal) ||
1796 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1797 ParseToken(lltok::StringConstant, "expected constraint string"))
1799 ID.StrVal2 = Lex.getStrVal();
1800 ID.UIntVal = HasSideEffect;
1801 ID.Kind = ValID::t_InlineAsm;
1805 case lltok::kw_trunc:
1806 case lltok::kw_zext:
1807 case lltok::kw_sext:
1808 case lltok::kw_fptrunc:
1809 case lltok::kw_fpext:
1810 case lltok::kw_bitcast:
1811 case lltok::kw_uitofp:
1812 case lltok::kw_sitofp:
1813 case lltok::kw_fptoui:
1814 case lltok::kw_fptosi:
1815 case lltok::kw_inttoptr:
1816 case lltok::kw_ptrtoint: {
1817 unsigned Opc = Lex.getUIntVal();
1818 PATypeHolder DestTy(Type::VoidTy);
1821 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1822 ParseGlobalTypeAndValue(SrcVal) ||
1823 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1824 ParseType(DestTy) ||
1825 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1827 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1828 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1829 SrcVal->getType()->getDescription() + "' to '" +
1830 DestTy->getDescription() + "'");
1831 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1833 ID.Kind = ValID::t_Constant;
1836 case lltok::kw_extractvalue: {
1839 SmallVector<unsigned, 4> Indices;
1840 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1841 ParseGlobalTypeAndValue(Val) ||
1842 ParseIndexList(Indices) ||
1843 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1845 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1846 return Error(ID.Loc, "extractvalue operand must be array or struct");
1847 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1849 return Error(ID.Loc, "invalid indices for extractvalue");
1851 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1852 ID.Kind = ValID::t_Constant;
1855 case lltok::kw_insertvalue: {
1857 Constant *Val0, *Val1;
1858 SmallVector<unsigned, 4> Indices;
1859 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1860 ParseGlobalTypeAndValue(Val0) ||
1861 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1862 ParseGlobalTypeAndValue(Val1) ||
1863 ParseIndexList(Indices) ||
1864 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1866 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1867 return Error(ID.Loc, "extractvalue operand must be array or struct");
1868 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1870 return Error(ID.Loc, "invalid indices for insertvalue");
1871 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1872 Indices.data(), Indices.size());
1873 ID.Kind = ValID::t_Constant;
1876 case lltok::kw_icmp:
1877 case lltok::kw_fcmp: {
1878 unsigned PredVal, Opc = Lex.getUIntVal();
1879 Constant *Val0, *Val1;
1881 if (ParseCmpPredicate(PredVal, Opc) ||
1882 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1883 ParseGlobalTypeAndValue(Val0) ||
1884 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1885 ParseGlobalTypeAndValue(Val1) ||
1886 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1889 if (Val0->getType() != Val1->getType())
1890 return Error(ID.Loc, "compare operands must have the same type");
1892 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1894 if (Opc == Instruction::FCmp) {
1895 if (!Val0->getType()->isFPOrFPVector())
1896 return Error(ID.Loc, "fcmp requires floating point operands");
1897 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1899 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1900 if (!Val0->getType()->isIntOrIntVector() &&
1901 !isa<PointerType>(Val0->getType()))
1902 return Error(ID.Loc, "icmp requires pointer or integer operands");
1903 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1905 ID.Kind = ValID::t_Constant;
1909 // Binary Operators.
1911 case lltok::kw_fadd:
1913 case lltok::kw_fsub:
1915 case lltok::kw_fmul:
1916 case lltok::kw_udiv:
1917 case lltok::kw_sdiv:
1918 case lltok::kw_fdiv:
1919 case lltok::kw_urem:
1920 case lltok::kw_srem:
1921 case lltok::kw_frem: {
1922 unsigned Opc = Lex.getUIntVal();
1923 Constant *Val0, *Val1;
1925 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1926 ParseGlobalTypeAndValue(Val0) ||
1927 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1928 ParseGlobalTypeAndValue(Val1) ||
1929 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1931 if (Val0->getType() != Val1->getType())
1932 return Error(ID.Loc, "operands of constexpr must have same type");
1933 if (!Val0->getType()->isIntOrIntVector() &&
1934 !Val0->getType()->isFPOrFPVector())
1935 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1936 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1937 ID.Kind = ValID::t_Constant;
1941 // Logical Operations
1943 case lltok::kw_lshr:
1944 case lltok::kw_ashr:
1947 case lltok::kw_xor: {
1948 unsigned Opc = Lex.getUIntVal();
1949 Constant *Val0, *Val1;
1951 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1952 ParseGlobalTypeAndValue(Val0) ||
1953 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1954 ParseGlobalTypeAndValue(Val1) ||
1955 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1957 if (Val0->getType() != Val1->getType())
1958 return Error(ID.Loc, "operands of constexpr must have same type");
1959 if (!Val0->getType()->isIntOrIntVector())
1960 return Error(ID.Loc,
1961 "constexpr requires integer or integer vector operands");
1962 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1963 ID.Kind = ValID::t_Constant;
1967 case lltok::kw_getelementptr:
1968 case lltok::kw_shufflevector:
1969 case lltok::kw_insertelement:
1970 case lltok::kw_extractelement:
1971 case lltok::kw_select: {
1972 unsigned Opc = Lex.getUIntVal();
1973 SmallVector<Constant*, 16> Elts;
1975 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1976 ParseGlobalValueVector(Elts) ||
1977 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1980 if (Opc == Instruction::GetElementPtr) {
1981 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1982 return Error(ID.Loc, "getelementptr requires pointer operand");
1984 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1985 (Value**)&Elts[1], Elts.size()-1))
1986 return Error(ID.Loc, "invalid indices for getelementptr");
1987 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
1988 &Elts[1], Elts.size()-1);
1989 } else if (Opc == Instruction::Select) {
1990 if (Elts.size() != 3)
1991 return Error(ID.Loc, "expected three operands to select");
1992 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1994 return Error(ID.Loc, Reason);
1995 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
1996 } else if (Opc == Instruction::ShuffleVector) {
1997 if (Elts.size() != 3)
1998 return Error(ID.Loc, "expected three operands to shufflevector");
1999 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2000 return Error(ID.Loc, "invalid operands to shufflevector");
2002 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2003 } else if (Opc == Instruction::ExtractElement) {
2004 if (Elts.size() != 2)
2005 return Error(ID.Loc, "expected two operands to extractelement");
2006 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2007 return Error(ID.Loc, "invalid extractelement operands");
2008 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2010 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2011 if (Elts.size() != 3)
2012 return Error(ID.Loc, "expected three operands to insertelement");
2013 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2014 return Error(ID.Loc, "invalid insertelement operands");
2016 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2019 ID.Kind = ValID::t_Constant;
2028 /// ParseGlobalValue - Parse a global value with the specified type.
2029 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2032 return ParseValID(ID) ||
2033 ConvertGlobalValIDToValue(Ty, ID, V);
2036 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2038 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2040 if (isa<FunctionType>(Ty))
2041 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2044 default: llvm_unreachable("Unknown ValID!");
2045 case ValID::t_LocalID:
2046 case ValID::t_LocalName:
2047 return Error(ID.Loc, "invalid use of function-local name");
2048 case ValID::t_InlineAsm:
2049 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2050 case ValID::t_GlobalName:
2051 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2053 case ValID::t_GlobalID:
2054 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2056 case ValID::t_APSInt:
2057 if (!isa<IntegerType>(Ty))
2058 return Error(ID.Loc, "integer constant must have integer type");
2059 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2060 V = Context.getConstantInt(ID.APSIntVal);
2062 case ValID::t_APFloat:
2063 if (!Ty->isFloatingPoint() ||
2064 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2065 return Error(ID.Loc, "floating point constant invalid for type");
2067 // The lexer has no type info, so builds all float and double FP constants
2068 // as double. Fix this here. Long double does not need this.
2069 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2070 Ty == Type::FloatTy) {
2072 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2075 V = Context.getConstantFP(ID.APFloatVal);
2077 if (V->getType() != Ty)
2078 return Error(ID.Loc, "floating point constant does not have type '" +
2079 Ty->getDescription() + "'");
2083 if (!isa<PointerType>(Ty))
2084 return Error(ID.Loc, "null must be a pointer type");
2085 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2087 case ValID::t_Undef:
2088 // FIXME: LabelTy should not be a first-class type.
2089 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2090 !isa<OpaqueType>(Ty))
2091 return Error(ID.Loc, "invalid type for undef constant");
2092 V = Context.getUndef(Ty);
2094 case ValID::t_EmptyArray:
2095 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2096 return Error(ID.Loc, "invalid empty array initializer");
2097 V = Context.getUndef(Ty);
2100 // FIXME: LabelTy should not be a first-class type.
2101 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2102 return Error(ID.Loc, "invalid type for null constant");
2103 V = Context.getNullValue(Ty);
2105 case ValID::t_Constant:
2106 if (ID.ConstantVal->getType() != Ty)
2107 return Error(ID.Loc, "constant expression type mismatch");
2113 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2114 PATypeHolder Type(Type::VoidTy);
2115 return ParseType(Type) ||
2116 ParseGlobalValue(Type, V);
2119 /// ParseGlobalValueVector
2121 /// ::= TypeAndValue (',' TypeAndValue)*
2122 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2124 if (Lex.getKind() == lltok::rbrace ||
2125 Lex.getKind() == lltok::rsquare ||
2126 Lex.getKind() == lltok::greater ||
2127 Lex.getKind() == lltok::rparen)
2131 if (ParseGlobalTypeAndValue(C)) return true;
2134 while (EatIfPresent(lltok::comma)) {
2135 if (ParseGlobalTypeAndValue(C)) return true;
2143 //===----------------------------------------------------------------------===//
2144 // Function Parsing.
2145 //===----------------------------------------------------------------------===//
2147 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2148 PerFunctionState &PFS) {
2149 if (ID.Kind == ValID::t_LocalID)
2150 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2151 else if (ID.Kind == ValID::t_LocalName)
2152 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2153 else if (ID.Kind == ValID::t_InlineAsm) {
2154 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2155 const FunctionType *FTy =
2156 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2157 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2158 return Error(ID.Loc, "invalid type for inline asm constraint string");
2159 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2163 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2171 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2174 return ParseValID(ID) ||
2175 ConvertValIDToValue(Ty, ID, V, PFS);
2178 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2179 PATypeHolder T(Type::VoidTy);
2180 return ParseType(T) ||
2181 ParseValue(T, V, PFS);
2185 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2186 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2187 /// OptionalAlign OptGC
2188 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2189 // Parse the linkage.
2190 LocTy LinkageLoc = Lex.getLoc();
2193 unsigned Visibility, CC, RetAttrs;
2194 PATypeHolder RetType(Type::VoidTy);
2195 LocTy RetTypeLoc = Lex.getLoc();
2196 if (ParseOptionalLinkage(Linkage) ||
2197 ParseOptionalVisibility(Visibility) ||
2198 ParseOptionalCallingConv(CC) ||
2199 ParseOptionalAttrs(RetAttrs, 1) ||
2200 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2203 // Verify that the linkage is ok.
2204 switch ((GlobalValue::LinkageTypes)Linkage) {
2205 case GlobalValue::ExternalLinkage:
2206 break; // always ok.
2207 case GlobalValue::DLLImportLinkage:
2208 case GlobalValue::ExternalWeakLinkage:
2210 return Error(LinkageLoc, "invalid linkage for function definition");
2212 case GlobalValue::PrivateLinkage:
2213 case GlobalValue::InternalLinkage:
2214 case GlobalValue::AvailableExternallyLinkage:
2215 case GlobalValue::LinkOnceAnyLinkage:
2216 case GlobalValue::LinkOnceODRLinkage:
2217 case GlobalValue::WeakAnyLinkage:
2218 case GlobalValue::WeakODRLinkage:
2219 case GlobalValue::DLLExportLinkage:
2221 return Error(LinkageLoc, "invalid linkage for function declaration");
2223 case GlobalValue::AppendingLinkage:
2224 case GlobalValue::GhostLinkage:
2225 case GlobalValue::CommonLinkage:
2226 return Error(LinkageLoc, "invalid function linkage type");
2229 if (!FunctionType::isValidReturnType(RetType) ||
2230 isa<OpaqueType>(RetType))
2231 return Error(RetTypeLoc, "invalid function return type");
2233 LocTy NameLoc = Lex.getLoc();
2235 std::string FunctionName;
2236 if (Lex.getKind() == lltok::GlobalVar) {
2237 FunctionName = Lex.getStrVal();
2238 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2239 unsigned NameID = Lex.getUIntVal();
2241 if (NameID != NumberedVals.size())
2242 return TokError("function expected to be numbered '%" +
2243 utostr(NumberedVals.size()) + "'");
2245 return TokError("expected function name");
2250 if (Lex.getKind() != lltok::lparen)
2251 return TokError("expected '(' in function argument list");
2253 std::vector<ArgInfo> ArgList;
2256 std::string Section;
2260 if (ParseArgumentList(ArgList, isVarArg, false) ||
2261 ParseOptionalAttrs(FuncAttrs, 2) ||
2262 (EatIfPresent(lltok::kw_section) &&
2263 ParseStringConstant(Section)) ||
2264 ParseOptionalAlignment(Alignment) ||
2265 (EatIfPresent(lltok::kw_gc) &&
2266 ParseStringConstant(GC)))
2269 // If the alignment was parsed as an attribute, move to the alignment field.
2270 if (FuncAttrs & Attribute::Alignment) {
2271 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2272 FuncAttrs &= ~Attribute::Alignment;
2275 // Okay, if we got here, the function is syntactically valid. Convert types
2276 // and do semantic checks.
2277 std::vector<const Type*> ParamTypeList;
2278 SmallVector<AttributeWithIndex, 8> Attrs;
2279 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2281 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2282 if (FuncAttrs & ObsoleteFuncAttrs) {
2283 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2284 FuncAttrs &= ~ObsoleteFuncAttrs;
2287 if (RetAttrs != Attribute::None)
2288 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2290 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2291 ParamTypeList.push_back(ArgList[i].Type);
2292 if (ArgList[i].Attrs != Attribute::None)
2293 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2296 if (FuncAttrs != Attribute::None)
2297 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2299 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2301 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2302 RetType != Type::VoidTy)
2303 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2305 const FunctionType *FT =
2306 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2307 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2310 if (!FunctionName.empty()) {
2311 // If this was a definition of a forward reference, remove the definition
2312 // from the forward reference table and fill in the forward ref.
2313 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2314 ForwardRefVals.find(FunctionName);
2315 if (FRVI != ForwardRefVals.end()) {
2316 Fn = M->getFunction(FunctionName);
2317 ForwardRefVals.erase(FRVI);
2318 } else if ((Fn = M->getFunction(FunctionName))) {
2319 // If this function already exists in the symbol table, then it is
2320 // multiply defined. We accept a few cases for old backwards compat.
2321 // FIXME: Remove this stuff for LLVM 3.0.
2322 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2323 (!Fn->isDeclaration() && isDefine)) {
2324 // If the redefinition has different type or different attributes,
2325 // reject it. If both have bodies, reject it.
2326 return Error(NameLoc, "invalid redefinition of function '" +
2327 FunctionName + "'");
2328 } else if (Fn->isDeclaration()) {
2329 // Make sure to strip off any argument names so we can't get conflicts.
2330 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2336 } else if (FunctionName.empty()) {
2337 // If this is a definition of a forward referenced function, make sure the
2339 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2340 = ForwardRefValIDs.find(NumberedVals.size());
2341 if (I != ForwardRefValIDs.end()) {
2342 Fn = cast<Function>(I->second.first);
2343 if (Fn->getType() != PFT)
2344 return Error(NameLoc, "type of definition and forward reference of '@" +
2345 utostr(NumberedVals.size()) +"' disagree");
2346 ForwardRefValIDs.erase(I);
2351 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2352 else // Move the forward-reference to the correct spot in the module.
2353 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2355 if (FunctionName.empty())
2356 NumberedVals.push_back(Fn);
2358 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2359 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2360 Fn->setCallingConv(CC);
2361 Fn->setAttributes(PAL);
2362 Fn->setAlignment(Alignment);
2363 Fn->setSection(Section);
2364 if (!GC.empty()) Fn->setGC(GC.c_str());
2366 // Add all of the arguments we parsed to the function.
2367 Function::arg_iterator ArgIt = Fn->arg_begin();
2368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2369 // If the argument has a name, insert it into the argument symbol table.
2370 if (ArgList[i].Name.empty()) continue;
2372 // Set the name, if it conflicted, it will be auto-renamed.
2373 ArgIt->setName(ArgList[i].Name);
2375 if (ArgIt->getNameStr() != ArgList[i].Name)
2376 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2377 ArgList[i].Name + "'");
2384 /// ParseFunctionBody
2385 /// ::= '{' BasicBlock+ '}'
2386 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2388 bool LLParser::ParseFunctionBody(Function &Fn) {
2389 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2390 return TokError("expected '{' in function body");
2391 Lex.Lex(); // eat the {.
2393 PerFunctionState PFS(*this, Fn);
2395 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2396 if (ParseBasicBlock(PFS)) return true;
2401 // Verify function is ok.
2402 return PFS.VerifyFunctionComplete();
2406 /// ::= LabelStr? Instruction*
2407 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2408 // If this basic block starts out with a name, remember it.
2410 LocTy NameLoc = Lex.getLoc();
2411 if (Lex.getKind() == lltok::LabelStr) {
2412 Name = Lex.getStrVal();
2416 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2417 if (BB == 0) return true;
2419 std::string NameStr;
2421 // Parse the instructions in this block until we get a terminator.
2424 // This instruction may have three possibilities for a name: a) none
2425 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2426 LocTy NameLoc = Lex.getLoc();
2430 if (Lex.getKind() == lltok::LocalVarID) {
2431 NameID = Lex.getUIntVal();
2433 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2435 } else if (Lex.getKind() == lltok::LocalVar ||
2436 // FIXME: REMOVE IN LLVM 3.0
2437 Lex.getKind() == lltok::StringConstant) {
2438 NameStr = Lex.getStrVal();
2440 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2444 if (ParseInstruction(Inst, BB, PFS)) return true;
2446 BB->getInstList().push_back(Inst);
2448 // Set the name on the instruction.
2449 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2450 } while (!isa<TerminatorInst>(Inst));
2455 //===----------------------------------------------------------------------===//
2456 // Instruction Parsing.
2457 //===----------------------------------------------------------------------===//
2459 /// ParseInstruction - Parse one of the many different instructions.
2461 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2462 PerFunctionState &PFS) {
2463 lltok::Kind Token = Lex.getKind();
2464 if (Token == lltok::Eof)
2465 return TokError("found end of file when expecting more instructions");
2466 LocTy Loc = Lex.getLoc();
2467 unsigned KeywordVal = Lex.getUIntVal();
2468 Lex.Lex(); // Eat the keyword.
2471 default: return Error(Loc, "expected instruction opcode");
2472 // Terminator Instructions.
2473 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2474 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2475 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2476 case lltok::kw_br: return ParseBr(Inst, PFS);
2477 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2478 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2479 // Binary Operators.
2483 // API compatibility: Accept either integer or floating-point types.
2484 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2485 case lltok::kw_fadd:
2486 case lltok::kw_fsub:
2487 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2489 case lltok::kw_udiv:
2490 case lltok::kw_sdiv:
2491 case lltok::kw_urem:
2492 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2493 case lltok::kw_fdiv:
2494 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2496 case lltok::kw_lshr:
2497 case lltok::kw_ashr:
2500 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2501 case lltok::kw_icmp:
2502 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2504 case lltok::kw_trunc:
2505 case lltok::kw_zext:
2506 case lltok::kw_sext:
2507 case lltok::kw_fptrunc:
2508 case lltok::kw_fpext:
2509 case lltok::kw_bitcast:
2510 case lltok::kw_uitofp:
2511 case lltok::kw_sitofp:
2512 case lltok::kw_fptoui:
2513 case lltok::kw_fptosi:
2514 case lltok::kw_inttoptr:
2515 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2517 case lltok::kw_select: return ParseSelect(Inst, PFS);
2518 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2519 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2520 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2521 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2522 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2523 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2524 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2526 case lltok::kw_alloca:
2527 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2528 case lltok::kw_free: return ParseFree(Inst, PFS);
2529 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2530 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2531 case lltok::kw_volatile:
2532 if (EatIfPresent(lltok::kw_load))
2533 return ParseLoad(Inst, PFS, true);
2534 else if (EatIfPresent(lltok::kw_store))
2535 return ParseStore(Inst, PFS, true);
2537 return TokError("expected 'load' or 'store'");
2538 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2539 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2540 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2541 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2545 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2546 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2547 if (Opc == Instruction::FCmp) {
2548 switch (Lex.getKind()) {
2549 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2550 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2551 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2552 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2553 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2554 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2555 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2556 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2557 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2558 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2559 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2560 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2561 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2562 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2563 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2564 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2565 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2568 switch (Lex.getKind()) {
2569 default: TokError("expected icmp predicate (e.g. 'eq')");
2570 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2571 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2572 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2573 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2574 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2575 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2576 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2577 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2578 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2579 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2586 //===----------------------------------------------------------------------===//
2587 // Terminator Instructions.
2588 //===----------------------------------------------------------------------===//
2590 /// ParseRet - Parse a return instruction.
2592 /// ::= 'ret' TypeAndValue
2593 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2594 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2595 PerFunctionState &PFS) {
2596 PATypeHolder Ty(Type::VoidTy);
2597 if (ParseType(Ty, true /*void allowed*/)) return true;
2599 if (Ty == Type::VoidTy) {
2600 Inst = ReturnInst::Create();
2605 if (ParseValue(Ty, RV, PFS)) return true;
2607 // The normal case is one return value.
2608 if (Lex.getKind() == lltok::comma) {
2609 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2610 // of 'ret {i32,i32} {i32 1, i32 2}'
2611 SmallVector<Value*, 8> RVs;
2614 while (EatIfPresent(lltok::comma)) {
2615 if (ParseTypeAndValue(RV, PFS)) return true;
2619 RV = Context.getUndef(PFS.getFunction().getReturnType());
2620 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2621 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2622 BB->getInstList().push_back(I);
2626 Inst = ReturnInst::Create(RV);
2632 /// ::= 'br' TypeAndValue
2633 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2634 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2636 Value *Op0, *Op1, *Op2;
2637 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2639 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2640 Inst = BranchInst::Create(BB);
2644 if (Op0->getType() != Type::Int1Ty)
2645 return Error(Loc, "branch condition must have 'i1' type");
2647 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2648 ParseTypeAndValue(Op1, Loc, PFS) ||
2649 ParseToken(lltok::comma, "expected ',' after true destination") ||
2650 ParseTypeAndValue(Op2, Loc2, PFS))
2653 if (!isa<BasicBlock>(Op1))
2654 return Error(Loc, "true destination of branch must be a basic block");
2655 if (!isa<BasicBlock>(Op2))
2656 return Error(Loc2, "true destination of branch must be a basic block");
2658 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2664 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2666 /// ::= (TypeAndValue ',' TypeAndValue)*
2667 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2668 LocTy CondLoc, BBLoc;
2669 Value *Cond, *DefaultBB;
2670 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2671 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2672 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2673 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2676 if (!isa<IntegerType>(Cond->getType()))
2677 return Error(CondLoc, "switch condition must have integer type");
2678 if (!isa<BasicBlock>(DefaultBB))
2679 return Error(BBLoc, "default destination must be a basic block");
2681 // Parse the jump table pairs.
2682 SmallPtrSet<Value*, 32> SeenCases;
2683 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2684 while (Lex.getKind() != lltok::rsquare) {
2685 Value *Constant, *DestBB;
2687 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2688 ParseToken(lltok::comma, "expected ',' after case value") ||
2689 ParseTypeAndValue(DestBB, BBLoc, PFS))
2692 if (!SeenCases.insert(Constant))
2693 return Error(CondLoc, "duplicate case value in switch");
2694 if (!isa<ConstantInt>(Constant))
2695 return Error(CondLoc, "case value is not a constant integer");
2696 if (!isa<BasicBlock>(DestBB))
2697 return Error(BBLoc, "case destination is not a basic block");
2699 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2700 cast<BasicBlock>(DestBB)));
2703 Lex.Lex(); // Eat the ']'.
2705 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2707 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2708 SI->addCase(Table[i].first, Table[i].second);
2714 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2715 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2716 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2717 LocTy CallLoc = Lex.getLoc();
2718 unsigned CC, RetAttrs, FnAttrs;
2719 PATypeHolder RetType(Type::VoidTy);
2722 SmallVector<ParamInfo, 16> ArgList;
2724 Value *NormalBB, *UnwindBB;
2725 if (ParseOptionalCallingConv(CC) ||
2726 ParseOptionalAttrs(RetAttrs, 1) ||
2727 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2728 ParseValID(CalleeID) ||
2729 ParseParameterList(ArgList, PFS) ||
2730 ParseOptionalAttrs(FnAttrs, 2) ||
2731 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2732 ParseTypeAndValue(NormalBB, PFS) ||
2733 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2734 ParseTypeAndValue(UnwindBB, PFS))
2737 if (!isa<BasicBlock>(NormalBB))
2738 return Error(CallLoc, "normal destination is not a basic block");
2739 if (!isa<BasicBlock>(UnwindBB))
2740 return Error(CallLoc, "unwind destination is not a basic block");
2742 // If RetType is a non-function pointer type, then this is the short syntax
2743 // for the call, which means that RetType is just the return type. Infer the
2744 // rest of the function argument types from the arguments that are present.
2745 const PointerType *PFTy = 0;
2746 const FunctionType *Ty = 0;
2747 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2748 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2749 // Pull out the types of all of the arguments...
2750 std::vector<const Type*> ParamTypes;
2751 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2752 ParamTypes.push_back(ArgList[i].V->getType());
2754 if (!FunctionType::isValidReturnType(RetType))
2755 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2757 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2758 PFTy = Context.getPointerTypeUnqual(Ty);
2761 // Look up the callee.
2763 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2765 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2766 // function attributes.
2767 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2768 if (FnAttrs & ObsoleteFuncAttrs) {
2769 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2770 FnAttrs &= ~ObsoleteFuncAttrs;
2773 // Set up the Attributes for the function.
2774 SmallVector<AttributeWithIndex, 8> Attrs;
2775 if (RetAttrs != Attribute::None)
2776 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2778 SmallVector<Value*, 8> Args;
2780 // Loop through FunctionType's arguments and ensure they are specified
2781 // correctly. Also, gather any parameter attributes.
2782 FunctionType::param_iterator I = Ty->param_begin();
2783 FunctionType::param_iterator E = Ty->param_end();
2784 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2785 const Type *ExpectedTy = 0;
2788 } else if (!Ty->isVarArg()) {
2789 return Error(ArgList[i].Loc, "too many arguments specified");
2792 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2793 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2794 ExpectedTy->getDescription() + "'");
2795 Args.push_back(ArgList[i].V);
2796 if (ArgList[i].Attrs != Attribute::None)
2797 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2801 return Error(CallLoc, "not enough parameters specified for call");
2803 if (FnAttrs != Attribute::None)
2804 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2806 // Finish off the Attributes and check them
2807 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2809 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2810 cast<BasicBlock>(UnwindBB),
2811 Args.begin(), Args.end());
2812 II->setCallingConv(CC);
2813 II->setAttributes(PAL);
2820 //===----------------------------------------------------------------------===//
2821 // Binary Operators.
2822 //===----------------------------------------------------------------------===//
2825 /// ::= ArithmeticOps TypeAndValue ',' Value
2827 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2828 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2829 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2830 unsigned Opc, unsigned OperandType) {
2831 LocTy Loc; Value *LHS, *RHS;
2832 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2833 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2834 ParseValue(LHS->getType(), RHS, PFS))
2838 switch (OperandType) {
2839 default: llvm_unreachable("Unknown operand type!");
2840 case 0: // int or FP.
2841 Valid = LHS->getType()->isIntOrIntVector() ||
2842 LHS->getType()->isFPOrFPVector();
2844 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2845 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2849 return Error(Loc, "invalid operand type for instruction");
2851 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2856 /// ::= ArithmeticOps TypeAndValue ',' Value {
2857 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2859 LocTy Loc; Value *LHS, *RHS;
2860 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2861 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2862 ParseValue(LHS->getType(), RHS, PFS))
2865 if (!LHS->getType()->isIntOrIntVector())
2866 return Error(Loc,"instruction requires integer or integer vector operands");
2868 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2874 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2875 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2876 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2878 // Parse the integer/fp comparison predicate.
2882 if (ParseCmpPredicate(Pred, Opc) ||
2883 ParseTypeAndValue(LHS, Loc, PFS) ||
2884 ParseToken(lltok::comma, "expected ',' after compare value") ||
2885 ParseValue(LHS->getType(), RHS, PFS))
2888 if (Opc == Instruction::FCmp) {
2889 if (!LHS->getType()->isFPOrFPVector())
2890 return Error(Loc, "fcmp requires floating point operands");
2891 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2893 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
2894 if (!LHS->getType()->isIntOrIntVector() &&
2895 !isa<PointerType>(LHS->getType()))
2896 return Error(Loc, "icmp requires integer operands");
2897 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2902 //===----------------------------------------------------------------------===//
2903 // Other Instructions.
2904 //===----------------------------------------------------------------------===//
2908 /// ::= CastOpc TypeAndValue 'to' Type
2909 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2911 LocTy Loc; Value *Op;
2912 PATypeHolder DestTy(Type::VoidTy);
2913 if (ParseTypeAndValue(Op, Loc, PFS) ||
2914 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2918 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2919 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2920 return Error(Loc, "invalid cast opcode for cast from '" +
2921 Op->getType()->getDescription() + "' to '" +
2922 DestTy->getDescription() + "'");
2924 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2929 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2930 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2932 Value *Op0, *Op1, *Op2;
2933 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2934 ParseToken(lltok::comma, "expected ',' after select condition") ||
2935 ParseTypeAndValue(Op1, PFS) ||
2936 ParseToken(lltok::comma, "expected ',' after select value") ||
2937 ParseTypeAndValue(Op2, PFS))
2940 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2941 return Error(Loc, Reason);
2943 Inst = SelectInst::Create(Op0, Op1, Op2);
2948 /// ::= 'va_arg' TypeAndValue ',' Type
2949 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2951 PATypeHolder EltTy(Type::VoidTy);
2953 if (ParseTypeAndValue(Op, PFS) ||
2954 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2955 ParseType(EltTy, TypeLoc))
2958 if (!EltTy->isFirstClassType())
2959 return Error(TypeLoc, "va_arg requires operand with first class type");
2961 Inst = new VAArgInst(Op, EltTy);
2965 /// ParseExtractElement
2966 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2967 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2970 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2971 ParseToken(lltok::comma, "expected ',' after extract value") ||
2972 ParseTypeAndValue(Op1, PFS))
2975 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2976 return Error(Loc, "invalid extractelement operands");
2978 Inst = new ExtractElementInst(Op0, Op1);
2982 /// ParseInsertElement
2983 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2984 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2986 Value *Op0, *Op1, *Op2;
2987 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2988 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2989 ParseTypeAndValue(Op1, PFS) ||
2990 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2991 ParseTypeAndValue(Op2, PFS))
2994 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2995 return Error(Loc, "invalid extractelement operands");
2997 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3001 /// ParseShuffleVector
3002 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3003 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3005 Value *Op0, *Op1, *Op2;
3006 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3007 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3008 ParseTypeAndValue(Op1, PFS) ||
3009 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3010 ParseTypeAndValue(Op2, PFS))
3013 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3014 return Error(Loc, "invalid extractelement operands");
3016 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3021 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3022 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3023 PATypeHolder Ty(Type::VoidTy);
3025 LocTy TypeLoc = Lex.getLoc();
3027 if (ParseType(Ty) ||
3028 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3029 ParseValue(Ty, Op0, PFS) ||
3030 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3031 ParseValue(Type::LabelTy, Op1, PFS) ||
3032 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3035 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3037 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3039 if (!EatIfPresent(lltok::comma))
3042 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3043 ParseValue(Ty, Op0, PFS) ||
3044 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3045 ParseValue(Type::LabelTy, Op1, PFS) ||
3046 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3050 if (!Ty->isFirstClassType())
3051 return Error(TypeLoc, "phi node must have first class type");
3053 PHINode *PN = PHINode::Create(Ty);
3054 PN->reserveOperandSpace(PHIVals.size());
3055 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3056 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3062 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3063 /// ParameterList OptionalAttrs
3064 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3066 unsigned CC, RetAttrs, FnAttrs;
3067 PATypeHolder RetType(Type::VoidTy);
3070 SmallVector<ParamInfo, 16> ArgList;
3071 LocTy CallLoc = Lex.getLoc();
3073 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3074 ParseOptionalCallingConv(CC) ||
3075 ParseOptionalAttrs(RetAttrs, 1) ||
3076 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3077 ParseValID(CalleeID) ||
3078 ParseParameterList(ArgList, PFS) ||
3079 ParseOptionalAttrs(FnAttrs, 2))
3082 // If RetType is a non-function pointer type, then this is the short syntax
3083 // for the call, which means that RetType is just the return type. Infer the
3084 // rest of the function argument types from the arguments that are present.
3085 const PointerType *PFTy = 0;
3086 const FunctionType *Ty = 0;
3087 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3088 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3089 // Pull out the types of all of the arguments...
3090 std::vector<const Type*> ParamTypes;
3091 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3092 ParamTypes.push_back(ArgList[i].V->getType());
3094 if (!FunctionType::isValidReturnType(RetType))
3095 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3097 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3098 PFTy = Context.getPointerTypeUnqual(Ty);
3101 // Look up the callee.
3103 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3105 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3106 // function attributes.
3107 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3108 if (FnAttrs & ObsoleteFuncAttrs) {
3109 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3110 FnAttrs &= ~ObsoleteFuncAttrs;
3113 // Set up the Attributes for the function.
3114 SmallVector<AttributeWithIndex, 8> Attrs;
3115 if (RetAttrs != Attribute::None)
3116 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3118 SmallVector<Value*, 8> Args;
3120 // Loop through FunctionType's arguments and ensure they are specified
3121 // correctly. Also, gather any parameter attributes.
3122 FunctionType::param_iterator I = Ty->param_begin();
3123 FunctionType::param_iterator E = Ty->param_end();
3124 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3125 const Type *ExpectedTy = 0;
3128 } else if (!Ty->isVarArg()) {
3129 return Error(ArgList[i].Loc, "too many arguments specified");
3132 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3133 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3134 ExpectedTy->getDescription() + "'");
3135 Args.push_back(ArgList[i].V);
3136 if (ArgList[i].Attrs != Attribute::None)
3137 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3141 return Error(CallLoc, "not enough parameters specified for call");
3143 if (FnAttrs != Attribute::None)
3144 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3146 // Finish off the Attributes and check them
3147 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3149 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3150 CI->setTailCall(isTail);
3151 CI->setCallingConv(CC);
3152 CI->setAttributes(PAL);
3157 //===----------------------------------------------------------------------===//
3158 // Memory Instructions.
3159 //===----------------------------------------------------------------------===//
3162 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3163 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3164 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3166 PATypeHolder Ty(Type::VoidTy);
3169 unsigned Alignment = 0;
3170 if (ParseType(Ty)) return true;
3172 if (EatIfPresent(lltok::comma)) {
3173 if (Lex.getKind() == lltok::kw_align) {
3174 if (ParseOptionalAlignment(Alignment)) return true;
3175 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3176 ParseOptionalCommaAlignment(Alignment)) {
3181 if (Size && Size->getType() != Type::Int32Ty)
3182 return Error(SizeLoc, "element count must be i32");
3184 if (Opc == Instruction::Malloc)
3185 Inst = new MallocInst(Context, Ty, Size, Alignment);
3187 Inst = new AllocaInst(Context, Ty, Size, Alignment);
3192 /// ::= 'free' TypeAndValue
3193 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3194 Value *Val; LocTy Loc;
3195 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3196 if (!isa<PointerType>(Val->getType()))
3197 return Error(Loc, "operand to free must be a pointer");
3198 Inst = new FreeInst(Val);
3203 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3204 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3206 Value *Val; LocTy Loc;
3208 if (ParseTypeAndValue(Val, Loc, PFS) ||
3209 ParseOptionalCommaAlignment(Alignment))
3212 if (!isa<PointerType>(Val->getType()) ||
3213 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3214 return Error(Loc, "load operand must be a pointer to a first class type");
3216 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3221 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3222 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3224 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3226 if (ParseTypeAndValue(Val, Loc, PFS) ||
3227 ParseToken(lltok::comma, "expected ',' after store operand") ||
3228 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3229 ParseOptionalCommaAlignment(Alignment))
3232 if (!isa<PointerType>(Ptr->getType()))
3233 return Error(PtrLoc, "store operand must be a pointer");
3234 if (!Val->getType()->isFirstClassType())
3235 return Error(Loc, "store operand must be a first class value");
3236 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3237 return Error(Loc, "stored value and pointer type do not match");
3239 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3244 /// ::= 'getresult' TypeAndValue ',' i32
3245 /// FIXME: Remove support for getresult in LLVM 3.0
3246 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3247 Value *Val; LocTy ValLoc, EltLoc;
3249 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3250 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3251 ParseUInt32(Element, EltLoc))
3254 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3255 return Error(ValLoc, "getresult inst requires an aggregate operand");
3256 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3257 return Error(EltLoc, "invalid getresult index for value");
3258 Inst = ExtractValueInst::Create(Val, Element);
3262 /// ParseGetElementPtr
3263 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3264 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3265 Value *Ptr, *Val; LocTy Loc, EltLoc;
3266 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3268 if (!isa<PointerType>(Ptr->getType()))
3269 return Error(Loc, "base of getelementptr must be a pointer");
3271 SmallVector<Value*, 16> Indices;
3272 while (EatIfPresent(lltok::comma)) {
3273 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3274 if (!isa<IntegerType>(Val->getType()))
3275 return Error(EltLoc, "getelementptr index must be an integer");
3276 Indices.push_back(Val);
3279 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3280 Indices.begin(), Indices.end()))
3281 return Error(Loc, "invalid getelementptr indices");
3282 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3286 /// ParseExtractValue
3287 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3288 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3289 Value *Val; LocTy Loc;
3290 SmallVector<unsigned, 4> Indices;
3291 if (ParseTypeAndValue(Val, Loc, PFS) ||
3292 ParseIndexList(Indices))
3295 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3296 return Error(Loc, "extractvalue operand must be array or struct");
3298 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3300 return Error(Loc, "invalid indices for extractvalue");
3301 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3305 /// ParseInsertValue
3306 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3307 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3308 Value *Val0, *Val1; LocTy Loc0, Loc1;
3309 SmallVector<unsigned, 4> Indices;
3310 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3311 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3312 ParseTypeAndValue(Val1, Loc1, PFS) ||
3313 ParseIndexList(Indices))
3316 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3317 return Error(Loc0, "extractvalue operand must be array or struct");
3319 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3321 return Error(Loc0, "invalid indices for insertvalue");
3322 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3326 //===----------------------------------------------------------------------===//
3327 // Embedded metadata.
3328 //===----------------------------------------------------------------------===//
3330 /// ParseMDNodeVector
3331 /// ::= Element (',' Element)*
3333 /// ::= 'null' | TypeAndValue
3334 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3335 assert(Lex.getKind() == lltok::lbrace);
3339 if (Lex.getKind() == lltok::kw_null) {
3344 if (ParseGlobalTypeAndValue(C)) return true;
3348 } while (EatIfPresent(lltok::comma));