1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
32 /// ValID - Represents a reference of a definition of some sort with no type.
33 /// There are several cases where we have to parse the value but where the
34 /// type can depend on later context. This may either be a numeric reference
35 /// or a symbolic (%var) reference. This is just a discriminated union.
38 t_LocalID, t_GlobalID, // ID in UIntVal.
39 t_LocalName, t_GlobalName, // Name in StrVal.
40 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
41 t_Null, t_Undef, t_Zero, // No value.
42 t_EmptyArray, // No value: []
43 t_Constant, // Value in ConstantVal.
44 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
49 std::string StrVal, StrVal2;
52 Constant *ConstantVal;
53 ValID() : APFloatVal(0.0) {}
57 /// Run: module ::= toplevelentity*
58 bool LLParser::Run() {
62 return ParseTopLevelEntities() ||
63 ValidateEndOfModule();
66 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
68 bool LLParser::ValidateEndOfModule() {
69 if (!ForwardRefTypes.empty())
70 return Error(ForwardRefTypes.begin()->second.second,
71 "use of undefined type named '" +
72 ForwardRefTypes.begin()->first + "'");
73 if (!ForwardRefTypeIDs.empty())
74 return Error(ForwardRefTypeIDs.begin()->second.second,
75 "use of undefined type '%" +
76 utostr(ForwardRefTypeIDs.begin()->first) + "'");
78 if (!ForwardRefVals.empty())
79 return Error(ForwardRefVals.begin()->second.second,
80 "use of undefined value '@" + ForwardRefVals.begin()->first +
83 if (!ForwardRefValIDs.empty())
84 return Error(ForwardRefValIDs.begin()->second.second,
85 "use of undefined value '@" +
86 utostr(ForwardRefValIDs.begin()->first) + "'");
88 if (!ForwardRefMDNodes.empty())
89 return Error(ForwardRefMDNodes.begin()->second.second,
90 "use of undefined metadata '!" +
91 utostr(ForwardRefMDNodes.begin()->first) + "'");
94 // Look for intrinsic functions and CallInst that need to be upgraded
95 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
96 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
101 //===----------------------------------------------------------------------===//
102 // Top-Level Entities
103 //===----------------------------------------------------------------------===//
105 bool LLParser::ParseTopLevelEntities() {
107 switch (Lex.getKind()) {
108 default: return TokError("expected top-level entity");
109 case lltok::Eof: return false;
110 //case lltok::kw_define:
111 case lltok::kw_declare: if (ParseDeclare()) return true; break;
112 case lltok::kw_define: if (ParseDefine()) return true; break;
113 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
114 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
115 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
116 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
117 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
118 case lltok::LocalVar: if (ParseNamedType()) return true; break;
119 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
120 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
122 // The Global variable production with no name can have many different
123 // optional leading prefixes, the production is:
124 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
125 // OptionalAddrSpace ('constant'|'global') ...
126 case lltok::kw_private: // OptionalLinkage
127 case lltok::kw_internal: // OptionalLinkage
128 case lltok::kw_weak: // OptionalLinkage
129 case lltok::kw_weak_odr: // OptionalLinkage
130 case lltok::kw_linkonce: // OptionalLinkage
131 case lltok::kw_linkonce_odr: // OptionalLinkage
132 case lltok::kw_appending: // OptionalLinkage
133 case lltok::kw_dllexport: // OptionalLinkage
134 case lltok::kw_common: // OptionalLinkage
135 case lltok::kw_dllimport: // OptionalLinkage
136 case lltok::kw_extern_weak: // OptionalLinkage
137 case lltok::kw_external: { // OptionalLinkage
138 unsigned Linkage, Visibility;
139 if (ParseOptionalLinkage(Linkage) ||
140 ParseOptionalVisibility(Visibility) ||
141 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
145 case lltok::kw_default: // OptionalVisibility
146 case lltok::kw_hidden: // OptionalVisibility
147 case lltok::kw_protected: { // OptionalVisibility
149 if (ParseOptionalVisibility(Visibility) ||
150 ParseGlobal("", SMLoc(), 0, false, Visibility))
155 case lltok::kw_thread_local: // OptionalThreadLocal
156 case lltok::kw_addrspace: // OptionalAddrSpace
157 case lltok::kw_constant: // GlobalType
158 case lltok::kw_global: // GlobalType
159 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
167 /// ::= 'module' 'asm' STRINGCONSTANT
168 bool LLParser::ParseModuleAsm() {
169 assert(Lex.getKind() == lltok::kw_module);
173 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
174 ParseStringConstant(AsmStr)) return true;
176 const std::string &AsmSoFar = M->getModuleInlineAsm();
177 if (AsmSoFar.empty())
178 M->setModuleInlineAsm(AsmStr);
180 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
185 /// ::= 'target' 'triple' '=' STRINGCONSTANT
186 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
187 bool LLParser::ParseTargetDefinition() {
188 assert(Lex.getKind() == lltok::kw_target);
191 default: return TokError("unknown target property");
192 case lltok::kw_triple:
194 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
195 ParseStringConstant(Str))
197 M->setTargetTriple(Str);
199 case lltok::kw_datalayout:
201 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
202 ParseStringConstant(Str))
204 M->setDataLayout(Str);
210 /// ::= 'deplibs' '=' '[' ']'
211 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
212 bool LLParser::ParseDepLibs() {
213 assert(Lex.getKind() == lltok::kw_deplibs);
215 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
216 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
219 if (EatIfPresent(lltok::rsquare))
223 if (ParseStringConstant(Str)) return true;
226 while (EatIfPresent(lltok::comma)) {
227 if (ParseStringConstant(Str)) return true;
231 return ParseToken(lltok::rsquare, "expected ']' at end of list");
236 bool LLParser::ParseUnnamedType() {
237 assert(Lex.getKind() == lltok::kw_type);
238 LocTy TypeLoc = Lex.getLoc();
239 Lex.Lex(); // eat kw_type
241 PATypeHolder Ty(Type::VoidTy);
242 if (ParseType(Ty)) return true;
244 unsigned TypeID = NumberedTypes.size();
246 // See if this type was previously referenced.
247 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
248 FI = ForwardRefTypeIDs.find(TypeID);
249 if (FI != ForwardRefTypeIDs.end()) {
250 if (FI->second.first.get() == Ty)
251 return Error(TypeLoc, "self referential type is invalid");
253 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
254 Ty = FI->second.first.get();
255 ForwardRefTypeIDs.erase(FI);
258 NumberedTypes.push_back(Ty);
264 /// ::= LocalVar '=' 'type' type
265 bool LLParser::ParseNamedType() {
266 std::string Name = Lex.getStrVal();
267 LocTy NameLoc = Lex.getLoc();
268 Lex.Lex(); // eat LocalVar.
270 PATypeHolder Ty(Type::VoidTy);
272 if (ParseToken(lltok::equal, "expected '=' after name") ||
273 ParseToken(lltok::kw_type, "expected 'type' after name") ||
277 // Set the type name, checking for conflicts as we do so.
278 bool AlreadyExists = M->addTypeName(Name, Ty);
279 if (!AlreadyExists) return false;
281 // See if this type is a forward reference. We need to eagerly resolve
282 // types to allow recursive type redefinitions below.
283 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
284 FI = ForwardRefTypes.find(Name);
285 if (FI != ForwardRefTypes.end()) {
286 if (FI->second.first.get() == Ty)
287 return Error(NameLoc, "self referential type is invalid");
289 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
290 Ty = FI->second.first.get();
291 ForwardRefTypes.erase(FI);
294 // Inserting a name that is already defined, get the existing name.
295 const Type *Existing = M->getTypeByName(Name);
296 assert(Existing && "Conflict but no matching type?!");
298 // Otherwise, this is an attempt to redefine a type. That's okay if
299 // the redefinition is identical to the original.
300 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
301 if (Existing == Ty) return false;
303 // Any other kind of (non-equivalent) redefinition is an error.
304 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
305 Ty->getDescription() + "'");
310 /// ::= 'declare' FunctionHeader
311 bool LLParser::ParseDeclare() {
312 assert(Lex.getKind() == lltok::kw_declare);
316 return ParseFunctionHeader(F, false);
320 /// ::= 'define' FunctionHeader '{' ...
321 bool LLParser::ParseDefine() {
322 assert(Lex.getKind() == lltok::kw_define);
326 return ParseFunctionHeader(F, true) ||
327 ParseFunctionBody(*F);
333 bool LLParser::ParseGlobalType(bool &IsConstant) {
334 if (Lex.getKind() == lltok::kw_constant)
336 else if (Lex.getKind() == lltok::kw_global)
340 return TokError("expected 'global' or 'constant'");
346 /// ParseNamedGlobal:
347 /// GlobalVar '=' OptionalVisibility ALIAS ...
348 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
349 bool LLParser::ParseNamedGlobal() {
350 assert(Lex.getKind() == lltok::GlobalVar);
351 LocTy NameLoc = Lex.getLoc();
352 std::string Name = Lex.getStrVal();
356 unsigned Linkage, Visibility;
357 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
358 ParseOptionalLinkage(Linkage, HasLinkage) ||
359 ParseOptionalVisibility(Visibility))
362 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
363 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
364 return ParseAlias(Name, NameLoc, Visibility);
367 /// ParseStandaloneMetadata:
369 bool LLParser::ParseStandaloneMetadata() {
370 assert(Lex.getKind() == lltok::Metadata);
372 unsigned MetadataID = 0;
373 if (ParseUInt32(MetadataID))
375 if (MetadataCache.find(MetadataID) != MetadataCache.end())
376 return TokError("Metadata id is already used");
377 if (ParseToken(lltok::equal, "expected '=' here"))
381 PATypeHolder Ty(Type::VoidTy);
382 if (ParseType(Ty, TyLoc))
386 if (ParseGlobalValue(Ty, Init))
389 MetadataCache[MetadataID] = Init;
390 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
391 FI = ForwardRefMDNodes.find(MetadataID);
392 if (FI != ForwardRefMDNodes.end()) {
393 Constant *FwdNode = FI->second.first;
394 FwdNode->replaceAllUsesWith(Init);
395 ForwardRefMDNodes.erase(FI);
402 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
405 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
406 /// ::= 'getelementptr' '(' ... ')'
408 /// Everything through visibility has already been parsed.
410 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
411 unsigned Visibility) {
412 assert(Lex.getKind() == lltok::kw_alias);
415 LocTy LinkageLoc = Lex.getLoc();
416 if (ParseOptionalLinkage(Linkage))
419 if (Linkage != GlobalValue::ExternalLinkage &&
420 Linkage != GlobalValue::WeakAnyLinkage &&
421 Linkage != GlobalValue::WeakODRLinkage &&
422 Linkage != GlobalValue::InternalLinkage &&
423 Linkage != GlobalValue::PrivateLinkage)
424 return Error(LinkageLoc, "invalid linkage type for alias");
427 LocTy AliaseeLoc = Lex.getLoc();
428 if (Lex.getKind() != lltok::kw_bitcast &&
429 Lex.getKind() != lltok::kw_getelementptr) {
430 if (ParseGlobalTypeAndValue(Aliasee)) return true;
432 // The bitcast dest type is not present, it is implied by the dest type.
434 if (ParseValID(ID)) return true;
435 if (ID.Kind != ValID::t_Constant)
436 return Error(AliaseeLoc, "invalid aliasee");
437 Aliasee = ID.ConstantVal;
440 if (!isa<PointerType>(Aliasee->getType()))
441 return Error(AliaseeLoc, "alias must have pointer type");
443 // Okay, create the alias but do not insert it into the module yet.
444 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
445 (GlobalValue::LinkageTypes)Linkage, Name,
447 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
449 // See if this value already exists in the symbol table. If so, it is either
450 // a redefinition or a definition of a forward reference.
451 if (GlobalValue *Val =
452 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
453 // See if this was a redefinition. If so, there is no entry in
455 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
456 I = ForwardRefVals.find(Name);
457 if (I == ForwardRefVals.end())
458 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
460 // Otherwise, this was a definition of forward ref. Verify that types
462 if (Val->getType() != GA->getType())
463 return Error(NameLoc,
464 "forward reference and definition of alias have different types");
466 // If they agree, just RAUW the old value with the alias and remove the
468 Val->replaceAllUsesWith(GA);
469 Val->eraseFromParent();
470 ForwardRefVals.erase(I);
473 // Insert into the module, we know its name won't collide now.
474 M->getAliasList().push_back(GA);
475 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
481 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
482 /// OptionalAddrSpace GlobalType Type Const
483 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
484 /// OptionalAddrSpace GlobalType Type Const
486 /// Everything through visibility has been parsed already.
488 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
489 unsigned Linkage, bool HasLinkage,
490 unsigned Visibility) {
492 bool ThreadLocal, IsConstant;
495 PATypeHolder Ty(Type::VoidTy);
496 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
497 ParseOptionalAddrSpace(AddrSpace) ||
498 ParseGlobalType(IsConstant) ||
499 ParseType(Ty, TyLoc))
502 // If the linkage is specified and is external, then no initializer is
505 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
506 Linkage != GlobalValue::ExternalWeakLinkage &&
507 Linkage != GlobalValue::ExternalLinkage)) {
508 if (ParseGlobalValue(Ty, Init))
512 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
513 return Error(TyLoc, "invalid type for global variable");
515 GlobalVariable *GV = 0;
517 // See if the global was forward referenced, if so, use the global.
519 if ((GV = M->getGlobalVariable(Name, true)) &&
520 !ForwardRefVals.erase(Name))
521 return Error(NameLoc, "redefinition of global '@" + Name + "'");
523 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
524 I = ForwardRefValIDs.find(NumberedVals.size());
525 if (I != ForwardRefValIDs.end()) {
526 GV = cast<GlobalVariable>(I->second.first);
527 ForwardRefValIDs.erase(I);
532 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
533 Name, 0, false, AddrSpace);
535 if (GV->getType()->getElementType() != Ty)
537 "forward reference and definition of global have different types");
539 // Move the forward-reference to the correct spot in the module.
540 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
544 NumberedVals.push_back(GV);
546 // Set the parsed properties on the global.
548 GV->setInitializer(Init);
549 GV->setConstant(IsConstant);
550 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
551 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
552 GV->setThreadLocal(ThreadLocal);
554 // Parse attributes on the global.
555 while (Lex.getKind() == lltok::comma) {
558 if (Lex.getKind() == lltok::kw_section) {
560 GV->setSection(Lex.getStrVal());
561 if (ParseToken(lltok::StringConstant, "expected global section string"))
563 } else if (Lex.getKind() == lltok::kw_align) {
565 if (ParseOptionalAlignment(Alignment)) return true;
566 GV->setAlignment(Alignment);
568 TokError("unknown global variable property!");
576 //===----------------------------------------------------------------------===//
577 // GlobalValue Reference/Resolution Routines.
578 //===----------------------------------------------------------------------===//
580 /// GetGlobalVal - Get a value with the specified name or ID, creating a
581 /// forward reference record if needed. This can return null if the value
582 /// exists but does not have the right type.
583 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
587 Error(Loc, "global variable reference must have pointer type");
591 // Look this name up in the normal function symbol table.
593 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
595 // If this is a forward reference for the value, see if we already created a
596 // forward ref record.
598 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
599 I = ForwardRefVals.find(Name);
600 if (I != ForwardRefVals.end())
601 Val = I->second.first;
604 // If we have the value in the symbol table or fwd-ref table, return it.
606 if (Val->getType() == Ty) return Val;
607 Error(Loc, "'@" + Name + "' defined with type '" +
608 Val->getType()->getDescription() + "'");
612 // Otherwise, create a new forward reference for this value and remember it.
614 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
615 // Function types can return opaque but functions can't.
616 if (isa<OpaqueType>(FT->getReturnType())) {
617 Error(Loc, "function may not return opaque type");
621 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
623 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
624 GlobalValue::ExternalWeakLinkage, 0, Name);
627 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
631 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
632 const PointerType *PTy = dyn_cast<PointerType>(Ty);
634 Error(Loc, "global variable reference must have pointer type");
638 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
640 // If this is a forward reference for the value, see if we already created a
641 // forward ref record.
643 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
644 I = ForwardRefValIDs.find(ID);
645 if (I != ForwardRefValIDs.end())
646 Val = I->second.first;
649 // If we have the value in the symbol table or fwd-ref table, return it.
651 if (Val->getType() == Ty) return Val;
652 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
653 Val->getType()->getDescription() + "'");
657 // Otherwise, create a new forward reference for this value and remember it.
659 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
660 // Function types can return opaque but functions can't.
661 if (isa<OpaqueType>(FT->getReturnType())) {
662 Error(Loc, "function may not return opaque type");
665 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
667 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
668 GlobalValue::ExternalWeakLinkage, 0, "");
671 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
676 //===----------------------------------------------------------------------===//
678 //===----------------------------------------------------------------------===//
680 /// ParseToken - If the current token has the specified kind, eat it and return
681 /// success. Otherwise, emit the specified error and return failure.
682 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
683 if (Lex.getKind() != T)
684 return TokError(ErrMsg);
689 /// ParseStringConstant
690 /// ::= StringConstant
691 bool LLParser::ParseStringConstant(std::string &Result) {
692 if (Lex.getKind() != lltok::StringConstant)
693 return TokError("expected string constant");
694 Result = Lex.getStrVal();
701 bool LLParser::ParseUInt32(unsigned &Val) {
702 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
703 return TokError("expected integer");
704 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
705 if (Val64 != unsigned(Val64))
706 return TokError("expected 32-bit integer (too large)");
713 /// ParseOptionalAddrSpace
715 /// := 'addrspace' '(' uint32 ')'
716 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
718 if (!EatIfPresent(lltok::kw_addrspace))
720 return ParseToken(lltok::lparen, "expected '(' in address space") ||
721 ParseUInt32(AddrSpace) ||
722 ParseToken(lltok::rparen, "expected ')' in address space");
725 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
726 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
727 /// 2: function attr.
728 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
729 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
730 Attrs = Attribute::None;
731 LocTy AttrLoc = Lex.getLoc();
734 switch (Lex.getKind()) {
737 // Treat these as signext/zeroext if they occur in the argument list after
738 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
739 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
741 // FIXME: REMOVE THIS IN LLVM 3.0
743 if (Lex.getKind() == lltok::kw_sext)
744 Attrs |= Attribute::SExt;
746 Attrs |= Attribute::ZExt;
750 default: // End of attributes.
751 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
752 return Error(AttrLoc, "invalid use of function-only attribute");
754 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
755 return Error(AttrLoc, "invalid use of parameter-only attribute");
758 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
759 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
760 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
761 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
762 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
763 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
764 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
765 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
767 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
768 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
769 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
770 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
771 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
772 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
773 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
774 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
775 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
776 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
777 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
778 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
780 case lltok::kw_align: {
782 if (ParseOptionalAlignment(Alignment))
784 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
792 /// ParseOptionalLinkage
799 /// ::= 'linkonce_odr'
804 /// ::= 'extern_weak'
806 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
808 switch (Lex.getKind()) {
809 default: Res = GlobalValue::ExternalLinkage; return false;
810 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
811 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
812 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
813 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
814 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
815 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
816 case lltok::kw_available_externally:
817 Res = GlobalValue::AvailableExternallyLinkage;
819 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
820 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
821 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
822 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
823 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
824 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
831 /// ParseOptionalVisibility
837 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
838 switch (Lex.getKind()) {
839 default: Res = GlobalValue::DefaultVisibility; return false;
840 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
841 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
842 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
848 /// ParseOptionalCallingConv
853 /// ::= 'x86_stdcallcc'
854 /// ::= 'x86_fastcallcc'
856 /// ::= 'arm_aapcscc'
857 /// ::= 'arm_aapcs_vfpcc'
860 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
861 switch (Lex.getKind()) {
862 default: CC = CallingConv::C; return false;
863 case lltok::kw_ccc: CC = CallingConv::C; break;
864 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
865 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
866 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
867 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
868 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
869 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
870 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
871 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
877 /// ParseOptionalAlignment
880 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
882 if (!EatIfPresent(lltok::kw_align))
884 LocTy AlignLoc = Lex.getLoc();
885 if (ParseUInt32(Alignment)) return true;
886 if (!isPowerOf2_32(Alignment))
887 return Error(AlignLoc, "alignment is not a power of two");
891 /// ParseOptionalCommaAlignment
893 /// ::= ',' 'align' 4
894 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
896 if (!EatIfPresent(lltok::comma))
898 return ParseToken(lltok::kw_align, "expected 'align'") ||
899 ParseUInt32(Alignment);
903 /// ::= (',' uint32)+
904 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
905 if (Lex.getKind() != lltok::comma)
906 return TokError("expected ',' as start of index list");
908 while (EatIfPresent(lltok::comma)) {
910 if (ParseUInt32(Idx)) return true;
911 Indices.push_back(Idx);
917 //===----------------------------------------------------------------------===//
919 //===----------------------------------------------------------------------===//
921 /// ParseType - Parse and resolve a full type.
922 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
923 LocTy TypeLoc = Lex.getLoc();
924 if (ParseTypeRec(Result)) return true;
926 // Verify no unresolved uprefs.
928 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
930 if (!AllowVoid && Result.get() == Type::VoidTy)
931 return Error(TypeLoc, "void type only allowed for function results");
936 /// HandleUpRefs - Every time we finish a new layer of types, this function is
937 /// called. It loops through the UpRefs vector, which is a list of the
938 /// currently active types. For each type, if the up-reference is contained in
939 /// the newly completed type, we decrement the level count. When the level
940 /// count reaches zero, the up-referenced type is the type that is passed in:
941 /// thus we can complete the cycle.
943 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
944 // If Ty isn't abstract, or if there are no up-references in it, then there is
945 // nothing to resolve here.
946 if (!ty->isAbstract() || UpRefs.empty()) return ty;
950 errs() << "Type '" << Ty->getDescription()
951 << "' newly formed. Resolving upreferences.\n"
952 << UpRefs.size() << " upreferences active!\n";
955 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
956 // to zero), we resolve them all together before we resolve them to Ty. At
957 // the end of the loop, if there is anything to resolve to Ty, it will be in
959 OpaqueType *TypeToResolve = 0;
961 for (unsigned i = 0; i != UpRefs.size(); ++i) {
962 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
964 std::find(Ty->subtype_begin(), Ty->subtype_end(),
965 UpRefs[i].LastContainedTy) != Ty->subtype_end();
968 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
969 << UpRefs[i].LastContainedTy->getDescription() << ") = "
970 << (ContainsType ? "true" : "false")
971 << " level=" << UpRefs[i].NestingLevel << "\n";
976 // Decrement level of upreference
977 unsigned Level = --UpRefs[i].NestingLevel;
978 UpRefs[i].LastContainedTy = Ty;
980 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
985 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
988 TypeToResolve = UpRefs[i].UpRefTy;
990 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
991 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
992 --i; // Do not skip the next element.
996 TypeToResolve->refineAbstractTypeTo(Ty);
1002 /// ParseTypeRec - The recursive function used to process the internal
1003 /// implementation details of types.
1004 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1005 switch (Lex.getKind()) {
1007 return TokError("expected type");
1009 // TypeRec ::= 'float' | 'void' (etc)
1010 Result = Lex.getTyVal();
1013 case lltok::kw_opaque:
1014 // TypeRec ::= 'opaque'
1015 Result = Context.getOpaqueType();
1019 // TypeRec ::= '{' ... '}'
1020 if (ParseStructType(Result, false))
1023 case lltok::lsquare:
1024 // TypeRec ::= '[' ... ']'
1025 Lex.Lex(); // eat the lsquare.
1026 if (ParseArrayVectorType(Result, false))
1029 case lltok::less: // Either vector or packed struct.
1030 // TypeRec ::= '<' ... '>'
1032 if (Lex.getKind() == lltok::lbrace) {
1033 if (ParseStructType(Result, true) ||
1034 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1036 } else if (ParseArrayVectorType(Result, true))
1039 case lltok::LocalVar:
1040 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1042 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1045 Result = Context.getOpaqueType();
1046 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1047 std::make_pair(Result,
1049 M->addTypeName(Lex.getStrVal(), Result.get());
1054 case lltok::LocalVarID:
1056 if (Lex.getUIntVal() < NumberedTypes.size())
1057 Result = NumberedTypes[Lex.getUIntVal()];
1059 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1060 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1061 if (I != ForwardRefTypeIDs.end())
1062 Result = I->second.first;
1064 Result = Context.getOpaqueType();
1065 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1066 std::make_pair(Result,
1072 case lltok::backslash: {
1073 // TypeRec ::= '\' 4
1076 if (ParseUInt32(Val)) return true;
1077 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1078 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1084 // Parse the type suffixes.
1086 switch (Lex.getKind()) {
1088 default: return false;
1090 // TypeRec ::= TypeRec '*'
1092 if (Result.get() == Type::LabelTy)
1093 return TokError("basic block pointers are invalid");
1094 if (Result.get() == Type::VoidTy)
1095 return TokError("pointers to void are invalid; use i8* instead");
1096 if (!PointerType::isValidElementType(Result.get()))
1097 return TokError("pointer to this type is invalid");
1098 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1102 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1103 case lltok::kw_addrspace: {
1104 if (Result.get() == Type::LabelTy)
1105 return TokError("basic block pointers are invalid");
1106 if (Result.get() == Type::VoidTy)
1107 return TokError("pointers to void are invalid; use i8* instead");
1108 if (!PointerType::isValidElementType(Result.get()))
1109 return TokError("pointer to this type is invalid");
1111 if (ParseOptionalAddrSpace(AddrSpace) ||
1112 ParseToken(lltok::star, "expected '*' in address space"))
1115 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1119 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1121 if (ParseFunctionType(Result))
1128 /// ParseParameterList
1130 /// ::= '(' Arg (',' Arg)* ')'
1132 /// ::= Type OptionalAttributes Value OptionalAttributes
1133 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1134 PerFunctionState &PFS) {
1135 if (ParseToken(lltok::lparen, "expected '(' in call"))
1138 while (Lex.getKind() != lltok::rparen) {
1139 // If this isn't the first argument, we need a comma.
1140 if (!ArgList.empty() &&
1141 ParseToken(lltok::comma, "expected ',' in argument list"))
1144 // Parse the argument.
1146 PATypeHolder ArgTy(Type::VoidTy);
1147 unsigned ArgAttrs1, ArgAttrs2;
1149 if (ParseType(ArgTy, ArgLoc) ||
1150 ParseOptionalAttrs(ArgAttrs1, 0) ||
1151 ParseValue(ArgTy, V, PFS) ||
1152 // FIXME: Should not allow attributes after the argument, remove this in
1154 ParseOptionalAttrs(ArgAttrs2, 3))
1156 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1159 Lex.Lex(); // Lex the ')'.
1165 /// ParseArgumentList - Parse the argument list for a function type or function
1166 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1167 /// ::= '(' ArgTypeListI ')'
1171 /// ::= ArgTypeList ',' '...'
1172 /// ::= ArgType (',' ArgType)*
1174 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1175 bool &isVarArg, bool inType) {
1177 assert(Lex.getKind() == lltok::lparen);
1178 Lex.Lex(); // eat the (.
1180 if (Lex.getKind() == lltok::rparen) {
1182 } else if (Lex.getKind() == lltok::dotdotdot) {
1186 LocTy TypeLoc = Lex.getLoc();
1187 PATypeHolder ArgTy(Type::VoidTy);
1191 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1192 // types (such as a function returning a pointer to itself). If parsing a
1193 // function prototype, we require fully resolved types.
1194 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1195 ParseOptionalAttrs(Attrs, 0)) return true;
1197 if (ArgTy == Type::VoidTy)
1198 return Error(TypeLoc, "argument can not have void type");
1200 if (Lex.getKind() == lltok::LocalVar ||
1201 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1202 Name = Lex.getStrVal();
1206 if (!FunctionType::isValidArgumentType(ArgTy))
1207 return Error(TypeLoc, "invalid type for function argument");
1209 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1211 while (EatIfPresent(lltok::comma)) {
1212 // Handle ... at end of arg list.
1213 if (EatIfPresent(lltok::dotdotdot)) {
1218 // Otherwise must be an argument type.
1219 TypeLoc = Lex.getLoc();
1220 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1221 ParseOptionalAttrs(Attrs, 0)) return true;
1223 if (ArgTy == Type::VoidTy)
1224 return Error(TypeLoc, "argument can not have void type");
1226 if (Lex.getKind() == lltok::LocalVar ||
1227 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1228 Name = Lex.getStrVal();
1234 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1235 return Error(TypeLoc, "invalid type for function argument");
1237 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1241 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1244 /// ParseFunctionType
1245 /// ::= Type ArgumentList OptionalAttrs
1246 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1247 assert(Lex.getKind() == lltok::lparen);
1249 if (!FunctionType::isValidReturnType(Result))
1250 return TokError("invalid function return type");
1252 std::vector<ArgInfo> ArgList;
1255 if (ParseArgumentList(ArgList, isVarArg, true) ||
1256 // FIXME: Allow, but ignore attributes on function types!
1257 // FIXME: Remove in LLVM 3.0
1258 ParseOptionalAttrs(Attrs, 2))
1261 // Reject names on the arguments lists.
1262 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1263 if (!ArgList[i].Name.empty())
1264 return Error(ArgList[i].Loc, "argument name invalid in function type");
1265 if (!ArgList[i].Attrs != 0) {
1266 // Allow but ignore attributes on function types; this permits
1268 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1272 std::vector<const Type*> ArgListTy;
1273 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1274 ArgListTy.push_back(ArgList[i].Type);
1276 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1277 ArgListTy, isVarArg));
1281 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1284 /// ::= '{' TypeRec (',' TypeRec)* '}'
1285 /// ::= '<' '{' '}' '>'
1286 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1287 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1288 assert(Lex.getKind() == lltok::lbrace);
1289 Lex.Lex(); // Consume the '{'
1291 if (EatIfPresent(lltok::rbrace)) {
1292 Result = Context.getStructType(Packed);
1296 std::vector<PATypeHolder> ParamsList;
1297 LocTy EltTyLoc = Lex.getLoc();
1298 if (ParseTypeRec(Result)) return true;
1299 ParamsList.push_back(Result);
1301 if (Result == Type::VoidTy)
1302 return Error(EltTyLoc, "struct element can not have void type");
1303 if (!StructType::isValidElementType(Result))
1304 return Error(EltTyLoc, "invalid element type for struct");
1306 while (EatIfPresent(lltok::comma)) {
1307 EltTyLoc = Lex.getLoc();
1308 if (ParseTypeRec(Result)) return true;
1310 if (Result == Type::VoidTy)
1311 return Error(EltTyLoc, "struct element can not have void type");
1312 if (!StructType::isValidElementType(Result))
1313 return Error(EltTyLoc, "invalid element type for struct");
1315 ParamsList.push_back(Result);
1318 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1321 std::vector<const Type*> ParamsListTy;
1322 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1323 ParamsListTy.push_back(ParamsList[i].get());
1324 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1328 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1329 /// token has already been consumed.
1331 /// ::= '[' APSINTVAL 'x' Types ']'
1332 /// ::= '<' APSINTVAL 'x' Types '>'
1333 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1334 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1335 Lex.getAPSIntVal().getBitWidth() > 64)
1336 return TokError("expected number in address space");
1338 LocTy SizeLoc = Lex.getLoc();
1339 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1342 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1345 LocTy TypeLoc = Lex.getLoc();
1346 PATypeHolder EltTy(Type::VoidTy);
1347 if (ParseTypeRec(EltTy)) return true;
1349 if (EltTy == Type::VoidTy)
1350 return Error(TypeLoc, "array and vector element type cannot be void");
1352 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1353 "expected end of sequential type"))
1358 return Error(SizeLoc, "zero element vector is illegal");
1359 if ((unsigned)Size != Size)
1360 return Error(SizeLoc, "size too large for vector");
1361 if (!VectorType::isValidElementType(EltTy))
1362 return Error(TypeLoc, "vector element type must be fp or integer");
1363 Result = Context.getVectorType(EltTy, unsigned(Size));
1365 if (!ArrayType::isValidElementType(EltTy))
1366 return Error(TypeLoc, "invalid array element type");
1367 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1372 //===----------------------------------------------------------------------===//
1373 // Function Semantic Analysis.
1374 //===----------------------------------------------------------------------===//
1376 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1379 // Insert unnamed arguments into the NumberedVals list.
1380 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1383 NumberedVals.push_back(AI);
1386 LLParser::PerFunctionState::~PerFunctionState() {
1387 // If there were any forward referenced non-basicblock values, delete them.
1388 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1389 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1390 if (!isa<BasicBlock>(I->second.first)) {
1391 I->second.first->replaceAllUsesWith(
1392 P.getContext().getUndef(I->second.first->getType()));
1393 delete I->second.first;
1394 I->second.first = 0;
1397 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1398 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1399 if (!isa<BasicBlock>(I->second.first)) {
1400 I->second.first->replaceAllUsesWith(
1401 P.getContext().getUndef(I->second.first->getType()));
1402 delete I->second.first;
1403 I->second.first = 0;
1407 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1408 if (!ForwardRefVals.empty())
1409 return P.Error(ForwardRefVals.begin()->second.second,
1410 "use of undefined value '%" + ForwardRefVals.begin()->first +
1412 if (!ForwardRefValIDs.empty())
1413 return P.Error(ForwardRefValIDs.begin()->second.second,
1414 "use of undefined value '%" +
1415 utostr(ForwardRefValIDs.begin()->first) + "'");
1420 /// GetVal - Get a value with the specified name or ID, creating a
1421 /// forward reference record if needed. This can return null if the value
1422 /// exists but does not have the right type.
1423 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1424 const Type *Ty, LocTy Loc) {
1425 // Look this name up in the normal function symbol table.
1426 Value *Val = F.getValueSymbolTable().lookup(Name);
1428 // If this is a forward reference for the value, see if we already created a
1429 // forward ref record.
1431 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1432 I = ForwardRefVals.find(Name);
1433 if (I != ForwardRefVals.end())
1434 Val = I->second.first;
1437 // If we have the value in the symbol table or fwd-ref table, return it.
1439 if (Val->getType() == Ty) return Val;
1440 if (Ty == Type::LabelTy)
1441 P.Error(Loc, "'%" + Name + "' is not a basic block");
1443 P.Error(Loc, "'%" + Name + "' defined with type '" +
1444 Val->getType()->getDescription() + "'");
1448 // Don't make placeholders with invalid type.
1449 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1450 P.Error(Loc, "invalid use of a non-first-class type");
1454 // Otherwise, create a new forward reference for this value and remember it.
1456 if (Ty == Type::LabelTy)
1457 FwdVal = BasicBlock::Create(Name, &F);
1459 FwdVal = new Argument(Ty, Name);
1461 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1465 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1467 // Look this name up in the normal function symbol table.
1468 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1470 // If this is a forward reference for the value, see if we already created a
1471 // forward ref record.
1473 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1474 I = ForwardRefValIDs.find(ID);
1475 if (I != ForwardRefValIDs.end())
1476 Val = I->second.first;
1479 // If we have the value in the symbol table or fwd-ref table, return it.
1481 if (Val->getType() == Ty) return Val;
1482 if (Ty == Type::LabelTy)
1483 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1485 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1486 Val->getType()->getDescription() + "'");
1490 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1491 P.Error(Loc, "invalid use of a non-first-class type");
1495 // Otherwise, create a new forward reference for this value and remember it.
1497 if (Ty == Type::LabelTy)
1498 FwdVal = BasicBlock::Create("", &F);
1500 FwdVal = new Argument(Ty);
1502 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1506 /// SetInstName - After an instruction is parsed and inserted into its
1507 /// basic block, this installs its name.
1508 bool LLParser::PerFunctionState::SetInstName(int NameID,
1509 const std::string &NameStr,
1510 LocTy NameLoc, Instruction *Inst) {
1511 // If this instruction has void type, it cannot have a name or ID specified.
1512 if (Inst->getType() == Type::VoidTy) {
1513 if (NameID != -1 || !NameStr.empty())
1514 return P.Error(NameLoc, "instructions returning void cannot have a name");
1518 // If this was a numbered instruction, verify that the instruction is the
1519 // expected value and resolve any forward references.
1520 if (NameStr.empty()) {
1521 // If neither a name nor an ID was specified, just use the next ID.
1523 NameID = NumberedVals.size();
1525 if (unsigned(NameID) != NumberedVals.size())
1526 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1527 utostr(NumberedVals.size()) + "'");
1529 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1530 ForwardRefValIDs.find(NameID);
1531 if (FI != ForwardRefValIDs.end()) {
1532 if (FI->second.first->getType() != Inst->getType())
1533 return P.Error(NameLoc, "instruction forward referenced with type '" +
1534 FI->second.first->getType()->getDescription() + "'");
1535 FI->second.first->replaceAllUsesWith(Inst);
1536 ForwardRefValIDs.erase(FI);
1539 NumberedVals.push_back(Inst);
1543 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1544 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1545 FI = ForwardRefVals.find(NameStr);
1546 if (FI != ForwardRefVals.end()) {
1547 if (FI->second.first->getType() != Inst->getType())
1548 return P.Error(NameLoc, "instruction forward referenced with type '" +
1549 FI->second.first->getType()->getDescription() + "'");
1550 FI->second.first->replaceAllUsesWith(Inst);
1551 ForwardRefVals.erase(FI);
1554 // Set the name on the instruction.
1555 Inst->setName(NameStr);
1557 if (Inst->getNameStr() != NameStr)
1558 return P.Error(NameLoc, "multiple definition of local value named '" +
1563 /// GetBB - Get a basic block with the specified name or ID, creating a
1564 /// forward reference record if needed.
1565 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1567 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1570 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1571 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1574 /// DefineBB - Define the specified basic block, which is either named or
1575 /// unnamed. If there is an error, this returns null otherwise it returns
1576 /// the block being defined.
1577 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1581 BB = GetBB(NumberedVals.size(), Loc);
1583 BB = GetBB(Name, Loc);
1584 if (BB == 0) return 0; // Already diagnosed error.
1586 // Move the block to the end of the function. Forward ref'd blocks are
1587 // inserted wherever they happen to be referenced.
1588 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1590 // Remove the block from forward ref sets.
1592 ForwardRefValIDs.erase(NumberedVals.size());
1593 NumberedVals.push_back(BB);
1595 // BB forward references are already in the function symbol table.
1596 ForwardRefVals.erase(Name);
1602 //===----------------------------------------------------------------------===//
1604 //===----------------------------------------------------------------------===//
1606 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1607 /// type implied. For example, if we parse "4" we don't know what integer type
1608 /// it has. The value will later be combined with its type and checked for
1610 bool LLParser::ParseValID(ValID &ID) {
1611 ID.Loc = Lex.getLoc();
1612 switch (Lex.getKind()) {
1613 default: return TokError("expected value token");
1614 case lltok::GlobalID: // @42
1615 ID.UIntVal = Lex.getUIntVal();
1616 ID.Kind = ValID::t_GlobalID;
1618 case lltok::GlobalVar: // @foo
1619 ID.StrVal = Lex.getStrVal();
1620 ID.Kind = ValID::t_GlobalName;
1622 case lltok::LocalVarID: // %42
1623 ID.UIntVal = Lex.getUIntVal();
1624 ID.Kind = ValID::t_LocalID;
1626 case lltok::LocalVar: // %foo
1627 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1628 ID.StrVal = Lex.getStrVal();
1629 ID.Kind = ValID::t_LocalName;
1631 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1632 ID.Kind = ValID::t_Constant;
1634 if (Lex.getKind() == lltok::lbrace) {
1635 SmallVector<Value*, 16> Elts;
1636 if (ParseMDNodeVector(Elts) ||
1637 ParseToken(lltok::rbrace, "expected end of metadata node"))
1640 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1644 // Standalone metadata reference
1645 // !{ ..., !42, ... }
1647 if (!ParseUInt32(MID)) {
1648 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1649 if (I != MetadataCache.end())
1650 ID.ConstantVal = I->second;
1652 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1653 FI = ForwardRefMDNodes.find(MID);
1654 if (FI != ForwardRefMDNodes.end())
1655 ID.ConstantVal = FI->second.first;
1657 // Create MDNode forward reference
1658 SmallVector<Value *, 1> Elts;
1659 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
1660 Elts.push_back(Context.getMDString(FwdRefName));
1661 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1662 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1663 ID.ConstantVal = FwdNode;
1671 // ::= '!' STRINGCONSTANT
1673 if (ParseStringConstant(Str)) return true;
1675 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
1679 ID.APSIntVal = Lex.getAPSIntVal();
1680 ID.Kind = ValID::t_APSInt;
1682 case lltok::APFloat:
1683 ID.APFloatVal = Lex.getAPFloatVal();
1684 ID.Kind = ValID::t_APFloat;
1686 case lltok::kw_true:
1687 ID.ConstantVal = Context.getConstantIntTrue();
1688 ID.Kind = ValID::t_Constant;
1690 case lltok::kw_false:
1691 ID.ConstantVal = Context.getConstantIntFalse();
1692 ID.Kind = ValID::t_Constant;
1694 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1695 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1696 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1698 case lltok::lbrace: {
1699 // ValID ::= '{' ConstVector '}'
1701 SmallVector<Constant*, 16> Elts;
1702 if (ParseGlobalValueVector(Elts) ||
1703 ParseToken(lltok::rbrace, "expected end of struct constant"))
1706 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1707 ID.Kind = ValID::t_Constant;
1711 // ValID ::= '<' ConstVector '>' --> Vector.
1712 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1714 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1716 SmallVector<Constant*, 16> Elts;
1717 LocTy FirstEltLoc = Lex.getLoc();
1718 if (ParseGlobalValueVector(Elts) ||
1720 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1721 ParseToken(lltok::greater, "expected end of constant"))
1724 if (isPackedStruct) {
1726 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1727 ID.Kind = ValID::t_Constant;
1732 return Error(ID.Loc, "constant vector must not be empty");
1734 if (!Elts[0]->getType()->isInteger() &&
1735 !Elts[0]->getType()->isFloatingPoint())
1736 return Error(FirstEltLoc,
1737 "vector elements must have integer or floating point type");
1739 // Verify that all the vector elements have the same type.
1740 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1741 if (Elts[i]->getType() != Elts[0]->getType())
1742 return Error(FirstEltLoc,
1743 "vector element #" + utostr(i) +
1744 " is not of type '" + Elts[0]->getType()->getDescription());
1746 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1747 ID.Kind = ValID::t_Constant;
1750 case lltok::lsquare: { // Array Constant
1752 SmallVector<Constant*, 16> Elts;
1753 LocTy FirstEltLoc = Lex.getLoc();
1754 if (ParseGlobalValueVector(Elts) ||
1755 ParseToken(lltok::rsquare, "expected end of array constant"))
1758 // Handle empty element.
1760 // Use undef instead of an array because it's inconvenient to determine
1761 // the element type at this point, there being no elements to examine.
1762 ID.Kind = ValID::t_EmptyArray;
1766 if (!Elts[0]->getType()->isFirstClassType())
1767 return Error(FirstEltLoc, "invalid array element type: " +
1768 Elts[0]->getType()->getDescription());
1770 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1772 // Verify all elements are correct type!
1773 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1774 if (Elts[i]->getType() != Elts[0]->getType())
1775 return Error(FirstEltLoc,
1776 "array element #" + utostr(i) +
1777 " is not of type '" +Elts[0]->getType()->getDescription());
1780 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1781 ID.Kind = ValID::t_Constant;
1784 case lltok::kw_c: // c "foo"
1786 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1787 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1788 ID.Kind = ValID::t_Constant;
1791 case lltok::kw_asm: {
1792 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1795 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1796 ParseStringConstant(ID.StrVal) ||
1797 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1798 ParseToken(lltok::StringConstant, "expected constraint string"))
1800 ID.StrVal2 = Lex.getStrVal();
1801 ID.UIntVal = HasSideEffect;
1802 ID.Kind = ValID::t_InlineAsm;
1806 case lltok::kw_trunc:
1807 case lltok::kw_zext:
1808 case lltok::kw_sext:
1809 case lltok::kw_fptrunc:
1810 case lltok::kw_fpext:
1811 case lltok::kw_bitcast:
1812 case lltok::kw_uitofp:
1813 case lltok::kw_sitofp:
1814 case lltok::kw_fptoui:
1815 case lltok::kw_fptosi:
1816 case lltok::kw_inttoptr:
1817 case lltok::kw_ptrtoint: {
1818 unsigned Opc = Lex.getUIntVal();
1819 PATypeHolder DestTy(Type::VoidTy);
1822 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1823 ParseGlobalTypeAndValue(SrcVal) ||
1824 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1825 ParseType(DestTy) ||
1826 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1828 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1829 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1830 SrcVal->getType()->getDescription() + "' to '" +
1831 DestTy->getDescription() + "'");
1832 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1834 ID.Kind = ValID::t_Constant;
1837 case lltok::kw_extractvalue: {
1840 SmallVector<unsigned, 4> Indices;
1841 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1842 ParseGlobalTypeAndValue(Val) ||
1843 ParseIndexList(Indices) ||
1844 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1846 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1847 return Error(ID.Loc, "extractvalue operand must be array or struct");
1848 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1850 return Error(ID.Loc, "invalid indices for extractvalue");
1852 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1853 ID.Kind = ValID::t_Constant;
1856 case lltok::kw_insertvalue: {
1858 Constant *Val0, *Val1;
1859 SmallVector<unsigned, 4> Indices;
1860 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1861 ParseGlobalTypeAndValue(Val0) ||
1862 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1863 ParseGlobalTypeAndValue(Val1) ||
1864 ParseIndexList(Indices) ||
1865 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1867 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1868 return Error(ID.Loc, "extractvalue operand must be array or struct");
1869 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1871 return Error(ID.Loc, "invalid indices for insertvalue");
1872 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1873 Indices.data(), Indices.size());
1874 ID.Kind = ValID::t_Constant;
1877 case lltok::kw_icmp:
1878 case lltok::kw_fcmp: {
1879 unsigned PredVal, Opc = Lex.getUIntVal();
1880 Constant *Val0, *Val1;
1882 if (ParseCmpPredicate(PredVal, Opc) ||
1883 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1884 ParseGlobalTypeAndValue(Val0) ||
1885 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1886 ParseGlobalTypeAndValue(Val1) ||
1887 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1890 if (Val0->getType() != Val1->getType())
1891 return Error(ID.Loc, "compare operands must have the same type");
1893 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1895 if (Opc == Instruction::FCmp) {
1896 if (!Val0->getType()->isFPOrFPVector())
1897 return Error(ID.Loc, "fcmp requires floating point operands");
1898 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1900 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1901 if (!Val0->getType()->isIntOrIntVector() &&
1902 !isa<PointerType>(Val0->getType()))
1903 return Error(ID.Loc, "icmp requires pointer or integer operands");
1904 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1906 ID.Kind = ValID::t_Constant;
1910 // Binary Operators.
1912 case lltok::kw_fadd:
1914 case lltok::kw_fsub:
1916 case lltok::kw_fmul:
1917 case lltok::kw_udiv:
1918 case lltok::kw_sdiv:
1919 case lltok::kw_fdiv:
1920 case lltok::kw_urem:
1921 case lltok::kw_srem:
1922 case lltok::kw_frem: {
1923 unsigned Opc = Lex.getUIntVal();
1924 Constant *Val0, *Val1;
1926 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1927 ParseGlobalTypeAndValue(Val0) ||
1928 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1929 ParseGlobalTypeAndValue(Val1) ||
1930 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1932 if (Val0->getType() != Val1->getType())
1933 return Error(ID.Loc, "operands of constexpr must have same type");
1934 if (!Val0->getType()->isIntOrIntVector() &&
1935 !Val0->getType()->isFPOrFPVector())
1936 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1937 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1938 ID.Kind = ValID::t_Constant;
1942 // Logical Operations
1944 case lltok::kw_lshr:
1945 case lltok::kw_ashr:
1948 case lltok::kw_xor: {
1949 unsigned Opc = Lex.getUIntVal();
1950 Constant *Val0, *Val1;
1952 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1953 ParseGlobalTypeAndValue(Val0) ||
1954 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1955 ParseGlobalTypeAndValue(Val1) ||
1956 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1958 if (Val0->getType() != Val1->getType())
1959 return Error(ID.Loc, "operands of constexpr must have same type");
1960 if (!Val0->getType()->isIntOrIntVector())
1961 return Error(ID.Loc,
1962 "constexpr requires integer or integer vector operands");
1963 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1964 ID.Kind = ValID::t_Constant;
1968 case lltok::kw_getelementptr:
1969 case lltok::kw_shufflevector:
1970 case lltok::kw_insertelement:
1971 case lltok::kw_extractelement:
1972 case lltok::kw_select: {
1973 unsigned Opc = Lex.getUIntVal();
1974 SmallVector<Constant*, 16> Elts;
1976 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1977 ParseGlobalValueVector(Elts) ||
1978 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1981 if (Opc == Instruction::GetElementPtr) {
1982 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1983 return Error(ID.Loc, "getelementptr requires pointer operand");
1985 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1986 (Value**)&Elts[1], Elts.size()-1))
1987 return Error(ID.Loc, "invalid indices for getelementptr");
1988 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
1989 &Elts[1], Elts.size()-1);
1990 } else if (Opc == Instruction::Select) {
1991 if (Elts.size() != 3)
1992 return Error(ID.Loc, "expected three operands to select");
1993 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1995 return Error(ID.Loc, Reason);
1996 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
1997 } else if (Opc == Instruction::ShuffleVector) {
1998 if (Elts.size() != 3)
1999 return Error(ID.Loc, "expected three operands to shufflevector");
2000 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2001 return Error(ID.Loc, "invalid operands to shufflevector");
2003 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2004 } else if (Opc == Instruction::ExtractElement) {
2005 if (Elts.size() != 2)
2006 return Error(ID.Loc, "expected two operands to extractelement");
2007 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2008 return Error(ID.Loc, "invalid extractelement operands");
2009 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2011 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2012 if (Elts.size() != 3)
2013 return Error(ID.Loc, "expected three operands to insertelement");
2014 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2015 return Error(ID.Loc, "invalid insertelement operands");
2017 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2020 ID.Kind = ValID::t_Constant;
2029 /// ParseGlobalValue - Parse a global value with the specified type.
2030 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2033 return ParseValID(ID) ||
2034 ConvertGlobalValIDToValue(Ty, ID, V);
2037 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2039 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2041 if (isa<FunctionType>(Ty))
2042 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2045 default: llvm_unreachable("Unknown ValID!");
2046 case ValID::t_LocalID:
2047 case ValID::t_LocalName:
2048 return Error(ID.Loc, "invalid use of function-local name");
2049 case ValID::t_InlineAsm:
2050 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2051 case ValID::t_GlobalName:
2052 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2054 case ValID::t_GlobalID:
2055 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2057 case ValID::t_APSInt:
2058 if (!isa<IntegerType>(Ty))
2059 return Error(ID.Loc, "integer constant must have integer type");
2060 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2061 V = Context.getConstantInt(ID.APSIntVal);
2063 case ValID::t_APFloat:
2064 if (!Ty->isFloatingPoint() ||
2065 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2066 return Error(ID.Loc, "floating point constant invalid for type");
2068 // The lexer has no type info, so builds all float and double FP constants
2069 // as double. Fix this here. Long double does not need this.
2070 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2071 Ty == Type::FloatTy) {
2073 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2076 V = Context.getConstantFP(ID.APFloatVal);
2078 if (V->getType() != Ty)
2079 return Error(ID.Loc, "floating point constant does not have type '" +
2080 Ty->getDescription() + "'");
2084 if (!isa<PointerType>(Ty))
2085 return Error(ID.Loc, "null must be a pointer type");
2086 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2088 case ValID::t_Undef:
2089 // FIXME: LabelTy should not be a first-class type.
2090 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2091 !isa<OpaqueType>(Ty))
2092 return Error(ID.Loc, "invalid type for undef constant");
2093 V = Context.getUndef(Ty);
2095 case ValID::t_EmptyArray:
2096 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2097 return Error(ID.Loc, "invalid empty array initializer");
2098 V = Context.getUndef(Ty);
2101 // FIXME: LabelTy should not be a first-class type.
2102 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2103 return Error(ID.Loc, "invalid type for null constant");
2104 V = Context.getNullValue(Ty);
2106 case ValID::t_Constant:
2107 if (ID.ConstantVal->getType() != Ty)
2108 return Error(ID.Loc, "constant expression type mismatch");
2114 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2115 PATypeHolder Type(Type::VoidTy);
2116 return ParseType(Type) ||
2117 ParseGlobalValue(Type, V);
2120 /// ParseGlobalValueVector
2122 /// ::= TypeAndValue (',' TypeAndValue)*
2123 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2125 if (Lex.getKind() == lltok::rbrace ||
2126 Lex.getKind() == lltok::rsquare ||
2127 Lex.getKind() == lltok::greater ||
2128 Lex.getKind() == lltok::rparen)
2132 if (ParseGlobalTypeAndValue(C)) return true;
2135 while (EatIfPresent(lltok::comma)) {
2136 if (ParseGlobalTypeAndValue(C)) return true;
2144 //===----------------------------------------------------------------------===//
2145 // Function Parsing.
2146 //===----------------------------------------------------------------------===//
2148 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2149 PerFunctionState &PFS) {
2150 if (ID.Kind == ValID::t_LocalID)
2151 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2152 else if (ID.Kind == ValID::t_LocalName)
2153 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2154 else if (ID.Kind == ValID::t_InlineAsm) {
2155 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2156 const FunctionType *FTy =
2157 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2158 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2159 return Error(ID.Loc, "invalid type for inline asm constraint string");
2160 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2164 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2172 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2175 return ParseValID(ID) ||
2176 ConvertValIDToValue(Ty, ID, V, PFS);
2179 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2180 PATypeHolder T(Type::VoidTy);
2181 return ParseType(T) ||
2182 ParseValue(T, V, PFS);
2186 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2187 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2188 /// OptionalAlign OptGC
2189 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2190 // Parse the linkage.
2191 LocTy LinkageLoc = Lex.getLoc();
2194 unsigned Visibility, CC, RetAttrs;
2195 PATypeHolder RetType(Type::VoidTy);
2196 LocTy RetTypeLoc = Lex.getLoc();
2197 if (ParseOptionalLinkage(Linkage) ||
2198 ParseOptionalVisibility(Visibility) ||
2199 ParseOptionalCallingConv(CC) ||
2200 ParseOptionalAttrs(RetAttrs, 1) ||
2201 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2204 // Verify that the linkage is ok.
2205 switch ((GlobalValue::LinkageTypes)Linkage) {
2206 case GlobalValue::ExternalLinkage:
2207 break; // always ok.
2208 case GlobalValue::DLLImportLinkage:
2209 case GlobalValue::ExternalWeakLinkage:
2211 return Error(LinkageLoc, "invalid linkage for function definition");
2213 case GlobalValue::PrivateLinkage:
2214 case GlobalValue::InternalLinkage:
2215 case GlobalValue::AvailableExternallyLinkage:
2216 case GlobalValue::LinkOnceAnyLinkage:
2217 case GlobalValue::LinkOnceODRLinkage:
2218 case GlobalValue::WeakAnyLinkage:
2219 case GlobalValue::WeakODRLinkage:
2220 case GlobalValue::DLLExportLinkage:
2222 return Error(LinkageLoc, "invalid linkage for function declaration");
2224 case GlobalValue::AppendingLinkage:
2225 case GlobalValue::GhostLinkage:
2226 case GlobalValue::CommonLinkage:
2227 return Error(LinkageLoc, "invalid function linkage type");
2230 if (!FunctionType::isValidReturnType(RetType) ||
2231 isa<OpaqueType>(RetType))
2232 return Error(RetTypeLoc, "invalid function return type");
2234 LocTy NameLoc = Lex.getLoc();
2236 std::string FunctionName;
2237 if (Lex.getKind() == lltok::GlobalVar) {
2238 FunctionName = Lex.getStrVal();
2239 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2240 unsigned NameID = Lex.getUIntVal();
2242 if (NameID != NumberedVals.size())
2243 return TokError("function expected to be numbered '%" +
2244 utostr(NumberedVals.size()) + "'");
2246 return TokError("expected function name");
2251 if (Lex.getKind() != lltok::lparen)
2252 return TokError("expected '(' in function argument list");
2254 std::vector<ArgInfo> ArgList;
2257 std::string Section;
2261 if (ParseArgumentList(ArgList, isVarArg, false) ||
2262 ParseOptionalAttrs(FuncAttrs, 2) ||
2263 (EatIfPresent(lltok::kw_section) &&
2264 ParseStringConstant(Section)) ||
2265 ParseOptionalAlignment(Alignment) ||
2266 (EatIfPresent(lltok::kw_gc) &&
2267 ParseStringConstant(GC)))
2270 // If the alignment was parsed as an attribute, move to the alignment field.
2271 if (FuncAttrs & Attribute::Alignment) {
2272 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2273 FuncAttrs &= ~Attribute::Alignment;
2276 // Okay, if we got here, the function is syntactically valid. Convert types
2277 // and do semantic checks.
2278 std::vector<const Type*> ParamTypeList;
2279 SmallVector<AttributeWithIndex, 8> Attrs;
2280 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2282 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2283 if (FuncAttrs & ObsoleteFuncAttrs) {
2284 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2285 FuncAttrs &= ~ObsoleteFuncAttrs;
2288 if (RetAttrs != Attribute::None)
2289 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2291 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2292 ParamTypeList.push_back(ArgList[i].Type);
2293 if (ArgList[i].Attrs != Attribute::None)
2294 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2297 if (FuncAttrs != Attribute::None)
2298 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2300 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2302 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2303 RetType != Type::VoidTy)
2304 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2306 const FunctionType *FT =
2307 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2308 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2311 if (!FunctionName.empty()) {
2312 // If this was a definition of a forward reference, remove the definition
2313 // from the forward reference table and fill in the forward ref.
2314 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2315 ForwardRefVals.find(FunctionName);
2316 if (FRVI != ForwardRefVals.end()) {
2317 Fn = M->getFunction(FunctionName);
2318 ForwardRefVals.erase(FRVI);
2319 } else if ((Fn = M->getFunction(FunctionName))) {
2320 // If this function already exists in the symbol table, then it is
2321 // multiply defined. We accept a few cases for old backwards compat.
2322 // FIXME: Remove this stuff for LLVM 3.0.
2323 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2324 (!Fn->isDeclaration() && isDefine)) {
2325 // If the redefinition has different type or different attributes,
2326 // reject it. If both have bodies, reject it.
2327 return Error(NameLoc, "invalid redefinition of function '" +
2328 FunctionName + "'");
2329 } else if (Fn->isDeclaration()) {
2330 // Make sure to strip off any argument names so we can't get conflicts.
2331 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2337 } else if (FunctionName.empty()) {
2338 // If this is a definition of a forward referenced function, make sure the
2340 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2341 = ForwardRefValIDs.find(NumberedVals.size());
2342 if (I != ForwardRefValIDs.end()) {
2343 Fn = cast<Function>(I->second.first);
2344 if (Fn->getType() != PFT)
2345 return Error(NameLoc, "type of definition and forward reference of '@" +
2346 utostr(NumberedVals.size()) +"' disagree");
2347 ForwardRefValIDs.erase(I);
2352 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2353 else // Move the forward-reference to the correct spot in the module.
2354 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2356 if (FunctionName.empty())
2357 NumberedVals.push_back(Fn);
2359 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2360 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2361 Fn->setCallingConv(CC);
2362 Fn->setAttributes(PAL);
2363 Fn->setAlignment(Alignment);
2364 Fn->setSection(Section);
2365 if (!GC.empty()) Fn->setGC(GC.c_str());
2367 // Add all of the arguments we parsed to the function.
2368 Function::arg_iterator ArgIt = Fn->arg_begin();
2369 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2370 // If the argument has a name, insert it into the argument symbol table.
2371 if (ArgList[i].Name.empty()) continue;
2373 // Set the name, if it conflicted, it will be auto-renamed.
2374 ArgIt->setName(ArgList[i].Name);
2376 if (ArgIt->getNameStr() != ArgList[i].Name)
2377 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2378 ArgList[i].Name + "'");
2385 /// ParseFunctionBody
2386 /// ::= '{' BasicBlock+ '}'
2387 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2389 bool LLParser::ParseFunctionBody(Function &Fn) {
2390 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2391 return TokError("expected '{' in function body");
2392 Lex.Lex(); // eat the {.
2394 PerFunctionState PFS(*this, Fn);
2396 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2397 if (ParseBasicBlock(PFS)) return true;
2402 // Verify function is ok.
2403 return PFS.VerifyFunctionComplete();
2407 /// ::= LabelStr? Instruction*
2408 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2409 // If this basic block starts out with a name, remember it.
2411 LocTy NameLoc = Lex.getLoc();
2412 if (Lex.getKind() == lltok::LabelStr) {
2413 Name = Lex.getStrVal();
2417 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2418 if (BB == 0) return true;
2420 std::string NameStr;
2422 // Parse the instructions in this block until we get a terminator.
2425 // This instruction may have three possibilities for a name: a) none
2426 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2427 LocTy NameLoc = Lex.getLoc();
2431 if (Lex.getKind() == lltok::LocalVarID) {
2432 NameID = Lex.getUIntVal();
2434 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2436 } else if (Lex.getKind() == lltok::LocalVar ||
2437 // FIXME: REMOVE IN LLVM 3.0
2438 Lex.getKind() == lltok::StringConstant) {
2439 NameStr = Lex.getStrVal();
2441 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2445 if (ParseInstruction(Inst, BB, PFS)) return true;
2447 BB->getInstList().push_back(Inst);
2449 // Set the name on the instruction.
2450 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2451 } while (!isa<TerminatorInst>(Inst));
2456 //===----------------------------------------------------------------------===//
2457 // Instruction Parsing.
2458 //===----------------------------------------------------------------------===//
2460 /// ParseInstruction - Parse one of the many different instructions.
2462 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2463 PerFunctionState &PFS) {
2464 lltok::Kind Token = Lex.getKind();
2465 if (Token == lltok::Eof)
2466 return TokError("found end of file when expecting more instructions");
2467 LocTy Loc = Lex.getLoc();
2468 unsigned KeywordVal = Lex.getUIntVal();
2469 Lex.Lex(); // Eat the keyword.
2472 default: return Error(Loc, "expected instruction opcode");
2473 // Terminator Instructions.
2474 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2475 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2476 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2477 case lltok::kw_br: return ParseBr(Inst, PFS);
2478 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2479 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2480 // Binary Operators.
2484 // API compatibility: Accept either integer or floating-point types.
2485 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2486 case lltok::kw_fadd:
2487 case lltok::kw_fsub:
2488 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2490 case lltok::kw_udiv:
2491 case lltok::kw_sdiv:
2492 case lltok::kw_urem:
2493 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2494 case lltok::kw_fdiv:
2495 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2497 case lltok::kw_lshr:
2498 case lltok::kw_ashr:
2501 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2502 case lltok::kw_icmp:
2503 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2505 case lltok::kw_trunc:
2506 case lltok::kw_zext:
2507 case lltok::kw_sext:
2508 case lltok::kw_fptrunc:
2509 case lltok::kw_fpext:
2510 case lltok::kw_bitcast:
2511 case lltok::kw_uitofp:
2512 case lltok::kw_sitofp:
2513 case lltok::kw_fptoui:
2514 case lltok::kw_fptosi:
2515 case lltok::kw_inttoptr:
2516 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2518 case lltok::kw_select: return ParseSelect(Inst, PFS);
2519 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2520 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2521 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2522 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2523 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2524 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2525 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2527 case lltok::kw_alloca:
2528 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2529 case lltok::kw_free: return ParseFree(Inst, PFS);
2530 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2531 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2532 case lltok::kw_volatile:
2533 if (EatIfPresent(lltok::kw_load))
2534 return ParseLoad(Inst, PFS, true);
2535 else if (EatIfPresent(lltok::kw_store))
2536 return ParseStore(Inst, PFS, true);
2538 return TokError("expected 'load' or 'store'");
2539 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2540 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2541 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2542 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2546 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2547 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2548 if (Opc == Instruction::FCmp) {
2549 switch (Lex.getKind()) {
2550 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2551 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2552 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2553 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2554 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2555 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2556 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2557 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2558 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2559 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2560 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2561 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2562 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2563 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2564 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2565 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2566 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2569 switch (Lex.getKind()) {
2570 default: TokError("expected icmp predicate (e.g. 'eq')");
2571 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2572 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2573 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2574 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2575 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2576 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2577 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2578 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2579 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2580 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2587 //===----------------------------------------------------------------------===//
2588 // Terminator Instructions.
2589 //===----------------------------------------------------------------------===//
2591 /// ParseRet - Parse a return instruction.
2593 /// ::= 'ret' TypeAndValue
2594 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2595 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2596 PerFunctionState &PFS) {
2597 PATypeHolder Ty(Type::VoidTy);
2598 if (ParseType(Ty, true /*void allowed*/)) return true;
2600 if (Ty == Type::VoidTy) {
2601 Inst = ReturnInst::Create();
2606 if (ParseValue(Ty, RV, PFS)) return true;
2608 // The normal case is one return value.
2609 if (Lex.getKind() == lltok::comma) {
2610 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2611 // of 'ret {i32,i32} {i32 1, i32 2}'
2612 SmallVector<Value*, 8> RVs;
2615 while (EatIfPresent(lltok::comma)) {
2616 if (ParseTypeAndValue(RV, PFS)) return true;
2620 RV = Context.getUndef(PFS.getFunction().getReturnType());
2621 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2622 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2623 BB->getInstList().push_back(I);
2627 Inst = ReturnInst::Create(RV);
2633 /// ::= 'br' TypeAndValue
2634 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2635 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2637 Value *Op0, *Op1, *Op2;
2638 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2640 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2641 Inst = BranchInst::Create(BB);
2645 if (Op0->getType() != Type::Int1Ty)
2646 return Error(Loc, "branch condition must have 'i1' type");
2648 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2649 ParseTypeAndValue(Op1, Loc, PFS) ||
2650 ParseToken(lltok::comma, "expected ',' after true destination") ||
2651 ParseTypeAndValue(Op2, Loc2, PFS))
2654 if (!isa<BasicBlock>(Op1))
2655 return Error(Loc, "true destination of branch must be a basic block");
2656 if (!isa<BasicBlock>(Op2))
2657 return Error(Loc2, "true destination of branch must be a basic block");
2659 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2665 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2667 /// ::= (TypeAndValue ',' TypeAndValue)*
2668 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2669 LocTy CondLoc, BBLoc;
2670 Value *Cond, *DefaultBB;
2671 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2672 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2673 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2674 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2677 if (!isa<IntegerType>(Cond->getType()))
2678 return Error(CondLoc, "switch condition must have integer type");
2679 if (!isa<BasicBlock>(DefaultBB))
2680 return Error(BBLoc, "default destination must be a basic block");
2682 // Parse the jump table pairs.
2683 SmallPtrSet<Value*, 32> SeenCases;
2684 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2685 while (Lex.getKind() != lltok::rsquare) {
2686 Value *Constant, *DestBB;
2688 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2689 ParseToken(lltok::comma, "expected ',' after case value") ||
2690 ParseTypeAndValue(DestBB, BBLoc, PFS))
2693 if (!SeenCases.insert(Constant))
2694 return Error(CondLoc, "duplicate case value in switch");
2695 if (!isa<ConstantInt>(Constant))
2696 return Error(CondLoc, "case value is not a constant integer");
2697 if (!isa<BasicBlock>(DestBB))
2698 return Error(BBLoc, "case destination is not a basic block");
2700 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2701 cast<BasicBlock>(DestBB)));
2704 Lex.Lex(); // Eat the ']'.
2706 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2708 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2709 SI->addCase(Table[i].first, Table[i].second);
2715 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2716 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2717 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2718 LocTy CallLoc = Lex.getLoc();
2719 unsigned CC, RetAttrs, FnAttrs;
2720 PATypeHolder RetType(Type::VoidTy);
2723 SmallVector<ParamInfo, 16> ArgList;
2725 Value *NormalBB, *UnwindBB;
2726 if (ParseOptionalCallingConv(CC) ||
2727 ParseOptionalAttrs(RetAttrs, 1) ||
2728 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2729 ParseValID(CalleeID) ||
2730 ParseParameterList(ArgList, PFS) ||
2731 ParseOptionalAttrs(FnAttrs, 2) ||
2732 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2733 ParseTypeAndValue(NormalBB, PFS) ||
2734 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2735 ParseTypeAndValue(UnwindBB, PFS))
2738 if (!isa<BasicBlock>(NormalBB))
2739 return Error(CallLoc, "normal destination is not a basic block");
2740 if (!isa<BasicBlock>(UnwindBB))
2741 return Error(CallLoc, "unwind destination is not a basic block");
2743 // If RetType is a non-function pointer type, then this is the short syntax
2744 // for the call, which means that RetType is just the return type. Infer the
2745 // rest of the function argument types from the arguments that are present.
2746 const PointerType *PFTy = 0;
2747 const FunctionType *Ty = 0;
2748 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2749 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2750 // Pull out the types of all of the arguments...
2751 std::vector<const Type*> ParamTypes;
2752 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2753 ParamTypes.push_back(ArgList[i].V->getType());
2755 if (!FunctionType::isValidReturnType(RetType))
2756 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2758 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2759 PFTy = Context.getPointerTypeUnqual(Ty);
2762 // Look up the callee.
2764 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2766 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2767 // function attributes.
2768 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2769 if (FnAttrs & ObsoleteFuncAttrs) {
2770 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2771 FnAttrs &= ~ObsoleteFuncAttrs;
2774 // Set up the Attributes for the function.
2775 SmallVector<AttributeWithIndex, 8> Attrs;
2776 if (RetAttrs != Attribute::None)
2777 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2779 SmallVector<Value*, 8> Args;
2781 // Loop through FunctionType's arguments and ensure they are specified
2782 // correctly. Also, gather any parameter attributes.
2783 FunctionType::param_iterator I = Ty->param_begin();
2784 FunctionType::param_iterator E = Ty->param_end();
2785 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2786 const Type *ExpectedTy = 0;
2789 } else if (!Ty->isVarArg()) {
2790 return Error(ArgList[i].Loc, "too many arguments specified");
2793 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2794 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2795 ExpectedTy->getDescription() + "'");
2796 Args.push_back(ArgList[i].V);
2797 if (ArgList[i].Attrs != Attribute::None)
2798 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2802 return Error(CallLoc, "not enough parameters specified for call");
2804 if (FnAttrs != Attribute::None)
2805 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2807 // Finish off the Attributes and check them
2808 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2810 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2811 cast<BasicBlock>(UnwindBB),
2812 Args.begin(), Args.end());
2813 II->setCallingConv(CC);
2814 II->setAttributes(PAL);
2821 //===----------------------------------------------------------------------===//
2822 // Binary Operators.
2823 //===----------------------------------------------------------------------===//
2826 /// ::= ArithmeticOps TypeAndValue ',' Value
2828 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2829 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2830 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2831 unsigned Opc, unsigned OperandType) {
2832 LocTy Loc; Value *LHS, *RHS;
2833 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2834 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2835 ParseValue(LHS->getType(), RHS, PFS))
2839 switch (OperandType) {
2840 default: llvm_unreachable("Unknown operand type!");
2841 case 0: // int or FP.
2842 Valid = LHS->getType()->isIntOrIntVector() ||
2843 LHS->getType()->isFPOrFPVector();
2845 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2846 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2850 return Error(Loc, "invalid operand type for instruction");
2852 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2857 /// ::= ArithmeticOps TypeAndValue ',' Value {
2858 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2860 LocTy Loc; Value *LHS, *RHS;
2861 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2862 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2863 ParseValue(LHS->getType(), RHS, PFS))
2866 if (!LHS->getType()->isIntOrIntVector())
2867 return Error(Loc,"instruction requires integer or integer vector operands");
2869 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2875 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2876 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2877 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2879 // Parse the integer/fp comparison predicate.
2883 if (ParseCmpPredicate(Pred, Opc) ||
2884 ParseTypeAndValue(LHS, Loc, PFS) ||
2885 ParseToken(lltok::comma, "expected ',' after compare value") ||
2886 ParseValue(LHS->getType(), RHS, PFS))
2889 if (Opc == Instruction::FCmp) {
2890 if (!LHS->getType()->isFPOrFPVector())
2891 return Error(Loc, "fcmp requires floating point operands");
2892 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2894 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
2895 if (!LHS->getType()->isIntOrIntVector() &&
2896 !isa<PointerType>(LHS->getType()))
2897 return Error(Loc, "icmp requires integer operands");
2898 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2903 //===----------------------------------------------------------------------===//
2904 // Other Instructions.
2905 //===----------------------------------------------------------------------===//
2909 /// ::= CastOpc TypeAndValue 'to' Type
2910 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2912 LocTy Loc; Value *Op;
2913 PATypeHolder DestTy(Type::VoidTy);
2914 if (ParseTypeAndValue(Op, Loc, PFS) ||
2915 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2919 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2920 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2921 return Error(Loc, "invalid cast opcode for cast from '" +
2922 Op->getType()->getDescription() + "' to '" +
2923 DestTy->getDescription() + "'");
2925 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2930 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2931 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2933 Value *Op0, *Op1, *Op2;
2934 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after select condition") ||
2936 ParseTypeAndValue(Op1, PFS) ||
2937 ParseToken(lltok::comma, "expected ',' after select value") ||
2938 ParseTypeAndValue(Op2, PFS))
2941 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2942 return Error(Loc, Reason);
2944 Inst = SelectInst::Create(Op0, Op1, Op2);
2949 /// ::= 'va_arg' TypeAndValue ',' Type
2950 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2952 PATypeHolder EltTy(Type::VoidTy);
2954 if (ParseTypeAndValue(Op, PFS) ||
2955 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2956 ParseType(EltTy, TypeLoc))
2959 if (!EltTy->isFirstClassType())
2960 return Error(TypeLoc, "va_arg requires operand with first class type");
2962 Inst = new VAArgInst(Op, EltTy);
2966 /// ParseExtractElement
2967 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2968 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2971 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2972 ParseToken(lltok::comma, "expected ',' after extract value") ||
2973 ParseTypeAndValue(Op1, PFS))
2976 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2977 return Error(Loc, "invalid extractelement operands");
2979 Inst = new ExtractElementInst(Op0, Op1);
2983 /// ParseInsertElement
2984 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2985 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2987 Value *Op0, *Op1, *Op2;
2988 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2989 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2990 ParseTypeAndValue(Op1, PFS) ||
2991 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2992 ParseTypeAndValue(Op2, PFS))
2995 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2996 return Error(Loc, "invalid extractelement operands");
2998 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3002 /// ParseShuffleVector
3003 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3004 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3006 Value *Op0, *Op1, *Op2;
3007 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3008 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3009 ParseTypeAndValue(Op1, PFS) ||
3010 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3011 ParseTypeAndValue(Op2, PFS))
3014 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3015 return Error(Loc, "invalid extractelement operands");
3017 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3022 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3023 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3024 PATypeHolder Ty(Type::VoidTy);
3026 LocTy TypeLoc = Lex.getLoc();
3028 if (ParseType(Ty) ||
3029 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3030 ParseValue(Ty, Op0, PFS) ||
3031 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3032 ParseValue(Type::LabelTy, Op1, PFS) ||
3033 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3036 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3038 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3040 if (!EatIfPresent(lltok::comma))
3043 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3044 ParseValue(Ty, Op0, PFS) ||
3045 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3046 ParseValue(Type::LabelTy, Op1, PFS) ||
3047 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3051 if (!Ty->isFirstClassType())
3052 return Error(TypeLoc, "phi node must have first class type");
3054 PHINode *PN = PHINode::Create(Ty);
3055 PN->reserveOperandSpace(PHIVals.size());
3056 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3057 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3063 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3064 /// ParameterList OptionalAttrs
3065 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3067 unsigned CC, RetAttrs, FnAttrs;
3068 PATypeHolder RetType(Type::VoidTy);
3071 SmallVector<ParamInfo, 16> ArgList;
3072 LocTy CallLoc = Lex.getLoc();
3074 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3075 ParseOptionalCallingConv(CC) ||
3076 ParseOptionalAttrs(RetAttrs, 1) ||
3077 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3078 ParseValID(CalleeID) ||
3079 ParseParameterList(ArgList, PFS) ||
3080 ParseOptionalAttrs(FnAttrs, 2))
3083 // If RetType is a non-function pointer type, then this is the short syntax
3084 // for the call, which means that RetType is just the return type. Infer the
3085 // rest of the function argument types from the arguments that are present.
3086 const PointerType *PFTy = 0;
3087 const FunctionType *Ty = 0;
3088 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3089 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3090 // Pull out the types of all of the arguments...
3091 std::vector<const Type*> ParamTypes;
3092 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3093 ParamTypes.push_back(ArgList[i].V->getType());
3095 if (!FunctionType::isValidReturnType(RetType))
3096 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3098 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3099 PFTy = Context.getPointerTypeUnqual(Ty);
3102 // Look up the callee.
3104 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3106 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3107 // function attributes.
3108 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3109 if (FnAttrs & ObsoleteFuncAttrs) {
3110 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3111 FnAttrs &= ~ObsoleteFuncAttrs;
3114 // Set up the Attributes for the function.
3115 SmallVector<AttributeWithIndex, 8> Attrs;
3116 if (RetAttrs != Attribute::None)
3117 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3119 SmallVector<Value*, 8> Args;
3121 // Loop through FunctionType's arguments and ensure they are specified
3122 // correctly. Also, gather any parameter attributes.
3123 FunctionType::param_iterator I = Ty->param_begin();
3124 FunctionType::param_iterator E = Ty->param_end();
3125 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3126 const Type *ExpectedTy = 0;
3129 } else if (!Ty->isVarArg()) {
3130 return Error(ArgList[i].Loc, "too many arguments specified");
3133 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3134 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3135 ExpectedTy->getDescription() + "'");
3136 Args.push_back(ArgList[i].V);
3137 if (ArgList[i].Attrs != Attribute::None)
3138 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3142 return Error(CallLoc, "not enough parameters specified for call");
3144 if (FnAttrs != Attribute::None)
3145 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3147 // Finish off the Attributes and check them
3148 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3150 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3151 CI->setTailCall(isTail);
3152 CI->setCallingConv(CC);
3153 CI->setAttributes(PAL);
3158 //===----------------------------------------------------------------------===//
3159 // Memory Instructions.
3160 //===----------------------------------------------------------------------===//
3163 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3164 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3165 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3167 PATypeHolder Ty(Type::VoidTy);
3170 unsigned Alignment = 0;
3171 if (ParseType(Ty)) return true;
3173 if (EatIfPresent(lltok::comma)) {
3174 if (Lex.getKind() == lltok::kw_align) {
3175 if (ParseOptionalAlignment(Alignment)) return true;
3176 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3177 ParseOptionalCommaAlignment(Alignment)) {
3182 if (Size && Size->getType() != Type::Int32Ty)
3183 return Error(SizeLoc, "element count must be i32");
3185 if (Opc == Instruction::Malloc)
3186 Inst = new MallocInst(Ty, Size, Alignment);
3188 Inst = new AllocaInst(Ty, Size, Alignment);
3193 /// ::= 'free' TypeAndValue
3194 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3195 Value *Val; LocTy Loc;
3196 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3197 if (!isa<PointerType>(Val->getType()))
3198 return Error(Loc, "operand to free must be a pointer");
3199 Inst = new FreeInst(Val);
3204 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3205 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3207 Value *Val; LocTy Loc;
3209 if (ParseTypeAndValue(Val, Loc, PFS) ||
3210 ParseOptionalCommaAlignment(Alignment))
3213 if (!isa<PointerType>(Val->getType()) ||
3214 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3215 return Error(Loc, "load operand must be a pointer to a first class type");
3217 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3222 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3223 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3225 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3227 if (ParseTypeAndValue(Val, Loc, PFS) ||
3228 ParseToken(lltok::comma, "expected ',' after store operand") ||
3229 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3230 ParseOptionalCommaAlignment(Alignment))
3233 if (!isa<PointerType>(Ptr->getType()))
3234 return Error(PtrLoc, "store operand must be a pointer");
3235 if (!Val->getType()->isFirstClassType())
3236 return Error(Loc, "store operand must be a first class value");
3237 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3238 return Error(Loc, "stored value and pointer type do not match");
3240 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3245 /// ::= 'getresult' TypeAndValue ',' i32
3246 /// FIXME: Remove support for getresult in LLVM 3.0
3247 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3248 Value *Val; LocTy ValLoc, EltLoc;
3250 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3251 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3252 ParseUInt32(Element, EltLoc))
3255 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3256 return Error(ValLoc, "getresult inst requires an aggregate operand");
3257 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3258 return Error(EltLoc, "invalid getresult index for value");
3259 Inst = ExtractValueInst::Create(Val, Element);
3263 /// ParseGetElementPtr
3264 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3265 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3266 Value *Ptr, *Val; LocTy Loc, EltLoc;
3267 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3269 if (!isa<PointerType>(Ptr->getType()))
3270 return Error(Loc, "base of getelementptr must be a pointer");
3272 SmallVector<Value*, 16> Indices;
3273 while (EatIfPresent(lltok::comma)) {
3274 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3275 if (!isa<IntegerType>(Val->getType()))
3276 return Error(EltLoc, "getelementptr index must be an integer");
3277 Indices.push_back(Val);
3280 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3281 Indices.begin(), Indices.end()))
3282 return Error(Loc, "invalid getelementptr indices");
3283 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3287 /// ParseExtractValue
3288 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3289 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3290 Value *Val; LocTy Loc;
3291 SmallVector<unsigned, 4> Indices;
3292 if (ParseTypeAndValue(Val, Loc, PFS) ||
3293 ParseIndexList(Indices))
3296 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3297 return Error(Loc, "extractvalue operand must be array or struct");
3299 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3301 return Error(Loc, "invalid indices for extractvalue");
3302 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3306 /// ParseInsertValue
3307 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3308 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3309 Value *Val0, *Val1; LocTy Loc0, Loc1;
3310 SmallVector<unsigned, 4> Indices;
3311 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3312 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3313 ParseTypeAndValue(Val1, Loc1, PFS) ||
3314 ParseIndexList(Indices))
3317 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3318 return Error(Loc0, "extractvalue operand must be array or struct");
3320 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3322 return Error(Loc0, "invalid indices for insertvalue");
3323 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3327 //===----------------------------------------------------------------------===//
3328 // Embedded metadata.
3329 //===----------------------------------------------------------------------===//
3331 /// ParseMDNodeVector
3332 /// ::= Element (',' Element)*
3334 /// ::= 'null' | TypeAndValue
3335 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3336 assert(Lex.getKind() == lltok::lbrace);
3340 if (Lex.getKind() == lltok::kw_null) {
3345 if (ParseGlobalTypeAndValue(C)) return true;
3349 } while (EatIfPresent(lltok::comma));