1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
32 /// ValID - Represents a reference of a definition of some sort with no type.
33 /// There are several cases where we have to parse the value but where the
34 /// type can depend on later context. This may either be a numeric reference
35 /// or a symbolic (%var) reference. This is just a discriminated union.
38 t_LocalID, t_GlobalID, // ID in UIntVal.
39 t_LocalName, t_GlobalName, // Name in StrVal.
40 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
41 t_Null, t_Undef, t_Zero, // No value.
42 t_EmptyArray, // No value: []
43 t_Constant, // Value in ConstantVal.
44 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
49 std::string StrVal, StrVal2;
52 Constant *ConstantVal;
53 ValID() : APFloatVal(0.0) {}
57 /// Run: module ::= toplevelentity*
58 bool LLParser::Run() {
62 return ParseTopLevelEntities() ||
63 ValidateEndOfModule();
66 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
68 bool LLParser::ValidateEndOfModule() {
69 if (!ForwardRefTypes.empty())
70 return Error(ForwardRefTypes.begin()->second.second,
71 "use of undefined type named '" +
72 ForwardRefTypes.begin()->first + "'");
73 if (!ForwardRefTypeIDs.empty())
74 return Error(ForwardRefTypeIDs.begin()->second.second,
75 "use of undefined type '%" +
76 utostr(ForwardRefTypeIDs.begin()->first) + "'");
78 if (!ForwardRefVals.empty())
79 return Error(ForwardRefVals.begin()->second.second,
80 "use of undefined value '@" + ForwardRefVals.begin()->first +
83 if (!ForwardRefValIDs.empty())
84 return Error(ForwardRefValIDs.begin()->second.second,
85 "use of undefined value '@" +
86 utostr(ForwardRefValIDs.begin()->first) + "'");
88 if (!ForwardRefMDNodes.empty())
89 return Error(ForwardRefMDNodes.begin()->second.second,
90 "use of undefined metadata '!" +
91 utostr(ForwardRefMDNodes.begin()->first) + "'");
94 // Look for intrinsic functions and CallInst that need to be upgraded
95 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
96 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
101 //===----------------------------------------------------------------------===//
102 // Top-Level Entities
103 //===----------------------------------------------------------------------===//
105 bool LLParser::ParseTopLevelEntities() {
107 switch (Lex.getKind()) {
108 default: return TokError("expected top-level entity");
109 case lltok::Eof: return false;
110 //case lltok::kw_define:
111 case lltok::kw_declare: if (ParseDeclare()) return true; break;
112 case lltok::kw_define: if (ParseDefine()) return true; break;
113 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
114 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
115 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
116 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
117 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
118 case lltok::LocalVar: if (ParseNamedType()) return true; break;
119 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
120 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
122 // The Global variable production with no name can have many different
123 // optional leading prefixes, the production is:
124 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
125 // OptionalAddrSpace ('constant'|'global') ...
126 case lltok::kw_private : // OptionalLinkage
127 case lltok::kw_linker_private: // OptionalLinkage
128 case lltok::kw_internal: // OptionalLinkage
129 case lltok::kw_weak: // OptionalLinkage
130 case lltok::kw_weak_odr: // OptionalLinkage
131 case lltok::kw_linkonce: // OptionalLinkage
132 case lltok::kw_linkonce_odr: // OptionalLinkage
133 case lltok::kw_appending: // OptionalLinkage
134 case lltok::kw_dllexport: // OptionalLinkage
135 case lltok::kw_common: // OptionalLinkage
136 case lltok::kw_dllimport: // OptionalLinkage
137 case lltok::kw_extern_weak: // OptionalLinkage
138 case lltok::kw_external: { // OptionalLinkage
139 unsigned Linkage, Visibility;
140 if (ParseOptionalLinkage(Linkage) ||
141 ParseOptionalVisibility(Visibility) ||
142 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
146 case lltok::kw_default: // OptionalVisibility
147 case lltok::kw_hidden: // OptionalVisibility
148 case lltok::kw_protected: { // OptionalVisibility
150 if (ParseOptionalVisibility(Visibility) ||
151 ParseGlobal("", SMLoc(), 0, false, Visibility))
156 case lltok::kw_thread_local: // OptionalThreadLocal
157 case lltok::kw_addrspace: // OptionalAddrSpace
158 case lltok::kw_constant: // GlobalType
159 case lltok::kw_global: // GlobalType
160 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
168 /// ::= 'module' 'asm' STRINGCONSTANT
169 bool LLParser::ParseModuleAsm() {
170 assert(Lex.getKind() == lltok::kw_module);
174 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
175 ParseStringConstant(AsmStr)) return true;
177 const std::string &AsmSoFar = M->getModuleInlineAsm();
178 if (AsmSoFar.empty())
179 M->setModuleInlineAsm(AsmStr);
181 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
186 /// ::= 'target' 'triple' '=' STRINGCONSTANT
187 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
188 bool LLParser::ParseTargetDefinition() {
189 assert(Lex.getKind() == lltok::kw_target);
192 default: return TokError("unknown target property");
193 case lltok::kw_triple:
195 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
196 ParseStringConstant(Str))
198 M->setTargetTriple(Str);
200 case lltok::kw_datalayout:
202 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
203 ParseStringConstant(Str))
205 M->setDataLayout(Str);
211 /// ::= 'deplibs' '=' '[' ']'
212 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
213 bool LLParser::ParseDepLibs() {
214 assert(Lex.getKind() == lltok::kw_deplibs);
216 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
217 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
220 if (EatIfPresent(lltok::rsquare))
224 if (ParseStringConstant(Str)) return true;
227 while (EatIfPresent(lltok::comma)) {
228 if (ParseStringConstant(Str)) return true;
232 return ParseToken(lltok::rsquare, "expected ']' at end of list");
237 bool LLParser::ParseUnnamedType() {
238 assert(Lex.getKind() == lltok::kw_type);
239 LocTy TypeLoc = Lex.getLoc();
240 Lex.Lex(); // eat kw_type
242 PATypeHolder Ty(Type::VoidTy);
243 if (ParseType(Ty)) return true;
245 unsigned TypeID = NumberedTypes.size();
247 // See if this type was previously referenced.
248 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
249 FI = ForwardRefTypeIDs.find(TypeID);
250 if (FI != ForwardRefTypeIDs.end()) {
251 if (FI->second.first.get() == Ty)
252 return Error(TypeLoc, "self referential type is invalid");
254 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
255 Ty = FI->second.first.get();
256 ForwardRefTypeIDs.erase(FI);
259 NumberedTypes.push_back(Ty);
265 /// ::= LocalVar '=' 'type' type
266 bool LLParser::ParseNamedType() {
267 std::string Name = Lex.getStrVal();
268 LocTy NameLoc = Lex.getLoc();
269 Lex.Lex(); // eat LocalVar.
271 PATypeHolder Ty(Type::VoidTy);
273 if (ParseToken(lltok::equal, "expected '=' after name") ||
274 ParseToken(lltok::kw_type, "expected 'type' after name") ||
278 // Set the type name, checking for conflicts as we do so.
279 bool AlreadyExists = M->addTypeName(Name, Ty);
280 if (!AlreadyExists) return false;
282 // See if this type is a forward reference. We need to eagerly resolve
283 // types to allow recursive type redefinitions below.
284 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
285 FI = ForwardRefTypes.find(Name);
286 if (FI != ForwardRefTypes.end()) {
287 if (FI->second.first.get() == Ty)
288 return Error(NameLoc, "self referential type is invalid");
290 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
291 Ty = FI->second.first.get();
292 ForwardRefTypes.erase(FI);
295 // Inserting a name that is already defined, get the existing name.
296 const Type *Existing = M->getTypeByName(Name);
297 assert(Existing && "Conflict but no matching type?!");
299 // Otherwise, this is an attempt to redefine a type. That's okay if
300 // the redefinition is identical to the original.
301 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
302 if (Existing == Ty) return false;
304 // Any other kind of (non-equivalent) redefinition is an error.
305 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
306 Ty->getDescription() + "'");
311 /// ::= 'declare' FunctionHeader
312 bool LLParser::ParseDeclare() {
313 assert(Lex.getKind() == lltok::kw_declare);
317 return ParseFunctionHeader(F, false);
321 /// ::= 'define' FunctionHeader '{' ...
322 bool LLParser::ParseDefine() {
323 assert(Lex.getKind() == lltok::kw_define);
327 return ParseFunctionHeader(F, true) ||
328 ParseFunctionBody(*F);
334 bool LLParser::ParseGlobalType(bool &IsConstant) {
335 if (Lex.getKind() == lltok::kw_constant)
337 else if (Lex.getKind() == lltok::kw_global)
341 return TokError("expected 'global' or 'constant'");
347 /// ParseNamedGlobal:
348 /// GlobalVar '=' OptionalVisibility ALIAS ...
349 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
350 bool LLParser::ParseNamedGlobal() {
351 assert(Lex.getKind() == lltok::GlobalVar);
352 LocTy NameLoc = Lex.getLoc();
353 std::string Name = Lex.getStrVal();
357 unsigned Linkage, Visibility;
358 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
359 ParseOptionalLinkage(Linkage, HasLinkage) ||
360 ParseOptionalVisibility(Visibility))
363 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
364 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
365 return ParseAlias(Name, NameLoc, Visibility);
368 /// ParseStandaloneMetadata:
370 bool LLParser::ParseStandaloneMetadata() {
371 assert(Lex.getKind() == lltok::Metadata);
373 unsigned MetadataID = 0;
374 if (ParseUInt32(MetadataID))
376 if (MetadataCache.find(MetadataID) != MetadataCache.end())
377 return TokError("Metadata id is already used");
378 if (ParseToken(lltok::equal, "expected '=' here"))
382 PATypeHolder Ty(Type::VoidTy);
383 if (ParseType(Ty, TyLoc))
387 if (ParseGlobalValue(Ty, Init))
390 MetadataCache[MetadataID] = Init;
391 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
392 FI = ForwardRefMDNodes.find(MetadataID);
393 if (FI != ForwardRefMDNodes.end()) {
394 Constant *FwdNode = FI->second.first;
395 FwdNode->replaceAllUsesWith(Init);
396 ForwardRefMDNodes.erase(FI);
403 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
406 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
407 /// ::= 'getelementptr' '(' ... ')'
409 /// Everything through visibility has already been parsed.
411 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
412 unsigned Visibility) {
413 assert(Lex.getKind() == lltok::kw_alias);
416 LocTy LinkageLoc = Lex.getLoc();
417 if (ParseOptionalLinkage(Linkage))
420 if (Linkage != GlobalValue::ExternalLinkage &&
421 Linkage != GlobalValue::WeakAnyLinkage &&
422 Linkage != GlobalValue::WeakODRLinkage &&
423 Linkage != GlobalValue::InternalLinkage &&
424 Linkage != GlobalValue::PrivateLinkage &&
425 Linkage != GlobalValue::LinkerPrivateLinkage)
426 return Error(LinkageLoc, "invalid linkage type for alias");
429 LocTy AliaseeLoc = Lex.getLoc();
430 if (Lex.getKind() != lltok::kw_bitcast &&
431 Lex.getKind() != lltok::kw_getelementptr) {
432 if (ParseGlobalTypeAndValue(Aliasee)) return true;
434 // The bitcast dest type is not present, it is implied by the dest type.
436 if (ParseValID(ID)) return true;
437 if (ID.Kind != ValID::t_Constant)
438 return Error(AliaseeLoc, "invalid aliasee");
439 Aliasee = ID.ConstantVal;
442 if (!isa<PointerType>(Aliasee->getType()))
443 return Error(AliaseeLoc, "alias must have pointer type");
445 // Okay, create the alias but do not insert it into the module yet.
446 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
447 (GlobalValue::LinkageTypes)Linkage, Name,
449 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
451 // See if this value already exists in the symbol table. If so, it is either
452 // a redefinition or a definition of a forward reference.
453 if (GlobalValue *Val =
454 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
455 // See if this was a redefinition. If so, there is no entry in
457 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
458 I = ForwardRefVals.find(Name);
459 if (I == ForwardRefVals.end())
460 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
462 // Otherwise, this was a definition of forward ref. Verify that types
464 if (Val->getType() != GA->getType())
465 return Error(NameLoc,
466 "forward reference and definition of alias have different types");
468 // If they agree, just RAUW the old value with the alias and remove the
470 Val->replaceAllUsesWith(GA);
471 Val->eraseFromParent();
472 ForwardRefVals.erase(I);
475 // Insert into the module, we know its name won't collide now.
476 M->getAliasList().push_back(GA);
477 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
483 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
484 /// OptionalAddrSpace GlobalType Type Const
485 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
486 /// OptionalAddrSpace GlobalType Type Const
488 /// Everything through visibility has been parsed already.
490 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
491 unsigned Linkage, bool HasLinkage,
492 unsigned Visibility) {
494 bool ThreadLocal, IsConstant;
497 PATypeHolder Ty(Type::VoidTy);
498 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
499 ParseOptionalAddrSpace(AddrSpace) ||
500 ParseGlobalType(IsConstant) ||
501 ParseType(Ty, TyLoc))
504 // If the linkage is specified and is external, then no initializer is
507 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
508 Linkage != GlobalValue::ExternalWeakLinkage &&
509 Linkage != GlobalValue::ExternalLinkage)) {
510 if (ParseGlobalValue(Ty, Init))
514 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
515 return Error(TyLoc, "invalid type for global variable");
517 GlobalVariable *GV = 0;
519 // See if the global was forward referenced, if so, use the global.
521 if ((GV = M->getGlobalVariable(Name, true)) &&
522 !ForwardRefVals.erase(Name))
523 return Error(NameLoc, "redefinition of global '@" + Name + "'");
525 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
526 I = ForwardRefValIDs.find(NumberedVals.size());
527 if (I != ForwardRefValIDs.end()) {
528 GV = cast<GlobalVariable>(I->second.first);
529 ForwardRefValIDs.erase(I);
534 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
535 Name, 0, false, AddrSpace);
537 if (GV->getType()->getElementType() != Ty)
539 "forward reference and definition of global have different types");
541 // Move the forward-reference to the correct spot in the module.
542 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
546 NumberedVals.push_back(GV);
548 // Set the parsed properties on the global.
550 GV->setInitializer(Init);
551 GV->setConstant(IsConstant);
552 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
553 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
554 GV->setThreadLocal(ThreadLocal);
556 // Parse attributes on the global.
557 while (Lex.getKind() == lltok::comma) {
560 if (Lex.getKind() == lltok::kw_section) {
562 GV->setSection(Lex.getStrVal());
563 if (ParseToken(lltok::StringConstant, "expected global section string"))
565 } else if (Lex.getKind() == lltok::kw_align) {
567 if (ParseOptionalAlignment(Alignment)) return true;
568 GV->setAlignment(Alignment);
570 TokError("unknown global variable property!");
578 //===----------------------------------------------------------------------===//
579 // GlobalValue Reference/Resolution Routines.
580 //===----------------------------------------------------------------------===//
582 /// GetGlobalVal - Get a value with the specified name or ID, creating a
583 /// forward reference record if needed. This can return null if the value
584 /// exists but does not have the right type.
585 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
587 const PointerType *PTy = dyn_cast<PointerType>(Ty);
589 Error(Loc, "global variable reference must have pointer type");
593 // Look this name up in the normal function symbol table.
595 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
597 // If this is a forward reference for the value, see if we already created a
598 // forward ref record.
600 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
601 I = ForwardRefVals.find(Name);
602 if (I != ForwardRefVals.end())
603 Val = I->second.first;
606 // If we have the value in the symbol table or fwd-ref table, return it.
608 if (Val->getType() == Ty) return Val;
609 Error(Loc, "'@" + Name + "' defined with type '" +
610 Val->getType()->getDescription() + "'");
614 // Otherwise, create a new forward reference for this value and remember it.
616 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
617 // Function types can return opaque but functions can't.
618 if (isa<OpaqueType>(FT->getReturnType())) {
619 Error(Loc, "function may not return opaque type");
623 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
625 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
626 GlobalValue::ExternalWeakLinkage, 0, Name);
629 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
633 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
634 const PointerType *PTy = dyn_cast<PointerType>(Ty);
636 Error(Loc, "global variable reference must have pointer type");
640 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
642 // If this is a forward reference for the value, see if we already created a
643 // forward ref record.
645 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
646 I = ForwardRefValIDs.find(ID);
647 if (I != ForwardRefValIDs.end())
648 Val = I->second.first;
651 // If we have the value in the symbol table or fwd-ref table, return it.
653 if (Val->getType() == Ty) return Val;
654 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
655 Val->getType()->getDescription() + "'");
659 // Otherwise, create a new forward reference for this value and remember it.
661 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
662 // Function types can return opaque but functions can't.
663 if (isa<OpaqueType>(FT->getReturnType())) {
664 Error(Loc, "function may not return opaque type");
667 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
669 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
670 GlobalValue::ExternalWeakLinkage, 0, "");
673 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
678 //===----------------------------------------------------------------------===//
680 //===----------------------------------------------------------------------===//
682 /// ParseToken - If the current token has the specified kind, eat it and return
683 /// success. Otherwise, emit the specified error and return failure.
684 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
685 if (Lex.getKind() != T)
686 return TokError(ErrMsg);
691 /// ParseStringConstant
692 /// ::= StringConstant
693 bool LLParser::ParseStringConstant(std::string &Result) {
694 if (Lex.getKind() != lltok::StringConstant)
695 return TokError("expected string constant");
696 Result = Lex.getStrVal();
703 bool LLParser::ParseUInt32(unsigned &Val) {
704 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
705 return TokError("expected integer");
706 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
707 if (Val64 != unsigned(Val64))
708 return TokError("expected 32-bit integer (too large)");
715 /// ParseOptionalAddrSpace
717 /// := 'addrspace' '(' uint32 ')'
718 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
720 if (!EatIfPresent(lltok::kw_addrspace))
722 return ParseToken(lltok::lparen, "expected '(' in address space") ||
723 ParseUInt32(AddrSpace) ||
724 ParseToken(lltok::rparen, "expected ')' in address space");
727 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
728 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
729 /// 2: function attr.
730 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
731 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
732 Attrs = Attribute::None;
733 LocTy AttrLoc = Lex.getLoc();
736 switch (Lex.getKind()) {
739 // Treat these as signext/zeroext if they occur in the argument list after
740 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
741 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
743 // FIXME: REMOVE THIS IN LLVM 3.0
745 if (Lex.getKind() == lltok::kw_sext)
746 Attrs |= Attribute::SExt;
748 Attrs |= Attribute::ZExt;
752 default: // End of attributes.
753 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
754 return Error(AttrLoc, "invalid use of function-only attribute");
756 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
757 return Error(AttrLoc, "invalid use of parameter-only attribute");
760 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
761 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
762 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
763 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
764 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
765 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
766 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
767 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
769 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
770 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
771 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
772 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
773 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
774 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
775 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
776 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
777 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
778 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
779 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
780 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
782 case lltok::kw_align: {
784 if (ParseOptionalAlignment(Alignment))
786 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
794 /// ParseOptionalLinkage
797 /// ::= 'linker_private'
802 /// ::= 'linkonce_odr'
807 /// ::= 'extern_weak'
809 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
811 switch (Lex.getKind()) {
812 default: Res=GlobalValue::ExternalLinkage; return false;
813 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
814 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
815 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
816 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
817 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
818 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
819 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
820 case lltok::kw_available_externally:
821 Res = GlobalValue::AvailableExternallyLinkage;
823 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
824 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
825 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
826 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
827 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
828 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
835 /// ParseOptionalVisibility
841 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
842 switch (Lex.getKind()) {
843 default: Res = GlobalValue::DefaultVisibility; return false;
844 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
845 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
846 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
852 /// ParseOptionalCallingConv
857 /// ::= 'x86_stdcallcc'
858 /// ::= 'x86_fastcallcc'
860 /// ::= 'arm_aapcscc'
861 /// ::= 'arm_aapcs_vfpcc'
864 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
865 switch (Lex.getKind()) {
866 default: CC = CallingConv::C; return false;
867 case lltok::kw_ccc: CC = CallingConv::C; break;
868 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
869 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
870 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
871 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
872 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
873 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
874 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
875 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
881 /// ParseOptionalAlignment
884 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
886 if (!EatIfPresent(lltok::kw_align))
888 LocTy AlignLoc = Lex.getLoc();
889 if (ParseUInt32(Alignment)) return true;
890 if (!isPowerOf2_32(Alignment))
891 return Error(AlignLoc, "alignment is not a power of two");
895 /// ParseOptionalCommaAlignment
897 /// ::= ',' 'align' 4
898 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
900 if (!EatIfPresent(lltok::comma))
902 return ParseToken(lltok::kw_align, "expected 'align'") ||
903 ParseUInt32(Alignment);
907 /// ::= (',' uint32)+
908 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
909 if (Lex.getKind() != lltok::comma)
910 return TokError("expected ',' as start of index list");
912 while (EatIfPresent(lltok::comma)) {
914 if (ParseUInt32(Idx)) return true;
915 Indices.push_back(Idx);
921 //===----------------------------------------------------------------------===//
923 //===----------------------------------------------------------------------===//
925 /// ParseType - Parse and resolve a full type.
926 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
927 LocTy TypeLoc = Lex.getLoc();
928 if (ParseTypeRec(Result)) return true;
930 // Verify no unresolved uprefs.
932 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
934 if (!AllowVoid && Result.get() == Type::VoidTy)
935 return Error(TypeLoc, "void type only allowed for function results");
940 /// HandleUpRefs - Every time we finish a new layer of types, this function is
941 /// called. It loops through the UpRefs vector, which is a list of the
942 /// currently active types. For each type, if the up-reference is contained in
943 /// the newly completed type, we decrement the level count. When the level
944 /// count reaches zero, the up-referenced type is the type that is passed in:
945 /// thus we can complete the cycle.
947 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
948 // If Ty isn't abstract, or if there are no up-references in it, then there is
949 // nothing to resolve here.
950 if (!ty->isAbstract() || UpRefs.empty()) return ty;
954 errs() << "Type '" << Ty->getDescription()
955 << "' newly formed. Resolving upreferences.\n"
956 << UpRefs.size() << " upreferences active!\n";
959 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
960 // to zero), we resolve them all together before we resolve them to Ty. At
961 // the end of the loop, if there is anything to resolve to Ty, it will be in
963 OpaqueType *TypeToResolve = 0;
965 for (unsigned i = 0; i != UpRefs.size(); ++i) {
966 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
968 std::find(Ty->subtype_begin(), Ty->subtype_end(),
969 UpRefs[i].LastContainedTy) != Ty->subtype_end();
972 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
973 << UpRefs[i].LastContainedTy->getDescription() << ") = "
974 << (ContainsType ? "true" : "false")
975 << " level=" << UpRefs[i].NestingLevel << "\n";
980 // Decrement level of upreference
981 unsigned Level = --UpRefs[i].NestingLevel;
982 UpRefs[i].LastContainedTy = Ty;
984 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
989 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
992 TypeToResolve = UpRefs[i].UpRefTy;
994 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
995 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
996 --i; // Do not skip the next element.
1000 TypeToResolve->refineAbstractTypeTo(Ty);
1006 /// ParseTypeRec - The recursive function used to process the internal
1007 /// implementation details of types.
1008 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1009 switch (Lex.getKind()) {
1011 return TokError("expected type");
1013 // TypeRec ::= 'float' | 'void' (etc)
1014 Result = Lex.getTyVal();
1017 case lltok::kw_opaque:
1018 // TypeRec ::= 'opaque'
1019 Result = Context.getOpaqueType();
1023 // TypeRec ::= '{' ... '}'
1024 if (ParseStructType(Result, false))
1027 case lltok::lsquare:
1028 // TypeRec ::= '[' ... ']'
1029 Lex.Lex(); // eat the lsquare.
1030 if (ParseArrayVectorType(Result, false))
1033 case lltok::less: // Either vector or packed struct.
1034 // TypeRec ::= '<' ... '>'
1036 if (Lex.getKind() == lltok::lbrace) {
1037 if (ParseStructType(Result, true) ||
1038 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1040 } else if (ParseArrayVectorType(Result, true))
1043 case lltok::LocalVar:
1044 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1046 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1049 Result = Context.getOpaqueType();
1050 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1051 std::make_pair(Result,
1053 M->addTypeName(Lex.getStrVal(), Result.get());
1058 case lltok::LocalVarID:
1060 if (Lex.getUIntVal() < NumberedTypes.size())
1061 Result = NumberedTypes[Lex.getUIntVal()];
1063 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1064 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1065 if (I != ForwardRefTypeIDs.end())
1066 Result = I->second.first;
1068 Result = Context.getOpaqueType();
1069 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1070 std::make_pair(Result,
1076 case lltok::backslash: {
1077 // TypeRec ::= '\' 4
1080 if (ParseUInt32(Val)) return true;
1081 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1082 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1088 // Parse the type suffixes.
1090 switch (Lex.getKind()) {
1092 default: return false;
1094 // TypeRec ::= TypeRec '*'
1096 if (Result.get() == Type::LabelTy)
1097 return TokError("basic block pointers are invalid");
1098 if (Result.get() == Type::VoidTy)
1099 return TokError("pointers to void are invalid; use i8* instead");
1100 if (!PointerType::isValidElementType(Result.get()))
1101 return TokError("pointer to this type is invalid");
1102 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1106 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1107 case lltok::kw_addrspace: {
1108 if (Result.get() == Type::LabelTy)
1109 return TokError("basic block pointers are invalid");
1110 if (Result.get() == Type::VoidTy)
1111 return TokError("pointers to void are invalid; use i8* instead");
1112 if (!PointerType::isValidElementType(Result.get()))
1113 return TokError("pointer to this type is invalid");
1115 if (ParseOptionalAddrSpace(AddrSpace) ||
1116 ParseToken(lltok::star, "expected '*' in address space"))
1119 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1123 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1125 if (ParseFunctionType(Result))
1132 /// ParseParameterList
1134 /// ::= '(' Arg (',' Arg)* ')'
1136 /// ::= Type OptionalAttributes Value OptionalAttributes
1137 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1138 PerFunctionState &PFS) {
1139 if (ParseToken(lltok::lparen, "expected '(' in call"))
1142 while (Lex.getKind() != lltok::rparen) {
1143 // If this isn't the first argument, we need a comma.
1144 if (!ArgList.empty() &&
1145 ParseToken(lltok::comma, "expected ',' in argument list"))
1148 // Parse the argument.
1150 PATypeHolder ArgTy(Type::VoidTy);
1151 unsigned ArgAttrs1, ArgAttrs2;
1153 if (ParseType(ArgTy, ArgLoc) ||
1154 ParseOptionalAttrs(ArgAttrs1, 0) ||
1155 ParseValue(ArgTy, V, PFS) ||
1156 // FIXME: Should not allow attributes after the argument, remove this in
1158 ParseOptionalAttrs(ArgAttrs2, 3))
1160 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1163 Lex.Lex(); // Lex the ')'.
1169 /// ParseArgumentList - Parse the argument list for a function type or function
1170 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1171 /// ::= '(' ArgTypeListI ')'
1175 /// ::= ArgTypeList ',' '...'
1176 /// ::= ArgType (',' ArgType)*
1178 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1179 bool &isVarArg, bool inType) {
1181 assert(Lex.getKind() == lltok::lparen);
1182 Lex.Lex(); // eat the (.
1184 if (Lex.getKind() == lltok::rparen) {
1186 } else if (Lex.getKind() == lltok::dotdotdot) {
1190 LocTy TypeLoc = Lex.getLoc();
1191 PATypeHolder ArgTy(Type::VoidTy);
1195 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1196 // types (such as a function returning a pointer to itself). If parsing a
1197 // function prototype, we require fully resolved types.
1198 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1199 ParseOptionalAttrs(Attrs, 0)) return true;
1201 if (ArgTy == Type::VoidTy)
1202 return Error(TypeLoc, "argument can not have void type");
1204 if (Lex.getKind() == lltok::LocalVar ||
1205 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1206 Name = Lex.getStrVal();
1210 if (!FunctionType::isValidArgumentType(ArgTy))
1211 return Error(TypeLoc, "invalid type for function argument");
1213 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1215 while (EatIfPresent(lltok::comma)) {
1216 // Handle ... at end of arg list.
1217 if (EatIfPresent(lltok::dotdotdot)) {
1222 // Otherwise must be an argument type.
1223 TypeLoc = Lex.getLoc();
1224 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1225 ParseOptionalAttrs(Attrs, 0)) return true;
1227 if (ArgTy == Type::VoidTy)
1228 return Error(TypeLoc, "argument can not have void type");
1230 if (Lex.getKind() == lltok::LocalVar ||
1231 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1232 Name = Lex.getStrVal();
1238 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1239 return Error(TypeLoc, "invalid type for function argument");
1241 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1245 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1248 /// ParseFunctionType
1249 /// ::= Type ArgumentList OptionalAttrs
1250 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1251 assert(Lex.getKind() == lltok::lparen);
1253 if (!FunctionType::isValidReturnType(Result))
1254 return TokError("invalid function return type");
1256 std::vector<ArgInfo> ArgList;
1259 if (ParseArgumentList(ArgList, isVarArg, true) ||
1260 // FIXME: Allow, but ignore attributes on function types!
1261 // FIXME: Remove in LLVM 3.0
1262 ParseOptionalAttrs(Attrs, 2))
1265 // Reject names on the arguments lists.
1266 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1267 if (!ArgList[i].Name.empty())
1268 return Error(ArgList[i].Loc, "argument name invalid in function type");
1269 if (!ArgList[i].Attrs != 0) {
1270 // Allow but ignore attributes on function types; this permits
1272 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1276 std::vector<const Type*> ArgListTy;
1277 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1278 ArgListTy.push_back(ArgList[i].Type);
1280 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1281 ArgListTy, isVarArg));
1285 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1288 /// ::= '{' TypeRec (',' TypeRec)* '}'
1289 /// ::= '<' '{' '}' '>'
1290 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1291 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1292 assert(Lex.getKind() == lltok::lbrace);
1293 Lex.Lex(); // Consume the '{'
1295 if (EatIfPresent(lltok::rbrace)) {
1296 Result = Context.getStructType(Packed);
1300 std::vector<PATypeHolder> ParamsList;
1301 LocTy EltTyLoc = Lex.getLoc();
1302 if (ParseTypeRec(Result)) return true;
1303 ParamsList.push_back(Result);
1305 if (Result == Type::VoidTy)
1306 return Error(EltTyLoc, "struct element can not have void type");
1307 if (!StructType::isValidElementType(Result))
1308 return Error(EltTyLoc, "invalid element type for struct");
1310 while (EatIfPresent(lltok::comma)) {
1311 EltTyLoc = Lex.getLoc();
1312 if (ParseTypeRec(Result)) return true;
1314 if (Result == Type::VoidTy)
1315 return Error(EltTyLoc, "struct element can not have void type");
1316 if (!StructType::isValidElementType(Result))
1317 return Error(EltTyLoc, "invalid element type for struct");
1319 ParamsList.push_back(Result);
1322 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1325 std::vector<const Type*> ParamsListTy;
1326 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1327 ParamsListTy.push_back(ParamsList[i].get());
1328 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1332 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1333 /// token has already been consumed.
1335 /// ::= '[' APSINTVAL 'x' Types ']'
1336 /// ::= '<' APSINTVAL 'x' Types '>'
1337 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1338 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1339 Lex.getAPSIntVal().getBitWidth() > 64)
1340 return TokError("expected number in address space");
1342 LocTy SizeLoc = Lex.getLoc();
1343 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1346 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1349 LocTy TypeLoc = Lex.getLoc();
1350 PATypeHolder EltTy(Type::VoidTy);
1351 if (ParseTypeRec(EltTy)) return true;
1353 if (EltTy == Type::VoidTy)
1354 return Error(TypeLoc, "array and vector element type cannot be void");
1356 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1357 "expected end of sequential type"))
1362 return Error(SizeLoc, "zero element vector is illegal");
1363 if ((unsigned)Size != Size)
1364 return Error(SizeLoc, "size too large for vector");
1365 if (!VectorType::isValidElementType(EltTy))
1366 return Error(TypeLoc, "vector element type must be fp or integer");
1367 Result = Context.getVectorType(EltTy, unsigned(Size));
1369 if (!ArrayType::isValidElementType(EltTy))
1370 return Error(TypeLoc, "invalid array element type");
1371 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1376 //===----------------------------------------------------------------------===//
1377 // Function Semantic Analysis.
1378 //===----------------------------------------------------------------------===//
1380 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1383 // Insert unnamed arguments into the NumberedVals list.
1384 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1387 NumberedVals.push_back(AI);
1390 LLParser::PerFunctionState::~PerFunctionState() {
1391 // If there were any forward referenced non-basicblock values, delete them.
1392 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1393 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1394 if (!isa<BasicBlock>(I->second.first)) {
1395 I->second.first->replaceAllUsesWith(
1396 P.getContext().getUndef(I->second.first->getType()));
1397 delete I->second.first;
1398 I->second.first = 0;
1401 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1402 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1403 if (!isa<BasicBlock>(I->second.first)) {
1404 I->second.first->replaceAllUsesWith(
1405 P.getContext().getUndef(I->second.first->getType()));
1406 delete I->second.first;
1407 I->second.first = 0;
1411 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1412 if (!ForwardRefVals.empty())
1413 return P.Error(ForwardRefVals.begin()->second.second,
1414 "use of undefined value '%" + ForwardRefVals.begin()->first +
1416 if (!ForwardRefValIDs.empty())
1417 return P.Error(ForwardRefValIDs.begin()->second.second,
1418 "use of undefined value '%" +
1419 utostr(ForwardRefValIDs.begin()->first) + "'");
1424 /// GetVal - Get a value with the specified name or ID, creating a
1425 /// forward reference record if needed. This can return null if the value
1426 /// exists but does not have the right type.
1427 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1428 const Type *Ty, LocTy Loc) {
1429 // Look this name up in the normal function symbol table.
1430 Value *Val = F.getValueSymbolTable().lookup(Name);
1432 // If this is a forward reference for the value, see if we already created a
1433 // forward ref record.
1435 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1436 I = ForwardRefVals.find(Name);
1437 if (I != ForwardRefVals.end())
1438 Val = I->second.first;
1441 // If we have the value in the symbol table or fwd-ref table, return it.
1443 if (Val->getType() == Ty) return Val;
1444 if (Ty == Type::LabelTy)
1445 P.Error(Loc, "'%" + Name + "' is not a basic block");
1447 P.Error(Loc, "'%" + Name + "' defined with type '" +
1448 Val->getType()->getDescription() + "'");
1452 // Don't make placeholders with invalid type.
1453 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1454 P.Error(Loc, "invalid use of a non-first-class type");
1458 // Otherwise, create a new forward reference for this value and remember it.
1460 if (Ty == Type::LabelTy)
1461 FwdVal = BasicBlock::Create(Name, &F);
1463 FwdVal = new Argument(Ty, Name);
1465 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1469 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1471 // Look this name up in the normal function symbol table.
1472 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1474 // If this is a forward reference for the value, see if we already created a
1475 // forward ref record.
1477 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1478 I = ForwardRefValIDs.find(ID);
1479 if (I != ForwardRefValIDs.end())
1480 Val = I->second.first;
1483 // If we have the value in the symbol table or fwd-ref table, return it.
1485 if (Val->getType() == Ty) return Val;
1486 if (Ty == Type::LabelTy)
1487 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1489 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1490 Val->getType()->getDescription() + "'");
1494 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1495 P.Error(Loc, "invalid use of a non-first-class type");
1499 // Otherwise, create a new forward reference for this value and remember it.
1501 if (Ty == Type::LabelTy)
1502 FwdVal = BasicBlock::Create("", &F);
1504 FwdVal = new Argument(Ty);
1506 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1510 /// SetInstName - After an instruction is parsed and inserted into its
1511 /// basic block, this installs its name.
1512 bool LLParser::PerFunctionState::SetInstName(int NameID,
1513 const std::string &NameStr,
1514 LocTy NameLoc, Instruction *Inst) {
1515 // If this instruction has void type, it cannot have a name or ID specified.
1516 if (Inst->getType() == Type::VoidTy) {
1517 if (NameID != -1 || !NameStr.empty())
1518 return P.Error(NameLoc, "instructions returning void cannot have a name");
1522 // If this was a numbered instruction, verify that the instruction is the
1523 // expected value and resolve any forward references.
1524 if (NameStr.empty()) {
1525 // If neither a name nor an ID was specified, just use the next ID.
1527 NameID = NumberedVals.size();
1529 if (unsigned(NameID) != NumberedVals.size())
1530 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1531 utostr(NumberedVals.size()) + "'");
1533 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1534 ForwardRefValIDs.find(NameID);
1535 if (FI != ForwardRefValIDs.end()) {
1536 if (FI->second.first->getType() != Inst->getType())
1537 return P.Error(NameLoc, "instruction forward referenced with type '" +
1538 FI->second.first->getType()->getDescription() + "'");
1539 FI->second.first->replaceAllUsesWith(Inst);
1540 ForwardRefValIDs.erase(FI);
1543 NumberedVals.push_back(Inst);
1547 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1548 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1549 FI = ForwardRefVals.find(NameStr);
1550 if (FI != ForwardRefVals.end()) {
1551 if (FI->second.first->getType() != Inst->getType())
1552 return P.Error(NameLoc, "instruction forward referenced with type '" +
1553 FI->second.first->getType()->getDescription() + "'");
1554 FI->second.first->replaceAllUsesWith(Inst);
1555 ForwardRefVals.erase(FI);
1558 // Set the name on the instruction.
1559 Inst->setName(NameStr);
1561 if (Inst->getNameStr() != NameStr)
1562 return P.Error(NameLoc, "multiple definition of local value named '" +
1567 /// GetBB - Get a basic block with the specified name or ID, creating a
1568 /// forward reference record if needed.
1569 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1571 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1574 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1575 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1578 /// DefineBB - Define the specified basic block, which is either named or
1579 /// unnamed. If there is an error, this returns null otherwise it returns
1580 /// the block being defined.
1581 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1585 BB = GetBB(NumberedVals.size(), Loc);
1587 BB = GetBB(Name, Loc);
1588 if (BB == 0) return 0; // Already diagnosed error.
1590 // Move the block to the end of the function. Forward ref'd blocks are
1591 // inserted wherever they happen to be referenced.
1592 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1594 // Remove the block from forward ref sets.
1596 ForwardRefValIDs.erase(NumberedVals.size());
1597 NumberedVals.push_back(BB);
1599 // BB forward references are already in the function symbol table.
1600 ForwardRefVals.erase(Name);
1606 //===----------------------------------------------------------------------===//
1608 //===----------------------------------------------------------------------===//
1610 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1611 /// type implied. For example, if we parse "4" we don't know what integer type
1612 /// it has. The value will later be combined with its type and checked for
1614 bool LLParser::ParseValID(ValID &ID) {
1615 ID.Loc = Lex.getLoc();
1616 switch (Lex.getKind()) {
1617 default: return TokError("expected value token");
1618 case lltok::GlobalID: // @42
1619 ID.UIntVal = Lex.getUIntVal();
1620 ID.Kind = ValID::t_GlobalID;
1622 case lltok::GlobalVar: // @foo
1623 ID.StrVal = Lex.getStrVal();
1624 ID.Kind = ValID::t_GlobalName;
1626 case lltok::LocalVarID: // %42
1627 ID.UIntVal = Lex.getUIntVal();
1628 ID.Kind = ValID::t_LocalID;
1630 case lltok::LocalVar: // %foo
1631 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1632 ID.StrVal = Lex.getStrVal();
1633 ID.Kind = ValID::t_LocalName;
1635 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1636 ID.Kind = ValID::t_Constant;
1638 if (Lex.getKind() == lltok::lbrace) {
1639 SmallVector<Value*, 16> Elts;
1640 if (ParseMDNodeVector(Elts) ||
1641 ParseToken(lltok::rbrace, "expected end of metadata node"))
1644 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1648 // Standalone metadata reference
1649 // !{ ..., !42, ... }
1651 if (!ParseUInt32(MID)) {
1652 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1653 if (I != MetadataCache.end())
1654 ID.ConstantVal = I->second;
1656 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1657 FI = ForwardRefMDNodes.find(MID);
1658 if (FI != ForwardRefMDNodes.end())
1659 ID.ConstantVal = FI->second.first;
1661 // Create MDNode forward reference
1662 SmallVector<Value *, 1> Elts;
1663 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
1664 Elts.push_back(Context.getMDString(FwdRefName));
1665 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1666 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1667 ID.ConstantVal = FwdNode;
1675 // ::= '!' STRINGCONSTANT
1677 if (ParseStringConstant(Str)) return true;
1679 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
1683 ID.APSIntVal = Lex.getAPSIntVal();
1684 ID.Kind = ValID::t_APSInt;
1686 case lltok::APFloat:
1687 ID.APFloatVal = Lex.getAPFloatVal();
1688 ID.Kind = ValID::t_APFloat;
1690 case lltok::kw_true:
1691 ID.ConstantVal = Context.getConstantIntTrue();
1692 ID.Kind = ValID::t_Constant;
1694 case lltok::kw_false:
1695 ID.ConstantVal = Context.getConstantIntFalse();
1696 ID.Kind = ValID::t_Constant;
1698 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1699 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1700 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1702 case lltok::lbrace: {
1703 // ValID ::= '{' ConstVector '}'
1705 SmallVector<Constant*, 16> Elts;
1706 if (ParseGlobalValueVector(Elts) ||
1707 ParseToken(lltok::rbrace, "expected end of struct constant"))
1710 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1711 ID.Kind = ValID::t_Constant;
1715 // ValID ::= '<' ConstVector '>' --> Vector.
1716 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1718 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1720 SmallVector<Constant*, 16> Elts;
1721 LocTy FirstEltLoc = Lex.getLoc();
1722 if (ParseGlobalValueVector(Elts) ||
1724 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1725 ParseToken(lltok::greater, "expected end of constant"))
1728 if (isPackedStruct) {
1730 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1731 ID.Kind = ValID::t_Constant;
1736 return Error(ID.Loc, "constant vector must not be empty");
1738 if (!Elts[0]->getType()->isInteger() &&
1739 !Elts[0]->getType()->isFloatingPoint())
1740 return Error(FirstEltLoc,
1741 "vector elements must have integer or floating point type");
1743 // Verify that all the vector elements have the same type.
1744 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1745 if (Elts[i]->getType() != Elts[0]->getType())
1746 return Error(FirstEltLoc,
1747 "vector element #" + utostr(i) +
1748 " is not of type '" + Elts[0]->getType()->getDescription());
1750 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1751 ID.Kind = ValID::t_Constant;
1754 case lltok::lsquare: { // Array Constant
1756 SmallVector<Constant*, 16> Elts;
1757 LocTy FirstEltLoc = Lex.getLoc();
1758 if (ParseGlobalValueVector(Elts) ||
1759 ParseToken(lltok::rsquare, "expected end of array constant"))
1762 // Handle empty element.
1764 // Use undef instead of an array because it's inconvenient to determine
1765 // the element type at this point, there being no elements to examine.
1766 ID.Kind = ValID::t_EmptyArray;
1770 if (!Elts[0]->getType()->isFirstClassType())
1771 return Error(FirstEltLoc, "invalid array element type: " +
1772 Elts[0]->getType()->getDescription());
1774 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1776 // Verify all elements are correct type!
1777 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1778 if (Elts[i]->getType() != Elts[0]->getType())
1779 return Error(FirstEltLoc,
1780 "array element #" + utostr(i) +
1781 " is not of type '" +Elts[0]->getType()->getDescription());
1784 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1785 ID.Kind = ValID::t_Constant;
1788 case lltok::kw_c: // c "foo"
1790 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1791 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1792 ID.Kind = ValID::t_Constant;
1795 case lltok::kw_asm: {
1796 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1799 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1800 ParseStringConstant(ID.StrVal) ||
1801 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1802 ParseToken(lltok::StringConstant, "expected constraint string"))
1804 ID.StrVal2 = Lex.getStrVal();
1805 ID.UIntVal = HasSideEffect;
1806 ID.Kind = ValID::t_InlineAsm;
1810 case lltok::kw_trunc:
1811 case lltok::kw_zext:
1812 case lltok::kw_sext:
1813 case lltok::kw_fptrunc:
1814 case lltok::kw_fpext:
1815 case lltok::kw_bitcast:
1816 case lltok::kw_uitofp:
1817 case lltok::kw_sitofp:
1818 case lltok::kw_fptoui:
1819 case lltok::kw_fptosi:
1820 case lltok::kw_inttoptr:
1821 case lltok::kw_ptrtoint: {
1822 unsigned Opc = Lex.getUIntVal();
1823 PATypeHolder DestTy(Type::VoidTy);
1826 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1827 ParseGlobalTypeAndValue(SrcVal) ||
1828 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1829 ParseType(DestTy) ||
1830 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1832 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1833 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1834 SrcVal->getType()->getDescription() + "' to '" +
1835 DestTy->getDescription() + "'");
1836 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1838 ID.Kind = ValID::t_Constant;
1841 case lltok::kw_extractvalue: {
1844 SmallVector<unsigned, 4> Indices;
1845 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1846 ParseGlobalTypeAndValue(Val) ||
1847 ParseIndexList(Indices) ||
1848 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1850 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1851 return Error(ID.Loc, "extractvalue operand must be array or struct");
1852 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1854 return Error(ID.Loc, "invalid indices for extractvalue");
1856 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1857 ID.Kind = ValID::t_Constant;
1860 case lltok::kw_insertvalue: {
1862 Constant *Val0, *Val1;
1863 SmallVector<unsigned, 4> Indices;
1864 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1865 ParseGlobalTypeAndValue(Val0) ||
1866 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1867 ParseGlobalTypeAndValue(Val1) ||
1868 ParseIndexList(Indices) ||
1869 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1871 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1872 return Error(ID.Loc, "extractvalue operand must be array or struct");
1873 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1875 return Error(ID.Loc, "invalid indices for insertvalue");
1876 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1877 Indices.data(), Indices.size());
1878 ID.Kind = ValID::t_Constant;
1881 case lltok::kw_icmp:
1882 case lltok::kw_fcmp: {
1883 unsigned PredVal, Opc = Lex.getUIntVal();
1884 Constant *Val0, *Val1;
1886 if (ParseCmpPredicate(PredVal, Opc) ||
1887 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1888 ParseGlobalTypeAndValue(Val0) ||
1889 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1890 ParseGlobalTypeAndValue(Val1) ||
1891 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1894 if (Val0->getType() != Val1->getType())
1895 return Error(ID.Loc, "compare operands must have the same type");
1897 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1899 if (Opc == Instruction::FCmp) {
1900 if (!Val0->getType()->isFPOrFPVector())
1901 return Error(ID.Loc, "fcmp requires floating point operands");
1902 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1904 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1905 if (!Val0->getType()->isIntOrIntVector() &&
1906 !isa<PointerType>(Val0->getType()))
1907 return Error(ID.Loc, "icmp requires pointer or integer operands");
1908 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1910 ID.Kind = ValID::t_Constant;
1914 // Binary Operators.
1916 case lltok::kw_fadd:
1918 case lltok::kw_fsub:
1920 case lltok::kw_fmul:
1921 case lltok::kw_udiv:
1922 case lltok::kw_sdiv:
1923 case lltok::kw_fdiv:
1924 case lltok::kw_urem:
1925 case lltok::kw_srem:
1926 case lltok::kw_frem: {
1927 unsigned Opc = Lex.getUIntVal();
1928 Constant *Val0, *Val1;
1930 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1931 ParseGlobalTypeAndValue(Val0) ||
1932 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1933 ParseGlobalTypeAndValue(Val1) ||
1934 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1936 if (Val0->getType() != Val1->getType())
1937 return Error(ID.Loc, "operands of constexpr must have same type");
1938 if (!Val0->getType()->isIntOrIntVector() &&
1939 !Val0->getType()->isFPOrFPVector())
1940 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1941 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1942 ID.Kind = ValID::t_Constant;
1946 // Logical Operations
1948 case lltok::kw_lshr:
1949 case lltok::kw_ashr:
1952 case lltok::kw_xor: {
1953 unsigned Opc = Lex.getUIntVal();
1954 Constant *Val0, *Val1;
1956 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1957 ParseGlobalTypeAndValue(Val0) ||
1958 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1959 ParseGlobalTypeAndValue(Val1) ||
1960 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1962 if (Val0->getType() != Val1->getType())
1963 return Error(ID.Loc, "operands of constexpr must have same type");
1964 if (!Val0->getType()->isIntOrIntVector())
1965 return Error(ID.Loc,
1966 "constexpr requires integer or integer vector operands");
1967 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1968 ID.Kind = ValID::t_Constant;
1972 case lltok::kw_getelementptr:
1973 case lltok::kw_shufflevector:
1974 case lltok::kw_insertelement:
1975 case lltok::kw_extractelement:
1976 case lltok::kw_select: {
1977 unsigned Opc = Lex.getUIntVal();
1978 SmallVector<Constant*, 16> Elts;
1980 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1981 ParseGlobalValueVector(Elts) ||
1982 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1985 if (Opc == Instruction::GetElementPtr) {
1986 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1987 return Error(ID.Loc, "getelementptr requires pointer operand");
1989 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1990 (Value**)&Elts[1], Elts.size()-1))
1991 return Error(ID.Loc, "invalid indices for getelementptr");
1992 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
1993 &Elts[1], Elts.size()-1);
1994 } else if (Opc == Instruction::Select) {
1995 if (Elts.size() != 3)
1996 return Error(ID.Loc, "expected three operands to select");
1997 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1999 return Error(ID.Loc, Reason);
2000 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
2001 } else if (Opc == Instruction::ShuffleVector) {
2002 if (Elts.size() != 3)
2003 return Error(ID.Loc, "expected three operands to shufflevector");
2004 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2005 return Error(ID.Loc, "invalid operands to shufflevector");
2007 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2008 } else if (Opc == Instruction::ExtractElement) {
2009 if (Elts.size() != 2)
2010 return Error(ID.Loc, "expected two operands to extractelement");
2011 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2012 return Error(ID.Loc, "invalid extractelement operands");
2013 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2015 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2016 if (Elts.size() != 3)
2017 return Error(ID.Loc, "expected three operands to insertelement");
2018 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2019 return Error(ID.Loc, "invalid insertelement operands");
2021 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2024 ID.Kind = ValID::t_Constant;
2033 /// ParseGlobalValue - Parse a global value with the specified type.
2034 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2037 return ParseValID(ID) ||
2038 ConvertGlobalValIDToValue(Ty, ID, V);
2041 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2043 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2045 if (isa<FunctionType>(Ty))
2046 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2049 default: llvm_unreachable("Unknown ValID!");
2050 case ValID::t_LocalID:
2051 case ValID::t_LocalName:
2052 return Error(ID.Loc, "invalid use of function-local name");
2053 case ValID::t_InlineAsm:
2054 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2055 case ValID::t_GlobalName:
2056 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2058 case ValID::t_GlobalID:
2059 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2061 case ValID::t_APSInt:
2062 if (!isa<IntegerType>(Ty))
2063 return Error(ID.Loc, "integer constant must have integer type");
2064 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2065 V = Context.getConstantInt(ID.APSIntVal);
2067 case ValID::t_APFloat:
2068 if (!Ty->isFloatingPoint() ||
2069 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2070 return Error(ID.Loc, "floating point constant invalid for type");
2072 // The lexer has no type info, so builds all float and double FP constants
2073 // as double. Fix this here. Long double does not need this.
2074 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2075 Ty == Type::FloatTy) {
2077 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2080 V = Context.getConstantFP(ID.APFloatVal);
2082 if (V->getType() != Ty)
2083 return Error(ID.Loc, "floating point constant does not have type '" +
2084 Ty->getDescription() + "'");
2088 if (!isa<PointerType>(Ty))
2089 return Error(ID.Loc, "null must be a pointer type");
2090 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2092 case ValID::t_Undef:
2093 // FIXME: LabelTy should not be a first-class type.
2094 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2095 !isa<OpaqueType>(Ty))
2096 return Error(ID.Loc, "invalid type for undef constant");
2097 V = Context.getUndef(Ty);
2099 case ValID::t_EmptyArray:
2100 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2101 return Error(ID.Loc, "invalid empty array initializer");
2102 V = Context.getUndef(Ty);
2105 // FIXME: LabelTy should not be a first-class type.
2106 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2107 return Error(ID.Loc, "invalid type for null constant");
2108 V = Context.getNullValue(Ty);
2110 case ValID::t_Constant:
2111 if (ID.ConstantVal->getType() != Ty)
2112 return Error(ID.Loc, "constant expression type mismatch");
2118 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2119 PATypeHolder Type(Type::VoidTy);
2120 return ParseType(Type) ||
2121 ParseGlobalValue(Type, V);
2124 /// ParseGlobalValueVector
2126 /// ::= TypeAndValue (',' TypeAndValue)*
2127 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2129 if (Lex.getKind() == lltok::rbrace ||
2130 Lex.getKind() == lltok::rsquare ||
2131 Lex.getKind() == lltok::greater ||
2132 Lex.getKind() == lltok::rparen)
2136 if (ParseGlobalTypeAndValue(C)) return true;
2139 while (EatIfPresent(lltok::comma)) {
2140 if (ParseGlobalTypeAndValue(C)) return true;
2148 //===----------------------------------------------------------------------===//
2149 // Function Parsing.
2150 //===----------------------------------------------------------------------===//
2152 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2153 PerFunctionState &PFS) {
2154 if (ID.Kind == ValID::t_LocalID)
2155 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2156 else if (ID.Kind == ValID::t_LocalName)
2157 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2158 else if (ID.Kind == ValID::t_InlineAsm) {
2159 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2160 const FunctionType *FTy =
2161 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2162 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2163 return Error(ID.Loc, "invalid type for inline asm constraint string");
2164 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2168 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2176 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2179 return ParseValID(ID) ||
2180 ConvertValIDToValue(Ty, ID, V, PFS);
2183 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2184 PATypeHolder T(Type::VoidTy);
2185 return ParseType(T) ||
2186 ParseValue(T, V, PFS);
2190 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2191 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2192 /// OptionalAlign OptGC
2193 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2194 // Parse the linkage.
2195 LocTy LinkageLoc = Lex.getLoc();
2198 unsigned Visibility, CC, RetAttrs;
2199 PATypeHolder RetType(Type::VoidTy);
2200 LocTy RetTypeLoc = Lex.getLoc();
2201 if (ParseOptionalLinkage(Linkage) ||
2202 ParseOptionalVisibility(Visibility) ||
2203 ParseOptionalCallingConv(CC) ||
2204 ParseOptionalAttrs(RetAttrs, 1) ||
2205 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2208 // Verify that the linkage is ok.
2209 switch ((GlobalValue::LinkageTypes)Linkage) {
2210 case GlobalValue::ExternalLinkage:
2211 break; // always ok.
2212 case GlobalValue::DLLImportLinkage:
2213 case GlobalValue::ExternalWeakLinkage:
2215 return Error(LinkageLoc, "invalid linkage for function definition");
2217 case GlobalValue::PrivateLinkage:
2218 case GlobalValue::LinkerPrivateLinkage:
2219 case GlobalValue::InternalLinkage:
2220 case GlobalValue::AvailableExternallyLinkage:
2221 case GlobalValue::LinkOnceAnyLinkage:
2222 case GlobalValue::LinkOnceODRLinkage:
2223 case GlobalValue::WeakAnyLinkage:
2224 case GlobalValue::WeakODRLinkage:
2225 case GlobalValue::DLLExportLinkage:
2227 return Error(LinkageLoc, "invalid linkage for function declaration");
2229 case GlobalValue::AppendingLinkage:
2230 case GlobalValue::GhostLinkage:
2231 case GlobalValue::CommonLinkage:
2232 return Error(LinkageLoc, "invalid function linkage type");
2235 if (!FunctionType::isValidReturnType(RetType) ||
2236 isa<OpaqueType>(RetType))
2237 return Error(RetTypeLoc, "invalid function return type");
2239 LocTy NameLoc = Lex.getLoc();
2241 std::string FunctionName;
2242 if (Lex.getKind() == lltok::GlobalVar) {
2243 FunctionName = Lex.getStrVal();
2244 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2245 unsigned NameID = Lex.getUIntVal();
2247 if (NameID != NumberedVals.size())
2248 return TokError("function expected to be numbered '%" +
2249 utostr(NumberedVals.size()) + "'");
2251 return TokError("expected function name");
2256 if (Lex.getKind() != lltok::lparen)
2257 return TokError("expected '(' in function argument list");
2259 std::vector<ArgInfo> ArgList;
2262 std::string Section;
2266 if (ParseArgumentList(ArgList, isVarArg, false) ||
2267 ParseOptionalAttrs(FuncAttrs, 2) ||
2268 (EatIfPresent(lltok::kw_section) &&
2269 ParseStringConstant(Section)) ||
2270 ParseOptionalAlignment(Alignment) ||
2271 (EatIfPresent(lltok::kw_gc) &&
2272 ParseStringConstant(GC)))
2275 // If the alignment was parsed as an attribute, move to the alignment field.
2276 if (FuncAttrs & Attribute::Alignment) {
2277 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2278 FuncAttrs &= ~Attribute::Alignment;
2281 // Okay, if we got here, the function is syntactically valid. Convert types
2282 // and do semantic checks.
2283 std::vector<const Type*> ParamTypeList;
2284 SmallVector<AttributeWithIndex, 8> Attrs;
2285 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2287 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2288 if (FuncAttrs & ObsoleteFuncAttrs) {
2289 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2290 FuncAttrs &= ~ObsoleteFuncAttrs;
2293 if (RetAttrs != Attribute::None)
2294 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2296 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2297 ParamTypeList.push_back(ArgList[i].Type);
2298 if (ArgList[i].Attrs != Attribute::None)
2299 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2302 if (FuncAttrs != Attribute::None)
2303 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2305 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2307 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2308 RetType != Type::VoidTy)
2309 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2311 const FunctionType *FT =
2312 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2313 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2316 if (!FunctionName.empty()) {
2317 // If this was a definition of a forward reference, remove the definition
2318 // from the forward reference table and fill in the forward ref.
2319 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2320 ForwardRefVals.find(FunctionName);
2321 if (FRVI != ForwardRefVals.end()) {
2322 Fn = M->getFunction(FunctionName);
2323 ForwardRefVals.erase(FRVI);
2324 } else if ((Fn = M->getFunction(FunctionName))) {
2325 // If this function already exists in the symbol table, then it is
2326 // multiply defined. We accept a few cases for old backwards compat.
2327 // FIXME: Remove this stuff for LLVM 3.0.
2328 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2329 (!Fn->isDeclaration() && isDefine)) {
2330 // If the redefinition has different type or different attributes,
2331 // reject it. If both have bodies, reject it.
2332 return Error(NameLoc, "invalid redefinition of function '" +
2333 FunctionName + "'");
2334 } else if (Fn->isDeclaration()) {
2335 // Make sure to strip off any argument names so we can't get conflicts.
2336 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2342 } else if (FunctionName.empty()) {
2343 // If this is a definition of a forward referenced function, make sure the
2345 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2346 = ForwardRefValIDs.find(NumberedVals.size());
2347 if (I != ForwardRefValIDs.end()) {
2348 Fn = cast<Function>(I->second.first);
2349 if (Fn->getType() != PFT)
2350 return Error(NameLoc, "type of definition and forward reference of '@" +
2351 utostr(NumberedVals.size()) +"' disagree");
2352 ForwardRefValIDs.erase(I);
2357 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2358 else // Move the forward-reference to the correct spot in the module.
2359 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2361 if (FunctionName.empty())
2362 NumberedVals.push_back(Fn);
2364 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2365 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2366 Fn->setCallingConv(CC);
2367 Fn->setAttributes(PAL);
2368 Fn->setAlignment(Alignment);
2369 Fn->setSection(Section);
2370 if (!GC.empty()) Fn->setGC(GC.c_str());
2372 // Add all of the arguments we parsed to the function.
2373 Function::arg_iterator ArgIt = Fn->arg_begin();
2374 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2375 // If the argument has a name, insert it into the argument symbol table.
2376 if (ArgList[i].Name.empty()) continue;
2378 // Set the name, if it conflicted, it will be auto-renamed.
2379 ArgIt->setName(ArgList[i].Name);
2381 if (ArgIt->getNameStr() != ArgList[i].Name)
2382 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2383 ArgList[i].Name + "'");
2390 /// ParseFunctionBody
2391 /// ::= '{' BasicBlock+ '}'
2392 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2394 bool LLParser::ParseFunctionBody(Function &Fn) {
2395 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2396 return TokError("expected '{' in function body");
2397 Lex.Lex(); // eat the {.
2399 PerFunctionState PFS(*this, Fn);
2401 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2402 if (ParseBasicBlock(PFS)) return true;
2407 // Verify function is ok.
2408 return PFS.VerifyFunctionComplete();
2412 /// ::= LabelStr? Instruction*
2413 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2414 // If this basic block starts out with a name, remember it.
2416 LocTy NameLoc = Lex.getLoc();
2417 if (Lex.getKind() == lltok::LabelStr) {
2418 Name = Lex.getStrVal();
2422 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2423 if (BB == 0) return true;
2425 std::string NameStr;
2427 // Parse the instructions in this block until we get a terminator.
2430 // This instruction may have three possibilities for a name: a) none
2431 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2432 LocTy NameLoc = Lex.getLoc();
2436 if (Lex.getKind() == lltok::LocalVarID) {
2437 NameID = Lex.getUIntVal();
2439 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2441 } else if (Lex.getKind() == lltok::LocalVar ||
2442 // FIXME: REMOVE IN LLVM 3.0
2443 Lex.getKind() == lltok::StringConstant) {
2444 NameStr = Lex.getStrVal();
2446 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2450 if (ParseInstruction(Inst, BB, PFS)) return true;
2452 BB->getInstList().push_back(Inst);
2454 // Set the name on the instruction.
2455 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2456 } while (!isa<TerminatorInst>(Inst));
2461 //===----------------------------------------------------------------------===//
2462 // Instruction Parsing.
2463 //===----------------------------------------------------------------------===//
2465 /// ParseInstruction - Parse one of the many different instructions.
2467 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2468 PerFunctionState &PFS) {
2469 lltok::Kind Token = Lex.getKind();
2470 if (Token == lltok::Eof)
2471 return TokError("found end of file when expecting more instructions");
2472 LocTy Loc = Lex.getLoc();
2473 unsigned KeywordVal = Lex.getUIntVal();
2474 Lex.Lex(); // Eat the keyword.
2477 default: return Error(Loc, "expected instruction opcode");
2478 // Terminator Instructions.
2479 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2480 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2481 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2482 case lltok::kw_br: return ParseBr(Inst, PFS);
2483 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2484 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2485 // Binary Operators.
2489 // API compatibility: Accept either integer or floating-point types.
2490 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2491 case lltok::kw_fadd:
2492 case lltok::kw_fsub:
2493 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2495 case lltok::kw_udiv:
2496 case lltok::kw_sdiv:
2497 case lltok::kw_urem:
2498 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2499 case lltok::kw_fdiv:
2500 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2502 case lltok::kw_lshr:
2503 case lltok::kw_ashr:
2506 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2507 case lltok::kw_icmp:
2508 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2510 case lltok::kw_trunc:
2511 case lltok::kw_zext:
2512 case lltok::kw_sext:
2513 case lltok::kw_fptrunc:
2514 case lltok::kw_fpext:
2515 case lltok::kw_bitcast:
2516 case lltok::kw_uitofp:
2517 case lltok::kw_sitofp:
2518 case lltok::kw_fptoui:
2519 case lltok::kw_fptosi:
2520 case lltok::kw_inttoptr:
2521 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2523 case lltok::kw_select: return ParseSelect(Inst, PFS);
2524 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2525 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2526 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2527 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2528 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2529 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2530 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2532 case lltok::kw_alloca:
2533 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2534 case lltok::kw_free: return ParseFree(Inst, PFS);
2535 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2536 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2537 case lltok::kw_volatile:
2538 if (EatIfPresent(lltok::kw_load))
2539 return ParseLoad(Inst, PFS, true);
2540 else if (EatIfPresent(lltok::kw_store))
2541 return ParseStore(Inst, PFS, true);
2543 return TokError("expected 'load' or 'store'");
2544 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2545 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2546 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2547 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2551 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2552 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2553 if (Opc == Instruction::FCmp) {
2554 switch (Lex.getKind()) {
2555 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2556 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2557 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2558 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2559 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2560 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2561 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2562 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2563 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2564 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2565 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2566 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2567 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2568 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2569 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2570 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2571 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2574 switch (Lex.getKind()) {
2575 default: TokError("expected icmp predicate (e.g. 'eq')");
2576 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2577 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2578 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2579 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2580 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2581 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2582 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2583 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2584 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2585 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2592 //===----------------------------------------------------------------------===//
2593 // Terminator Instructions.
2594 //===----------------------------------------------------------------------===//
2596 /// ParseRet - Parse a return instruction.
2598 /// ::= 'ret' TypeAndValue
2599 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2600 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2601 PerFunctionState &PFS) {
2602 PATypeHolder Ty(Type::VoidTy);
2603 if (ParseType(Ty, true /*void allowed*/)) return true;
2605 if (Ty == Type::VoidTy) {
2606 Inst = ReturnInst::Create();
2611 if (ParseValue(Ty, RV, PFS)) return true;
2613 // The normal case is one return value.
2614 if (Lex.getKind() == lltok::comma) {
2615 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2616 // of 'ret {i32,i32} {i32 1, i32 2}'
2617 SmallVector<Value*, 8> RVs;
2620 while (EatIfPresent(lltok::comma)) {
2621 if (ParseTypeAndValue(RV, PFS)) return true;
2625 RV = Context.getUndef(PFS.getFunction().getReturnType());
2626 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2627 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2628 BB->getInstList().push_back(I);
2632 Inst = ReturnInst::Create(RV);
2638 /// ::= 'br' TypeAndValue
2639 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2640 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2642 Value *Op0, *Op1, *Op2;
2643 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2645 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2646 Inst = BranchInst::Create(BB);
2650 if (Op0->getType() != Type::Int1Ty)
2651 return Error(Loc, "branch condition must have 'i1' type");
2653 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2654 ParseTypeAndValue(Op1, Loc, PFS) ||
2655 ParseToken(lltok::comma, "expected ',' after true destination") ||
2656 ParseTypeAndValue(Op2, Loc2, PFS))
2659 if (!isa<BasicBlock>(Op1))
2660 return Error(Loc, "true destination of branch must be a basic block");
2661 if (!isa<BasicBlock>(Op2))
2662 return Error(Loc2, "true destination of branch must be a basic block");
2664 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2670 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2672 /// ::= (TypeAndValue ',' TypeAndValue)*
2673 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2674 LocTy CondLoc, BBLoc;
2675 Value *Cond, *DefaultBB;
2676 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2677 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2678 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2679 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2682 if (!isa<IntegerType>(Cond->getType()))
2683 return Error(CondLoc, "switch condition must have integer type");
2684 if (!isa<BasicBlock>(DefaultBB))
2685 return Error(BBLoc, "default destination must be a basic block");
2687 // Parse the jump table pairs.
2688 SmallPtrSet<Value*, 32> SeenCases;
2689 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2690 while (Lex.getKind() != lltok::rsquare) {
2691 Value *Constant, *DestBB;
2693 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2694 ParseToken(lltok::comma, "expected ',' after case value") ||
2695 ParseTypeAndValue(DestBB, BBLoc, PFS))
2698 if (!SeenCases.insert(Constant))
2699 return Error(CondLoc, "duplicate case value in switch");
2700 if (!isa<ConstantInt>(Constant))
2701 return Error(CondLoc, "case value is not a constant integer");
2702 if (!isa<BasicBlock>(DestBB))
2703 return Error(BBLoc, "case destination is not a basic block");
2705 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2706 cast<BasicBlock>(DestBB)));
2709 Lex.Lex(); // Eat the ']'.
2711 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2713 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2714 SI->addCase(Table[i].first, Table[i].second);
2720 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2721 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2722 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2723 LocTy CallLoc = Lex.getLoc();
2724 unsigned CC, RetAttrs, FnAttrs;
2725 PATypeHolder RetType(Type::VoidTy);
2728 SmallVector<ParamInfo, 16> ArgList;
2730 Value *NormalBB, *UnwindBB;
2731 if (ParseOptionalCallingConv(CC) ||
2732 ParseOptionalAttrs(RetAttrs, 1) ||
2733 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2734 ParseValID(CalleeID) ||
2735 ParseParameterList(ArgList, PFS) ||
2736 ParseOptionalAttrs(FnAttrs, 2) ||
2737 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2738 ParseTypeAndValue(NormalBB, PFS) ||
2739 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2740 ParseTypeAndValue(UnwindBB, PFS))
2743 if (!isa<BasicBlock>(NormalBB))
2744 return Error(CallLoc, "normal destination is not a basic block");
2745 if (!isa<BasicBlock>(UnwindBB))
2746 return Error(CallLoc, "unwind destination is not a basic block");
2748 // If RetType is a non-function pointer type, then this is the short syntax
2749 // for the call, which means that RetType is just the return type. Infer the
2750 // rest of the function argument types from the arguments that are present.
2751 const PointerType *PFTy = 0;
2752 const FunctionType *Ty = 0;
2753 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2754 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2755 // Pull out the types of all of the arguments...
2756 std::vector<const Type*> ParamTypes;
2757 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2758 ParamTypes.push_back(ArgList[i].V->getType());
2760 if (!FunctionType::isValidReturnType(RetType))
2761 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2763 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2764 PFTy = Context.getPointerTypeUnqual(Ty);
2767 // Look up the callee.
2769 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2771 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2772 // function attributes.
2773 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2774 if (FnAttrs & ObsoleteFuncAttrs) {
2775 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2776 FnAttrs &= ~ObsoleteFuncAttrs;
2779 // Set up the Attributes for the function.
2780 SmallVector<AttributeWithIndex, 8> Attrs;
2781 if (RetAttrs != Attribute::None)
2782 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2784 SmallVector<Value*, 8> Args;
2786 // Loop through FunctionType's arguments and ensure they are specified
2787 // correctly. Also, gather any parameter attributes.
2788 FunctionType::param_iterator I = Ty->param_begin();
2789 FunctionType::param_iterator E = Ty->param_end();
2790 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2791 const Type *ExpectedTy = 0;
2794 } else if (!Ty->isVarArg()) {
2795 return Error(ArgList[i].Loc, "too many arguments specified");
2798 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2799 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2800 ExpectedTy->getDescription() + "'");
2801 Args.push_back(ArgList[i].V);
2802 if (ArgList[i].Attrs != Attribute::None)
2803 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2807 return Error(CallLoc, "not enough parameters specified for call");
2809 if (FnAttrs != Attribute::None)
2810 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2812 // Finish off the Attributes and check them
2813 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2815 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2816 cast<BasicBlock>(UnwindBB),
2817 Args.begin(), Args.end());
2818 II->setCallingConv(CC);
2819 II->setAttributes(PAL);
2826 //===----------------------------------------------------------------------===//
2827 // Binary Operators.
2828 //===----------------------------------------------------------------------===//
2831 /// ::= ArithmeticOps TypeAndValue ',' Value
2833 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2834 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2835 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2836 unsigned Opc, unsigned OperandType) {
2837 LocTy Loc; Value *LHS, *RHS;
2838 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2839 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2840 ParseValue(LHS->getType(), RHS, PFS))
2844 switch (OperandType) {
2845 default: llvm_unreachable("Unknown operand type!");
2846 case 0: // int or FP.
2847 Valid = LHS->getType()->isIntOrIntVector() ||
2848 LHS->getType()->isFPOrFPVector();
2850 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2851 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2855 return Error(Loc, "invalid operand type for instruction");
2857 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2862 /// ::= ArithmeticOps TypeAndValue ',' Value {
2863 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2865 LocTy Loc; Value *LHS, *RHS;
2866 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2867 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2868 ParseValue(LHS->getType(), RHS, PFS))
2871 if (!LHS->getType()->isIntOrIntVector())
2872 return Error(Loc,"instruction requires integer or integer vector operands");
2874 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2880 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2881 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2882 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2884 // Parse the integer/fp comparison predicate.
2888 if (ParseCmpPredicate(Pred, Opc) ||
2889 ParseTypeAndValue(LHS, Loc, PFS) ||
2890 ParseToken(lltok::comma, "expected ',' after compare value") ||
2891 ParseValue(LHS->getType(), RHS, PFS))
2894 if (Opc == Instruction::FCmp) {
2895 if (!LHS->getType()->isFPOrFPVector())
2896 return Error(Loc, "fcmp requires floating point operands");
2897 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2899 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
2900 if (!LHS->getType()->isIntOrIntVector() &&
2901 !isa<PointerType>(LHS->getType()))
2902 return Error(Loc, "icmp requires integer operands");
2903 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2908 //===----------------------------------------------------------------------===//
2909 // Other Instructions.
2910 //===----------------------------------------------------------------------===//
2914 /// ::= CastOpc TypeAndValue 'to' Type
2915 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2917 LocTy Loc; Value *Op;
2918 PATypeHolder DestTy(Type::VoidTy);
2919 if (ParseTypeAndValue(Op, Loc, PFS) ||
2920 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2924 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2925 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2926 return Error(Loc, "invalid cast opcode for cast from '" +
2927 Op->getType()->getDescription() + "' to '" +
2928 DestTy->getDescription() + "'");
2930 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2935 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2936 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2938 Value *Op0, *Op1, *Op2;
2939 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2940 ParseToken(lltok::comma, "expected ',' after select condition") ||
2941 ParseTypeAndValue(Op1, PFS) ||
2942 ParseToken(lltok::comma, "expected ',' after select value") ||
2943 ParseTypeAndValue(Op2, PFS))
2946 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2947 return Error(Loc, Reason);
2949 Inst = SelectInst::Create(Op0, Op1, Op2);
2954 /// ::= 'va_arg' TypeAndValue ',' Type
2955 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2957 PATypeHolder EltTy(Type::VoidTy);
2959 if (ParseTypeAndValue(Op, PFS) ||
2960 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2961 ParseType(EltTy, TypeLoc))
2964 if (!EltTy->isFirstClassType())
2965 return Error(TypeLoc, "va_arg requires operand with first class type");
2967 Inst = new VAArgInst(Op, EltTy);
2971 /// ParseExtractElement
2972 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2973 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2976 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2977 ParseToken(lltok::comma, "expected ',' after extract value") ||
2978 ParseTypeAndValue(Op1, PFS))
2981 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2982 return Error(Loc, "invalid extractelement operands");
2984 Inst = new ExtractElementInst(Op0, Op1);
2988 /// ParseInsertElement
2989 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2990 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2992 Value *Op0, *Op1, *Op2;
2993 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2994 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2995 ParseTypeAndValue(Op1, PFS) ||
2996 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2997 ParseTypeAndValue(Op2, PFS))
3000 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3001 return Error(Loc, "invalid extractelement operands");
3003 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3007 /// ParseShuffleVector
3008 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3009 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3011 Value *Op0, *Op1, *Op2;
3012 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3013 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3014 ParseTypeAndValue(Op1, PFS) ||
3015 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3016 ParseTypeAndValue(Op2, PFS))
3019 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3020 return Error(Loc, "invalid extractelement operands");
3022 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3027 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3028 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3029 PATypeHolder Ty(Type::VoidTy);
3031 LocTy TypeLoc = Lex.getLoc();
3033 if (ParseType(Ty) ||
3034 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3035 ParseValue(Ty, Op0, PFS) ||
3036 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3037 ParseValue(Type::LabelTy, Op1, PFS) ||
3038 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3041 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3043 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3045 if (!EatIfPresent(lltok::comma))
3048 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3049 ParseValue(Ty, Op0, PFS) ||
3050 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3051 ParseValue(Type::LabelTy, Op1, PFS) ||
3052 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3056 if (!Ty->isFirstClassType())
3057 return Error(TypeLoc, "phi node must have first class type");
3059 PHINode *PN = PHINode::Create(Ty);
3060 PN->reserveOperandSpace(PHIVals.size());
3061 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3062 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3068 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3069 /// ParameterList OptionalAttrs
3070 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3072 unsigned CC, RetAttrs, FnAttrs;
3073 PATypeHolder RetType(Type::VoidTy);
3076 SmallVector<ParamInfo, 16> ArgList;
3077 LocTy CallLoc = Lex.getLoc();
3079 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3080 ParseOptionalCallingConv(CC) ||
3081 ParseOptionalAttrs(RetAttrs, 1) ||
3082 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3083 ParseValID(CalleeID) ||
3084 ParseParameterList(ArgList, PFS) ||
3085 ParseOptionalAttrs(FnAttrs, 2))
3088 // If RetType is a non-function pointer type, then this is the short syntax
3089 // for the call, which means that RetType is just the return type. Infer the
3090 // rest of the function argument types from the arguments that are present.
3091 const PointerType *PFTy = 0;
3092 const FunctionType *Ty = 0;
3093 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3094 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3095 // Pull out the types of all of the arguments...
3096 std::vector<const Type*> ParamTypes;
3097 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3098 ParamTypes.push_back(ArgList[i].V->getType());
3100 if (!FunctionType::isValidReturnType(RetType))
3101 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3103 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3104 PFTy = Context.getPointerTypeUnqual(Ty);
3107 // Look up the callee.
3109 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3111 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3112 // function attributes.
3113 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3114 if (FnAttrs & ObsoleteFuncAttrs) {
3115 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3116 FnAttrs &= ~ObsoleteFuncAttrs;
3119 // Set up the Attributes for the function.
3120 SmallVector<AttributeWithIndex, 8> Attrs;
3121 if (RetAttrs != Attribute::None)
3122 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3124 SmallVector<Value*, 8> Args;
3126 // Loop through FunctionType's arguments and ensure they are specified
3127 // correctly. Also, gather any parameter attributes.
3128 FunctionType::param_iterator I = Ty->param_begin();
3129 FunctionType::param_iterator E = Ty->param_end();
3130 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3131 const Type *ExpectedTy = 0;
3134 } else if (!Ty->isVarArg()) {
3135 return Error(ArgList[i].Loc, "too many arguments specified");
3138 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3139 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3140 ExpectedTy->getDescription() + "'");
3141 Args.push_back(ArgList[i].V);
3142 if (ArgList[i].Attrs != Attribute::None)
3143 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3147 return Error(CallLoc, "not enough parameters specified for call");
3149 if (FnAttrs != Attribute::None)
3150 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3152 // Finish off the Attributes and check them
3153 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3155 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3156 CI->setTailCall(isTail);
3157 CI->setCallingConv(CC);
3158 CI->setAttributes(PAL);
3163 //===----------------------------------------------------------------------===//
3164 // Memory Instructions.
3165 //===----------------------------------------------------------------------===//
3168 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3169 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3170 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3172 PATypeHolder Ty(Type::VoidTy);
3175 unsigned Alignment = 0;
3176 if (ParseType(Ty)) return true;
3178 if (EatIfPresent(lltok::comma)) {
3179 if (Lex.getKind() == lltok::kw_align) {
3180 if (ParseOptionalAlignment(Alignment)) return true;
3181 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3182 ParseOptionalCommaAlignment(Alignment)) {
3187 if (Size && Size->getType() != Type::Int32Ty)
3188 return Error(SizeLoc, "element count must be i32");
3190 if (Opc == Instruction::Malloc)
3191 Inst = new MallocInst(Ty, Size, Alignment);
3193 Inst = new AllocaInst(Ty, Size, Alignment);
3198 /// ::= 'free' TypeAndValue
3199 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3200 Value *Val; LocTy Loc;
3201 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3202 if (!isa<PointerType>(Val->getType()))
3203 return Error(Loc, "operand to free must be a pointer");
3204 Inst = new FreeInst(Val);
3209 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3210 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3212 Value *Val; LocTy Loc;
3214 if (ParseTypeAndValue(Val, Loc, PFS) ||
3215 ParseOptionalCommaAlignment(Alignment))
3218 if (!isa<PointerType>(Val->getType()) ||
3219 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3220 return Error(Loc, "load operand must be a pointer to a first class type");
3222 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3227 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3228 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3230 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3232 if (ParseTypeAndValue(Val, Loc, PFS) ||
3233 ParseToken(lltok::comma, "expected ',' after store operand") ||
3234 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3235 ParseOptionalCommaAlignment(Alignment))
3238 if (!isa<PointerType>(Ptr->getType()))
3239 return Error(PtrLoc, "store operand must be a pointer");
3240 if (!Val->getType()->isFirstClassType())
3241 return Error(Loc, "store operand must be a first class value");
3242 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3243 return Error(Loc, "stored value and pointer type do not match");
3245 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3250 /// ::= 'getresult' TypeAndValue ',' i32
3251 /// FIXME: Remove support for getresult in LLVM 3.0
3252 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3253 Value *Val; LocTy ValLoc, EltLoc;
3255 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3256 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3257 ParseUInt32(Element, EltLoc))
3260 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3261 return Error(ValLoc, "getresult inst requires an aggregate operand");
3262 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3263 return Error(EltLoc, "invalid getresult index for value");
3264 Inst = ExtractValueInst::Create(Val, Element);
3268 /// ParseGetElementPtr
3269 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3270 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3271 Value *Ptr, *Val; LocTy Loc, EltLoc;
3272 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3274 if (!isa<PointerType>(Ptr->getType()))
3275 return Error(Loc, "base of getelementptr must be a pointer");
3277 SmallVector<Value*, 16> Indices;
3278 while (EatIfPresent(lltok::comma)) {
3279 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3280 if (!isa<IntegerType>(Val->getType()))
3281 return Error(EltLoc, "getelementptr index must be an integer");
3282 Indices.push_back(Val);
3285 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3286 Indices.begin(), Indices.end()))
3287 return Error(Loc, "invalid getelementptr indices");
3288 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3292 /// ParseExtractValue
3293 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3294 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3295 Value *Val; LocTy Loc;
3296 SmallVector<unsigned, 4> Indices;
3297 if (ParseTypeAndValue(Val, Loc, PFS) ||
3298 ParseIndexList(Indices))
3301 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3302 return Error(Loc, "extractvalue operand must be array or struct");
3304 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3306 return Error(Loc, "invalid indices for extractvalue");
3307 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3311 /// ParseInsertValue
3312 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3313 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3314 Value *Val0, *Val1; LocTy Loc0, Loc1;
3315 SmallVector<unsigned, 4> Indices;
3316 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3317 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3318 ParseTypeAndValue(Val1, Loc1, PFS) ||
3319 ParseIndexList(Indices))
3322 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3323 return Error(Loc0, "extractvalue operand must be array or struct");
3325 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3327 return Error(Loc0, "invalid indices for insertvalue");
3328 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3332 //===----------------------------------------------------------------------===//
3333 // Embedded metadata.
3334 //===----------------------------------------------------------------------===//
3336 /// ParseMDNodeVector
3337 /// ::= Element (',' Element)*
3339 /// ::= 'null' | TypeAndValue
3340 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3341 assert(Lex.getKind() == lltok::lbrace);
3345 if (Lex.getKind() == lltok::kw_null) {
3350 if (ParseGlobalTypeAndValue(C)) return true;
3354 } while (EatIfPresent(lltok::comma));