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
123 // Upgrade to new EH scheme. N.B. This will go away in 3.1.
124 UpgradeExceptionHandling(M);
126 // Check debug info intrinsics.
127 CheckDebugInfoIntrinsics(M);
131 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
132 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
133 PerFunctionState *PFS) {
134 // Loop over all the references, resolving them.
135 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
138 if (Refs[i].first.Kind == ValID::t_LocalName)
139 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
141 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
142 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
143 return Error(Refs[i].first.Loc,
144 "cannot take address of numeric label after the function is defined");
146 Res = dyn_cast_or_null<BasicBlock>(
147 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
151 return Error(Refs[i].first.Loc,
152 "referenced value is not a basic block");
154 // Get the BlockAddress for this and update references to use it.
155 BlockAddress *BA = BlockAddress::get(TheFn, Res);
156 Refs[i].second->replaceAllUsesWith(BA);
157 Refs[i].second->eraseFromParent();
163 //===----------------------------------------------------------------------===//
164 // Top-Level Entities
165 //===----------------------------------------------------------------------===//
167 bool LLParser::ParseTopLevelEntities() {
169 switch (Lex.getKind()) {
170 default: return TokError("expected top-level entity");
171 case lltok::Eof: return false;
172 case lltok::kw_declare: if (ParseDeclare()) return true; break;
173 case lltok::kw_define: if (ParseDefine()) return true; break;
174 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
175 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
176 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
177 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
178 case lltok::LocalVar: if (ParseNamedType()) return true; break;
179 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
180 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
181 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
182 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
184 // The Global variable production with no name can have many different
185 // optional leading prefixes, the production is:
186 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
187 // OptionalAddrSpace OptionalUnNammedAddr
188 // ('constant'|'global') ...
189 case lltok::kw_private: // OptionalLinkage
190 case lltok::kw_linker_private: // OptionalLinkage
191 case lltok::kw_linker_private_weak: // OptionalLinkage
192 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
193 case lltok::kw_internal: // OptionalLinkage
194 case lltok::kw_weak: // OptionalLinkage
195 case lltok::kw_weak_odr: // OptionalLinkage
196 case lltok::kw_linkonce: // OptionalLinkage
197 case lltok::kw_linkonce_odr: // OptionalLinkage
198 case lltok::kw_appending: // OptionalLinkage
199 case lltok::kw_dllexport: // OptionalLinkage
200 case lltok::kw_common: // OptionalLinkage
201 case lltok::kw_dllimport: // OptionalLinkage
202 case lltok::kw_extern_weak: // OptionalLinkage
203 case lltok::kw_external: { // OptionalLinkage
204 unsigned Linkage, Visibility;
205 if (ParseOptionalLinkage(Linkage) ||
206 ParseOptionalVisibility(Visibility) ||
207 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
211 case lltok::kw_default: // OptionalVisibility
212 case lltok::kw_hidden: // OptionalVisibility
213 case lltok::kw_protected: { // OptionalVisibility
215 if (ParseOptionalVisibility(Visibility) ||
216 ParseGlobal("", SMLoc(), 0, false, Visibility))
221 case lltok::kw_thread_local: // OptionalThreadLocal
222 case lltok::kw_addrspace: // OptionalAddrSpace
223 case lltok::kw_constant: // GlobalType
224 case lltok::kw_global: // GlobalType
225 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
233 /// ::= 'module' 'asm' STRINGCONSTANT
234 bool LLParser::ParseModuleAsm() {
235 assert(Lex.getKind() == lltok::kw_module);
239 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
240 ParseStringConstant(AsmStr)) return true;
242 M->appendModuleInlineAsm(AsmStr);
247 /// ::= 'target' 'triple' '=' STRINGCONSTANT
248 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
249 bool LLParser::ParseTargetDefinition() {
250 assert(Lex.getKind() == lltok::kw_target);
253 default: return TokError("unknown target property");
254 case lltok::kw_triple:
256 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
257 ParseStringConstant(Str))
259 M->setTargetTriple(Str);
261 case lltok::kw_datalayout:
263 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
264 ParseStringConstant(Str))
266 M->setDataLayout(Str);
272 /// ::= 'deplibs' '=' '[' ']'
273 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
274 bool LLParser::ParseDepLibs() {
275 assert(Lex.getKind() == lltok::kw_deplibs);
277 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
278 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
281 if (EatIfPresent(lltok::rsquare))
285 if (ParseStringConstant(Str)) return true;
288 while (EatIfPresent(lltok::comma)) {
289 if (ParseStringConstant(Str)) return true;
293 return ParseToken(lltok::rsquare, "expected ']' at end of list");
296 /// ParseUnnamedType:
297 /// ::= LocalVarID '=' 'type' type
298 bool LLParser::ParseUnnamedType() {
299 LocTy TypeLoc = Lex.getLoc();
300 unsigned TypeID = Lex.getUIntVal();
301 Lex.Lex(); // eat LocalVarID;
303 if (ParseToken(lltok::equal, "expected '=' after name") ||
304 ParseToken(lltok::kw_type, "expected 'type' after '='"))
307 if (TypeID >= NumberedTypes.size())
308 NumberedTypes.resize(TypeID+1);
311 if (ParseStructDefinition(TypeLoc, "",
312 NumberedTypes[TypeID], Result)) return true;
314 if (!isa<StructType>(Result)) {
315 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
317 return Error(TypeLoc, "non-struct types may not be recursive");
318 Entry.first = Result;
319 Entry.second = SMLoc();
327 /// ::= LocalVar '=' 'type' type
328 bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
331 Lex.Lex(); // eat LocalVar.
333 if (ParseToken(lltok::equal, "expected '=' after name") ||
334 ParseToken(lltok::kw_type, "expected 'type' after name"))
338 if (ParseStructDefinition(NameLoc, Name,
339 NamedTypes[Name], Result)) return true;
341 if (!isa<StructType>(Result)) {
342 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
344 return Error(NameLoc, "non-struct types may not be recursive");
345 Entry.first = Result;
346 Entry.second = SMLoc();
354 /// ::= 'declare' FunctionHeader
355 bool LLParser::ParseDeclare() {
356 assert(Lex.getKind() == lltok::kw_declare);
360 return ParseFunctionHeader(F, false);
364 /// ::= 'define' FunctionHeader '{' ...
365 bool LLParser::ParseDefine() {
366 assert(Lex.getKind() == lltok::kw_define);
370 return ParseFunctionHeader(F, true) ||
371 ParseFunctionBody(*F);
377 bool LLParser::ParseGlobalType(bool &IsConstant) {
378 if (Lex.getKind() == lltok::kw_constant)
380 else if (Lex.getKind() == lltok::kw_global)
384 return TokError("expected 'global' or 'constant'");
390 /// ParseUnnamedGlobal:
391 /// OptionalVisibility ALIAS ...
392 /// OptionalLinkage OptionalVisibility ... -> global variable
393 /// GlobalID '=' OptionalVisibility ALIAS ...
394 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
395 bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
398 LocTy NameLoc = Lex.getLoc();
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
405 Lex.Lex(); // eat GlobalID;
407 if (ParseToken(lltok::equal, "expected '=' after name"))
412 unsigned Linkage, Visibility;
413 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
414 ParseOptionalVisibility(Visibility))
417 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
418 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
419 return ParseAlias(Name, NameLoc, Visibility);
422 /// ParseNamedGlobal:
423 /// GlobalVar '=' OptionalVisibility ALIAS ...
424 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
425 bool LLParser::ParseNamedGlobal() {
426 assert(Lex.getKind() == lltok::GlobalVar);
427 LocTy NameLoc = Lex.getLoc();
428 std::string Name = Lex.getStrVal();
432 unsigned Linkage, Visibility;
433 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
434 ParseOptionalLinkage(Linkage, HasLinkage) ||
435 ParseOptionalVisibility(Visibility))
438 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
439 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
440 return ParseAlias(Name, NameLoc, Visibility);
444 // ::= '!' STRINGCONSTANT
445 bool LLParser::ParseMDString(MDString *&Result) {
447 if (ParseStringConstant(Str)) return true;
448 Result = MDString::get(Context, Str);
453 // ::= '!' MDNodeNumber
455 /// This version of ParseMDNodeID returns the slot number and null in the case
456 /// of a forward reference.
457 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
458 // !{ ..., !42, ... }
459 if (ParseUInt32(SlotNo)) return true;
461 // Check existing MDNode.
462 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
463 Result = NumberedMetadata[SlotNo];
469 bool LLParser::ParseMDNodeID(MDNode *&Result) {
470 // !{ ..., !42, ... }
472 if (ParseMDNodeID(Result, MID)) return true;
474 // If not a forward reference, just return it now.
475 if (Result) return false;
477 // Otherwise, create MDNode forward reference.
478 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
479 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
481 if (NumberedMetadata.size() <= MID)
482 NumberedMetadata.resize(MID+1);
483 NumberedMetadata[MID] = FwdNode;
488 /// ParseNamedMetadata:
489 /// !foo = !{ !1, !2 }
490 bool LLParser::ParseNamedMetadata() {
491 assert(Lex.getKind() == lltok::MetadataVar);
492 std::string Name = Lex.getStrVal();
495 if (ParseToken(lltok::equal, "expected '=' here") ||
496 ParseToken(lltok::exclaim, "Expected '!' here") ||
497 ParseToken(lltok::lbrace, "Expected '{' here"))
500 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
501 if (Lex.getKind() != lltok::rbrace)
503 if (ParseToken(lltok::exclaim, "Expected '!' here"))
507 if (ParseMDNodeID(N)) return true;
509 } while (EatIfPresent(lltok::comma));
511 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
517 /// ParseStandaloneMetadata:
519 bool LLParser::ParseStandaloneMetadata() {
520 assert(Lex.getKind() == lltok::exclaim);
522 unsigned MetadataID = 0;
526 SmallVector<Value *, 16> Elts;
527 if (ParseUInt32(MetadataID) ||
528 ParseToken(lltok::equal, "expected '=' here") ||
529 ParseType(Ty, TyLoc) ||
530 ParseToken(lltok::exclaim, "Expected '!' here") ||
531 ParseToken(lltok::lbrace, "Expected '{' here") ||
532 ParseMDNodeVector(Elts, NULL) ||
533 ParseToken(lltok::rbrace, "expected end of metadata node"))
536 MDNode *Init = MDNode::get(Context, Elts);
538 // See if this was forward referenced, if so, handle it.
539 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
540 FI = ForwardRefMDNodes.find(MetadataID);
541 if (FI != ForwardRefMDNodes.end()) {
542 MDNode *Temp = FI->second.first;
543 Temp->replaceAllUsesWith(Init);
544 MDNode::deleteTemporary(Temp);
545 ForwardRefMDNodes.erase(FI);
547 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
549 if (MetadataID >= NumberedMetadata.size())
550 NumberedMetadata.resize(MetadataID+1);
552 if (NumberedMetadata[MetadataID] != 0)
553 return TokError("Metadata id is already used");
554 NumberedMetadata[MetadataID] = Init;
561 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
564 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
565 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
567 /// Everything through visibility has already been parsed.
569 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
570 unsigned Visibility) {
571 assert(Lex.getKind() == lltok::kw_alias);
574 LocTy LinkageLoc = Lex.getLoc();
575 if (ParseOptionalLinkage(Linkage))
578 if (Linkage != GlobalValue::ExternalLinkage &&
579 Linkage != GlobalValue::WeakAnyLinkage &&
580 Linkage != GlobalValue::WeakODRLinkage &&
581 Linkage != GlobalValue::InternalLinkage &&
582 Linkage != GlobalValue::PrivateLinkage &&
583 Linkage != GlobalValue::LinkerPrivateLinkage &&
584 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
585 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
586 return Error(LinkageLoc, "invalid linkage type for alias");
589 LocTy AliaseeLoc = Lex.getLoc();
590 if (Lex.getKind() != lltok::kw_bitcast &&
591 Lex.getKind() != lltok::kw_getelementptr) {
592 if (ParseGlobalTypeAndValue(Aliasee)) return true;
594 // The bitcast dest type is not present, it is implied by the dest type.
596 if (ParseValID(ID)) return true;
597 if (ID.Kind != ValID::t_Constant)
598 return Error(AliaseeLoc, "invalid aliasee");
599 Aliasee = ID.ConstantVal;
602 if (!Aliasee->getType()->isPointerTy())
603 return Error(AliaseeLoc, "alias must have pointer type");
605 // Okay, create the alias but do not insert it into the module yet.
606 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
607 (GlobalValue::LinkageTypes)Linkage, Name,
609 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
611 // See if this value already exists in the symbol table. If so, it is either
612 // a redefinition or a definition of a forward reference.
613 if (GlobalValue *Val = M->getNamedValue(Name)) {
614 // See if this was a redefinition. If so, there is no entry in
616 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
617 I = ForwardRefVals.find(Name);
618 if (I == ForwardRefVals.end())
619 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
621 // Otherwise, this was a definition of forward ref. Verify that types
623 if (Val->getType() != GA->getType())
624 return Error(NameLoc,
625 "forward reference and definition of alias have different types");
627 // If they agree, just RAUW the old value with the alias and remove the
629 Val->replaceAllUsesWith(GA);
630 Val->eraseFromParent();
631 ForwardRefVals.erase(I);
634 // Insert into the module, we know its name won't collide now.
635 M->getAliasList().push_back(GA);
636 assert(GA->getName() == Name && "Should not be a name conflict!");
642 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
643 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
644 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
645 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
647 /// Everything through visibility has been parsed already.
649 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
650 unsigned Linkage, bool HasLinkage,
651 unsigned Visibility) {
653 bool ThreadLocal, IsConstant, UnnamedAddr;
654 LocTy UnnamedAddrLoc;
658 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
659 ParseOptionalAddrSpace(AddrSpace) ||
660 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
662 ParseGlobalType(IsConstant) ||
663 ParseType(Ty, TyLoc))
666 // If the linkage is specified and is external, then no initializer is
669 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
670 Linkage != GlobalValue::ExternalWeakLinkage &&
671 Linkage != GlobalValue::ExternalLinkage)) {
672 if (ParseGlobalValue(Ty, Init))
676 if (Ty->isFunctionTy() || Ty->isLabelTy())
677 return Error(TyLoc, "invalid type for global variable");
679 GlobalVariable *GV = 0;
681 // See if the global was forward referenced, if so, use the global.
683 if (GlobalValue *GVal = M->getNamedValue(Name)) {
684 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
685 return Error(NameLoc, "redefinition of global '@" + Name + "'");
686 GV = cast<GlobalVariable>(GVal);
689 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
690 I = ForwardRefValIDs.find(NumberedVals.size());
691 if (I != ForwardRefValIDs.end()) {
692 GV = cast<GlobalVariable>(I->second.first);
693 ForwardRefValIDs.erase(I);
698 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
699 Name, 0, false, AddrSpace);
701 if (GV->getType()->getElementType() != Ty)
703 "forward reference and definition of global have different types");
705 // Move the forward-reference to the correct spot in the module.
706 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
710 NumberedVals.push_back(GV);
712 // Set the parsed properties on the global.
714 GV->setInitializer(Init);
715 GV->setConstant(IsConstant);
716 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
717 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
718 GV->setThreadLocal(ThreadLocal);
719 GV->setUnnamedAddr(UnnamedAddr);
721 // Parse attributes on the global.
722 while (Lex.getKind() == lltok::comma) {
725 if (Lex.getKind() == lltok::kw_section) {
727 GV->setSection(Lex.getStrVal());
728 if (ParseToken(lltok::StringConstant, "expected global section string"))
730 } else if (Lex.getKind() == lltok::kw_align) {
732 if (ParseOptionalAlignment(Alignment)) return true;
733 GV->setAlignment(Alignment);
735 TokError("unknown global variable property!");
743 //===----------------------------------------------------------------------===//
744 // GlobalValue Reference/Resolution Routines.
745 //===----------------------------------------------------------------------===//
747 /// GetGlobalVal - Get a value with the specified name or ID, creating a
748 /// forward reference record if needed. This can return null if the value
749 /// exists but does not have the right type.
750 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
752 PointerType *PTy = dyn_cast<PointerType>(Ty);
754 Error(Loc, "global variable reference must have pointer type");
758 // Look this name up in the normal function symbol table.
760 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
762 // If this is a forward reference for the value, see if we already created a
763 // forward ref record.
765 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
766 I = ForwardRefVals.find(Name);
767 if (I != ForwardRefVals.end())
768 Val = I->second.first;
771 // If we have the value in the symbol table or fwd-ref table, return it.
773 if (Val->getType() == Ty) return Val;
774 Error(Loc, "'@" + Name + "' defined with type '" +
775 getTypeString(Val->getType()) + "'");
779 // Otherwise, create a new forward reference for this value and remember it.
781 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
782 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
784 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
785 GlobalValue::ExternalWeakLinkage, 0, Name);
787 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
791 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
792 PointerType *PTy = dyn_cast<PointerType>(Ty);
794 Error(Loc, "global variable reference must have pointer type");
798 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
800 // If this is a forward reference for the value, see if we already created a
801 // forward ref record.
803 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
804 I = ForwardRefValIDs.find(ID);
805 if (I != ForwardRefValIDs.end())
806 Val = I->second.first;
809 // If we have the value in the symbol table or fwd-ref table, return it.
811 if (Val->getType() == Ty) return Val;
812 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
813 getTypeString(Val->getType()) + "'");
817 // Otherwise, create a new forward reference for this value and remember it.
819 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
820 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
822 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
823 GlobalValue::ExternalWeakLinkage, 0, "");
825 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
830 //===----------------------------------------------------------------------===//
832 //===----------------------------------------------------------------------===//
834 /// ParseToken - If the current token has the specified kind, eat it and return
835 /// success. Otherwise, emit the specified error and return failure.
836 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
837 if (Lex.getKind() != T)
838 return TokError(ErrMsg);
843 /// ParseStringConstant
844 /// ::= StringConstant
845 bool LLParser::ParseStringConstant(std::string &Result) {
846 if (Lex.getKind() != lltok::StringConstant)
847 return TokError("expected string constant");
848 Result = Lex.getStrVal();
855 bool LLParser::ParseUInt32(unsigned &Val) {
856 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
857 return TokError("expected integer");
858 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
859 if (Val64 != unsigned(Val64))
860 return TokError("expected 32-bit integer (too large)");
867 /// ParseOptionalAddrSpace
869 /// := 'addrspace' '(' uint32 ')'
870 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
872 if (!EatIfPresent(lltok::kw_addrspace))
874 return ParseToken(lltok::lparen, "expected '(' in address space") ||
875 ParseUInt32(AddrSpace) ||
876 ParseToken(lltok::rparen, "expected ')' in address space");
879 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
880 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
881 /// 2: function attr.
882 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
883 Attrs = Attribute::None;
884 LocTy AttrLoc = Lex.getLoc();
887 switch (Lex.getKind()) {
888 default: // End of attributes.
889 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
890 return Error(AttrLoc, "invalid use of function-only attribute");
892 // As a hack, we allow "align 2" on functions as a synonym for
895 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
896 return Error(AttrLoc, "invalid use of attribute on a function");
898 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
899 return Error(AttrLoc, "invalid use of parameter-only attribute");
902 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
903 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
904 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
905 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
906 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
907 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
908 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
909 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
911 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
912 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
913 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
914 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
915 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
916 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
917 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
918 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
919 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
920 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
921 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
922 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
923 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
924 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
925 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
926 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
928 case lltok::kw_alignstack: {
930 if (ParseOptionalStackAlignment(Alignment))
932 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
936 case lltok::kw_align: {
938 if (ParseOptionalAlignment(Alignment))
940 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
949 /// ParseOptionalLinkage
952 /// ::= 'linker_private'
953 /// ::= 'linker_private_weak'
954 /// ::= 'linker_private_weak_def_auto'
959 /// ::= 'linkonce_odr'
960 /// ::= 'available_externally'
965 /// ::= 'extern_weak'
967 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
969 switch (Lex.getKind()) {
970 default: Res=GlobalValue::ExternalLinkage; return false;
971 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
972 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
973 case lltok::kw_linker_private_weak:
974 Res = GlobalValue::LinkerPrivateWeakLinkage;
976 case lltok::kw_linker_private_weak_def_auto:
977 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
979 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
980 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
981 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
982 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
983 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
984 case lltok::kw_available_externally:
985 Res = GlobalValue::AvailableExternallyLinkage;
987 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
988 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
989 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
990 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
991 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
992 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
999 /// ParseOptionalVisibility
1005 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1006 switch (Lex.getKind()) {
1007 default: Res = GlobalValue::DefaultVisibility; return false;
1008 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1009 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1010 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1016 /// ParseOptionalCallingConv
1021 /// ::= 'x86_stdcallcc'
1022 /// ::= 'x86_fastcallcc'
1023 /// ::= 'x86_thiscallcc'
1024 /// ::= 'arm_apcscc'
1025 /// ::= 'arm_aapcscc'
1026 /// ::= 'arm_aapcs_vfpcc'
1027 /// ::= 'msp430_intrcc'
1028 /// ::= 'ptx_kernel'
1029 /// ::= 'ptx_device'
1032 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1033 switch (Lex.getKind()) {
1034 default: CC = CallingConv::C; return false;
1035 case lltok::kw_ccc: CC = CallingConv::C; break;
1036 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1037 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1038 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1039 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1040 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1041 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1042 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1043 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1044 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1045 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1046 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1047 case lltok::kw_cc: {
1048 unsigned ArbitraryCC;
1050 if (ParseUInt32(ArbitraryCC)) {
1053 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1063 /// ParseInstructionMetadata
1064 /// ::= !dbg !42 (',' !dbg !57)*
1065 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1066 PerFunctionState *PFS) {
1068 if (Lex.getKind() != lltok::MetadataVar)
1069 return TokError("expected metadata after comma");
1071 std::string Name = Lex.getStrVal();
1072 unsigned MDK = M->getMDKindID(Name.c_str());
1076 SMLoc Loc = Lex.getLoc();
1078 if (ParseToken(lltok::exclaim, "expected '!' here"))
1081 // This code is similar to that of ParseMetadataValue, however it needs to
1082 // have special-case code for a forward reference; see the comments on
1083 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1084 // at the top level here.
1085 if (Lex.getKind() == lltok::lbrace) {
1087 if (ParseMetadataListValue(ID, PFS))
1089 assert(ID.Kind == ValID::t_MDNode);
1090 Inst->setMetadata(MDK, ID.MDNodeVal);
1092 unsigned NodeID = 0;
1093 if (ParseMDNodeID(Node, NodeID))
1096 // If we got the node, add it to the instruction.
1097 Inst->setMetadata(MDK, Node);
1099 MDRef R = { Loc, MDK, NodeID };
1100 // Otherwise, remember that this should be resolved later.
1101 ForwardRefInstMetadata[Inst].push_back(R);
1105 // If this is the end of the list, we're done.
1106 } while (EatIfPresent(lltok::comma));
1110 /// ParseOptionalAlignment
1113 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1115 if (!EatIfPresent(lltok::kw_align))
1117 LocTy AlignLoc = Lex.getLoc();
1118 if (ParseUInt32(Alignment)) return true;
1119 if (!isPowerOf2_32(Alignment))
1120 return Error(AlignLoc, "alignment is not a power of two");
1121 if (Alignment > Value::MaximumAlignment)
1122 return Error(AlignLoc, "huge alignments are not supported yet");
1126 /// ParseOptionalCommaAlign
1130 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1132 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1133 bool &AteExtraComma) {
1134 AteExtraComma = false;
1135 while (EatIfPresent(lltok::comma)) {
1136 // Metadata at the end is an early exit.
1137 if (Lex.getKind() == lltok::MetadataVar) {
1138 AteExtraComma = true;
1142 if (Lex.getKind() != lltok::kw_align)
1143 return Error(Lex.getLoc(), "expected metadata or 'align'");
1145 if (ParseOptionalAlignment(Alignment)) return true;
1151 /// ParseScopeAndOrdering
1152 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1155 /// This sets Scope and Ordering to the parsed values.
1156 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1157 AtomicOrdering &Ordering) {
1161 Scope = CrossThread;
1162 if (EatIfPresent(lltok::kw_singlethread))
1163 Scope = SingleThread;
1164 switch (Lex.getKind()) {
1165 default: return TokError("Expected ordering on atomic instruction");
1166 case lltok::kw_unordered: Ordering = Unordered; break;
1167 case lltok::kw_monotonic: Ordering = Monotonic; break;
1168 case lltok::kw_acquire: Ordering = Acquire; break;
1169 case lltok::kw_release: Ordering = Release; break;
1170 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1171 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1177 /// ParseOptionalStackAlignment
1179 /// ::= 'alignstack' '(' 4 ')'
1180 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1182 if (!EatIfPresent(lltok::kw_alignstack))
1184 LocTy ParenLoc = Lex.getLoc();
1185 if (!EatIfPresent(lltok::lparen))
1186 return Error(ParenLoc, "expected '('");
1187 LocTy AlignLoc = Lex.getLoc();
1188 if (ParseUInt32(Alignment)) return true;
1189 ParenLoc = Lex.getLoc();
1190 if (!EatIfPresent(lltok::rparen))
1191 return Error(ParenLoc, "expected ')'");
1192 if (!isPowerOf2_32(Alignment))
1193 return Error(AlignLoc, "stack alignment is not a power of two");
1197 /// ParseIndexList - This parses the index list for an insert/extractvalue
1198 /// instruction. This sets AteExtraComma in the case where we eat an extra
1199 /// comma at the end of the line and find that it is followed by metadata.
1200 /// Clients that don't allow metadata can call the version of this function that
1201 /// only takes one argument.
1204 /// ::= (',' uint32)+
1206 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1207 bool &AteExtraComma) {
1208 AteExtraComma = false;
1210 if (Lex.getKind() != lltok::comma)
1211 return TokError("expected ',' as start of index list");
1213 while (EatIfPresent(lltok::comma)) {
1214 if (Lex.getKind() == lltok::MetadataVar) {
1215 AteExtraComma = true;
1219 if (ParseUInt32(Idx)) return true;
1220 Indices.push_back(Idx);
1226 //===----------------------------------------------------------------------===//
1228 //===----------------------------------------------------------------------===//
1230 /// ParseType - Parse a type.
1231 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1232 SMLoc TypeLoc = Lex.getLoc();
1233 switch (Lex.getKind()) {
1235 return TokError("expected type");
1237 // Type ::= 'float' | 'void' (etc)
1238 Result = Lex.getTyVal();
1242 // Type ::= StructType
1243 if (ParseAnonStructType(Result, false))
1246 case lltok::lsquare:
1247 // Type ::= '[' ... ']'
1248 Lex.Lex(); // eat the lsquare.
1249 if (ParseArrayVectorType(Result, false))
1252 case lltok::less: // Either vector or packed struct.
1253 // Type ::= '<' ... '>'
1255 if (Lex.getKind() == lltok::lbrace) {
1256 if (ParseAnonStructType(Result, true) ||
1257 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1259 } else if (ParseArrayVectorType(Result, true))
1262 case lltok::LocalVar: {
1264 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1266 // If the type hasn't been defined yet, create a forward definition and
1267 // remember where that forward def'n was seen (in case it never is defined).
1268 if (Entry.first == 0) {
1269 Entry.first = StructType::create(Context, Lex.getStrVal());
1270 Entry.second = Lex.getLoc();
1272 Result = Entry.first;
1277 case lltok::LocalVarID: {
1279 if (Lex.getUIntVal() >= NumberedTypes.size())
1280 NumberedTypes.resize(Lex.getUIntVal()+1);
1281 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1283 // If the type hasn't been defined yet, create a forward definition and
1284 // remember where that forward def'n was seen (in case it never is defined).
1285 if (Entry.first == 0) {
1286 Entry.first = StructType::create(Context);
1287 Entry.second = Lex.getLoc();
1289 Result = Entry.first;
1295 // Parse the type suffixes.
1297 switch (Lex.getKind()) {
1300 if (!AllowVoid && Result->isVoidTy())
1301 return Error(TypeLoc, "void type only allowed for function results");
1304 // Type ::= Type '*'
1306 if (Result->isLabelTy())
1307 return TokError("basic block pointers are invalid");
1308 if (Result->isVoidTy())
1309 return TokError("pointers to void are invalid - use i8* instead");
1310 if (!PointerType::isValidElementType(Result))
1311 return TokError("pointer to this type is invalid");
1312 Result = PointerType::getUnqual(Result);
1316 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1317 case lltok::kw_addrspace: {
1318 if (Result->isLabelTy())
1319 return TokError("basic block pointers are invalid");
1320 if (Result->isVoidTy())
1321 return TokError("pointers to void are invalid; use i8* instead");
1322 if (!PointerType::isValidElementType(Result))
1323 return TokError("pointer to this type is invalid");
1325 if (ParseOptionalAddrSpace(AddrSpace) ||
1326 ParseToken(lltok::star, "expected '*' in address space"))
1329 Result = PointerType::get(Result, AddrSpace);
1333 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1335 if (ParseFunctionType(Result))
1342 /// ParseParameterList
1344 /// ::= '(' Arg (',' Arg)* ')'
1346 /// ::= Type OptionalAttributes Value OptionalAttributes
1347 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1348 PerFunctionState &PFS) {
1349 if (ParseToken(lltok::lparen, "expected '(' in call"))
1352 while (Lex.getKind() != lltok::rparen) {
1353 // If this isn't the first argument, we need a comma.
1354 if (!ArgList.empty() &&
1355 ParseToken(lltok::comma, "expected ',' in argument list"))
1358 // Parse the argument.
1361 unsigned ArgAttrs1 = Attribute::None;
1362 unsigned ArgAttrs2 = Attribute::None;
1364 if (ParseType(ArgTy, ArgLoc))
1367 // Otherwise, handle normal operands.
1368 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1370 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1373 Lex.Lex(); // Lex the ')'.
1379 /// ParseArgumentList - Parse the argument list for a function type or function
1381 /// ::= '(' ArgTypeListI ')'
1385 /// ::= ArgTypeList ',' '...'
1386 /// ::= ArgType (',' ArgType)*
1388 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1391 assert(Lex.getKind() == lltok::lparen);
1392 Lex.Lex(); // eat the (.
1394 if (Lex.getKind() == lltok::rparen) {
1396 } else if (Lex.getKind() == lltok::dotdotdot) {
1400 LocTy TypeLoc = Lex.getLoc();
1405 if (ParseType(ArgTy) ||
1406 ParseOptionalAttrs(Attrs, 0)) return true;
1408 if (ArgTy->isVoidTy())
1409 return Error(TypeLoc, "argument can not have void type");
1411 if (Lex.getKind() == lltok::LocalVar) {
1412 Name = Lex.getStrVal();
1416 if (!FunctionType::isValidArgumentType(ArgTy))
1417 return Error(TypeLoc, "invalid type for function argument");
1419 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1421 while (EatIfPresent(lltok::comma)) {
1422 // Handle ... at end of arg list.
1423 if (EatIfPresent(lltok::dotdotdot)) {
1428 // Otherwise must be an argument type.
1429 TypeLoc = Lex.getLoc();
1430 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1432 if (ArgTy->isVoidTy())
1433 return Error(TypeLoc, "argument can not have void type");
1435 if (Lex.getKind() == lltok::LocalVar) {
1436 Name = Lex.getStrVal();
1442 if (!ArgTy->isFirstClassType())
1443 return Error(TypeLoc, "invalid type for function argument");
1445 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1449 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1452 /// ParseFunctionType
1453 /// ::= Type ArgumentList OptionalAttrs
1454 bool LLParser::ParseFunctionType(Type *&Result) {
1455 assert(Lex.getKind() == lltok::lparen);
1457 if (!FunctionType::isValidReturnType(Result))
1458 return TokError("invalid function return type");
1460 SmallVector<ArgInfo, 8> ArgList;
1462 if (ParseArgumentList(ArgList, isVarArg))
1465 // Reject names on the arguments lists.
1466 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1467 if (!ArgList[i].Name.empty())
1468 return Error(ArgList[i].Loc, "argument name invalid in function type");
1469 if (ArgList[i].Attrs != 0)
1470 return Error(ArgList[i].Loc,
1471 "argument attributes invalid in function type");
1474 SmallVector<Type*, 16> ArgListTy;
1475 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1476 ArgListTy.push_back(ArgList[i].Ty);
1478 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1482 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1484 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1485 SmallVector<Type*, 8> Elts;
1486 if (ParseStructBody(Elts)) return true;
1488 Result = StructType::get(Context, Elts, Packed);
1492 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1493 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1494 std::pair<Type*, LocTy> &Entry,
1496 // If the type was already defined, diagnose the redefinition.
1497 if (Entry.first && !Entry.second.isValid())
1498 return Error(TypeLoc, "redefinition of type");
1500 // If we have opaque, just return without filling in the definition for the
1501 // struct. This counts as a definition as far as the .ll file goes.
1502 if (EatIfPresent(lltok::kw_opaque)) {
1503 // This type is being defined, so clear the location to indicate this.
1504 Entry.second = SMLoc();
1506 // If this type number has never been uttered, create it.
1507 if (Entry.first == 0)
1508 Entry.first = StructType::create(Context, Name);
1509 ResultTy = Entry.first;
1513 // If the type starts with '<', then it is either a packed struct or a vector.
1514 bool isPacked = EatIfPresent(lltok::less);
1516 // If we don't have a struct, then we have a random type alias, which we
1517 // accept for compatibility with old files. These types are not allowed to be
1518 // forward referenced and not allowed to be recursive.
1519 if (Lex.getKind() != lltok::lbrace) {
1521 return Error(TypeLoc, "forward references to non-struct type");
1525 return ParseArrayVectorType(ResultTy, true);
1526 return ParseType(ResultTy);
1529 // This type is being defined, so clear the location to indicate this.
1530 Entry.second = SMLoc();
1532 // If this type number has never been uttered, create it.
1533 if (Entry.first == 0)
1534 Entry.first = StructType::create(Context, Name);
1536 StructType *STy = cast<StructType>(Entry.first);
1538 SmallVector<Type*, 8> Body;
1539 if (ParseStructBody(Body) ||
1540 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1543 STy->setBody(Body, isPacked);
1549 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1552 /// ::= '{' Type (',' Type)* '}'
1553 /// ::= '<' '{' '}' '>'
1554 /// ::= '<' '{' Type (',' Type)* '}' '>'
1555 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1556 assert(Lex.getKind() == lltok::lbrace);
1557 Lex.Lex(); // Consume the '{'
1559 // Handle the empty struct.
1560 if (EatIfPresent(lltok::rbrace))
1563 LocTy EltTyLoc = Lex.getLoc();
1565 if (ParseType(Ty)) return true;
1568 if (!StructType::isValidElementType(Ty))
1569 return Error(EltTyLoc, "invalid element type for struct");
1571 while (EatIfPresent(lltok::comma)) {
1572 EltTyLoc = Lex.getLoc();
1573 if (ParseType(Ty)) return true;
1575 if (!StructType::isValidElementType(Ty))
1576 return Error(EltTyLoc, "invalid element type for struct");
1581 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1584 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1585 /// token has already been consumed.
1587 /// ::= '[' APSINTVAL 'x' Types ']'
1588 /// ::= '<' APSINTVAL 'x' Types '>'
1589 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1590 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1591 Lex.getAPSIntVal().getBitWidth() > 64)
1592 return TokError("expected number in address space");
1594 LocTy SizeLoc = Lex.getLoc();
1595 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1598 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1601 LocTy TypeLoc = Lex.getLoc();
1603 if (ParseType(EltTy)) return true;
1605 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1606 "expected end of sequential type"))
1611 return Error(SizeLoc, "zero element vector is illegal");
1612 if ((unsigned)Size != Size)
1613 return Error(SizeLoc, "size too large for vector");
1614 if (!VectorType::isValidElementType(EltTy))
1615 return Error(TypeLoc, "vector element type must be fp or integer");
1616 Result = VectorType::get(EltTy, unsigned(Size));
1618 if (!ArrayType::isValidElementType(EltTy))
1619 return Error(TypeLoc, "invalid array element type");
1620 Result = ArrayType::get(EltTy, Size);
1625 //===----------------------------------------------------------------------===//
1626 // Function Semantic Analysis.
1627 //===----------------------------------------------------------------------===//
1629 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1631 : P(p), F(f), FunctionNumber(functionNumber) {
1633 // Insert unnamed arguments into the NumberedVals list.
1634 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1637 NumberedVals.push_back(AI);
1640 LLParser::PerFunctionState::~PerFunctionState() {
1641 // If there were any forward referenced non-basicblock values, delete them.
1642 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1643 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1644 if (!isa<BasicBlock>(I->second.first)) {
1645 I->second.first->replaceAllUsesWith(
1646 UndefValue::get(I->second.first->getType()));
1647 delete I->second.first;
1648 I->second.first = 0;
1651 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1652 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1653 if (!isa<BasicBlock>(I->second.first)) {
1654 I->second.first->replaceAllUsesWith(
1655 UndefValue::get(I->second.first->getType()));
1656 delete I->second.first;
1657 I->second.first = 0;
1661 bool LLParser::PerFunctionState::FinishFunction() {
1662 // Check to see if someone took the address of labels in this block.
1663 if (!P.ForwardRefBlockAddresses.empty()) {
1665 if (!F.getName().empty()) {
1666 FunctionID.Kind = ValID::t_GlobalName;
1667 FunctionID.StrVal = F.getName();
1669 FunctionID.Kind = ValID::t_GlobalID;
1670 FunctionID.UIntVal = FunctionNumber;
1673 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1674 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1675 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1676 // Resolve all these references.
1677 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1680 P.ForwardRefBlockAddresses.erase(FRBAI);
1684 if (!ForwardRefVals.empty())
1685 return P.Error(ForwardRefVals.begin()->second.second,
1686 "use of undefined value '%" + ForwardRefVals.begin()->first +
1688 if (!ForwardRefValIDs.empty())
1689 return P.Error(ForwardRefValIDs.begin()->second.second,
1690 "use of undefined value '%" +
1691 Twine(ForwardRefValIDs.begin()->first) + "'");
1696 /// GetVal - Get a value with the specified name or ID, creating a
1697 /// forward reference record if needed. This can return null if the value
1698 /// exists but does not have the right type.
1699 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1700 Type *Ty, LocTy Loc) {
1701 // Look this name up in the normal function symbol table.
1702 Value *Val = F.getValueSymbolTable().lookup(Name);
1704 // If this is a forward reference for the value, see if we already created a
1705 // forward ref record.
1707 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1708 I = ForwardRefVals.find(Name);
1709 if (I != ForwardRefVals.end())
1710 Val = I->second.first;
1713 // If we have the value in the symbol table or fwd-ref table, return it.
1715 if (Val->getType() == Ty) return Val;
1716 if (Ty->isLabelTy())
1717 P.Error(Loc, "'%" + Name + "' is not a basic block");
1719 P.Error(Loc, "'%" + Name + "' defined with type '" +
1720 getTypeString(Val->getType()) + "'");
1724 // Don't make placeholders with invalid type.
1725 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1726 P.Error(Loc, "invalid use of a non-first-class type");
1730 // Otherwise, create a new forward reference for this value and remember it.
1732 if (Ty->isLabelTy())
1733 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1735 FwdVal = new Argument(Ty, Name);
1737 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1741 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1743 // Look this name up in the normal function symbol table.
1744 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1746 // If this is a forward reference for the value, see if we already created a
1747 // forward ref record.
1749 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1750 I = ForwardRefValIDs.find(ID);
1751 if (I != ForwardRefValIDs.end())
1752 Val = I->second.first;
1755 // If we have the value in the symbol table or fwd-ref table, return it.
1757 if (Val->getType() == Ty) return Val;
1758 if (Ty->isLabelTy())
1759 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1761 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1762 getTypeString(Val->getType()) + "'");
1766 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1767 P.Error(Loc, "invalid use of a non-first-class type");
1771 // Otherwise, create a new forward reference for this value and remember it.
1773 if (Ty->isLabelTy())
1774 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1776 FwdVal = new Argument(Ty);
1778 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1782 /// SetInstName - After an instruction is parsed and inserted into its
1783 /// basic block, this installs its name.
1784 bool LLParser::PerFunctionState::SetInstName(int NameID,
1785 const std::string &NameStr,
1786 LocTy NameLoc, Instruction *Inst) {
1787 // If this instruction has void type, it cannot have a name or ID specified.
1788 if (Inst->getType()->isVoidTy()) {
1789 if (NameID != -1 || !NameStr.empty())
1790 return P.Error(NameLoc, "instructions returning void cannot have a name");
1794 // If this was a numbered instruction, verify that the instruction is the
1795 // expected value and resolve any forward references.
1796 if (NameStr.empty()) {
1797 // If neither a name nor an ID was specified, just use the next ID.
1799 NameID = NumberedVals.size();
1801 if (unsigned(NameID) != NumberedVals.size())
1802 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1803 Twine(NumberedVals.size()) + "'");
1805 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1806 ForwardRefValIDs.find(NameID);
1807 if (FI != ForwardRefValIDs.end()) {
1808 if (FI->second.first->getType() != Inst->getType())
1809 return P.Error(NameLoc, "instruction forward referenced with type '" +
1810 getTypeString(FI->second.first->getType()) + "'");
1811 FI->second.first->replaceAllUsesWith(Inst);
1812 delete FI->second.first;
1813 ForwardRefValIDs.erase(FI);
1816 NumberedVals.push_back(Inst);
1820 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1821 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1822 FI = ForwardRefVals.find(NameStr);
1823 if (FI != ForwardRefVals.end()) {
1824 if (FI->second.first->getType() != Inst->getType())
1825 return P.Error(NameLoc, "instruction forward referenced with type '" +
1826 getTypeString(FI->second.first->getType()) + "'");
1827 FI->second.first->replaceAllUsesWith(Inst);
1828 delete FI->second.first;
1829 ForwardRefVals.erase(FI);
1832 // Set the name on the instruction.
1833 Inst->setName(NameStr);
1835 if (Inst->getName() != NameStr)
1836 return P.Error(NameLoc, "multiple definition of local value named '" +
1841 /// GetBB - Get a basic block with the specified name or ID, creating a
1842 /// forward reference record if needed.
1843 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1845 return cast_or_null<BasicBlock>(GetVal(Name,
1846 Type::getLabelTy(F.getContext()), Loc));
1849 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1850 return cast_or_null<BasicBlock>(GetVal(ID,
1851 Type::getLabelTy(F.getContext()), Loc));
1854 /// DefineBB - Define the specified basic block, which is either named or
1855 /// unnamed. If there is an error, this returns null otherwise it returns
1856 /// the block being defined.
1857 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1861 BB = GetBB(NumberedVals.size(), Loc);
1863 BB = GetBB(Name, Loc);
1864 if (BB == 0) return 0; // Already diagnosed error.
1866 // Move the block to the end of the function. Forward ref'd blocks are
1867 // inserted wherever they happen to be referenced.
1868 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1870 // Remove the block from forward ref sets.
1872 ForwardRefValIDs.erase(NumberedVals.size());
1873 NumberedVals.push_back(BB);
1875 // BB forward references are already in the function symbol table.
1876 ForwardRefVals.erase(Name);
1882 //===----------------------------------------------------------------------===//
1884 //===----------------------------------------------------------------------===//
1886 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1887 /// type implied. For example, if we parse "4" we don't know what integer type
1888 /// it has. The value will later be combined with its type and checked for
1889 /// sanity. PFS is used to convert function-local operands of metadata (since
1890 /// metadata operands are not just parsed here but also converted to values).
1891 /// PFS can be null when we are not parsing metadata values inside a function.
1892 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1893 ID.Loc = Lex.getLoc();
1894 switch (Lex.getKind()) {
1895 default: return TokError("expected value token");
1896 case lltok::GlobalID: // @42
1897 ID.UIntVal = Lex.getUIntVal();
1898 ID.Kind = ValID::t_GlobalID;
1900 case lltok::GlobalVar: // @foo
1901 ID.StrVal = Lex.getStrVal();
1902 ID.Kind = ValID::t_GlobalName;
1904 case lltok::LocalVarID: // %42
1905 ID.UIntVal = Lex.getUIntVal();
1906 ID.Kind = ValID::t_LocalID;
1908 case lltok::LocalVar: // %foo
1909 ID.StrVal = Lex.getStrVal();
1910 ID.Kind = ValID::t_LocalName;
1912 case lltok::exclaim: // !42, !{...}, or !"foo"
1913 return ParseMetadataValue(ID, PFS);
1915 ID.APSIntVal = Lex.getAPSIntVal();
1916 ID.Kind = ValID::t_APSInt;
1918 case lltok::APFloat:
1919 ID.APFloatVal = Lex.getAPFloatVal();
1920 ID.Kind = ValID::t_APFloat;
1922 case lltok::kw_true:
1923 ID.ConstantVal = ConstantInt::getTrue(Context);
1924 ID.Kind = ValID::t_Constant;
1926 case lltok::kw_false:
1927 ID.ConstantVal = ConstantInt::getFalse(Context);
1928 ID.Kind = ValID::t_Constant;
1930 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1931 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1932 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1934 case lltok::lbrace: {
1935 // ValID ::= '{' ConstVector '}'
1937 SmallVector<Constant*, 16> Elts;
1938 if (ParseGlobalValueVector(Elts) ||
1939 ParseToken(lltok::rbrace, "expected end of struct constant"))
1942 ID.ConstantStructElts = new Constant*[Elts.size()];
1943 ID.UIntVal = Elts.size();
1944 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1945 ID.Kind = ValID::t_ConstantStruct;
1949 // ValID ::= '<' ConstVector '>' --> Vector.
1950 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1952 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1954 SmallVector<Constant*, 16> Elts;
1955 LocTy FirstEltLoc = Lex.getLoc();
1956 if (ParseGlobalValueVector(Elts) ||
1958 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1959 ParseToken(lltok::greater, "expected end of constant"))
1962 if (isPackedStruct) {
1963 ID.ConstantStructElts = new Constant*[Elts.size()];
1964 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1965 ID.UIntVal = Elts.size();
1966 ID.Kind = ValID::t_PackedConstantStruct;
1971 return Error(ID.Loc, "constant vector must not be empty");
1973 if (!Elts[0]->getType()->isIntegerTy() &&
1974 !Elts[0]->getType()->isFloatingPointTy())
1975 return Error(FirstEltLoc,
1976 "vector elements must have integer or floating point type");
1978 // Verify that all the vector elements have the same type.
1979 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1980 if (Elts[i]->getType() != Elts[0]->getType())
1981 return Error(FirstEltLoc,
1982 "vector element #" + Twine(i) +
1983 " is not of type '" + getTypeString(Elts[0]->getType()));
1985 ID.ConstantVal = ConstantVector::get(Elts);
1986 ID.Kind = ValID::t_Constant;
1989 case lltok::lsquare: { // Array Constant
1991 SmallVector<Constant*, 16> Elts;
1992 LocTy FirstEltLoc = Lex.getLoc();
1993 if (ParseGlobalValueVector(Elts) ||
1994 ParseToken(lltok::rsquare, "expected end of array constant"))
1997 // Handle empty element.
1999 // Use undef instead of an array because it's inconvenient to determine
2000 // the element type at this point, there being no elements to examine.
2001 ID.Kind = ValID::t_EmptyArray;
2005 if (!Elts[0]->getType()->isFirstClassType())
2006 return Error(FirstEltLoc, "invalid array element type: " +
2007 getTypeString(Elts[0]->getType()));
2009 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2011 // Verify all elements are correct type!
2012 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2013 if (Elts[i]->getType() != Elts[0]->getType())
2014 return Error(FirstEltLoc,
2015 "array element #" + Twine(i) +
2016 " is not of type '" + getTypeString(Elts[0]->getType()));
2019 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2020 ID.Kind = ValID::t_Constant;
2023 case lltok::kw_c: // c "foo"
2025 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2026 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2027 ID.Kind = ValID::t_Constant;
2030 case lltok::kw_asm: {
2031 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2032 bool HasSideEffect, AlignStack;
2034 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2035 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2036 ParseStringConstant(ID.StrVal) ||
2037 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2038 ParseToken(lltok::StringConstant, "expected constraint string"))
2040 ID.StrVal2 = Lex.getStrVal();
2041 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2042 ID.Kind = ValID::t_InlineAsm;
2046 case lltok::kw_blockaddress: {
2047 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2051 LocTy FnLoc, LabelLoc;
2053 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2055 ParseToken(lltok::comma, "expected comma in block address expression")||
2056 ParseValID(Label) ||
2057 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2060 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2061 return Error(Fn.Loc, "expected function name in blockaddress");
2062 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2063 return Error(Label.Loc, "expected basic block name in blockaddress");
2065 // Make a global variable as a placeholder for this reference.
2066 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2067 false, GlobalValue::InternalLinkage,
2069 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2070 ID.ConstantVal = FwdRef;
2071 ID.Kind = ValID::t_Constant;
2075 case lltok::kw_trunc:
2076 case lltok::kw_zext:
2077 case lltok::kw_sext:
2078 case lltok::kw_fptrunc:
2079 case lltok::kw_fpext:
2080 case lltok::kw_bitcast:
2081 case lltok::kw_uitofp:
2082 case lltok::kw_sitofp:
2083 case lltok::kw_fptoui:
2084 case lltok::kw_fptosi:
2085 case lltok::kw_inttoptr:
2086 case lltok::kw_ptrtoint: {
2087 unsigned Opc = Lex.getUIntVal();
2091 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2092 ParseGlobalTypeAndValue(SrcVal) ||
2093 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2094 ParseType(DestTy) ||
2095 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2097 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2098 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2099 getTypeString(SrcVal->getType()) + "' to '" +
2100 getTypeString(DestTy) + "'");
2101 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2103 ID.Kind = ValID::t_Constant;
2106 case lltok::kw_extractvalue: {
2109 SmallVector<unsigned, 4> Indices;
2110 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2111 ParseGlobalTypeAndValue(Val) ||
2112 ParseIndexList(Indices) ||
2113 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2116 if (!Val->getType()->isAggregateType())
2117 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2118 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2119 return Error(ID.Loc, "invalid indices for extractvalue");
2120 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2121 ID.Kind = ValID::t_Constant;
2124 case lltok::kw_insertvalue: {
2126 Constant *Val0, *Val1;
2127 SmallVector<unsigned, 4> Indices;
2128 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2129 ParseGlobalTypeAndValue(Val0) ||
2130 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2131 ParseGlobalTypeAndValue(Val1) ||
2132 ParseIndexList(Indices) ||
2133 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2135 if (!Val0->getType()->isAggregateType())
2136 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2137 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2138 return Error(ID.Loc, "invalid indices for insertvalue");
2139 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2140 ID.Kind = ValID::t_Constant;
2143 case lltok::kw_icmp:
2144 case lltok::kw_fcmp: {
2145 unsigned PredVal, Opc = Lex.getUIntVal();
2146 Constant *Val0, *Val1;
2148 if (ParseCmpPredicate(PredVal, Opc) ||
2149 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2150 ParseGlobalTypeAndValue(Val0) ||
2151 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2152 ParseGlobalTypeAndValue(Val1) ||
2153 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2156 if (Val0->getType() != Val1->getType())
2157 return Error(ID.Loc, "compare operands must have the same type");
2159 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2161 if (Opc == Instruction::FCmp) {
2162 if (!Val0->getType()->isFPOrFPVectorTy())
2163 return Error(ID.Loc, "fcmp requires floating point operands");
2164 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2166 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2167 if (!Val0->getType()->isIntOrIntVectorTy() &&
2168 !Val0->getType()->isPointerTy())
2169 return Error(ID.Loc, "icmp requires pointer or integer operands");
2170 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2172 ID.Kind = ValID::t_Constant;
2176 // Binary Operators.
2178 case lltok::kw_fadd:
2180 case lltok::kw_fsub:
2182 case lltok::kw_fmul:
2183 case lltok::kw_udiv:
2184 case lltok::kw_sdiv:
2185 case lltok::kw_fdiv:
2186 case lltok::kw_urem:
2187 case lltok::kw_srem:
2188 case lltok::kw_frem:
2190 case lltok::kw_lshr:
2191 case lltok::kw_ashr: {
2195 unsigned Opc = Lex.getUIntVal();
2196 Constant *Val0, *Val1;
2198 LocTy ModifierLoc = Lex.getLoc();
2199 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2200 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2201 if (EatIfPresent(lltok::kw_nuw))
2203 if (EatIfPresent(lltok::kw_nsw)) {
2205 if (EatIfPresent(lltok::kw_nuw))
2208 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2209 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2210 if (EatIfPresent(lltok::kw_exact))
2213 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2214 ParseGlobalTypeAndValue(Val0) ||
2215 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2216 ParseGlobalTypeAndValue(Val1) ||
2217 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2219 if (Val0->getType() != Val1->getType())
2220 return Error(ID.Loc, "operands of constexpr must have same type");
2221 if (!Val0->getType()->isIntOrIntVectorTy()) {
2223 return Error(ModifierLoc, "nuw only applies to integer operations");
2225 return Error(ModifierLoc, "nsw only applies to integer operations");
2227 // Check that the type is valid for the operator.
2229 case Instruction::Add:
2230 case Instruction::Sub:
2231 case Instruction::Mul:
2232 case Instruction::UDiv:
2233 case Instruction::SDiv:
2234 case Instruction::URem:
2235 case Instruction::SRem:
2236 case Instruction::Shl:
2237 case Instruction::AShr:
2238 case Instruction::LShr:
2239 if (!Val0->getType()->isIntOrIntVectorTy())
2240 return Error(ID.Loc, "constexpr requires integer operands");
2242 case Instruction::FAdd:
2243 case Instruction::FSub:
2244 case Instruction::FMul:
2245 case Instruction::FDiv:
2246 case Instruction::FRem:
2247 if (!Val0->getType()->isFPOrFPVectorTy())
2248 return Error(ID.Loc, "constexpr requires fp operands");
2250 default: llvm_unreachable("Unknown binary operator!");
2253 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2254 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2255 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2256 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2258 ID.Kind = ValID::t_Constant;
2262 // Logical Operations
2265 case lltok::kw_xor: {
2266 unsigned Opc = Lex.getUIntVal();
2267 Constant *Val0, *Val1;
2269 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2270 ParseGlobalTypeAndValue(Val0) ||
2271 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2272 ParseGlobalTypeAndValue(Val1) ||
2273 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2275 if (Val0->getType() != Val1->getType())
2276 return Error(ID.Loc, "operands of constexpr must have same type");
2277 if (!Val0->getType()->isIntOrIntVectorTy())
2278 return Error(ID.Loc,
2279 "constexpr requires integer or integer vector operands");
2280 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2281 ID.Kind = ValID::t_Constant;
2285 case lltok::kw_getelementptr:
2286 case lltok::kw_shufflevector:
2287 case lltok::kw_insertelement:
2288 case lltok::kw_extractelement:
2289 case lltok::kw_select: {
2290 unsigned Opc = Lex.getUIntVal();
2291 SmallVector<Constant*, 16> Elts;
2292 bool InBounds = false;
2294 if (Opc == Instruction::GetElementPtr)
2295 InBounds = EatIfPresent(lltok::kw_inbounds);
2296 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2297 ParseGlobalValueVector(Elts) ||
2298 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2301 if (Opc == Instruction::GetElementPtr) {
2302 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2303 return Error(ID.Loc, "getelementptr requires pointer operand");
2305 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2306 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2307 return Error(ID.Loc, "invalid indices for getelementptr");
2308 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2310 } else if (Opc == Instruction::Select) {
2311 if (Elts.size() != 3)
2312 return Error(ID.Loc, "expected three operands to select");
2313 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2315 return Error(ID.Loc, Reason);
2316 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2317 } else if (Opc == Instruction::ShuffleVector) {
2318 if (Elts.size() != 3)
2319 return Error(ID.Loc, "expected three operands to shufflevector");
2320 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2321 return Error(ID.Loc, "invalid operands to shufflevector");
2323 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2324 } else if (Opc == Instruction::ExtractElement) {
2325 if (Elts.size() != 2)
2326 return Error(ID.Loc, "expected two operands to extractelement");
2327 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2328 return Error(ID.Loc, "invalid extractelement operands");
2329 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2331 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2332 if (Elts.size() != 3)
2333 return Error(ID.Loc, "expected three operands to insertelement");
2334 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2335 return Error(ID.Loc, "invalid insertelement operands");
2337 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2340 ID.Kind = ValID::t_Constant;
2349 /// ParseGlobalValue - Parse a global value with the specified type.
2350 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2354 bool Parsed = ParseValID(ID) ||
2355 ConvertValIDToValue(Ty, ID, V, NULL);
2356 if (V && !(C = dyn_cast<Constant>(V)))
2357 return Error(ID.Loc, "global values must be constants");
2361 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2363 return ParseType(Ty) ||
2364 ParseGlobalValue(Ty, V);
2367 /// ParseGlobalValueVector
2369 /// ::= TypeAndValue (',' TypeAndValue)*
2370 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2372 if (Lex.getKind() == lltok::rbrace ||
2373 Lex.getKind() == lltok::rsquare ||
2374 Lex.getKind() == lltok::greater ||
2375 Lex.getKind() == lltok::rparen)
2379 if (ParseGlobalTypeAndValue(C)) return true;
2382 while (EatIfPresent(lltok::comma)) {
2383 if (ParseGlobalTypeAndValue(C)) return true;
2390 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2391 assert(Lex.getKind() == lltok::lbrace);
2394 SmallVector<Value*, 16> Elts;
2395 if (ParseMDNodeVector(Elts, PFS) ||
2396 ParseToken(lltok::rbrace, "expected end of metadata node"))
2399 ID.MDNodeVal = MDNode::get(Context, Elts);
2400 ID.Kind = ValID::t_MDNode;
2404 /// ParseMetadataValue
2408 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2409 assert(Lex.getKind() == lltok::exclaim);
2414 if (Lex.getKind() == lltok::lbrace)
2415 return ParseMetadataListValue(ID, PFS);
2417 // Standalone metadata reference
2419 if (Lex.getKind() == lltok::APSInt) {
2420 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2421 ID.Kind = ValID::t_MDNode;
2426 // ::= '!' STRINGCONSTANT
2427 if (ParseMDString(ID.MDStringVal)) return true;
2428 ID.Kind = ValID::t_MDString;
2433 //===----------------------------------------------------------------------===//
2434 // Function Parsing.
2435 //===----------------------------------------------------------------------===//
2437 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2438 PerFunctionState *PFS) {
2439 if (Ty->isFunctionTy())
2440 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2443 default: llvm_unreachable("Unknown ValID!");
2444 case ValID::t_LocalID:
2445 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2446 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2448 case ValID::t_LocalName:
2449 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2450 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2452 case ValID::t_InlineAsm: {
2453 PointerType *PTy = dyn_cast<PointerType>(Ty);
2455 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2456 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2457 return Error(ID.Loc, "invalid type for inline asm constraint string");
2458 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2461 case ValID::t_MDNode:
2462 if (!Ty->isMetadataTy())
2463 return Error(ID.Loc, "metadata value must have metadata type");
2466 case ValID::t_MDString:
2467 if (!Ty->isMetadataTy())
2468 return Error(ID.Loc, "metadata value must have metadata type");
2471 case ValID::t_GlobalName:
2472 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2474 case ValID::t_GlobalID:
2475 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2477 case ValID::t_APSInt:
2478 if (!Ty->isIntegerTy())
2479 return Error(ID.Loc, "integer constant must have integer type");
2480 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2481 V = ConstantInt::get(Context, ID.APSIntVal);
2483 case ValID::t_APFloat:
2484 if (!Ty->isFloatingPointTy() ||
2485 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2486 return Error(ID.Loc, "floating point constant invalid for type");
2488 // The lexer has no type info, so builds all float and double FP constants
2489 // as double. Fix this here. Long double does not need this.
2490 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2493 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2496 V = ConstantFP::get(Context, ID.APFloatVal);
2498 if (V->getType() != Ty)
2499 return Error(ID.Loc, "floating point constant does not have type '" +
2500 getTypeString(Ty) + "'");
2504 if (!Ty->isPointerTy())
2505 return Error(ID.Loc, "null must be a pointer type");
2506 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2508 case ValID::t_Undef:
2509 // FIXME: LabelTy should not be a first-class type.
2510 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2511 return Error(ID.Loc, "invalid type for undef constant");
2512 V = UndefValue::get(Ty);
2514 case ValID::t_EmptyArray:
2515 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2516 return Error(ID.Loc, "invalid empty array initializer");
2517 V = UndefValue::get(Ty);
2520 // FIXME: LabelTy should not be a first-class type.
2521 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2522 return Error(ID.Loc, "invalid type for null constant");
2523 V = Constant::getNullValue(Ty);
2525 case ValID::t_Constant:
2526 if (ID.ConstantVal->getType() != Ty)
2527 return Error(ID.Loc, "constant expression type mismatch");
2531 case ValID::t_ConstantStruct:
2532 case ValID::t_PackedConstantStruct:
2533 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2534 if (ST->getNumElements() != ID.UIntVal)
2535 return Error(ID.Loc,
2536 "initializer with struct type has wrong # elements");
2537 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2538 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2540 // Verify that the elements are compatible with the structtype.
2541 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2542 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2543 return Error(ID.Loc, "element " + Twine(i) +
2544 " of struct initializer doesn't match struct element type");
2546 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2549 return Error(ID.Loc, "constant expression type mismatch");
2554 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2557 return ParseValID(ID, PFS) ||
2558 ConvertValIDToValue(Ty, ID, V, PFS);
2561 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2563 return ParseType(Ty) ||
2564 ParseValue(Ty, V, PFS);
2567 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2568 PerFunctionState &PFS) {
2571 if (ParseTypeAndValue(V, PFS)) return true;
2572 if (!isa<BasicBlock>(V))
2573 return Error(Loc, "expected a basic block");
2574 BB = cast<BasicBlock>(V);
2580 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2581 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2582 /// OptionalAlign OptGC
2583 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2584 // Parse the linkage.
2585 LocTy LinkageLoc = Lex.getLoc();
2588 unsigned Visibility, RetAttrs;
2591 LocTy RetTypeLoc = Lex.getLoc();
2592 if (ParseOptionalLinkage(Linkage) ||
2593 ParseOptionalVisibility(Visibility) ||
2594 ParseOptionalCallingConv(CC) ||
2595 ParseOptionalAttrs(RetAttrs, 1) ||
2596 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2599 // Verify that the linkage is ok.
2600 switch ((GlobalValue::LinkageTypes)Linkage) {
2601 case GlobalValue::ExternalLinkage:
2602 break; // always ok.
2603 case GlobalValue::DLLImportLinkage:
2604 case GlobalValue::ExternalWeakLinkage:
2606 return Error(LinkageLoc, "invalid linkage for function definition");
2608 case GlobalValue::PrivateLinkage:
2609 case GlobalValue::LinkerPrivateLinkage:
2610 case GlobalValue::LinkerPrivateWeakLinkage:
2611 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2612 case GlobalValue::InternalLinkage:
2613 case GlobalValue::AvailableExternallyLinkage:
2614 case GlobalValue::LinkOnceAnyLinkage:
2615 case GlobalValue::LinkOnceODRLinkage:
2616 case GlobalValue::WeakAnyLinkage:
2617 case GlobalValue::WeakODRLinkage:
2618 case GlobalValue::DLLExportLinkage:
2620 return Error(LinkageLoc, "invalid linkage for function declaration");
2622 case GlobalValue::AppendingLinkage:
2623 case GlobalValue::CommonLinkage:
2624 return Error(LinkageLoc, "invalid function linkage type");
2627 if (!FunctionType::isValidReturnType(RetType))
2628 return Error(RetTypeLoc, "invalid function return type");
2630 LocTy NameLoc = Lex.getLoc();
2632 std::string FunctionName;
2633 if (Lex.getKind() == lltok::GlobalVar) {
2634 FunctionName = Lex.getStrVal();
2635 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2636 unsigned NameID = Lex.getUIntVal();
2638 if (NameID != NumberedVals.size())
2639 return TokError("function expected to be numbered '%" +
2640 Twine(NumberedVals.size()) + "'");
2642 return TokError("expected function name");
2647 if (Lex.getKind() != lltok::lparen)
2648 return TokError("expected '(' in function argument list");
2650 SmallVector<ArgInfo, 8> ArgList;
2653 std::string Section;
2657 LocTy UnnamedAddrLoc;
2659 if (ParseArgumentList(ArgList, isVarArg) ||
2660 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2662 ParseOptionalAttrs(FuncAttrs, 2) ||
2663 (EatIfPresent(lltok::kw_section) &&
2664 ParseStringConstant(Section)) ||
2665 ParseOptionalAlignment(Alignment) ||
2666 (EatIfPresent(lltok::kw_gc) &&
2667 ParseStringConstant(GC)))
2670 // If the alignment was parsed as an attribute, move to the alignment field.
2671 if (FuncAttrs & Attribute::Alignment) {
2672 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2673 FuncAttrs &= ~Attribute::Alignment;
2676 // Okay, if we got here, the function is syntactically valid. Convert types
2677 // and do semantic checks.
2678 std::vector<Type*> ParamTypeList;
2679 SmallVector<AttributeWithIndex, 8> Attrs;
2681 if (RetAttrs != Attribute::None)
2682 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2684 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2685 ParamTypeList.push_back(ArgList[i].Ty);
2686 if (ArgList[i].Attrs != Attribute::None)
2687 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2690 if (FuncAttrs != Attribute::None)
2691 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2693 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2695 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2696 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2699 FunctionType::get(RetType, ParamTypeList, isVarArg);
2700 PointerType *PFT = PointerType::getUnqual(FT);
2703 if (!FunctionName.empty()) {
2704 // If this was a definition of a forward reference, remove the definition
2705 // from the forward reference table and fill in the forward ref.
2706 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2707 ForwardRefVals.find(FunctionName);
2708 if (FRVI != ForwardRefVals.end()) {
2709 Fn = M->getFunction(FunctionName);
2710 if (Fn->getType() != PFT)
2711 return Error(FRVI->second.second, "invalid forward reference to "
2712 "function '" + FunctionName + "' with wrong type!");
2714 ForwardRefVals.erase(FRVI);
2715 } else if ((Fn = M->getFunction(FunctionName))) {
2716 // Reject redefinitions.
2717 return Error(NameLoc, "invalid redefinition of function '" +
2718 FunctionName + "'");
2719 } else if (M->getNamedValue(FunctionName)) {
2720 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2724 // If this is a definition of a forward referenced function, make sure the
2726 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2727 = ForwardRefValIDs.find(NumberedVals.size());
2728 if (I != ForwardRefValIDs.end()) {
2729 Fn = cast<Function>(I->second.first);
2730 if (Fn->getType() != PFT)
2731 return Error(NameLoc, "type of definition and forward reference of '@" +
2732 Twine(NumberedVals.size()) + "' disagree");
2733 ForwardRefValIDs.erase(I);
2738 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2739 else // Move the forward-reference to the correct spot in the module.
2740 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2742 if (FunctionName.empty())
2743 NumberedVals.push_back(Fn);
2745 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2746 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2747 Fn->setCallingConv(CC);
2748 Fn->setAttributes(PAL);
2749 Fn->setUnnamedAddr(UnnamedAddr);
2750 Fn->setAlignment(Alignment);
2751 Fn->setSection(Section);
2752 if (!GC.empty()) Fn->setGC(GC.c_str());
2754 // Add all of the arguments we parsed to the function.
2755 Function::arg_iterator ArgIt = Fn->arg_begin();
2756 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2757 // If the argument has a name, insert it into the argument symbol table.
2758 if (ArgList[i].Name.empty()) continue;
2760 // Set the name, if it conflicted, it will be auto-renamed.
2761 ArgIt->setName(ArgList[i].Name);
2763 if (ArgIt->getName() != ArgList[i].Name)
2764 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2765 ArgList[i].Name + "'");
2772 /// ParseFunctionBody
2773 /// ::= '{' BasicBlock+ '}'
2775 bool LLParser::ParseFunctionBody(Function &Fn) {
2776 if (Lex.getKind() != lltok::lbrace)
2777 return TokError("expected '{' in function body");
2778 Lex.Lex(); // eat the {.
2780 int FunctionNumber = -1;
2781 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2783 PerFunctionState PFS(*this, Fn, FunctionNumber);
2785 // We need at least one basic block.
2786 if (Lex.getKind() == lltok::rbrace)
2787 return TokError("function body requires at least one basic block");
2789 while (Lex.getKind() != lltok::rbrace)
2790 if (ParseBasicBlock(PFS)) return true;
2795 // Verify function is ok.
2796 return PFS.FinishFunction();
2800 /// ::= LabelStr? Instruction*
2801 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2802 // If this basic block starts out with a name, remember it.
2804 LocTy NameLoc = Lex.getLoc();
2805 if (Lex.getKind() == lltok::LabelStr) {
2806 Name = Lex.getStrVal();
2810 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2811 if (BB == 0) return true;
2813 std::string NameStr;
2815 // Parse the instructions in this block until we get a terminator.
2817 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2819 // This instruction may have three possibilities for a name: a) none
2820 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2821 LocTy NameLoc = Lex.getLoc();
2825 if (Lex.getKind() == lltok::LocalVarID) {
2826 NameID = Lex.getUIntVal();
2828 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2830 } else if (Lex.getKind() == lltok::LocalVar) {
2831 NameStr = Lex.getStrVal();
2833 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2837 switch (ParseInstruction(Inst, BB, PFS)) {
2838 default: assert(0 && "Unknown ParseInstruction result!");
2839 case InstError: return true;
2841 BB->getInstList().push_back(Inst);
2843 // With a normal result, we check to see if the instruction is followed by
2844 // a comma and metadata.
2845 if (EatIfPresent(lltok::comma))
2846 if (ParseInstructionMetadata(Inst, &PFS))
2849 case InstExtraComma:
2850 BB->getInstList().push_back(Inst);
2852 // If the instruction parser ate an extra comma at the end of it, it
2853 // *must* be followed by metadata.
2854 if (ParseInstructionMetadata(Inst, &PFS))
2859 // Set the name on the instruction.
2860 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2861 } while (!isa<TerminatorInst>(Inst));
2866 //===----------------------------------------------------------------------===//
2867 // Instruction Parsing.
2868 //===----------------------------------------------------------------------===//
2870 /// ParseInstruction - Parse one of the many different instructions.
2872 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2873 PerFunctionState &PFS) {
2874 lltok::Kind Token = Lex.getKind();
2875 if (Token == lltok::Eof)
2876 return TokError("found end of file when expecting more instructions");
2877 LocTy Loc = Lex.getLoc();
2878 unsigned KeywordVal = Lex.getUIntVal();
2879 Lex.Lex(); // Eat the keyword.
2882 default: return Error(Loc, "expected instruction opcode");
2883 // Terminator Instructions.
2884 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2885 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2886 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2887 case lltok::kw_br: return ParseBr(Inst, PFS);
2888 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2889 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2890 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2891 case lltok::kw_resume: return ParseResume(Inst, PFS);
2892 // Binary Operators.
2896 case lltok::kw_shl: {
2897 bool NUW = EatIfPresent(lltok::kw_nuw);
2898 bool NSW = EatIfPresent(lltok::kw_nsw);
2899 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2901 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2903 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2904 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2907 case lltok::kw_fadd:
2908 case lltok::kw_fsub:
2909 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2911 case lltok::kw_sdiv:
2912 case lltok::kw_udiv:
2913 case lltok::kw_lshr:
2914 case lltok::kw_ashr: {
2915 bool Exact = EatIfPresent(lltok::kw_exact);
2917 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2918 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2922 case lltok::kw_urem:
2923 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2924 case lltok::kw_fdiv:
2925 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2928 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2929 case lltok::kw_icmp:
2930 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2932 case lltok::kw_trunc:
2933 case lltok::kw_zext:
2934 case lltok::kw_sext:
2935 case lltok::kw_fptrunc:
2936 case lltok::kw_fpext:
2937 case lltok::kw_bitcast:
2938 case lltok::kw_uitofp:
2939 case lltok::kw_sitofp:
2940 case lltok::kw_fptoui:
2941 case lltok::kw_fptosi:
2942 case lltok::kw_inttoptr:
2943 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2945 case lltok::kw_select: return ParseSelect(Inst, PFS);
2946 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2947 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2948 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2949 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2950 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2951 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
2952 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2953 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2955 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2956 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2957 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2958 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
2959 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
2960 case lltok::kw_fence: return ParseFence(Inst, PFS);
2961 case lltok::kw_volatile:
2962 // For compatibility; canonical location is after load
2963 if (EatIfPresent(lltok::kw_load))
2964 return ParseLoad(Inst, PFS, true);
2965 else if (EatIfPresent(lltok::kw_store))
2966 return ParseStore(Inst, PFS, true);
2968 return TokError("expected 'load' or 'store'");
2969 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2970 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2971 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2975 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2976 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2977 if (Opc == Instruction::FCmp) {
2978 switch (Lex.getKind()) {
2979 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2980 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2981 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2982 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2983 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2984 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2985 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2986 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2987 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2988 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2989 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2990 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2991 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2992 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2993 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2994 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2995 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2998 switch (Lex.getKind()) {
2999 default: TokError("expected icmp predicate (e.g. 'eq')");
3000 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3001 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3002 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3003 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3004 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3005 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3006 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3007 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3008 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3009 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3016 //===----------------------------------------------------------------------===//
3017 // Terminator Instructions.
3018 //===----------------------------------------------------------------------===//
3020 /// ParseRet - Parse a return instruction.
3021 /// ::= 'ret' void (',' !dbg, !1)*
3022 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3023 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3024 PerFunctionState &PFS) {
3025 SMLoc TypeLoc = Lex.getLoc();
3027 if (ParseType(Ty, true /*void allowed*/)) return true;
3029 Type *ResType = PFS.getFunction().getReturnType();
3031 if (Ty->isVoidTy()) {
3032 if (!ResType->isVoidTy())
3033 return Error(TypeLoc, "value doesn't match function result type '" +
3034 getTypeString(ResType) + "'");
3036 Inst = ReturnInst::Create(Context);
3041 if (ParseValue(Ty, RV, PFS)) return true;
3043 if (ResType != RV->getType())
3044 return Error(TypeLoc, "value doesn't match function result type '" +
3045 getTypeString(ResType) + "'");
3047 Inst = ReturnInst::Create(Context, RV);
3053 /// ::= 'br' TypeAndValue
3054 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3055 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3058 BasicBlock *Op1, *Op2;
3059 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3061 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3062 Inst = BranchInst::Create(BB);
3066 if (Op0->getType() != Type::getInt1Ty(Context))
3067 return Error(Loc, "branch condition must have 'i1' type");
3069 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3070 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3071 ParseToken(lltok::comma, "expected ',' after true destination") ||
3072 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3075 Inst = BranchInst::Create(Op1, Op2, Op0);
3081 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3083 /// ::= (TypeAndValue ',' TypeAndValue)*
3084 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3085 LocTy CondLoc, BBLoc;
3087 BasicBlock *DefaultBB;
3088 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3089 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3090 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3091 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3094 if (!Cond->getType()->isIntegerTy())
3095 return Error(CondLoc, "switch condition must have integer type");
3097 // Parse the jump table pairs.
3098 SmallPtrSet<Value*, 32> SeenCases;
3099 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3100 while (Lex.getKind() != lltok::rsquare) {
3104 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3105 ParseToken(lltok::comma, "expected ',' after case value") ||
3106 ParseTypeAndBasicBlock(DestBB, PFS))
3109 if (!SeenCases.insert(Constant))
3110 return Error(CondLoc, "duplicate case value in switch");
3111 if (!isa<ConstantInt>(Constant))
3112 return Error(CondLoc, "case value is not a constant integer");
3114 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3117 Lex.Lex(); // Eat the ']'.
3119 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3120 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3121 SI->addCase(Table[i].first, Table[i].second);
3128 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3129 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3132 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3133 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3134 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3137 if (!Address->getType()->isPointerTy())
3138 return Error(AddrLoc, "indirectbr address must have pointer type");
3140 // Parse the destination list.
3141 SmallVector<BasicBlock*, 16> DestList;
3143 if (Lex.getKind() != lltok::rsquare) {
3145 if (ParseTypeAndBasicBlock(DestBB, PFS))
3147 DestList.push_back(DestBB);
3149 while (EatIfPresent(lltok::comma)) {
3150 if (ParseTypeAndBasicBlock(DestBB, PFS))
3152 DestList.push_back(DestBB);
3156 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3159 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3160 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3161 IBI->addDestination(DestList[i]);
3168 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3169 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3170 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3171 LocTy CallLoc = Lex.getLoc();
3172 unsigned RetAttrs, FnAttrs;
3177 SmallVector<ParamInfo, 16> ArgList;
3179 BasicBlock *NormalBB, *UnwindBB;
3180 if (ParseOptionalCallingConv(CC) ||
3181 ParseOptionalAttrs(RetAttrs, 1) ||
3182 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3183 ParseValID(CalleeID) ||
3184 ParseParameterList(ArgList, PFS) ||
3185 ParseOptionalAttrs(FnAttrs, 2) ||
3186 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3187 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3188 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3189 ParseTypeAndBasicBlock(UnwindBB, PFS))
3192 // If RetType is a non-function pointer type, then this is the short syntax
3193 // for the call, which means that RetType is just the return type. Infer the
3194 // rest of the function argument types from the arguments that are present.
3195 PointerType *PFTy = 0;
3196 FunctionType *Ty = 0;
3197 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3198 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3199 // Pull out the types of all of the arguments...
3200 std::vector<Type*> ParamTypes;
3201 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3202 ParamTypes.push_back(ArgList[i].V->getType());
3204 if (!FunctionType::isValidReturnType(RetType))
3205 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3207 Ty = FunctionType::get(RetType, ParamTypes, false);
3208 PFTy = PointerType::getUnqual(Ty);
3211 // Look up the callee.
3213 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3215 // Set up the Attributes for the function.
3216 SmallVector<AttributeWithIndex, 8> Attrs;
3217 if (RetAttrs != Attribute::None)
3218 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3220 SmallVector<Value*, 8> Args;
3222 // Loop through FunctionType's arguments and ensure they are specified
3223 // correctly. Also, gather any parameter attributes.
3224 FunctionType::param_iterator I = Ty->param_begin();
3225 FunctionType::param_iterator E = Ty->param_end();
3226 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3227 Type *ExpectedTy = 0;
3230 } else if (!Ty->isVarArg()) {
3231 return Error(ArgList[i].Loc, "too many arguments specified");
3234 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3235 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3236 getTypeString(ExpectedTy) + "'");
3237 Args.push_back(ArgList[i].V);
3238 if (ArgList[i].Attrs != Attribute::None)
3239 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3243 return Error(CallLoc, "not enough parameters specified for call");
3245 if (FnAttrs != Attribute::None)
3246 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3248 // Finish off the Attributes and check them
3249 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3251 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3252 II->setCallingConv(CC);
3253 II->setAttributes(PAL);
3259 /// ::= 'resume' TypeAndValue
3260 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3261 Value *Exn; LocTy ExnLoc;
3262 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3265 ResumeInst *RI = ResumeInst::Create(Exn);
3270 //===----------------------------------------------------------------------===//
3271 // Binary Operators.
3272 //===----------------------------------------------------------------------===//
3275 /// ::= ArithmeticOps TypeAndValue ',' Value
3277 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3278 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3279 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3280 unsigned Opc, unsigned OperandType) {
3281 LocTy Loc; Value *LHS, *RHS;
3282 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3283 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3284 ParseValue(LHS->getType(), RHS, PFS))
3288 switch (OperandType) {
3289 default: llvm_unreachable("Unknown operand type!");
3290 case 0: // int or FP.
3291 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3292 LHS->getType()->isFPOrFPVectorTy();
3294 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3295 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3299 return Error(Loc, "invalid operand type for instruction");
3301 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3306 /// ::= ArithmeticOps TypeAndValue ',' Value {
3307 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3309 LocTy Loc; Value *LHS, *RHS;
3310 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3311 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3312 ParseValue(LHS->getType(), RHS, PFS))
3315 if (!LHS->getType()->isIntOrIntVectorTy())
3316 return Error(Loc,"instruction requires integer or integer vector operands");
3318 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3324 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3325 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3326 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3328 // Parse the integer/fp comparison predicate.
3332 if (ParseCmpPredicate(Pred, Opc) ||
3333 ParseTypeAndValue(LHS, Loc, PFS) ||
3334 ParseToken(lltok::comma, "expected ',' after compare value") ||
3335 ParseValue(LHS->getType(), RHS, PFS))
3338 if (Opc == Instruction::FCmp) {
3339 if (!LHS->getType()->isFPOrFPVectorTy())
3340 return Error(Loc, "fcmp requires floating point operands");
3341 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3343 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3344 if (!LHS->getType()->isIntOrIntVectorTy() &&
3345 !LHS->getType()->isPointerTy())
3346 return Error(Loc, "icmp requires integer operands");
3347 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3352 //===----------------------------------------------------------------------===//
3353 // Other Instructions.
3354 //===----------------------------------------------------------------------===//
3358 /// ::= CastOpc TypeAndValue 'to' Type
3359 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3364 if (ParseTypeAndValue(Op, Loc, PFS) ||
3365 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3369 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3370 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3371 return Error(Loc, "invalid cast opcode for cast from '" +
3372 getTypeString(Op->getType()) + "' to '" +
3373 getTypeString(DestTy) + "'");
3375 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3380 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3381 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3383 Value *Op0, *Op1, *Op2;
3384 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3385 ParseToken(lltok::comma, "expected ',' after select condition") ||
3386 ParseTypeAndValue(Op1, PFS) ||
3387 ParseToken(lltok::comma, "expected ',' after select value") ||
3388 ParseTypeAndValue(Op2, PFS))
3391 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3392 return Error(Loc, Reason);
3394 Inst = SelectInst::Create(Op0, Op1, Op2);
3399 /// ::= 'va_arg' TypeAndValue ',' Type
3400 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3404 if (ParseTypeAndValue(Op, PFS) ||
3405 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3406 ParseType(EltTy, TypeLoc))
3409 if (!EltTy->isFirstClassType())
3410 return Error(TypeLoc, "va_arg requires operand with first class type");
3412 Inst = new VAArgInst(Op, EltTy);
3416 /// ParseExtractElement
3417 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3418 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3421 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after extract value") ||
3423 ParseTypeAndValue(Op1, PFS))
3426 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3427 return Error(Loc, "invalid extractelement operands");
3429 Inst = ExtractElementInst::Create(Op0, Op1);
3433 /// ParseInsertElement
3434 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3435 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3437 Value *Op0, *Op1, *Op2;
3438 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3439 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3440 ParseTypeAndValue(Op1, PFS) ||
3441 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3442 ParseTypeAndValue(Op2, PFS))
3445 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3446 return Error(Loc, "invalid insertelement operands");
3448 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3452 /// ParseShuffleVector
3453 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3454 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3456 Value *Op0, *Op1, *Op2;
3457 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3458 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3459 ParseTypeAndValue(Op1, PFS) ||
3460 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3461 ParseTypeAndValue(Op2, PFS))
3464 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3465 return Error(Loc, "invalid extractelement operands");
3467 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3472 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3473 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3474 Type *Ty = 0; LocTy TypeLoc;
3477 if (ParseType(Ty, TypeLoc) ||
3478 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3479 ParseValue(Ty, Op0, PFS) ||
3480 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3481 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3482 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3485 bool AteExtraComma = false;
3486 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3488 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3490 if (!EatIfPresent(lltok::comma))
3493 if (Lex.getKind() == lltok::MetadataVar) {
3494 AteExtraComma = true;
3498 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3499 ParseValue(Ty, Op0, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3501 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3502 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3506 if (!Ty->isFirstClassType())
3507 return Error(TypeLoc, "phi node must have first class type");
3509 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3510 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3511 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3513 return AteExtraComma ? InstExtraComma : InstNormal;
3517 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3519 /// ::= 'catch' TypeAndValue
3521 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3522 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3523 Type *Ty = 0; LocTy TyLoc;
3524 Value *PersFn; LocTy PersFnLoc;
3526 if (ParseType(Ty, TyLoc) ||
3527 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3528 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3531 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3532 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3534 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3535 LandingPadInst::ClauseType CT;
3536 if (EatIfPresent(lltok::kw_catch))
3537 CT = LandingPadInst::Catch;
3538 else if (EatIfPresent(lltok::kw_filter))
3539 CT = LandingPadInst::Filter;
3541 return TokError("expected 'catch' or 'filter' clause type");
3543 Value *V; LocTy VLoc;
3544 if (ParseTypeAndValue(V, VLoc, PFS)) {
3549 // A 'catch' type expects a non-array constant. A filter clause expects an
3551 if (CT == LandingPadInst::Catch) {
3552 if (isa<ArrayType>(V->getType()))
3553 Error(VLoc, "'catch' clause has an invalid type");
3555 if (!isa<ArrayType>(V->getType()))
3556 Error(VLoc, "'filter' clause has an invalid type");
3567 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3568 /// ParameterList OptionalAttrs
3569 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3571 unsigned RetAttrs, FnAttrs;
3576 SmallVector<ParamInfo, 16> ArgList;
3577 LocTy CallLoc = Lex.getLoc();
3579 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3580 ParseOptionalCallingConv(CC) ||
3581 ParseOptionalAttrs(RetAttrs, 1) ||
3582 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3583 ParseValID(CalleeID) ||
3584 ParseParameterList(ArgList, PFS) ||
3585 ParseOptionalAttrs(FnAttrs, 2))
3588 // If RetType is a non-function pointer type, then this is the short syntax
3589 // for the call, which means that RetType is just the return type. Infer the
3590 // rest of the function argument types from the arguments that are present.
3591 PointerType *PFTy = 0;
3592 FunctionType *Ty = 0;
3593 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3594 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3595 // Pull out the types of all of the arguments...
3596 std::vector<Type*> ParamTypes;
3597 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3598 ParamTypes.push_back(ArgList[i].V->getType());
3600 if (!FunctionType::isValidReturnType(RetType))
3601 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3603 Ty = FunctionType::get(RetType, ParamTypes, false);
3604 PFTy = PointerType::getUnqual(Ty);
3607 // Look up the callee.
3609 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3611 // Set up the Attributes for the function.
3612 SmallVector<AttributeWithIndex, 8> Attrs;
3613 if (RetAttrs != Attribute::None)
3614 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3616 SmallVector<Value*, 8> Args;
3618 // Loop through FunctionType's arguments and ensure they are specified
3619 // correctly. Also, gather any parameter attributes.
3620 FunctionType::param_iterator I = Ty->param_begin();
3621 FunctionType::param_iterator E = Ty->param_end();
3622 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3623 Type *ExpectedTy = 0;
3626 } else if (!Ty->isVarArg()) {
3627 return Error(ArgList[i].Loc, "too many arguments specified");
3630 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3631 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3632 getTypeString(ExpectedTy) + "'");
3633 Args.push_back(ArgList[i].V);
3634 if (ArgList[i].Attrs != Attribute::None)
3635 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3639 return Error(CallLoc, "not enough parameters specified for call");
3641 if (FnAttrs != Attribute::None)
3642 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3644 // Finish off the Attributes and check them
3645 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3647 CallInst *CI = CallInst::Create(Callee, Args);
3648 CI->setTailCall(isTail);
3649 CI->setCallingConv(CC);
3650 CI->setAttributes(PAL);
3655 //===----------------------------------------------------------------------===//
3656 // Memory Instructions.
3657 //===----------------------------------------------------------------------===//
3660 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3661 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3664 unsigned Alignment = 0;
3666 if (ParseType(Ty)) return true;
3668 bool AteExtraComma = false;
3669 if (EatIfPresent(lltok::comma)) {
3670 if (Lex.getKind() == lltok::kw_align) {
3671 if (ParseOptionalAlignment(Alignment)) return true;
3672 } else if (Lex.getKind() == lltok::MetadataVar) {
3673 AteExtraComma = true;
3675 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3676 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3681 if (Size && !Size->getType()->isIntegerTy())
3682 return Error(SizeLoc, "element count must have integer type");
3684 Inst = new AllocaInst(Ty, Size, Alignment);
3685 return AteExtraComma ? InstExtraComma : InstNormal;
3689 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3690 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3691 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3693 /// ::= 'volatile' 'load' TypeAndValue (',' 'align' i32)?
3694 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3696 Value *Val; LocTy Loc;
3697 unsigned Alignment = 0;
3698 bool AteExtraComma = false;
3699 bool isAtomic = false;
3700 AtomicOrdering Ordering = NotAtomic;
3701 SynchronizationScope Scope = CrossThread;
3703 if (Lex.getKind() == lltok::kw_atomic) {
3705 return TokError("mixing atomic with old volatile placement");
3710 if (Lex.getKind() == lltok::kw_volatile) {
3712 return TokError("duplicate volatile before and after store");
3717 if (ParseTypeAndValue(Val, Loc, PFS) ||
3718 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3719 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3722 if (!Val->getType()->isPointerTy() ||
3723 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3724 return Error(Loc, "load operand must be a pointer to a first class type");
3725 if (isAtomic && !Alignment)
3726 return Error(Loc, "atomic load must have explicit non-zero alignment");
3727 if (Ordering == Release || Ordering == AcquireRelease)
3728 return Error(Loc, "atomic load cannot use Release ordering");
3730 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3731 return AteExtraComma ? InstExtraComma : InstNormal;
3736 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3737 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3738 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3740 /// ::= 'volatile' 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3741 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3743 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3744 unsigned Alignment = 0;
3745 bool AteExtraComma = false;
3746 bool isAtomic = false;
3747 AtomicOrdering Ordering = NotAtomic;
3748 SynchronizationScope Scope = CrossThread;
3750 if (Lex.getKind() == lltok::kw_atomic) {
3752 return TokError("mixing atomic with old volatile placement");
3757 if (Lex.getKind() == lltok::kw_volatile) {
3759 return TokError("duplicate volatile before and after store");
3764 if (ParseTypeAndValue(Val, Loc, PFS) ||
3765 ParseToken(lltok::comma, "expected ',' after store operand") ||
3766 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3767 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3768 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3771 if (!Ptr->getType()->isPointerTy())
3772 return Error(PtrLoc, "store operand must be a pointer");
3773 if (!Val->getType()->isFirstClassType())
3774 return Error(Loc, "store operand must be a first class value");
3775 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3776 return Error(Loc, "stored value and pointer type do not match");
3777 if (isAtomic && !Alignment)
3778 return Error(Loc, "atomic store must have explicit non-zero alignment");
3779 if (Ordering == Acquire || Ordering == AcquireRelease)
3780 return Error(Loc, "atomic store cannot use Acquire ordering");
3782 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3783 return AteExtraComma ? InstExtraComma : InstNormal;
3787 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3788 /// 'singlethread'? AtomicOrdering
3789 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3790 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3791 bool AteExtraComma = false;
3792 AtomicOrdering Ordering = NotAtomic;
3793 SynchronizationScope Scope = CrossThread;
3794 bool isVolatile = false;
3796 if (EatIfPresent(lltok::kw_volatile))
3799 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3800 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3801 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3802 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3803 ParseTypeAndValue(New, NewLoc, PFS) ||
3804 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3807 if (Ordering == Unordered)
3808 return TokError("cmpxchg cannot be unordered");
3809 if (!Ptr->getType()->isPointerTy())
3810 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3811 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3812 return Error(CmpLoc, "compare value and pointer type do not match");
3813 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3814 return Error(NewLoc, "new value and pointer type do not match");
3815 if (!New->getType()->isIntegerTy())
3816 return Error(NewLoc, "cmpxchg operand must be an integer");
3817 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3818 if (Size < 8 || (Size & (Size - 1)))
3819 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3822 AtomicCmpXchgInst *CXI =
3823 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3824 CXI->setVolatile(isVolatile);
3826 return AteExtraComma ? InstExtraComma : InstNormal;
3830 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3831 /// 'singlethread'? AtomicOrdering
3832 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3833 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3834 bool AteExtraComma = false;
3835 AtomicOrdering Ordering = NotAtomic;
3836 SynchronizationScope Scope = CrossThread;
3837 bool isVolatile = false;
3838 AtomicRMWInst::BinOp Operation;
3840 if (EatIfPresent(lltok::kw_volatile))
3843 switch (Lex.getKind()) {
3844 default: return TokError("expected binary operation in atomicrmw");
3845 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3846 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3847 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3848 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3849 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3850 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3851 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3852 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3853 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3854 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3855 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3857 Lex.Lex(); // Eat the operation.
3859 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3860 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3861 ParseTypeAndValue(Val, ValLoc, PFS) ||
3862 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3865 if (Ordering == Unordered)
3866 return TokError("atomicrmw cannot be unordered");
3867 if (!Ptr->getType()->isPointerTy())
3868 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3869 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3870 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3871 if (!Val->getType()->isIntegerTy())
3872 return Error(ValLoc, "atomicrmw operand must be an integer");
3873 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3874 if (Size < 8 || (Size & (Size - 1)))
3875 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3878 AtomicRMWInst *RMWI =
3879 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3880 RMWI->setVolatile(isVolatile);
3882 return AteExtraComma ? InstExtraComma : InstNormal;
3886 /// ::= 'fence' 'singlethread'? AtomicOrdering
3887 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3888 AtomicOrdering Ordering = NotAtomic;
3889 SynchronizationScope Scope = CrossThread;
3890 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3893 if (Ordering == Unordered)
3894 return TokError("fence cannot be unordered");
3895 if (Ordering == Monotonic)
3896 return TokError("fence cannot be monotonic");
3898 Inst = new FenceInst(Context, Ordering, Scope);
3902 /// ParseGetElementPtr
3903 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3904 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3905 Value *Ptr, *Val; LocTy Loc, EltLoc;
3907 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3909 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3911 if (!Ptr->getType()->isPointerTy())
3912 return Error(Loc, "base of getelementptr must be a pointer");
3914 SmallVector<Value*, 16> Indices;
3915 bool AteExtraComma = false;
3916 while (EatIfPresent(lltok::comma)) {
3917 if (Lex.getKind() == lltok::MetadataVar) {
3918 AteExtraComma = true;
3921 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3922 if (!Val->getType()->isIntegerTy())
3923 return Error(EltLoc, "getelementptr index must be an integer");
3924 Indices.push_back(Val);
3927 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
3928 return Error(Loc, "invalid getelementptr indices");
3929 Inst = GetElementPtrInst::Create(Ptr, Indices);
3931 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3932 return AteExtraComma ? InstExtraComma : InstNormal;
3935 /// ParseExtractValue
3936 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3937 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3938 Value *Val; LocTy Loc;
3939 SmallVector<unsigned, 4> Indices;
3941 if (ParseTypeAndValue(Val, Loc, PFS) ||
3942 ParseIndexList(Indices, AteExtraComma))
3945 if (!Val->getType()->isAggregateType())
3946 return Error(Loc, "extractvalue operand must be aggregate type");
3948 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3949 return Error(Loc, "invalid indices for extractvalue");
3950 Inst = ExtractValueInst::Create(Val, Indices);
3951 return AteExtraComma ? InstExtraComma : InstNormal;
3954 /// ParseInsertValue
3955 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3956 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3957 Value *Val0, *Val1; LocTy Loc0, Loc1;
3958 SmallVector<unsigned, 4> Indices;
3960 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3961 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3962 ParseTypeAndValue(Val1, Loc1, PFS) ||
3963 ParseIndexList(Indices, AteExtraComma))
3966 if (!Val0->getType()->isAggregateType())
3967 return Error(Loc0, "insertvalue operand must be aggregate type");
3969 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
3970 return Error(Loc0, "invalid indices for insertvalue");
3971 Inst = InsertValueInst::Create(Val0, Val1, Indices);
3972 return AteExtraComma ? InstExtraComma : InstNormal;
3975 //===----------------------------------------------------------------------===//
3976 // Embedded metadata.
3977 //===----------------------------------------------------------------------===//
3979 /// ParseMDNodeVector
3980 /// ::= Element (',' Element)*
3982 /// ::= 'null' | TypeAndValue
3983 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3984 PerFunctionState *PFS) {
3985 // Check for an empty list.
3986 if (Lex.getKind() == lltok::rbrace)
3990 // Null is a special case since it is typeless.
3991 if (EatIfPresent(lltok::kw_null)) {
3997 if (ParseTypeAndValue(V, PFS)) return true;
3999 } while (EatIfPresent(lltok::comma));