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/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
187 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
193 case lltok::kw_appending: // OptionalLinkage
194 case lltok::kw_dllexport: // OptionalLinkage
195 case lltok::kw_common: // OptionalLinkage
196 case lltok::kw_dllimport: // OptionalLinkage
197 case lltok::kw_extern_weak: // OptionalLinkage
198 case lltok::kw_external: { // OptionalLinkage
199 unsigned Linkage, Visibility;
200 if (ParseOptionalLinkage(Linkage) ||
201 ParseOptionalVisibility(Visibility) ||
202 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
206 case lltok::kw_default: // OptionalVisibility
207 case lltok::kw_hidden: // OptionalVisibility
208 case lltok::kw_protected: { // OptionalVisibility
210 if (ParseOptionalVisibility(Visibility) ||
211 ParseGlobal("", SMLoc(), 0, false, Visibility))
216 case lltok::kw_thread_local: // OptionalThreadLocal
217 case lltok::kw_addrspace: // OptionalAddrSpace
218 case lltok::kw_constant: // GlobalType
219 case lltok::kw_global: // GlobalType
220 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
228 /// ::= 'module' 'asm' STRINGCONSTANT
229 bool LLParser::ParseModuleAsm() {
230 assert(Lex.getKind() == lltok::kw_module);
234 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
235 ParseStringConstant(AsmStr)) return true;
237 M->appendModuleInlineAsm(AsmStr);
242 /// ::= 'target' 'triple' '=' STRINGCONSTANT
243 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
244 bool LLParser::ParseTargetDefinition() {
245 assert(Lex.getKind() == lltok::kw_target);
248 default: return TokError("unknown target property");
249 case lltok::kw_triple:
251 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
252 ParseStringConstant(Str))
254 M->setTargetTriple(Str);
256 case lltok::kw_datalayout:
258 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
259 ParseStringConstant(Str))
261 M->setDataLayout(Str);
267 /// ::= 'deplibs' '=' '[' ']'
268 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
269 bool LLParser::ParseDepLibs() {
270 assert(Lex.getKind() == lltok::kw_deplibs);
272 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
273 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
276 if (EatIfPresent(lltok::rsquare))
280 if (ParseStringConstant(Str)) return true;
283 while (EatIfPresent(lltok::comma)) {
284 if (ParseStringConstant(Str)) return true;
288 return ParseToken(lltok::rsquare, "expected ']' at end of list");
291 /// ParseUnnamedType:
292 /// ::= LocalVarID '=' 'type' type
293 bool LLParser::ParseUnnamedType() {
294 LocTy TypeLoc = Lex.getLoc();
295 unsigned TypeID = Lex.getUIntVal();
296 Lex.Lex(); // eat LocalVarID;
298 if (ParseToken(lltok::equal, "expected '=' after name") ||
299 ParseToken(lltok::kw_type, "expected 'type' after '='"))
302 if (TypeID >= NumberedTypes.size())
303 NumberedTypes.resize(TypeID+1);
306 if (ParseStructDefinition(TypeLoc, "",
307 NumberedTypes[TypeID], Result)) return true;
309 if (!isa<StructType>(Result)) {
310 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
312 return Error(TypeLoc, "non-struct types may not be recursive");
313 Entry.first = Result;
314 Entry.second = SMLoc();
322 /// ::= LocalVar '=' 'type' type
323 bool LLParser::ParseNamedType() {
324 std::string Name = Lex.getStrVal();
325 LocTy NameLoc = Lex.getLoc();
326 Lex.Lex(); // eat LocalVar.
328 if (ParseToken(lltok::equal, "expected '=' after name") ||
329 ParseToken(lltok::kw_type, "expected 'type' after name"))
333 if (ParseStructDefinition(NameLoc, Name,
334 NamedTypes[Name], Result)) return true;
336 if (!isa<StructType>(Result)) {
337 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
339 return Error(NameLoc, "non-struct types may not be recursive");
340 Entry.first = Result;
341 Entry.second = SMLoc();
349 /// ::= 'declare' FunctionHeader
350 bool LLParser::ParseDeclare() {
351 assert(Lex.getKind() == lltok::kw_declare);
355 return ParseFunctionHeader(F, false);
359 /// ::= 'define' FunctionHeader '{' ...
360 bool LLParser::ParseDefine() {
361 assert(Lex.getKind() == lltok::kw_define);
365 return ParseFunctionHeader(F, true) ||
366 ParseFunctionBody(*F);
372 bool LLParser::ParseGlobalType(bool &IsConstant) {
373 if (Lex.getKind() == lltok::kw_constant)
375 else if (Lex.getKind() == lltok::kw_global)
379 return TokError("expected 'global' or 'constant'");
385 /// ParseUnnamedGlobal:
386 /// OptionalVisibility ALIAS ...
387 /// OptionalLinkage OptionalVisibility ... -> global variable
388 /// GlobalID '=' OptionalVisibility ALIAS ...
389 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
390 bool LLParser::ParseUnnamedGlobal() {
391 unsigned VarID = NumberedVals.size();
393 LocTy NameLoc = Lex.getLoc();
395 // Handle the GlobalID form.
396 if (Lex.getKind() == lltok::GlobalID) {
397 if (Lex.getUIntVal() != VarID)
398 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
400 Lex.Lex(); // eat GlobalID;
402 if (ParseToken(lltok::equal, "expected '=' after name"))
407 unsigned Linkage, Visibility;
408 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
409 ParseOptionalVisibility(Visibility))
412 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
413 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
414 return ParseAlias(Name, NameLoc, Visibility);
417 /// ParseNamedGlobal:
418 /// GlobalVar '=' OptionalVisibility ALIAS ...
419 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
420 bool LLParser::ParseNamedGlobal() {
421 assert(Lex.getKind() == lltok::GlobalVar);
422 LocTy NameLoc = Lex.getLoc();
423 std::string Name = Lex.getStrVal();
427 unsigned Linkage, Visibility;
428 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
429 ParseOptionalLinkage(Linkage, HasLinkage) ||
430 ParseOptionalVisibility(Visibility))
433 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
434 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
435 return ParseAlias(Name, NameLoc, Visibility);
439 // ::= '!' STRINGCONSTANT
440 bool LLParser::ParseMDString(MDString *&Result) {
442 if (ParseStringConstant(Str)) return true;
443 Result = MDString::get(Context, Str);
448 // ::= '!' MDNodeNumber
450 /// This version of ParseMDNodeID returns the slot number and null in the case
451 /// of a forward reference.
452 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
453 // !{ ..., !42, ... }
454 if (ParseUInt32(SlotNo)) return true;
456 // Check existing MDNode.
457 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
458 Result = NumberedMetadata[SlotNo];
464 bool LLParser::ParseMDNodeID(MDNode *&Result) {
465 // !{ ..., !42, ... }
467 if (ParseMDNodeID(Result, MID)) return true;
469 // If not a forward reference, just return it now.
470 if (Result) return false;
472 // Otherwise, create MDNode forward reference.
473 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
474 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
476 if (NumberedMetadata.size() <= MID)
477 NumberedMetadata.resize(MID+1);
478 NumberedMetadata[MID] = FwdNode;
483 /// ParseNamedMetadata:
484 /// !foo = !{ !1, !2 }
485 bool LLParser::ParseNamedMetadata() {
486 assert(Lex.getKind() == lltok::MetadataVar);
487 std::string Name = Lex.getStrVal();
490 if (ParseToken(lltok::equal, "expected '=' here") ||
491 ParseToken(lltok::exclaim, "Expected '!' here") ||
492 ParseToken(lltok::lbrace, "Expected '{' here"))
495 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
496 if (Lex.getKind() != lltok::rbrace)
498 if (ParseToken(lltok::exclaim, "Expected '!' here"))
502 if (ParseMDNodeID(N)) return true;
504 } while (EatIfPresent(lltok::comma));
506 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
512 /// ParseStandaloneMetadata:
514 bool LLParser::ParseStandaloneMetadata() {
515 assert(Lex.getKind() == lltok::exclaim);
517 unsigned MetadataID = 0;
521 SmallVector<Value *, 16> Elts;
522 if (ParseUInt32(MetadataID) ||
523 ParseToken(lltok::equal, "expected '=' here") ||
524 ParseType(Ty, TyLoc) ||
525 ParseToken(lltok::exclaim, "Expected '!' here") ||
526 ParseToken(lltok::lbrace, "Expected '{' here") ||
527 ParseMDNodeVector(Elts, NULL) ||
528 ParseToken(lltok::rbrace, "expected end of metadata node"))
531 MDNode *Init = MDNode::get(Context, Elts);
533 // See if this was forward referenced, if so, handle it.
534 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
535 FI = ForwardRefMDNodes.find(MetadataID);
536 if (FI != ForwardRefMDNodes.end()) {
537 MDNode *Temp = FI->second.first;
538 Temp->replaceAllUsesWith(Init);
539 MDNode::deleteTemporary(Temp);
540 ForwardRefMDNodes.erase(FI);
542 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
544 if (MetadataID >= NumberedMetadata.size())
545 NumberedMetadata.resize(MetadataID+1);
547 if (NumberedMetadata[MetadataID] != 0)
548 return TokError("Metadata id is already used");
549 NumberedMetadata[MetadataID] = Init;
556 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
559 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
560 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
562 /// Everything through visibility has already been parsed.
564 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565 unsigned Visibility) {
566 assert(Lex.getKind() == lltok::kw_alias);
569 LocTy LinkageLoc = Lex.getLoc();
570 if (ParseOptionalLinkage(Linkage))
573 if (Linkage != GlobalValue::ExternalLinkage &&
574 Linkage != GlobalValue::WeakAnyLinkage &&
575 Linkage != GlobalValue::WeakODRLinkage &&
576 Linkage != GlobalValue::InternalLinkage &&
577 Linkage != GlobalValue::PrivateLinkage &&
578 Linkage != GlobalValue::LinkerPrivateLinkage &&
579 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
580 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
581 return Error(LinkageLoc, "invalid linkage type for alias");
584 LocTy AliaseeLoc = Lex.getLoc();
585 if (Lex.getKind() != lltok::kw_bitcast &&
586 Lex.getKind() != lltok::kw_getelementptr) {
587 if (ParseGlobalTypeAndValue(Aliasee)) return true;
589 // The bitcast dest type is not present, it is implied by the dest type.
591 if (ParseValID(ID)) return true;
592 if (ID.Kind != ValID::t_Constant)
593 return Error(AliaseeLoc, "invalid aliasee");
594 Aliasee = ID.ConstantVal;
597 if (!Aliasee->getType()->isPointerTy())
598 return Error(AliaseeLoc, "alias must have pointer type");
600 // Okay, create the alias but do not insert it into the module yet.
601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
602 (GlobalValue::LinkageTypes)Linkage, Name,
604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
606 // See if this value already exists in the symbol table. If so, it is either
607 // a redefinition or a definition of a forward reference.
608 if (GlobalValue *Val = M->getNamedValue(Name)) {
609 // See if this was a redefinition. If so, there is no entry in
611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
612 I = ForwardRefVals.find(Name);
613 if (I == ForwardRefVals.end())
614 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
616 // Otherwise, this was a definition of forward ref. Verify that types
618 if (Val->getType() != GA->getType())
619 return Error(NameLoc,
620 "forward reference and definition of alias have different types");
622 // If they agree, just RAUW the old value with the alias and remove the
624 Val->replaceAllUsesWith(GA);
625 Val->eraseFromParent();
626 ForwardRefVals.erase(I);
629 // Insert into the module, we know its name won't collide now.
630 M->getAliasList().push_back(GA);
631 assert(GA->getName() == Name && "Should not be a name conflict!");
637 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
638 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
639 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
640 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
642 /// Everything through visibility has been parsed already.
644 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
648 bool ThreadLocal, IsConstant, UnnamedAddr;
649 LocTy UnnamedAddrLoc;
653 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
654 ParseOptionalAddrSpace(AddrSpace) ||
655 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
657 ParseGlobalType(IsConstant) ||
658 ParseType(Ty, TyLoc))
661 // If the linkage is specified and is external, then no initializer is
664 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
665 Linkage != GlobalValue::ExternalWeakLinkage &&
666 Linkage != GlobalValue::ExternalLinkage)) {
667 if (ParseGlobalValue(Ty, Init))
671 if (Ty->isFunctionTy() || Ty->isLabelTy())
672 return Error(TyLoc, "invalid type for global variable");
674 GlobalVariable *GV = 0;
676 // See if the global was forward referenced, if so, use the global.
678 if (GlobalValue *GVal = M->getNamedValue(Name)) {
679 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
680 return Error(NameLoc, "redefinition of global '@" + Name + "'");
681 GV = cast<GlobalVariable>(GVal);
684 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
685 I = ForwardRefValIDs.find(NumberedVals.size());
686 if (I != ForwardRefValIDs.end()) {
687 GV = cast<GlobalVariable>(I->second.first);
688 ForwardRefValIDs.erase(I);
693 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
694 Name, 0, false, AddrSpace);
696 if (GV->getType()->getElementType() != Ty)
698 "forward reference and definition of global have different types");
700 // Move the forward-reference to the correct spot in the module.
701 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
705 NumberedVals.push_back(GV);
707 // Set the parsed properties on the global.
709 GV->setInitializer(Init);
710 GV->setConstant(IsConstant);
711 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
712 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
713 GV->setThreadLocal(ThreadLocal);
714 GV->setUnnamedAddr(UnnamedAddr);
716 // Parse attributes on the global.
717 while (Lex.getKind() == lltok::comma) {
720 if (Lex.getKind() == lltok::kw_section) {
722 GV->setSection(Lex.getStrVal());
723 if (ParseToken(lltok::StringConstant, "expected global section string"))
725 } else if (Lex.getKind() == lltok::kw_align) {
727 if (ParseOptionalAlignment(Alignment)) return true;
728 GV->setAlignment(Alignment);
730 TokError("unknown global variable property!");
738 //===----------------------------------------------------------------------===//
739 // GlobalValue Reference/Resolution Routines.
740 //===----------------------------------------------------------------------===//
742 /// GetGlobalVal - Get a value with the specified name or ID, creating a
743 /// forward reference record if needed. This can return null if the value
744 /// exists but does not have the right type.
745 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
747 PointerType *PTy = dyn_cast<PointerType>(Ty);
749 Error(Loc, "global variable reference must have pointer type");
753 // Look this name up in the normal function symbol table.
755 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
757 // If this is a forward reference for the value, see if we already created a
758 // forward ref record.
760 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
761 I = ForwardRefVals.find(Name);
762 if (I != ForwardRefVals.end())
763 Val = I->second.first;
766 // If we have the value in the symbol table or fwd-ref table, return it.
768 if (Val->getType() == Ty) return Val;
769 Error(Loc, "'@" + Name + "' defined with type '" +
770 getTypeString(Val->getType()) + "'");
774 // Otherwise, create a new forward reference for this value and remember it.
776 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
777 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
779 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
780 GlobalValue::ExternalWeakLinkage, 0, Name);
782 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
786 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
787 PointerType *PTy = dyn_cast<PointerType>(Ty);
789 Error(Loc, "global variable reference must have pointer type");
793 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
795 // If this is a forward reference for the value, see if we already created a
796 // forward ref record.
798 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
799 I = ForwardRefValIDs.find(ID);
800 if (I != ForwardRefValIDs.end())
801 Val = I->second.first;
804 // If we have the value in the symbol table or fwd-ref table, return it.
806 if (Val->getType() == Ty) return Val;
807 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
808 getTypeString(Val->getType()) + "'");
812 // Otherwise, create a new forward reference for this value and remember it.
814 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
815 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
817 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
818 GlobalValue::ExternalWeakLinkage, 0, "");
820 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
825 //===----------------------------------------------------------------------===//
827 //===----------------------------------------------------------------------===//
829 /// ParseToken - If the current token has the specified kind, eat it and return
830 /// success. Otherwise, emit the specified error and return failure.
831 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
832 if (Lex.getKind() != T)
833 return TokError(ErrMsg);
838 /// ParseStringConstant
839 /// ::= StringConstant
840 bool LLParser::ParseStringConstant(std::string &Result) {
841 if (Lex.getKind() != lltok::StringConstant)
842 return TokError("expected string constant");
843 Result = Lex.getStrVal();
850 bool LLParser::ParseUInt32(unsigned &Val) {
851 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
852 return TokError("expected integer");
853 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
854 if (Val64 != unsigned(Val64))
855 return TokError("expected 32-bit integer (too large)");
862 /// ParseOptionalAddrSpace
864 /// := 'addrspace' '(' uint32 ')'
865 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
867 if (!EatIfPresent(lltok::kw_addrspace))
869 return ParseToken(lltok::lparen, "expected '(' in address space") ||
870 ParseUInt32(AddrSpace) ||
871 ParseToken(lltok::rparen, "expected ')' in address space");
874 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
875 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
876 /// 2: function attr.
877 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
878 Attrs = Attribute::None;
879 LocTy AttrLoc = Lex.getLoc();
882 switch (Lex.getKind()) {
883 default: // End of attributes.
884 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
885 return Error(AttrLoc, "invalid use of function-only attribute");
887 // As a hack, we allow "align 2" on functions as a synonym for
890 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
891 return Error(AttrLoc, "invalid use of attribute on a function");
893 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
894 return Error(AttrLoc, "invalid use of parameter-only attribute");
897 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
898 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
899 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
900 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
901 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
902 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
903 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
904 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
906 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
907 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
908 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
909 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
910 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
911 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
912 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
913 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
914 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
915 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
916 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
917 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
918 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
919 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
920 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
921 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
923 case lltok::kw_alignstack: {
925 if (ParseOptionalStackAlignment(Alignment))
927 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
931 case lltok::kw_align: {
933 if (ParseOptionalAlignment(Alignment))
935 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
944 /// ParseOptionalLinkage
947 /// ::= 'linker_private'
948 /// ::= 'linker_private_weak'
949 /// ::= 'linker_private_weak_def_auto'
954 /// ::= 'linkonce_odr'
955 /// ::= 'available_externally'
960 /// ::= 'extern_weak'
962 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
964 switch (Lex.getKind()) {
965 default: Res=GlobalValue::ExternalLinkage; return false;
966 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
967 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
968 case lltok::kw_linker_private_weak:
969 Res = GlobalValue::LinkerPrivateWeakLinkage;
971 case lltok::kw_linker_private_weak_def_auto:
972 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
974 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
975 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
976 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
977 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
978 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
979 case lltok::kw_available_externally:
980 Res = GlobalValue::AvailableExternallyLinkage;
982 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
983 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
984 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
985 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
986 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
987 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
994 /// ParseOptionalVisibility
1000 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1001 switch (Lex.getKind()) {
1002 default: Res = GlobalValue::DefaultVisibility; return false;
1003 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1004 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1005 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1011 /// ParseOptionalCallingConv
1016 /// ::= 'x86_stdcallcc'
1017 /// ::= 'x86_fastcallcc'
1018 /// ::= 'x86_thiscallcc'
1019 /// ::= 'arm_apcscc'
1020 /// ::= 'arm_aapcscc'
1021 /// ::= 'arm_aapcs_vfpcc'
1022 /// ::= 'msp430_intrcc'
1023 /// ::= 'ptx_kernel'
1024 /// ::= 'ptx_device'
1027 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1028 switch (Lex.getKind()) {
1029 default: CC = CallingConv::C; return false;
1030 case lltok::kw_ccc: CC = CallingConv::C; break;
1031 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1032 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1033 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1034 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1035 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1036 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1037 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1038 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1039 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1040 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1041 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1042 case lltok::kw_cc: {
1043 unsigned ArbitraryCC;
1045 if (ParseUInt32(ArbitraryCC)) {
1048 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1058 /// ParseInstructionMetadata
1059 /// ::= !dbg !42 (',' !dbg !57)*
1060 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1061 PerFunctionState *PFS) {
1063 if (Lex.getKind() != lltok::MetadataVar)
1064 return TokError("expected metadata after comma");
1066 std::string Name = Lex.getStrVal();
1067 unsigned MDK = M->getMDKindID(Name.c_str());
1071 SMLoc Loc = Lex.getLoc();
1073 if (ParseToken(lltok::exclaim, "expected '!' here"))
1076 // This code is similar to that of ParseMetadataValue, however it needs to
1077 // have special-case code for a forward reference; see the comments on
1078 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1079 // at the top level here.
1080 if (Lex.getKind() == lltok::lbrace) {
1082 if (ParseMetadataListValue(ID, PFS))
1084 assert(ID.Kind == ValID::t_MDNode);
1085 Inst->setMetadata(MDK, ID.MDNodeVal);
1087 unsigned NodeID = 0;
1088 if (ParseMDNodeID(Node, NodeID))
1091 // If we got the node, add it to the instruction.
1092 Inst->setMetadata(MDK, Node);
1094 MDRef R = { Loc, MDK, NodeID };
1095 // Otherwise, remember that this should be resolved later.
1096 ForwardRefInstMetadata[Inst].push_back(R);
1100 // If this is the end of the list, we're done.
1101 } while (EatIfPresent(lltok::comma));
1105 /// ParseOptionalAlignment
1108 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1110 if (!EatIfPresent(lltok::kw_align))
1112 LocTy AlignLoc = Lex.getLoc();
1113 if (ParseUInt32(Alignment)) return true;
1114 if (!isPowerOf2_32(Alignment))
1115 return Error(AlignLoc, "alignment is not a power of two");
1116 if (Alignment > Value::MaximumAlignment)
1117 return Error(AlignLoc, "huge alignments are not supported yet");
1121 /// ParseOptionalCommaAlign
1125 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1127 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1128 bool &AteExtraComma) {
1129 AteExtraComma = false;
1130 while (EatIfPresent(lltok::comma)) {
1131 // Metadata at the end is an early exit.
1132 if (Lex.getKind() == lltok::MetadataVar) {
1133 AteExtraComma = true;
1137 if (Lex.getKind() != lltok::kw_align)
1138 return Error(Lex.getLoc(), "expected metadata or 'align'");
1140 if (ParseOptionalAlignment(Alignment)) return true;
1146 /// ParseScopeAndOrdering
1147 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1150 /// This sets Scope and Ordering to the parsed values.
1151 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1152 AtomicOrdering &Ordering) {
1156 Scope = CrossThread;
1157 if (EatIfPresent(lltok::kw_singlethread))
1158 Scope = SingleThread;
1159 switch (Lex.getKind()) {
1160 default: return TokError("Expected ordering on atomic instruction");
1161 case lltok::kw_unordered: Ordering = Unordered; break;
1162 case lltok::kw_monotonic: Ordering = Monotonic; break;
1163 case lltok::kw_acquire: Ordering = Acquire; break;
1164 case lltok::kw_release: Ordering = Release; break;
1165 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1166 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1172 /// ParseOptionalStackAlignment
1174 /// ::= 'alignstack' '(' 4 ')'
1175 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1177 if (!EatIfPresent(lltok::kw_alignstack))
1179 LocTy ParenLoc = Lex.getLoc();
1180 if (!EatIfPresent(lltok::lparen))
1181 return Error(ParenLoc, "expected '('");
1182 LocTy AlignLoc = Lex.getLoc();
1183 if (ParseUInt32(Alignment)) return true;
1184 ParenLoc = Lex.getLoc();
1185 if (!EatIfPresent(lltok::rparen))
1186 return Error(ParenLoc, "expected ')'");
1187 if (!isPowerOf2_32(Alignment))
1188 return Error(AlignLoc, "stack alignment is not a power of two");
1192 /// ParseIndexList - This parses the index list for an insert/extractvalue
1193 /// instruction. This sets AteExtraComma in the case where we eat an extra
1194 /// comma at the end of the line and find that it is followed by metadata.
1195 /// Clients that don't allow metadata can call the version of this function that
1196 /// only takes one argument.
1199 /// ::= (',' uint32)+
1201 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1202 bool &AteExtraComma) {
1203 AteExtraComma = false;
1205 if (Lex.getKind() != lltok::comma)
1206 return TokError("expected ',' as start of index list");
1208 while (EatIfPresent(lltok::comma)) {
1209 if (Lex.getKind() == lltok::MetadataVar) {
1210 AteExtraComma = true;
1214 if (ParseUInt32(Idx)) return true;
1215 Indices.push_back(Idx);
1221 //===----------------------------------------------------------------------===//
1223 //===----------------------------------------------------------------------===//
1225 /// ParseType - Parse a type.
1226 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1227 SMLoc TypeLoc = Lex.getLoc();
1228 switch (Lex.getKind()) {
1230 return TokError("expected type");
1232 // Type ::= 'float' | 'void' (etc)
1233 Result = Lex.getTyVal();
1237 // Type ::= StructType
1238 if (ParseAnonStructType(Result, false))
1241 case lltok::lsquare:
1242 // Type ::= '[' ... ']'
1243 Lex.Lex(); // eat the lsquare.
1244 if (ParseArrayVectorType(Result, false))
1247 case lltok::less: // Either vector or packed struct.
1248 // Type ::= '<' ... '>'
1250 if (Lex.getKind() == lltok::lbrace) {
1251 if (ParseAnonStructType(Result, true) ||
1252 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1254 } else if (ParseArrayVectorType(Result, true))
1257 case lltok::LocalVar: {
1259 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1261 // If the type hasn't been defined yet, create a forward definition and
1262 // remember where that forward def'n was seen (in case it never is defined).
1263 if (Entry.first == 0) {
1264 Entry.first = StructType::create(Context, Lex.getStrVal());
1265 Entry.second = Lex.getLoc();
1267 Result = Entry.first;
1272 case lltok::LocalVarID: {
1274 if (Lex.getUIntVal() >= NumberedTypes.size())
1275 NumberedTypes.resize(Lex.getUIntVal()+1);
1276 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1278 // If the type hasn't been defined yet, create a forward definition and
1279 // remember where that forward def'n was seen (in case it never is defined).
1280 if (Entry.first == 0) {
1281 Entry.first = StructType::create(Context);
1282 Entry.second = Lex.getLoc();
1284 Result = Entry.first;
1290 // Parse the type suffixes.
1292 switch (Lex.getKind()) {
1295 if (!AllowVoid && Result->isVoidTy())
1296 return Error(TypeLoc, "void type only allowed for function results");
1299 // Type ::= Type '*'
1301 if (Result->isLabelTy())
1302 return TokError("basic block pointers are invalid");
1303 if (Result->isVoidTy())
1304 return TokError("pointers to void are invalid - use i8* instead");
1305 if (!PointerType::isValidElementType(Result))
1306 return TokError("pointer to this type is invalid");
1307 Result = PointerType::getUnqual(Result);
1311 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1312 case lltok::kw_addrspace: {
1313 if (Result->isLabelTy())
1314 return TokError("basic block pointers are invalid");
1315 if (Result->isVoidTy())
1316 return TokError("pointers to void are invalid; use i8* instead");
1317 if (!PointerType::isValidElementType(Result))
1318 return TokError("pointer to this type is invalid");
1320 if (ParseOptionalAddrSpace(AddrSpace) ||
1321 ParseToken(lltok::star, "expected '*' in address space"))
1324 Result = PointerType::get(Result, AddrSpace);
1328 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1330 if (ParseFunctionType(Result))
1337 /// ParseParameterList
1339 /// ::= '(' Arg (',' Arg)* ')'
1341 /// ::= Type OptionalAttributes Value OptionalAttributes
1342 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1343 PerFunctionState &PFS) {
1344 if (ParseToken(lltok::lparen, "expected '(' in call"))
1347 while (Lex.getKind() != lltok::rparen) {
1348 // If this isn't the first argument, we need a comma.
1349 if (!ArgList.empty() &&
1350 ParseToken(lltok::comma, "expected ',' in argument list"))
1353 // Parse the argument.
1356 unsigned ArgAttrs1 = Attribute::None;
1357 unsigned ArgAttrs2 = Attribute::None;
1359 if (ParseType(ArgTy, ArgLoc))
1362 // Otherwise, handle normal operands.
1363 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1365 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1368 Lex.Lex(); // Lex the ')'.
1374 /// ParseArgumentList - Parse the argument list for a function type or function
1376 /// ::= '(' ArgTypeListI ')'
1380 /// ::= ArgTypeList ',' '...'
1381 /// ::= ArgType (',' ArgType)*
1383 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1386 assert(Lex.getKind() == lltok::lparen);
1387 Lex.Lex(); // eat the (.
1389 if (Lex.getKind() == lltok::rparen) {
1391 } else if (Lex.getKind() == lltok::dotdotdot) {
1395 LocTy TypeLoc = Lex.getLoc();
1400 if (ParseType(ArgTy) ||
1401 ParseOptionalAttrs(Attrs, 0)) return true;
1403 if (ArgTy->isVoidTy())
1404 return Error(TypeLoc, "argument can not have void type");
1406 if (Lex.getKind() == lltok::LocalVar) {
1407 Name = Lex.getStrVal();
1411 if (!FunctionType::isValidArgumentType(ArgTy))
1412 return Error(TypeLoc, "invalid type for function argument");
1414 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1416 while (EatIfPresent(lltok::comma)) {
1417 // Handle ... at end of arg list.
1418 if (EatIfPresent(lltok::dotdotdot)) {
1423 // Otherwise must be an argument type.
1424 TypeLoc = Lex.getLoc();
1425 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1427 if (ArgTy->isVoidTy())
1428 return Error(TypeLoc, "argument can not have void type");
1430 if (Lex.getKind() == lltok::LocalVar) {
1431 Name = Lex.getStrVal();
1437 if (!ArgTy->isFirstClassType())
1438 return Error(TypeLoc, "invalid type for function argument");
1440 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1444 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1447 /// ParseFunctionType
1448 /// ::= Type ArgumentList OptionalAttrs
1449 bool LLParser::ParseFunctionType(Type *&Result) {
1450 assert(Lex.getKind() == lltok::lparen);
1452 if (!FunctionType::isValidReturnType(Result))
1453 return TokError("invalid function return type");
1455 SmallVector<ArgInfo, 8> ArgList;
1457 if (ParseArgumentList(ArgList, isVarArg))
1460 // Reject names on the arguments lists.
1461 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1462 if (!ArgList[i].Name.empty())
1463 return Error(ArgList[i].Loc, "argument name invalid in function type");
1464 if (ArgList[i].Attrs != 0)
1465 return Error(ArgList[i].Loc,
1466 "argument attributes invalid in function type");
1469 SmallVector<Type*, 16> ArgListTy;
1470 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1471 ArgListTy.push_back(ArgList[i].Ty);
1473 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1477 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1479 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1480 SmallVector<Type*, 8> Elts;
1481 if (ParseStructBody(Elts)) return true;
1483 Result = StructType::get(Context, Elts, Packed);
1487 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1488 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1489 std::pair<Type*, LocTy> &Entry,
1491 // If the type was already defined, diagnose the redefinition.
1492 if (Entry.first && !Entry.second.isValid())
1493 return Error(TypeLoc, "redefinition of type");
1495 // If we have opaque, just return without filling in the definition for the
1496 // struct. This counts as a definition as far as the .ll file goes.
1497 if (EatIfPresent(lltok::kw_opaque)) {
1498 // This type is being defined, so clear the location to indicate this.
1499 Entry.second = SMLoc();
1501 // If this type number has never been uttered, create it.
1502 if (Entry.first == 0)
1503 Entry.first = StructType::create(Context, Name);
1504 ResultTy = Entry.first;
1508 // If the type starts with '<', then it is either a packed struct or a vector.
1509 bool isPacked = EatIfPresent(lltok::less);
1511 // If we don't have a struct, then we have a random type alias, which we
1512 // accept for compatibility with old files. These types are not allowed to be
1513 // forward referenced and not allowed to be recursive.
1514 if (Lex.getKind() != lltok::lbrace) {
1516 return Error(TypeLoc, "forward references to non-struct type");
1520 return ParseArrayVectorType(ResultTy, true);
1521 return ParseType(ResultTy);
1524 // This type is being defined, so clear the location to indicate this.
1525 Entry.second = SMLoc();
1527 // If this type number has never been uttered, create it.
1528 if (Entry.first == 0)
1529 Entry.first = StructType::create(Context, Name);
1531 StructType *STy = cast<StructType>(Entry.first);
1533 SmallVector<Type*, 8> Body;
1534 if (ParseStructBody(Body) ||
1535 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1538 STy->setBody(Body, isPacked);
1544 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1547 /// ::= '{' Type (',' Type)* '}'
1548 /// ::= '<' '{' '}' '>'
1549 /// ::= '<' '{' Type (',' Type)* '}' '>'
1550 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1551 assert(Lex.getKind() == lltok::lbrace);
1552 Lex.Lex(); // Consume the '{'
1554 // Handle the empty struct.
1555 if (EatIfPresent(lltok::rbrace))
1558 LocTy EltTyLoc = Lex.getLoc();
1560 if (ParseType(Ty)) return true;
1563 if (!StructType::isValidElementType(Ty))
1564 return Error(EltTyLoc, "invalid element type for struct");
1566 while (EatIfPresent(lltok::comma)) {
1567 EltTyLoc = Lex.getLoc();
1568 if (ParseType(Ty)) return true;
1570 if (!StructType::isValidElementType(Ty))
1571 return Error(EltTyLoc, "invalid element type for struct");
1576 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1579 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1580 /// token has already been consumed.
1582 /// ::= '[' APSINTVAL 'x' Types ']'
1583 /// ::= '<' APSINTVAL 'x' Types '>'
1584 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1585 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1586 Lex.getAPSIntVal().getBitWidth() > 64)
1587 return TokError("expected number in address space");
1589 LocTy SizeLoc = Lex.getLoc();
1590 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1593 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1596 LocTy TypeLoc = Lex.getLoc();
1598 if (ParseType(EltTy)) return true;
1600 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1601 "expected end of sequential type"))
1606 return Error(SizeLoc, "zero element vector is illegal");
1607 if ((unsigned)Size != Size)
1608 return Error(SizeLoc, "size too large for vector");
1609 if (!VectorType::isValidElementType(EltTy))
1610 return Error(TypeLoc, "vector element type must be fp or integer");
1611 Result = VectorType::get(EltTy, unsigned(Size));
1613 if (!ArrayType::isValidElementType(EltTy))
1614 return Error(TypeLoc, "invalid array element type");
1615 Result = ArrayType::get(EltTy, Size);
1620 //===----------------------------------------------------------------------===//
1621 // Function Semantic Analysis.
1622 //===----------------------------------------------------------------------===//
1624 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1626 : P(p), F(f), FunctionNumber(functionNumber) {
1628 // Insert unnamed arguments into the NumberedVals list.
1629 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1632 NumberedVals.push_back(AI);
1635 LLParser::PerFunctionState::~PerFunctionState() {
1636 // If there were any forward referenced non-basicblock values, delete them.
1637 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1638 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1639 if (!isa<BasicBlock>(I->second.first)) {
1640 I->second.first->replaceAllUsesWith(
1641 UndefValue::get(I->second.first->getType()));
1642 delete I->second.first;
1643 I->second.first = 0;
1646 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1647 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1648 if (!isa<BasicBlock>(I->second.first)) {
1649 I->second.first->replaceAllUsesWith(
1650 UndefValue::get(I->second.first->getType()));
1651 delete I->second.first;
1652 I->second.first = 0;
1656 bool LLParser::PerFunctionState::FinishFunction() {
1657 // Check to see if someone took the address of labels in this block.
1658 if (!P.ForwardRefBlockAddresses.empty()) {
1660 if (!F.getName().empty()) {
1661 FunctionID.Kind = ValID::t_GlobalName;
1662 FunctionID.StrVal = F.getName();
1664 FunctionID.Kind = ValID::t_GlobalID;
1665 FunctionID.UIntVal = FunctionNumber;
1668 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1669 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1670 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1671 // Resolve all these references.
1672 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1675 P.ForwardRefBlockAddresses.erase(FRBAI);
1679 if (!ForwardRefVals.empty())
1680 return P.Error(ForwardRefVals.begin()->second.second,
1681 "use of undefined value '%" + ForwardRefVals.begin()->first +
1683 if (!ForwardRefValIDs.empty())
1684 return P.Error(ForwardRefValIDs.begin()->second.second,
1685 "use of undefined value '%" +
1686 Twine(ForwardRefValIDs.begin()->first) + "'");
1691 /// GetVal - Get a value with the specified name or ID, creating a
1692 /// forward reference record if needed. This can return null if the value
1693 /// exists but does not have the right type.
1694 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1695 Type *Ty, LocTy Loc) {
1696 // Look this name up in the normal function symbol table.
1697 Value *Val = F.getValueSymbolTable().lookup(Name);
1699 // If this is a forward reference for the value, see if we already created a
1700 // forward ref record.
1702 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1703 I = ForwardRefVals.find(Name);
1704 if (I != ForwardRefVals.end())
1705 Val = I->second.first;
1708 // If we have the value in the symbol table or fwd-ref table, return it.
1710 if (Val->getType() == Ty) return Val;
1711 if (Ty->isLabelTy())
1712 P.Error(Loc, "'%" + Name + "' is not a basic block");
1714 P.Error(Loc, "'%" + Name + "' defined with type '" +
1715 getTypeString(Val->getType()) + "'");
1719 // Don't make placeholders with invalid type.
1720 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1721 P.Error(Loc, "invalid use of a non-first-class type");
1725 // Otherwise, create a new forward reference for this value and remember it.
1727 if (Ty->isLabelTy())
1728 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1730 FwdVal = new Argument(Ty, Name);
1732 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1736 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1738 // Look this name up in the normal function symbol table.
1739 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1741 // If this is a forward reference for the value, see if we already created a
1742 // forward ref record.
1744 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1745 I = ForwardRefValIDs.find(ID);
1746 if (I != ForwardRefValIDs.end())
1747 Val = I->second.first;
1750 // If we have the value in the symbol table or fwd-ref table, return it.
1752 if (Val->getType() == Ty) return Val;
1753 if (Ty->isLabelTy())
1754 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1756 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1757 getTypeString(Val->getType()) + "'");
1761 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1762 P.Error(Loc, "invalid use of a non-first-class type");
1766 // Otherwise, create a new forward reference for this value and remember it.
1768 if (Ty->isLabelTy())
1769 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1771 FwdVal = new Argument(Ty);
1773 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1777 /// SetInstName - After an instruction is parsed and inserted into its
1778 /// basic block, this installs its name.
1779 bool LLParser::PerFunctionState::SetInstName(int NameID,
1780 const std::string &NameStr,
1781 LocTy NameLoc, Instruction *Inst) {
1782 // If this instruction has void type, it cannot have a name or ID specified.
1783 if (Inst->getType()->isVoidTy()) {
1784 if (NameID != -1 || !NameStr.empty())
1785 return P.Error(NameLoc, "instructions returning void cannot have a name");
1789 // If this was a numbered instruction, verify that the instruction is the
1790 // expected value and resolve any forward references.
1791 if (NameStr.empty()) {
1792 // If neither a name nor an ID was specified, just use the next ID.
1794 NameID = NumberedVals.size();
1796 if (unsigned(NameID) != NumberedVals.size())
1797 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1798 Twine(NumberedVals.size()) + "'");
1800 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1801 ForwardRefValIDs.find(NameID);
1802 if (FI != ForwardRefValIDs.end()) {
1803 if (FI->second.first->getType() != Inst->getType())
1804 return P.Error(NameLoc, "instruction forward referenced with type '" +
1805 getTypeString(FI->second.first->getType()) + "'");
1806 FI->second.first->replaceAllUsesWith(Inst);
1807 delete FI->second.first;
1808 ForwardRefValIDs.erase(FI);
1811 NumberedVals.push_back(Inst);
1815 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1816 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1817 FI = ForwardRefVals.find(NameStr);
1818 if (FI != ForwardRefVals.end()) {
1819 if (FI->second.first->getType() != Inst->getType())
1820 return P.Error(NameLoc, "instruction forward referenced with type '" +
1821 getTypeString(FI->second.first->getType()) + "'");
1822 FI->second.first->replaceAllUsesWith(Inst);
1823 delete FI->second.first;
1824 ForwardRefVals.erase(FI);
1827 // Set the name on the instruction.
1828 Inst->setName(NameStr);
1830 if (Inst->getName() != NameStr)
1831 return P.Error(NameLoc, "multiple definition of local value named '" +
1836 /// GetBB - Get a basic block with the specified name or ID, creating a
1837 /// forward reference record if needed.
1838 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1840 return cast_or_null<BasicBlock>(GetVal(Name,
1841 Type::getLabelTy(F.getContext()), Loc));
1844 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1845 return cast_or_null<BasicBlock>(GetVal(ID,
1846 Type::getLabelTy(F.getContext()), Loc));
1849 /// DefineBB - Define the specified basic block, which is either named or
1850 /// unnamed. If there is an error, this returns null otherwise it returns
1851 /// the block being defined.
1852 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1856 BB = GetBB(NumberedVals.size(), Loc);
1858 BB = GetBB(Name, Loc);
1859 if (BB == 0) return 0; // Already diagnosed error.
1861 // Move the block to the end of the function. Forward ref'd blocks are
1862 // inserted wherever they happen to be referenced.
1863 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1865 // Remove the block from forward ref sets.
1867 ForwardRefValIDs.erase(NumberedVals.size());
1868 NumberedVals.push_back(BB);
1870 // BB forward references are already in the function symbol table.
1871 ForwardRefVals.erase(Name);
1877 //===----------------------------------------------------------------------===//
1879 //===----------------------------------------------------------------------===//
1881 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1882 /// type implied. For example, if we parse "4" we don't know what integer type
1883 /// it has. The value will later be combined with its type and checked for
1884 /// sanity. PFS is used to convert function-local operands of metadata (since
1885 /// metadata operands are not just parsed here but also converted to values).
1886 /// PFS can be null when we are not parsing metadata values inside a function.
1887 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1888 ID.Loc = Lex.getLoc();
1889 switch (Lex.getKind()) {
1890 default: return TokError("expected value token");
1891 case lltok::GlobalID: // @42
1892 ID.UIntVal = Lex.getUIntVal();
1893 ID.Kind = ValID::t_GlobalID;
1895 case lltok::GlobalVar: // @foo
1896 ID.StrVal = Lex.getStrVal();
1897 ID.Kind = ValID::t_GlobalName;
1899 case lltok::LocalVarID: // %42
1900 ID.UIntVal = Lex.getUIntVal();
1901 ID.Kind = ValID::t_LocalID;
1903 case lltok::LocalVar: // %foo
1904 ID.StrVal = Lex.getStrVal();
1905 ID.Kind = ValID::t_LocalName;
1907 case lltok::exclaim: // !42, !{...}, or !"foo"
1908 return ParseMetadataValue(ID, PFS);
1910 ID.APSIntVal = Lex.getAPSIntVal();
1911 ID.Kind = ValID::t_APSInt;
1913 case lltok::APFloat:
1914 ID.APFloatVal = Lex.getAPFloatVal();
1915 ID.Kind = ValID::t_APFloat;
1917 case lltok::kw_true:
1918 ID.ConstantVal = ConstantInt::getTrue(Context);
1919 ID.Kind = ValID::t_Constant;
1921 case lltok::kw_false:
1922 ID.ConstantVal = ConstantInt::getFalse(Context);
1923 ID.Kind = ValID::t_Constant;
1925 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1926 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1927 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1929 case lltok::lbrace: {
1930 // ValID ::= '{' ConstVector '}'
1932 SmallVector<Constant*, 16> Elts;
1933 if (ParseGlobalValueVector(Elts) ||
1934 ParseToken(lltok::rbrace, "expected end of struct constant"))
1937 ID.ConstantStructElts = new Constant*[Elts.size()];
1938 ID.UIntVal = Elts.size();
1939 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1940 ID.Kind = ValID::t_ConstantStruct;
1944 // ValID ::= '<' ConstVector '>' --> Vector.
1945 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1947 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1949 SmallVector<Constant*, 16> Elts;
1950 LocTy FirstEltLoc = Lex.getLoc();
1951 if (ParseGlobalValueVector(Elts) ||
1953 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1954 ParseToken(lltok::greater, "expected end of constant"))
1957 if (isPackedStruct) {
1958 ID.ConstantStructElts = new Constant*[Elts.size()];
1959 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1960 ID.UIntVal = Elts.size();
1961 ID.Kind = ValID::t_PackedConstantStruct;
1966 return Error(ID.Loc, "constant vector must not be empty");
1968 if (!Elts[0]->getType()->isIntegerTy() &&
1969 !Elts[0]->getType()->isFloatingPointTy())
1970 return Error(FirstEltLoc,
1971 "vector elements must have integer or floating point type");
1973 // Verify that all the vector elements have the same type.
1974 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1975 if (Elts[i]->getType() != Elts[0]->getType())
1976 return Error(FirstEltLoc,
1977 "vector element #" + Twine(i) +
1978 " is not of type '" + getTypeString(Elts[0]->getType()));
1980 ID.ConstantVal = ConstantVector::get(Elts);
1981 ID.Kind = ValID::t_Constant;
1984 case lltok::lsquare: { // Array Constant
1986 SmallVector<Constant*, 16> Elts;
1987 LocTy FirstEltLoc = Lex.getLoc();
1988 if (ParseGlobalValueVector(Elts) ||
1989 ParseToken(lltok::rsquare, "expected end of array constant"))
1992 // Handle empty element.
1994 // Use undef instead of an array because it's inconvenient to determine
1995 // the element type at this point, there being no elements to examine.
1996 ID.Kind = ValID::t_EmptyArray;
2000 if (!Elts[0]->getType()->isFirstClassType())
2001 return Error(FirstEltLoc, "invalid array element type: " +
2002 getTypeString(Elts[0]->getType()));
2004 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2006 // Verify all elements are correct type!
2007 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2008 if (Elts[i]->getType() != Elts[0]->getType())
2009 return Error(FirstEltLoc,
2010 "array element #" + Twine(i) +
2011 " is not of type '" + getTypeString(Elts[0]->getType()));
2014 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2015 ID.Kind = ValID::t_Constant;
2018 case lltok::kw_c: // c "foo"
2020 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2021 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2022 ID.Kind = ValID::t_Constant;
2025 case lltok::kw_asm: {
2026 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2027 bool HasSideEffect, AlignStack;
2029 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2030 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2031 ParseStringConstant(ID.StrVal) ||
2032 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2033 ParseToken(lltok::StringConstant, "expected constraint string"))
2035 ID.StrVal2 = Lex.getStrVal();
2036 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2037 ID.Kind = ValID::t_InlineAsm;
2041 case lltok::kw_blockaddress: {
2042 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2046 LocTy FnLoc, LabelLoc;
2048 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2050 ParseToken(lltok::comma, "expected comma in block address expression")||
2051 ParseValID(Label) ||
2052 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2055 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2056 return Error(Fn.Loc, "expected function name in blockaddress");
2057 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2058 return Error(Label.Loc, "expected basic block name in blockaddress");
2060 // Make a global variable as a placeholder for this reference.
2061 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2062 false, GlobalValue::InternalLinkage,
2064 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2065 ID.ConstantVal = FwdRef;
2066 ID.Kind = ValID::t_Constant;
2070 case lltok::kw_trunc:
2071 case lltok::kw_zext:
2072 case lltok::kw_sext:
2073 case lltok::kw_fptrunc:
2074 case lltok::kw_fpext:
2075 case lltok::kw_bitcast:
2076 case lltok::kw_uitofp:
2077 case lltok::kw_sitofp:
2078 case lltok::kw_fptoui:
2079 case lltok::kw_fptosi:
2080 case lltok::kw_inttoptr:
2081 case lltok::kw_ptrtoint: {
2082 unsigned Opc = Lex.getUIntVal();
2086 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2087 ParseGlobalTypeAndValue(SrcVal) ||
2088 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2089 ParseType(DestTy) ||
2090 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2092 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2093 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2094 getTypeString(SrcVal->getType()) + "' to '" +
2095 getTypeString(DestTy) + "'");
2096 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2098 ID.Kind = ValID::t_Constant;
2101 case lltok::kw_extractvalue: {
2104 SmallVector<unsigned, 4> Indices;
2105 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2106 ParseGlobalTypeAndValue(Val) ||
2107 ParseIndexList(Indices) ||
2108 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2111 if (!Val->getType()->isAggregateType())
2112 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2113 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2114 return Error(ID.Loc, "invalid indices for extractvalue");
2115 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2116 ID.Kind = ValID::t_Constant;
2119 case lltok::kw_insertvalue: {
2121 Constant *Val0, *Val1;
2122 SmallVector<unsigned, 4> Indices;
2123 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2124 ParseGlobalTypeAndValue(Val0) ||
2125 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2126 ParseGlobalTypeAndValue(Val1) ||
2127 ParseIndexList(Indices) ||
2128 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2130 if (!Val0->getType()->isAggregateType())
2131 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2132 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2133 return Error(ID.Loc, "invalid indices for insertvalue");
2134 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2135 ID.Kind = ValID::t_Constant;
2138 case lltok::kw_icmp:
2139 case lltok::kw_fcmp: {
2140 unsigned PredVal, Opc = Lex.getUIntVal();
2141 Constant *Val0, *Val1;
2143 if (ParseCmpPredicate(PredVal, Opc) ||
2144 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2145 ParseGlobalTypeAndValue(Val0) ||
2146 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2147 ParseGlobalTypeAndValue(Val1) ||
2148 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2151 if (Val0->getType() != Val1->getType())
2152 return Error(ID.Loc, "compare operands must have the same type");
2154 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2156 if (Opc == Instruction::FCmp) {
2157 if (!Val0->getType()->isFPOrFPVectorTy())
2158 return Error(ID.Loc, "fcmp requires floating point operands");
2159 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2161 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2162 if (!Val0->getType()->isIntOrIntVectorTy() &&
2163 !Val0->getType()->isPointerTy())
2164 return Error(ID.Loc, "icmp requires pointer or integer operands");
2165 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2167 ID.Kind = ValID::t_Constant;
2171 // Binary Operators.
2173 case lltok::kw_fadd:
2175 case lltok::kw_fsub:
2177 case lltok::kw_fmul:
2178 case lltok::kw_udiv:
2179 case lltok::kw_sdiv:
2180 case lltok::kw_fdiv:
2181 case lltok::kw_urem:
2182 case lltok::kw_srem:
2183 case lltok::kw_frem:
2185 case lltok::kw_lshr:
2186 case lltok::kw_ashr: {
2190 unsigned Opc = Lex.getUIntVal();
2191 Constant *Val0, *Val1;
2193 LocTy ModifierLoc = Lex.getLoc();
2194 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2195 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2196 if (EatIfPresent(lltok::kw_nuw))
2198 if (EatIfPresent(lltok::kw_nsw)) {
2200 if (EatIfPresent(lltok::kw_nuw))
2203 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2204 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2205 if (EatIfPresent(lltok::kw_exact))
2208 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2209 ParseGlobalTypeAndValue(Val0) ||
2210 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2211 ParseGlobalTypeAndValue(Val1) ||
2212 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2214 if (Val0->getType() != Val1->getType())
2215 return Error(ID.Loc, "operands of constexpr must have same type");
2216 if (!Val0->getType()->isIntOrIntVectorTy()) {
2218 return Error(ModifierLoc, "nuw only applies to integer operations");
2220 return Error(ModifierLoc, "nsw only applies to integer operations");
2222 // Check that the type is valid for the operator.
2224 case Instruction::Add:
2225 case Instruction::Sub:
2226 case Instruction::Mul:
2227 case Instruction::UDiv:
2228 case Instruction::SDiv:
2229 case Instruction::URem:
2230 case Instruction::SRem:
2231 case Instruction::Shl:
2232 case Instruction::AShr:
2233 case Instruction::LShr:
2234 if (!Val0->getType()->isIntOrIntVectorTy())
2235 return Error(ID.Loc, "constexpr requires integer operands");
2237 case Instruction::FAdd:
2238 case Instruction::FSub:
2239 case Instruction::FMul:
2240 case Instruction::FDiv:
2241 case Instruction::FRem:
2242 if (!Val0->getType()->isFPOrFPVectorTy())
2243 return Error(ID.Loc, "constexpr requires fp operands");
2245 default: llvm_unreachable("Unknown binary operator!");
2248 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2249 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2250 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2251 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2253 ID.Kind = ValID::t_Constant;
2257 // Logical Operations
2260 case lltok::kw_xor: {
2261 unsigned Opc = Lex.getUIntVal();
2262 Constant *Val0, *Val1;
2264 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2265 ParseGlobalTypeAndValue(Val0) ||
2266 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2267 ParseGlobalTypeAndValue(Val1) ||
2268 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2270 if (Val0->getType() != Val1->getType())
2271 return Error(ID.Loc, "operands of constexpr must have same type");
2272 if (!Val0->getType()->isIntOrIntVectorTy())
2273 return Error(ID.Loc,
2274 "constexpr requires integer or integer vector operands");
2275 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2276 ID.Kind = ValID::t_Constant;
2280 case lltok::kw_getelementptr:
2281 case lltok::kw_shufflevector:
2282 case lltok::kw_insertelement:
2283 case lltok::kw_extractelement:
2284 case lltok::kw_select: {
2285 unsigned Opc = Lex.getUIntVal();
2286 SmallVector<Constant*, 16> Elts;
2287 bool InBounds = false;
2289 if (Opc == Instruction::GetElementPtr)
2290 InBounds = EatIfPresent(lltok::kw_inbounds);
2291 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2292 ParseGlobalValueVector(Elts) ||
2293 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2296 if (Opc == Instruction::GetElementPtr) {
2297 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2298 return Error(ID.Loc, "getelementptr requires pointer operand");
2300 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2301 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2302 return Error(ID.Loc, "invalid indices for getelementptr");
2303 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2305 } else if (Opc == Instruction::Select) {
2306 if (Elts.size() != 3)
2307 return Error(ID.Loc, "expected three operands to select");
2308 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2310 return Error(ID.Loc, Reason);
2311 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2312 } else if (Opc == Instruction::ShuffleVector) {
2313 if (Elts.size() != 3)
2314 return Error(ID.Loc, "expected three operands to shufflevector");
2315 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2316 return Error(ID.Loc, "invalid operands to shufflevector");
2318 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2319 } else if (Opc == Instruction::ExtractElement) {
2320 if (Elts.size() != 2)
2321 return Error(ID.Loc, "expected two operands to extractelement");
2322 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2323 return Error(ID.Loc, "invalid extractelement operands");
2324 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2326 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2327 if (Elts.size() != 3)
2328 return Error(ID.Loc, "expected three operands to insertelement");
2329 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2330 return Error(ID.Loc, "invalid insertelement operands");
2332 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2335 ID.Kind = ValID::t_Constant;
2344 /// ParseGlobalValue - Parse a global value with the specified type.
2345 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2349 bool Parsed = ParseValID(ID) ||
2350 ConvertValIDToValue(Ty, ID, V, NULL);
2351 if (V && !(C = dyn_cast<Constant>(V)))
2352 return Error(ID.Loc, "global values must be constants");
2356 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2358 return ParseType(Ty) ||
2359 ParseGlobalValue(Ty, V);
2362 /// ParseGlobalValueVector
2364 /// ::= TypeAndValue (',' TypeAndValue)*
2365 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2367 if (Lex.getKind() == lltok::rbrace ||
2368 Lex.getKind() == lltok::rsquare ||
2369 Lex.getKind() == lltok::greater ||
2370 Lex.getKind() == lltok::rparen)
2374 if (ParseGlobalTypeAndValue(C)) return true;
2377 while (EatIfPresent(lltok::comma)) {
2378 if (ParseGlobalTypeAndValue(C)) return true;
2385 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2386 assert(Lex.getKind() == lltok::lbrace);
2389 SmallVector<Value*, 16> Elts;
2390 if (ParseMDNodeVector(Elts, PFS) ||
2391 ParseToken(lltok::rbrace, "expected end of metadata node"))
2394 ID.MDNodeVal = MDNode::get(Context, Elts);
2395 ID.Kind = ValID::t_MDNode;
2399 /// ParseMetadataValue
2403 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2404 assert(Lex.getKind() == lltok::exclaim);
2409 if (Lex.getKind() == lltok::lbrace)
2410 return ParseMetadataListValue(ID, PFS);
2412 // Standalone metadata reference
2414 if (Lex.getKind() == lltok::APSInt) {
2415 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2416 ID.Kind = ValID::t_MDNode;
2421 // ::= '!' STRINGCONSTANT
2422 if (ParseMDString(ID.MDStringVal)) return true;
2423 ID.Kind = ValID::t_MDString;
2428 //===----------------------------------------------------------------------===//
2429 // Function Parsing.
2430 //===----------------------------------------------------------------------===//
2432 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2433 PerFunctionState *PFS) {
2434 if (Ty->isFunctionTy())
2435 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2438 default: llvm_unreachable("Unknown ValID!");
2439 case ValID::t_LocalID:
2440 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2441 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2443 case ValID::t_LocalName:
2444 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2445 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2447 case ValID::t_InlineAsm: {
2448 PointerType *PTy = dyn_cast<PointerType>(Ty);
2450 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2451 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2452 return Error(ID.Loc, "invalid type for inline asm constraint string");
2453 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2456 case ValID::t_MDNode:
2457 if (!Ty->isMetadataTy())
2458 return Error(ID.Loc, "metadata value must have metadata type");
2461 case ValID::t_MDString:
2462 if (!Ty->isMetadataTy())
2463 return Error(ID.Loc, "metadata value must have metadata type");
2466 case ValID::t_GlobalName:
2467 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2469 case ValID::t_GlobalID:
2470 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2472 case ValID::t_APSInt:
2473 if (!Ty->isIntegerTy())
2474 return Error(ID.Loc, "integer constant must have integer type");
2475 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2476 V = ConstantInt::get(Context, ID.APSIntVal);
2478 case ValID::t_APFloat:
2479 if (!Ty->isFloatingPointTy() ||
2480 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2481 return Error(ID.Loc, "floating point constant invalid for type");
2483 // The lexer has no type info, so builds all float and double FP constants
2484 // as double. Fix this here. Long double does not need this.
2485 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2488 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2491 V = ConstantFP::get(Context, ID.APFloatVal);
2493 if (V->getType() != Ty)
2494 return Error(ID.Loc, "floating point constant does not have type '" +
2495 getTypeString(Ty) + "'");
2499 if (!Ty->isPointerTy())
2500 return Error(ID.Loc, "null must be a pointer type");
2501 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2503 case ValID::t_Undef:
2504 // FIXME: LabelTy should not be a first-class type.
2505 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2506 return Error(ID.Loc, "invalid type for undef constant");
2507 V = UndefValue::get(Ty);
2509 case ValID::t_EmptyArray:
2510 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2511 return Error(ID.Loc, "invalid empty array initializer");
2512 V = UndefValue::get(Ty);
2515 // FIXME: LabelTy should not be a first-class type.
2516 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2517 return Error(ID.Loc, "invalid type for null constant");
2518 V = Constant::getNullValue(Ty);
2520 case ValID::t_Constant:
2521 if (ID.ConstantVal->getType() != Ty)
2522 return Error(ID.Loc, "constant expression type mismatch");
2526 case ValID::t_ConstantStruct:
2527 case ValID::t_PackedConstantStruct:
2528 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2529 if (ST->getNumElements() != ID.UIntVal)
2530 return Error(ID.Loc,
2531 "initializer with struct type has wrong # elements");
2532 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2533 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2535 // Verify that the elements are compatible with the structtype.
2536 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2537 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2538 return Error(ID.Loc, "element " + Twine(i) +
2539 " of struct initializer doesn't match struct element type");
2541 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2544 return Error(ID.Loc, "constant expression type mismatch");
2549 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2552 return ParseValID(ID, PFS) ||
2553 ConvertValIDToValue(Ty, ID, V, PFS);
2556 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2558 return ParseType(Ty) ||
2559 ParseValue(Ty, V, PFS);
2562 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2563 PerFunctionState &PFS) {
2566 if (ParseTypeAndValue(V, PFS)) return true;
2567 if (!isa<BasicBlock>(V))
2568 return Error(Loc, "expected a basic block");
2569 BB = cast<BasicBlock>(V);
2575 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2576 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2577 /// OptionalAlign OptGC
2578 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2579 // Parse the linkage.
2580 LocTy LinkageLoc = Lex.getLoc();
2583 unsigned Visibility, RetAttrs;
2586 LocTy RetTypeLoc = Lex.getLoc();
2587 if (ParseOptionalLinkage(Linkage) ||
2588 ParseOptionalVisibility(Visibility) ||
2589 ParseOptionalCallingConv(CC) ||
2590 ParseOptionalAttrs(RetAttrs, 1) ||
2591 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2594 // Verify that the linkage is ok.
2595 switch ((GlobalValue::LinkageTypes)Linkage) {
2596 case GlobalValue::ExternalLinkage:
2597 break; // always ok.
2598 case GlobalValue::DLLImportLinkage:
2599 case GlobalValue::ExternalWeakLinkage:
2601 return Error(LinkageLoc, "invalid linkage for function definition");
2603 case GlobalValue::PrivateLinkage:
2604 case GlobalValue::LinkerPrivateLinkage:
2605 case GlobalValue::LinkerPrivateWeakLinkage:
2606 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2607 case GlobalValue::InternalLinkage:
2608 case GlobalValue::AvailableExternallyLinkage:
2609 case GlobalValue::LinkOnceAnyLinkage:
2610 case GlobalValue::LinkOnceODRLinkage:
2611 case GlobalValue::WeakAnyLinkage:
2612 case GlobalValue::WeakODRLinkage:
2613 case GlobalValue::DLLExportLinkage:
2615 return Error(LinkageLoc, "invalid linkage for function declaration");
2617 case GlobalValue::AppendingLinkage:
2618 case GlobalValue::CommonLinkage:
2619 return Error(LinkageLoc, "invalid function linkage type");
2622 if (!FunctionType::isValidReturnType(RetType))
2623 return Error(RetTypeLoc, "invalid function return type");
2625 LocTy NameLoc = Lex.getLoc();
2627 std::string FunctionName;
2628 if (Lex.getKind() == lltok::GlobalVar) {
2629 FunctionName = Lex.getStrVal();
2630 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2631 unsigned NameID = Lex.getUIntVal();
2633 if (NameID != NumberedVals.size())
2634 return TokError("function expected to be numbered '%" +
2635 Twine(NumberedVals.size()) + "'");
2637 return TokError("expected function name");
2642 if (Lex.getKind() != lltok::lparen)
2643 return TokError("expected '(' in function argument list");
2645 SmallVector<ArgInfo, 8> ArgList;
2648 std::string Section;
2652 LocTy UnnamedAddrLoc;
2654 if (ParseArgumentList(ArgList, isVarArg) ||
2655 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2657 ParseOptionalAttrs(FuncAttrs, 2) ||
2658 (EatIfPresent(lltok::kw_section) &&
2659 ParseStringConstant(Section)) ||
2660 ParseOptionalAlignment(Alignment) ||
2661 (EatIfPresent(lltok::kw_gc) &&
2662 ParseStringConstant(GC)))
2665 // If the alignment was parsed as an attribute, move to the alignment field.
2666 if (FuncAttrs & Attribute::Alignment) {
2667 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2668 FuncAttrs &= ~Attribute::Alignment;
2671 // Okay, if we got here, the function is syntactically valid. Convert types
2672 // and do semantic checks.
2673 std::vector<Type*> ParamTypeList;
2674 SmallVector<AttributeWithIndex, 8> Attrs;
2676 if (RetAttrs != Attribute::None)
2677 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2679 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2680 ParamTypeList.push_back(ArgList[i].Ty);
2681 if (ArgList[i].Attrs != Attribute::None)
2682 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2685 if (FuncAttrs != Attribute::None)
2686 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2688 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2690 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2691 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2694 FunctionType::get(RetType, ParamTypeList, isVarArg);
2695 PointerType *PFT = PointerType::getUnqual(FT);
2698 if (!FunctionName.empty()) {
2699 // If this was a definition of a forward reference, remove the definition
2700 // from the forward reference table and fill in the forward ref.
2701 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2702 ForwardRefVals.find(FunctionName);
2703 if (FRVI != ForwardRefVals.end()) {
2704 Fn = M->getFunction(FunctionName);
2705 if (Fn->getType() != PFT)
2706 return Error(FRVI->second.second, "invalid forward reference to "
2707 "function '" + FunctionName + "' with wrong type!");
2709 ForwardRefVals.erase(FRVI);
2710 } else if ((Fn = M->getFunction(FunctionName))) {
2711 // Reject redefinitions.
2712 return Error(NameLoc, "invalid redefinition of function '" +
2713 FunctionName + "'");
2714 } else if (M->getNamedValue(FunctionName)) {
2715 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2719 // If this is a definition of a forward referenced function, make sure the
2721 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2722 = ForwardRefValIDs.find(NumberedVals.size());
2723 if (I != ForwardRefValIDs.end()) {
2724 Fn = cast<Function>(I->second.first);
2725 if (Fn->getType() != PFT)
2726 return Error(NameLoc, "type of definition and forward reference of '@" +
2727 Twine(NumberedVals.size()) + "' disagree");
2728 ForwardRefValIDs.erase(I);
2733 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2734 else // Move the forward-reference to the correct spot in the module.
2735 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2737 if (FunctionName.empty())
2738 NumberedVals.push_back(Fn);
2740 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2741 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2742 Fn->setCallingConv(CC);
2743 Fn->setAttributes(PAL);
2744 Fn->setUnnamedAddr(UnnamedAddr);
2745 Fn->setAlignment(Alignment);
2746 Fn->setSection(Section);
2747 if (!GC.empty()) Fn->setGC(GC.c_str());
2749 // Add all of the arguments we parsed to the function.
2750 Function::arg_iterator ArgIt = Fn->arg_begin();
2751 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2752 // If the argument has a name, insert it into the argument symbol table.
2753 if (ArgList[i].Name.empty()) continue;
2755 // Set the name, if it conflicted, it will be auto-renamed.
2756 ArgIt->setName(ArgList[i].Name);
2758 if (ArgIt->getName() != ArgList[i].Name)
2759 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2760 ArgList[i].Name + "'");
2767 /// ParseFunctionBody
2768 /// ::= '{' BasicBlock+ '}'
2770 bool LLParser::ParseFunctionBody(Function &Fn) {
2771 if (Lex.getKind() != lltok::lbrace)
2772 return TokError("expected '{' in function body");
2773 Lex.Lex(); // eat the {.
2775 int FunctionNumber = -1;
2776 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2778 PerFunctionState PFS(*this, Fn, FunctionNumber);
2780 // We need at least one basic block.
2781 if (Lex.getKind() == lltok::rbrace)
2782 return TokError("function body requires at least one basic block");
2784 while (Lex.getKind() != lltok::rbrace)
2785 if (ParseBasicBlock(PFS)) return true;
2790 // Verify function is ok.
2791 return PFS.FinishFunction();
2795 /// ::= LabelStr? Instruction*
2796 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2797 // If this basic block starts out with a name, remember it.
2799 LocTy NameLoc = Lex.getLoc();
2800 if (Lex.getKind() == lltok::LabelStr) {
2801 Name = Lex.getStrVal();
2805 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2806 if (BB == 0) return true;
2808 std::string NameStr;
2810 // Parse the instructions in this block until we get a terminator.
2812 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2814 // This instruction may have three possibilities for a name: a) none
2815 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2816 LocTy NameLoc = Lex.getLoc();
2820 if (Lex.getKind() == lltok::LocalVarID) {
2821 NameID = Lex.getUIntVal();
2823 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2825 } else if (Lex.getKind() == lltok::LocalVar) {
2826 NameStr = Lex.getStrVal();
2828 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2832 switch (ParseInstruction(Inst, BB, PFS)) {
2833 default: assert(0 && "Unknown ParseInstruction result!");
2834 case InstError: return true;
2836 BB->getInstList().push_back(Inst);
2838 // With a normal result, we check to see if the instruction is followed by
2839 // a comma and metadata.
2840 if (EatIfPresent(lltok::comma))
2841 if (ParseInstructionMetadata(Inst, &PFS))
2844 case InstExtraComma:
2845 BB->getInstList().push_back(Inst);
2847 // If the instruction parser ate an extra comma at the end of it, it
2848 // *must* be followed by metadata.
2849 if (ParseInstructionMetadata(Inst, &PFS))
2854 // Set the name on the instruction.
2855 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2856 } while (!isa<TerminatorInst>(Inst));
2861 //===----------------------------------------------------------------------===//
2862 // Instruction Parsing.
2863 //===----------------------------------------------------------------------===//
2865 /// ParseInstruction - Parse one of the many different instructions.
2867 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2868 PerFunctionState &PFS) {
2869 lltok::Kind Token = Lex.getKind();
2870 if (Token == lltok::Eof)
2871 return TokError("found end of file when expecting more instructions");
2872 LocTy Loc = Lex.getLoc();
2873 unsigned KeywordVal = Lex.getUIntVal();
2874 Lex.Lex(); // Eat the keyword.
2877 default: return Error(Loc, "expected instruction opcode");
2878 // Terminator Instructions.
2879 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2880 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2881 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2882 case lltok::kw_br: return ParseBr(Inst, PFS);
2883 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2884 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2885 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2886 case lltok::kw_resume: return ParseResume(Inst, PFS);
2887 // Binary Operators.
2891 case lltok::kw_shl: {
2892 bool NUW = EatIfPresent(lltok::kw_nuw);
2893 bool NSW = EatIfPresent(lltok::kw_nsw);
2894 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2896 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2898 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2899 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2902 case lltok::kw_fadd:
2903 case lltok::kw_fsub:
2904 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2906 case lltok::kw_sdiv:
2907 case lltok::kw_udiv:
2908 case lltok::kw_lshr:
2909 case lltok::kw_ashr: {
2910 bool Exact = EatIfPresent(lltok::kw_exact);
2912 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2913 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2917 case lltok::kw_urem:
2918 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2919 case lltok::kw_fdiv:
2920 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2923 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2924 case lltok::kw_icmp:
2925 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2927 case lltok::kw_trunc:
2928 case lltok::kw_zext:
2929 case lltok::kw_sext:
2930 case lltok::kw_fptrunc:
2931 case lltok::kw_fpext:
2932 case lltok::kw_bitcast:
2933 case lltok::kw_uitofp:
2934 case lltok::kw_sitofp:
2935 case lltok::kw_fptoui:
2936 case lltok::kw_fptosi:
2937 case lltok::kw_inttoptr:
2938 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2940 case lltok::kw_select: return ParseSelect(Inst, PFS);
2941 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2942 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2943 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2944 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2945 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2946 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
2947 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2948 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2950 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2951 case lltok::kw_load: return ParseLoad(Inst, PFS);
2952 case lltok::kw_store: return ParseStore(Inst, PFS);
2953 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
2954 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
2955 case lltok::kw_fence: return ParseFence(Inst, PFS);
2956 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2957 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2958 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2962 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2963 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2964 if (Opc == Instruction::FCmp) {
2965 switch (Lex.getKind()) {
2966 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2967 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2968 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2969 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2970 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2971 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2972 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2973 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2974 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2975 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2976 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2977 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2978 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2979 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2980 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2981 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2982 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2985 switch (Lex.getKind()) {
2986 default: TokError("expected icmp predicate (e.g. 'eq')");
2987 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2988 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2989 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2990 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2991 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2992 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2993 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2994 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2995 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2996 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3003 //===----------------------------------------------------------------------===//
3004 // Terminator Instructions.
3005 //===----------------------------------------------------------------------===//
3007 /// ParseRet - Parse a return instruction.
3008 /// ::= 'ret' void (',' !dbg, !1)*
3009 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3010 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3011 PerFunctionState &PFS) {
3012 SMLoc TypeLoc = Lex.getLoc();
3014 if (ParseType(Ty, true /*void allowed*/)) return true;
3016 Type *ResType = PFS.getFunction().getReturnType();
3018 if (Ty->isVoidTy()) {
3019 if (!ResType->isVoidTy())
3020 return Error(TypeLoc, "value doesn't match function result type '" +
3021 getTypeString(ResType) + "'");
3023 Inst = ReturnInst::Create(Context);
3028 if (ParseValue(Ty, RV, PFS)) return true;
3030 if (ResType != RV->getType())
3031 return Error(TypeLoc, "value doesn't match function result type '" +
3032 getTypeString(ResType) + "'");
3034 Inst = ReturnInst::Create(Context, RV);
3040 /// ::= 'br' TypeAndValue
3041 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3042 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3045 BasicBlock *Op1, *Op2;
3046 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3048 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3049 Inst = BranchInst::Create(BB);
3053 if (Op0->getType() != Type::getInt1Ty(Context))
3054 return Error(Loc, "branch condition must have 'i1' type");
3056 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3057 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3058 ParseToken(lltok::comma, "expected ',' after true destination") ||
3059 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3062 Inst = BranchInst::Create(Op1, Op2, Op0);
3068 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3070 /// ::= (TypeAndValue ',' TypeAndValue)*
3071 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3072 LocTy CondLoc, BBLoc;
3074 BasicBlock *DefaultBB;
3075 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3076 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3077 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3078 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3081 if (!Cond->getType()->isIntegerTy())
3082 return Error(CondLoc, "switch condition must have integer type");
3084 // Parse the jump table pairs.
3085 SmallPtrSet<Value*, 32> SeenCases;
3086 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3087 while (Lex.getKind() != lltok::rsquare) {
3091 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3092 ParseToken(lltok::comma, "expected ',' after case value") ||
3093 ParseTypeAndBasicBlock(DestBB, PFS))
3096 if (!SeenCases.insert(Constant))
3097 return Error(CondLoc, "duplicate case value in switch");
3098 if (!isa<ConstantInt>(Constant))
3099 return Error(CondLoc, "case value is not a constant integer");
3101 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3104 Lex.Lex(); // Eat the ']'.
3106 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3107 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3108 SI->addCase(Table[i].first, Table[i].second);
3115 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3116 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3119 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3120 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3121 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3124 if (!Address->getType()->isPointerTy())
3125 return Error(AddrLoc, "indirectbr address must have pointer type");
3127 // Parse the destination list.
3128 SmallVector<BasicBlock*, 16> DestList;
3130 if (Lex.getKind() != lltok::rsquare) {
3132 if (ParseTypeAndBasicBlock(DestBB, PFS))
3134 DestList.push_back(DestBB);
3136 while (EatIfPresent(lltok::comma)) {
3137 if (ParseTypeAndBasicBlock(DestBB, PFS))
3139 DestList.push_back(DestBB);
3143 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3146 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3147 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3148 IBI->addDestination(DestList[i]);
3155 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3156 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3157 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3158 LocTy CallLoc = Lex.getLoc();
3159 unsigned RetAttrs, FnAttrs;
3164 SmallVector<ParamInfo, 16> ArgList;
3166 BasicBlock *NormalBB, *UnwindBB;
3167 if (ParseOptionalCallingConv(CC) ||
3168 ParseOptionalAttrs(RetAttrs, 1) ||
3169 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3170 ParseValID(CalleeID) ||
3171 ParseParameterList(ArgList, PFS) ||
3172 ParseOptionalAttrs(FnAttrs, 2) ||
3173 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3174 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3175 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3176 ParseTypeAndBasicBlock(UnwindBB, PFS))
3179 // If RetType is a non-function pointer type, then this is the short syntax
3180 // for the call, which means that RetType is just the return type. Infer the
3181 // rest of the function argument types from the arguments that are present.
3182 PointerType *PFTy = 0;
3183 FunctionType *Ty = 0;
3184 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3185 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3186 // Pull out the types of all of the arguments...
3187 std::vector<Type*> ParamTypes;
3188 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3189 ParamTypes.push_back(ArgList[i].V->getType());
3191 if (!FunctionType::isValidReturnType(RetType))
3192 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3194 Ty = FunctionType::get(RetType, ParamTypes, false);
3195 PFTy = PointerType::getUnqual(Ty);
3198 // Look up the callee.
3200 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3202 // Set up the Attributes for the function.
3203 SmallVector<AttributeWithIndex, 8> Attrs;
3204 if (RetAttrs != Attribute::None)
3205 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3207 SmallVector<Value*, 8> Args;
3209 // Loop through FunctionType's arguments and ensure they are specified
3210 // correctly. Also, gather any parameter attributes.
3211 FunctionType::param_iterator I = Ty->param_begin();
3212 FunctionType::param_iterator E = Ty->param_end();
3213 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3214 Type *ExpectedTy = 0;
3217 } else if (!Ty->isVarArg()) {
3218 return Error(ArgList[i].Loc, "too many arguments specified");
3221 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3222 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3223 getTypeString(ExpectedTy) + "'");
3224 Args.push_back(ArgList[i].V);
3225 if (ArgList[i].Attrs != Attribute::None)
3226 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3230 return Error(CallLoc, "not enough parameters specified for call");
3232 if (FnAttrs != Attribute::None)
3233 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3235 // Finish off the Attributes and check them
3236 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3238 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3239 II->setCallingConv(CC);
3240 II->setAttributes(PAL);
3246 /// ::= 'resume' TypeAndValue
3247 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3248 Value *Exn; LocTy ExnLoc;
3249 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3252 ResumeInst *RI = ResumeInst::Create(Exn);
3257 //===----------------------------------------------------------------------===//
3258 // Binary Operators.
3259 //===----------------------------------------------------------------------===//
3262 /// ::= ArithmeticOps TypeAndValue ',' Value
3264 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3265 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3266 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3267 unsigned Opc, unsigned OperandType) {
3268 LocTy Loc; Value *LHS, *RHS;
3269 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3270 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3271 ParseValue(LHS->getType(), RHS, PFS))
3275 switch (OperandType) {
3276 default: llvm_unreachable("Unknown operand type!");
3277 case 0: // int or FP.
3278 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3279 LHS->getType()->isFPOrFPVectorTy();
3281 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3282 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3286 return Error(Loc, "invalid operand type for instruction");
3288 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3293 /// ::= ArithmeticOps TypeAndValue ',' Value {
3294 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3296 LocTy Loc; Value *LHS, *RHS;
3297 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3298 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3299 ParseValue(LHS->getType(), RHS, PFS))
3302 if (!LHS->getType()->isIntOrIntVectorTy())
3303 return Error(Loc,"instruction requires integer or integer vector operands");
3305 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3311 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3312 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3313 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3315 // Parse the integer/fp comparison predicate.
3319 if (ParseCmpPredicate(Pred, Opc) ||
3320 ParseTypeAndValue(LHS, Loc, PFS) ||
3321 ParseToken(lltok::comma, "expected ',' after compare value") ||
3322 ParseValue(LHS->getType(), RHS, PFS))
3325 if (Opc == Instruction::FCmp) {
3326 if (!LHS->getType()->isFPOrFPVectorTy())
3327 return Error(Loc, "fcmp requires floating point operands");
3328 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3330 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3331 if (!LHS->getType()->isIntOrIntVectorTy() &&
3332 !LHS->getType()->isPointerTy())
3333 return Error(Loc, "icmp requires integer operands");
3334 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3339 //===----------------------------------------------------------------------===//
3340 // Other Instructions.
3341 //===----------------------------------------------------------------------===//
3345 /// ::= CastOpc TypeAndValue 'to' Type
3346 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3351 if (ParseTypeAndValue(Op, Loc, PFS) ||
3352 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3356 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3357 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3358 return Error(Loc, "invalid cast opcode for cast from '" +
3359 getTypeString(Op->getType()) + "' to '" +
3360 getTypeString(DestTy) + "'");
3362 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3367 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3368 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3370 Value *Op0, *Op1, *Op2;
3371 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3372 ParseToken(lltok::comma, "expected ',' after select condition") ||
3373 ParseTypeAndValue(Op1, PFS) ||
3374 ParseToken(lltok::comma, "expected ',' after select value") ||
3375 ParseTypeAndValue(Op2, PFS))
3378 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3379 return Error(Loc, Reason);
3381 Inst = SelectInst::Create(Op0, Op1, Op2);
3386 /// ::= 'va_arg' TypeAndValue ',' Type
3387 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3391 if (ParseTypeAndValue(Op, PFS) ||
3392 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3393 ParseType(EltTy, TypeLoc))
3396 if (!EltTy->isFirstClassType())
3397 return Error(TypeLoc, "va_arg requires operand with first class type");
3399 Inst = new VAArgInst(Op, EltTy);
3403 /// ParseExtractElement
3404 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3405 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3408 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3409 ParseToken(lltok::comma, "expected ',' after extract value") ||
3410 ParseTypeAndValue(Op1, PFS))
3413 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3414 return Error(Loc, "invalid extractelement operands");
3416 Inst = ExtractElementInst::Create(Op0, Op1);
3420 /// ParseInsertElement
3421 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3422 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3424 Value *Op0, *Op1, *Op2;
3425 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3426 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3427 ParseTypeAndValue(Op1, PFS) ||
3428 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3429 ParseTypeAndValue(Op2, PFS))
3432 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3433 return Error(Loc, "invalid insertelement operands");
3435 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3439 /// ParseShuffleVector
3440 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3441 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3443 Value *Op0, *Op1, *Op2;
3444 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3446 ParseTypeAndValue(Op1, PFS) ||
3447 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3448 ParseTypeAndValue(Op2, PFS))
3451 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3452 return Error(Loc, "invalid extractelement operands");
3454 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3459 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3460 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3461 Type *Ty = 0; LocTy TypeLoc;
3464 if (ParseType(Ty, TypeLoc) ||
3465 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3466 ParseValue(Ty, Op0, PFS) ||
3467 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3468 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3469 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3472 bool AteExtraComma = false;
3473 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3475 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3477 if (!EatIfPresent(lltok::comma))
3480 if (Lex.getKind() == lltok::MetadataVar) {
3481 AteExtraComma = true;
3485 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3486 ParseValue(Ty, Op0, PFS) ||
3487 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3488 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3489 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3493 if (!Ty->isFirstClassType())
3494 return Error(TypeLoc, "phi node must have first class type");
3496 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3497 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3498 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3500 return AteExtraComma ? InstExtraComma : InstNormal;
3504 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3506 /// ::= 'catch' TypeAndValue
3508 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3509 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3510 Type *Ty = 0; LocTy TyLoc;
3511 Value *PersFn; LocTy PersFnLoc;
3513 if (ParseType(Ty, TyLoc) ||
3514 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3515 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3518 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3519 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3521 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3522 LandingPadInst::ClauseType CT;
3523 if (EatIfPresent(lltok::kw_catch))
3524 CT = LandingPadInst::Catch;
3525 else if (EatIfPresent(lltok::kw_filter))
3526 CT = LandingPadInst::Filter;
3528 return TokError("expected 'catch' or 'filter' clause type");
3530 Value *V; LocTy VLoc;
3531 if (ParseTypeAndValue(V, VLoc, PFS)) {
3536 // A 'catch' type expects a non-array constant. A filter clause expects an
3538 if (CT == LandingPadInst::Catch) {
3539 if (isa<ArrayType>(V->getType()))
3540 Error(VLoc, "'catch' clause has an invalid type");
3542 if (!isa<ArrayType>(V->getType()))
3543 Error(VLoc, "'filter' clause has an invalid type");
3554 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3555 /// ParameterList OptionalAttrs
3556 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3558 unsigned RetAttrs, FnAttrs;
3563 SmallVector<ParamInfo, 16> ArgList;
3564 LocTy CallLoc = Lex.getLoc();
3566 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3567 ParseOptionalCallingConv(CC) ||
3568 ParseOptionalAttrs(RetAttrs, 1) ||
3569 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3570 ParseValID(CalleeID) ||
3571 ParseParameterList(ArgList, PFS) ||
3572 ParseOptionalAttrs(FnAttrs, 2))
3575 // If RetType is a non-function pointer type, then this is the short syntax
3576 // for the call, which means that RetType is just the return type. Infer the
3577 // rest of the function argument types from the arguments that are present.
3578 PointerType *PFTy = 0;
3579 FunctionType *Ty = 0;
3580 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3581 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3582 // Pull out the types of all of the arguments...
3583 std::vector<Type*> ParamTypes;
3584 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3585 ParamTypes.push_back(ArgList[i].V->getType());
3587 if (!FunctionType::isValidReturnType(RetType))
3588 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3590 Ty = FunctionType::get(RetType, ParamTypes, false);
3591 PFTy = PointerType::getUnqual(Ty);
3594 // Look up the callee.
3596 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3598 // Set up the Attributes for the function.
3599 SmallVector<AttributeWithIndex, 8> Attrs;
3600 if (RetAttrs != Attribute::None)
3601 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3603 SmallVector<Value*, 8> Args;
3605 // Loop through FunctionType's arguments and ensure they are specified
3606 // correctly. Also, gather any parameter attributes.
3607 FunctionType::param_iterator I = Ty->param_begin();
3608 FunctionType::param_iterator E = Ty->param_end();
3609 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3610 Type *ExpectedTy = 0;
3613 } else if (!Ty->isVarArg()) {
3614 return Error(ArgList[i].Loc, "too many arguments specified");
3617 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3618 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3619 getTypeString(ExpectedTy) + "'");
3620 Args.push_back(ArgList[i].V);
3621 if (ArgList[i].Attrs != Attribute::None)
3622 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3626 return Error(CallLoc, "not enough parameters specified for call");
3628 if (FnAttrs != Attribute::None)
3629 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3631 // Finish off the Attributes and check them
3632 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3634 CallInst *CI = CallInst::Create(Callee, Args);
3635 CI->setTailCall(isTail);
3636 CI->setCallingConv(CC);
3637 CI->setAttributes(PAL);
3642 //===----------------------------------------------------------------------===//
3643 // Memory Instructions.
3644 //===----------------------------------------------------------------------===//
3647 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3648 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3651 unsigned Alignment = 0;
3653 if (ParseType(Ty)) return true;
3655 bool AteExtraComma = false;
3656 if (EatIfPresent(lltok::comma)) {
3657 if (Lex.getKind() == lltok::kw_align) {
3658 if (ParseOptionalAlignment(Alignment)) return true;
3659 } else if (Lex.getKind() == lltok::MetadataVar) {
3660 AteExtraComma = true;
3662 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3663 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3668 if (Size && !Size->getType()->isIntegerTy())
3669 return Error(SizeLoc, "element count must have integer type");
3671 Inst = new AllocaInst(Ty, Size, Alignment);
3672 return AteExtraComma ? InstExtraComma : InstNormal;
3676 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3677 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3678 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3679 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3680 Value *Val; LocTy Loc;
3681 unsigned Alignment = 0;
3682 bool AteExtraComma = false;
3683 bool isAtomic = false;
3684 AtomicOrdering Ordering = NotAtomic;
3685 SynchronizationScope Scope = CrossThread;
3687 if (Lex.getKind() == lltok::kw_atomic) {
3692 bool isVolatile = false;
3693 if (Lex.getKind() == lltok::kw_volatile) {
3698 if (ParseTypeAndValue(Val, Loc, PFS) ||
3699 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3700 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3703 if (!Val->getType()->isPointerTy() ||
3704 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3705 return Error(Loc, "load operand must be a pointer to a first class type");
3706 if (isAtomic && !Alignment)
3707 return Error(Loc, "atomic load must have explicit non-zero alignment");
3708 if (Ordering == Release || Ordering == AcquireRelease)
3709 return Error(Loc, "atomic load cannot use Release ordering");
3711 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3712 return AteExtraComma ? InstExtraComma : InstNormal;
3717 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3718 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3719 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3720 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3721 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3722 unsigned Alignment = 0;
3723 bool AteExtraComma = false;
3724 bool isAtomic = false;
3725 AtomicOrdering Ordering = NotAtomic;
3726 SynchronizationScope Scope = CrossThread;
3728 if (Lex.getKind() == lltok::kw_atomic) {
3733 bool isVolatile = false;
3734 if (Lex.getKind() == lltok::kw_volatile) {
3739 if (ParseTypeAndValue(Val, Loc, PFS) ||
3740 ParseToken(lltok::comma, "expected ',' after store operand") ||
3741 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3742 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3743 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3746 if (!Ptr->getType()->isPointerTy())
3747 return Error(PtrLoc, "store operand must be a pointer");
3748 if (!Val->getType()->isFirstClassType())
3749 return Error(Loc, "store operand must be a first class value");
3750 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3751 return Error(Loc, "stored value and pointer type do not match");
3752 if (isAtomic && !Alignment)
3753 return Error(Loc, "atomic store must have explicit non-zero alignment");
3754 if (Ordering == Acquire || Ordering == AcquireRelease)
3755 return Error(Loc, "atomic store cannot use Acquire ordering");
3757 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3758 return AteExtraComma ? InstExtraComma : InstNormal;
3762 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3763 /// 'singlethread'? AtomicOrdering
3764 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3765 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3766 bool AteExtraComma = false;
3767 AtomicOrdering Ordering = NotAtomic;
3768 SynchronizationScope Scope = CrossThread;
3769 bool isVolatile = false;
3771 if (EatIfPresent(lltok::kw_volatile))
3774 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3775 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3776 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3777 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3778 ParseTypeAndValue(New, NewLoc, PFS) ||
3779 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3782 if (Ordering == Unordered)
3783 return TokError("cmpxchg cannot be unordered");
3784 if (!Ptr->getType()->isPointerTy())
3785 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3786 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3787 return Error(CmpLoc, "compare value and pointer type do not match");
3788 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3789 return Error(NewLoc, "new value and pointer type do not match");
3790 if (!New->getType()->isIntegerTy())
3791 return Error(NewLoc, "cmpxchg operand must be an integer");
3792 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3793 if (Size < 8 || (Size & (Size - 1)))
3794 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3797 AtomicCmpXchgInst *CXI =
3798 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3799 CXI->setVolatile(isVolatile);
3801 return AteExtraComma ? InstExtraComma : InstNormal;
3805 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3806 /// 'singlethread'? AtomicOrdering
3807 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3808 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3809 bool AteExtraComma = false;
3810 AtomicOrdering Ordering = NotAtomic;
3811 SynchronizationScope Scope = CrossThread;
3812 bool isVolatile = false;
3813 AtomicRMWInst::BinOp Operation;
3815 if (EatIfPresent(lltok::kw_volatile))
3818 switch (Lex.getKind()) {
3819 default: return TokError("expected binary operation in atomicrmw");
3820 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3821 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3822 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3823 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3824 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3825 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3826 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3827 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3828 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3829 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3830 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3832 Lex.Lex(); // Eat the operation.
3834 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3835 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3836 ParseTypeAndValue(Val, ValLoc, PFS) ||
3837 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3840 if (Ordering == Unordered)
3841 return TokError("atomicrmw cannot be unordered");
3842 if (!Ptr->getType()->isPointerTy())
3843 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3844 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3845 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3846 if (!Val->getType()->isIntegerTy())
3847 return Error(ValLoc, "atomicrmw operand must be an integer");
3848 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3849 if (Size < 8 || (Size & (Size - 1)))
3850 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3853 AtomicRMWInst *RMWI =
3854 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3855 RMWI->setVolatile(isVolatile);
3857 return AteExtraComma ? InstExtraComma : InstNormal;
3861 /// ::= 'fence' 'singlethread'? AtomicOrdering
3862 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3863 AtomicOrdering Ordering = NotAtomic;
3864 SynchronizationScope Scope = CrossThread;
3865 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3868 if (Ordering == Unordered)
3869 return TokError("fence cannot be unordered");
3870 if (Ordering == Monotonic)
3871 return TokError("fence cannot be monotonic");
3873 Inst = new FenceInst(Context, Ordering, Scope);
3877 /// ParseGetElementPtr
3878 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3879 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3880 Value *Ptr, *Val; LocTy Loc, EltLoc;
3882 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3884 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3886 if (!Ptr->getType()->isPointerTy())
3887 return Error(Loc, "base of getelementptr must be a pointer");
3889 SmallVector<Value*, 16> Indices;
3890 bool AteExtraComma = false;
3891 while (EatIfPresent(lltok::comma)) {
3892 if (Lex.getKind() == lltok::MetadataVar) {
3893 AteExtraComma = true;
3896 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3897 if (!Val->getType()->isIntegerTy())
3898 return Error(EltLoc, "getelementptr index must be an integer");
3899 Indices.push_back(Val);
3902 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
3903 return Error(Loc, "invalid getelementptr indices");
3904 Inst = GetElementPtrInst::Create(Ptr, Indices);
3906 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3907 return AteExtraComma ? InstExtraComma : InstNormal;
3910 /// ParseExtractValue
3911 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3912 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3913 Value *Val; LocTy Loc;
3914 SmallVector<unsigned, 4> Indices;
3916 if (ParseTypeAndValue(Val, Loc, PFS) ||
3917 ParseIndexList(Indices, AteExtraComma))
3920 if (!Val->getType()->isAggregateType())
3921 return Error(Loc, "extractvalue operand must be aggregate type");
3923 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3924 return Error(Loc, "invalid indices for extractvalue");
3925 Inst = ExtractValueInst::Create(Val, Indices);
3926 return AteExtraComma ? InstExtraComma : InstNormal;
3929 /// ParseInsertValue
3930 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3931 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3932 Value *Val0, *Val1; LocTy Loc0, Loc1;
3933 SmallVector<unsigned, 4> Indices;
3935 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3936 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3937 ParseTypeAndValue(Val1, Loc1, PFS) ||
3938 ParseIndexList(Indices, AteExtraComma))
3941 if (!Val0->getType()->isAggregateType())
3942 return Error(Loc0, "insertvalue operand must be aggregate type");
3944 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
3945 return Error(Loc0, "invalid indices for insertvalue");
3946 Inst = InsertValueInst::Create(Val0, Val1, Indices);
3947 return AteExtraComma ? InstExtraComma : InstNormal;
3950 //===----------------------------------------------------------------------===//
3951 // Embedded metadata.
3952 //===----------------------------------------------------------------------===//
3954 /// ParseMDNodeVector
3955 /// ::= Element (',' Element)*
3957 /// ::= 'null' | TypeAndValue
3958 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3959 PerFunctionState *PFS) {
3960 // Check for an empty list.
3961 if (Lex.getKind() == lltok::rbrace)
3965 // Null is a special case since it is typeless.
3966 if (EatIfPresent(lltok::kw_null)) {
3972 if (ParseTypeAndValue(V, PFS)) return true;
3974 } while (EatIfPresent(lltok::comma));