1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
187 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
193 case lltok::kw_appending: // OptionalLinkage
194 case lltok::kw_dllexport: // OptionalLinkage
195 case lltok::kw_common: // OptionalLinkage
196 case lltok::kw_dllimport: // OptionalLinkage
197 case lltok::kw_extern_weak: // OptionalLinkage
198 case lltok::kw_external: { // OptionalLinkage
199 unsigned Linkage, Visibility;
200 if (ParseOptionalLinkage(Linkage) ||
201 ParseOptionalVisibility(Visibility) ||
202 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
206 case lltok::kw_default: // OptionalVisibility
207 case lltok::kw_hidden: // OptionalVisibility
208 case lltok::kw_protected: { // OptionalVisibility
210 if (ParseOptionalVisibility(Visibility) ||
211 ParseGlobal("", SMLoc(), 0, false, Visibility))
216 case lltok::kw_thread_local: // OptionalThreadLocal
217 case lltok::kw_addrspace: // OptionalAddrSpace
218 case lltok::kw_constant: // GlobalType
219 case lltok::kw_global: // GlobalType
220 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
228 /// ::= 'module' 'asm' STRINGCONSTANT
229 bool LLParser::ParseModuleAsm() {
230 assert(Lex.getKind() == lltok::kw_module);
234 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
235 ParseStringConstant(AsmStr)) return true;
237 M->appendModuleInlineAsm(AsmStr);
242 /// ::= 'target' 'triple' '=' STRINGCONSTANT
243 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
244 bool LLParser::ParseTargetDefinition() {
245 assert(Lex.getKind() == lltok::kw_target);
248 default: return TokError("unknown target property");
249 case lltok::kw_triple:
251 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
252 ParseStringConstant(Str))
254 M->setTargetTriple(Str);
256 case lltok::kw_datalayout:
258 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
259 ParseStringConstant(Str))
261 M->setDataLayout(Str);
267 /// ::= 'deplibs' '=' '[' ']'
268 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
269 bool LLParser::ParseDepLibs() {
270 assert(Lex.getKind() == lltok::kw_deplibs);
272 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
273 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
276 if (EatIfPresent(lltok::rsquare))
280 if (ParseStringConstant(Str)) return true;
283 while (EatIfPresent(lltok::comma)) {
284 if (ParseStringConstant(Str)) return true;
288 return ParseToken(lltok::rsquare, "expected ']' at end of list");
291 /// ParseUnnamedType:
292 /// ::= LocalVarID '=' 'type' type
293 bool LLParser::ParseUnnamedType() {
294 LocTy TypeLoc = Lex.getLoc();
295 unsigned TypeID = Lex.getUIntVal();
296 Lex.Lex(); // eat LocalVarID;
298 if (ParseToken(lltok::equal, "expected '=' after name") ||
299 ParseToken(lltok::kw_type, "expected 'type' after '='"))
302 if (TypeID >= NumberedTypes.size())
303 NumberedTypes.resize(TypeID+1);
306 if (ParseStructDefinition(TypeLoc, "",
307 NumberedTypes[TypeID], Result)) return true;
309 if (!isa<StructType>(Result)) {
310 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
312 return Error(TypeLoc, "non-struct types may not be recursive");
313 Entry.first = Result;
314 Entry.second = SMLoc();
322 /// ::= LocalVar '=' 'type' type
323 bool LLParser::ParseNamedType() {
324 std::string Name = Lex.getStrVal();
325 LocTy NameLoc = Lex.getLoc();
326 Lex.Lex(); // eat LocalVar.
328 if (ParseToken(lltok::equal, "expected '=' after name") ||
329 ParseToken(lltok::kw_type, "expected 'type' after name"))
333 if (ParseStructDefinition(NameLoc, Name,
334 NamedTypes[Name], Result)) return true;
336 if (!isa<StructType>(Result)) {
337 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
339 return Error(NameLoc, "non-struct types may not be recursive");
340 Entry.first = Result;
341 Entry.second = SMLoc();
349 /// ::= 'declare' FunctionHeader
350 bool LLParser::ParseDeclare() {
351 assert(Lex.getKind() == lltok::kw_declare);
355 return ParseFunctionHeader(F, false);
359 /// ::= 'define' FunctionHeader '{' ...
360 bool LLParser::ParseDefine() {
361 assert(Lex.getKind() == lltok::kw_define);
365 return ParseFunctionHeader(F, true) ||
366 ParseFunctionBody(*F);
372 bool LLParser::ParseGlobalType(bool &IsConstant) {
373 if (Lex.getKind() == lltok::kw_constant)
375 else if (Lex.getKind() == lltok::kw_global)
379 return TokError("expected 'global' or 'constant'");
385 /// ParseUnnamedGlobal:
386 /// OptionalVisibility ALIAS ...
387 /// OptionalLinkage OptionalVisibility ... -> global variable
388 /// GlobalID '=' OptionalVisibility ALIAS ...
389 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
390 bool LLParser::ParseUnnamedGlobal() {
391 unsigned VarID = NumberedVals.size();
393 LocTy NameLoc = Lex.getLoc();
395 // Handle the GlobalID form.
396 if (Lex.getKind() == lltok::GlobalID) {
397 if (Lex.getUIntVal() != VarID)
398 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
400 Lex.Lex(); // eat GlobalID;
402 if (ParseToken(lltok::equal, "expected '=' after name"))
407 unsigned Linkage, Visibility;
408 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
409 ParseOptionalVisibility(Visibility))
412 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
413 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
414 return ParseAlias(Name, NameLoc, Visibility);
417 /// ParseNamedGlobal:
418 /// GlobalVar '=' OptionalVisibility ALIAS ...
419 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
420 bool LLParser::ParseNamedGlobal() {
421 assert(Lex.getKind() == lltok::GlobalVar);
422 LocTy NameLoc = Lex.getLoc();
423 std::string Name = Lex.getStrVal();
427 unsigned Linkage, Visibility;
428 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
429 ParseOptionalLinkage(Linkage, HasLinkage) ||
430 ParseOptionalVisibility(Visibility))
433 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
434 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
435 return ParseAlias(Name, NameLoc, Visibility);
439 // ::= '!' STRINGCONSTANT
440 bool LLParser::ParseMDString(MDString *&Result) {
442 if (ParseStringConstant(Str)) return true;
443 Result = MDString::get(Context, Str);
448 // ::= '!' MDNodeNumber
450 /// This version of ParseMDNodeID returns the slot number and null in the case
451 /// of a forward reference.
452 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
453 // !{ ..., !42, ... }
454 if (ParseUInt32(SlotNo)) return true;
456 // Check existing MDNode.
457 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
458 Result = NumberedMetadata[SlotNo];
464 bool LLParser::ParseMDNodeID(MDNode *&Result) {
465 // !{ ..., !42, ... }
467 if (ParseMDNodeID(Result, MID)) return true;
469 // If not a forward reference, just return it now.
470 if (Result) return false;
472 // Otherwise, create MDNode forward reference.
473 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
474 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
476 if (NumberedMetadata.size() <= MID)
477 NumberedMetadata.resize(MID+1);
478 NumberedMetadata[MID] = FwdNode;
483 /// ParseNamedMetadata:
484 /// !foo = !{ !1, !2 }
485 bool LLParser::ParseNamedMetadata() {
486 assert(Lex.getKind() == lltok::MetadataVar);
487 std::string Name = Lex.getStrVal();
490 if (ParseToken(lltok::equal, "expected '=' here") ||
491 ParseToken(lltok::exclaim, "Expected '!' here") ||
492 ParseToken(lltok::lbrace, "Expected '{' here"))
495 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
496 if (Lex.getKind() != lltok::rbrace)
498 if (ParseToken(lltok::exclaim, "Expected '!' here"))
502 if (ParseMDNodeID(N)) return true;
504 } while (EatIfPresent(lltok::comma));
506 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
512 /// ParseStandaloneMetadata:
514 bool LLParser::ParseStandaloneMetadata() {
515 assert(Lex.getKind() == lltok::exclaim);
517 unsigned MetadataID = 0;
521 SmallVector<Value *, 16> Elts;
522 if (ParseUInt32(MetadataID) ||
523 ParseToken(lltok::equal, "expected '=' here") ||
524 ParseType(Ty, TyLoc) ||
525 ParseToken(lltok::exclaim, "Expected '!' here") ||
526 ParseToken(lltok::lbrace, "Expected '{' here") ||
527 ParseMDNodeVector(Elts, NULL) ||
528 ParseToken(lltok::rbrace, "expected end of metadata node"))
531 MDNode *Init = MDNode::get(Context, Elts);
533 // See if this was forward referenced, if so, handle it.
534 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
535 FI = ForwardRefMDNodes.find(MetadataID);
536 if (FI != ForwardRefMDNodes.end()) {
537 MDNode *Temp = FI->second.first;
538 Temp->replaceAllUsesWith(Init);
539 MDNode::deleteTemporary(Temp);
540 ForwardRefMDNodes.erase(FI);
542 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
544 if (MetadataID >= NumberedMetadata.size())
545 NumberedMetadata.resize(MetadataID+1);
547 if (NumberedMetadata[MetadataID] != 0)
548 return TokError("Metadata id is already used");
549 NumberedMetadata[MetadataID] = Init;
556 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
559 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
560 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
562 /// Everything through visibility has already been parsed.
564 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565 unsigned Visibility) {
566 assert(Lex.getKind() == lltok::kw_alias);
569 LocTy LinkageLoc = Lex.getLoc();
570 if (ParseOptionalLinkage(Linkage))
573 if (Linkage != GlobalValue::ExternalLinkage &&
574 Linkage != GlobalValue::WeakAnyLinkage &&
575 Linkage != GlobalValue::WeakODRLinkage &&
576 Linkage != GlobalValue::InternalLinkage &&
577 Linkage != GlobalValue::PrivateLinkage &&
578 Linkage != GlobalValue::LinkerPrivateLinkage &&
579 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
580 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
581 return Error(LinkageLoc, "invalid linkage type for alias");
584 LocTy AliaseeLoc = Lex.getLoc();
585 if (Lex.getKind() != lltok::kw_bitcast &&
586 Lex.getKind() != lltok::kw_getelementptr) {
587 if (ParseGlobalTypeAndValue(Aliasee)) return true;
589 // The bitcast dest type is not present, it is implied by the dest type.
591 if (ParseValID(ID)) return true;
592 if (ID.Kind != ValID::t_Constant)
593 return Error(AliaseeLoc, "invalid aliasee");
594 Aliasee = ID.ConstantVal;
597 if (!Aliasee->getType()->isPointerTy())
598 return Error(AliaseeLoc, "alias must have pointer type");
600 // Okay, create the alias but do not insert it into the module yet.
601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
602 (GlobalValue::LinkageTypes)Linkage, Name,
604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
606 // See if this value already exists in the symbol table. If so, it is either
607 // a redefinition or a definition of a forward reference.
608 if (GlobalValue *Val = M->getNamedValue(Name)) {
609 // See if this was a redefinition. If so, there is no entry in
611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
612 I = ForwardRefVals.find(Name);
613 if (I == ForwardRefVals.end())
614 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
616 // Otherwise, this was a definition of forward ref. Verify that types
618 if (Val->getType() != GA->getType())
619 return Error(NameLoc,
620 "forward reference and definition of alias have different types");
622 // If they agree, just RAUW the old value with the alias and remove the
624 Val->replaceAllUsesWith(GA);
625 Val->eraseFromParent();
626 ForwardRefVals.erase(I);
629 // Insert into the module, we know its name won't collide now.
630 M->getAliasList().push_back(GA);
631 assert(GA->getName() == Name && "Should not be a name conflict!");
637 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
638 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
639 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
640 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
642 /// Everything through visibility has been parsed already.
644 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
648 bool IsConstant, UnnamedAddr;
649 GlobalVariable::ThreadLocalMode TLM;
650 LocTy UnnamedAddrLoc;
654 if (ParseOptionalThreadLocal(TLM) ||
655 ParseOptionalAddrSpace(AddrSpace) ||
656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
662 // If the linkage is specified and is external, then no initializer is
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
666 Linkage != GlobalValue::ExternalWeakLinkage &&
667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
672 if (Ty->isFunctionTy() || Ty->isLabelTy())
673 return Error(TyLoc, "invalid type for global variable");
675 GlobalVariable *GV = 0;
677 // See if the global was forward referenced, if so, use the global.
679 if (GlobalValue *GVal = M->getNamedValue(Name)) {
680 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
682 GV = cast<GlobalVariable>(GVal);
685 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefValIDs.find(NumberedVals.size());
687 if (I != ForwardRefValIDs.end()) {
688 GV = cast<GlobalVariable>(I->second.first);
689 ForwardRefValIDs.erase(I);
694 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
695 Name, 0, GlobalVariable::NotThreadLocal,
698 if (GV->getType()->getElementType() != Ty)
700 "forward reference and definition of global have different types");
702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
707 NumberedVals.push_back(GV);
709 // Set the parsed properties on the global.
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
715 GV->setThreadLocalMode(TLM);
716 GV->setUnnamedAddr(UnnamedAddr);
718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
722 if (Lex.getKind() == lltok::kw_section) {
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
727 } else if (Lex.getKind() == lltok::kw_align) {
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
732 TokError("unknown global variable property!");
740 //===----------------------------------------------------------------------===//
741 // GlobalValue Reference/Resolution Routines.
742 //===----------------------------------------------------------------------===//
744 /// GetGlobalVal - Get a value with the specified name or ID, creating a
745 /// forward reference record if needed. This can return null if the value
746 /// exists but does not have the right type.
747 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
749 PointerType *PTy = dyn_cast<PointerType>(Ty);
751 Error(Loc, "global variable reference must have pointer type");
755 // Look this name up in the normal function symbol table.
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
768 // If we have the value in the symbol table or fwd-ref table, return it.
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
772 getTypeString(Val->getType()) + "'");
776 // Otherwise, create a new forward reference for this value and remember it.
778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name);
784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
788 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
789 PointerType *PTy = dyn_cast<PointerType>(Ty);
791 Error(Loc, "global variable reference must have pointer type");
795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
797 // If this is a forward reference for the value, see if we already created a
798 // forward ref record.
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(ID);
802 if (I != ForwardRefValIDs.end())
803 Val = I->second.first;
806 // If we have the value in the symbol table or fwd-ref table, return it.
808 if (Val->getType() == Ty) return Val;
809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
810 getTypeString(Val->getType()) + "'");
814 // Otherwise, create a new forward reference for this value and remember it.
816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
820 GlobalValue::ExternalWeakLinkage, 0, "");
822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
827 //===----------------------------------------------------------------------===//
829 //===----------------------------------------------------------------------===//
831 /// ParseToken - If the current token has the specified kind, eat it and return
832 /// success. Otherwise, emit the specified error and return failure.
833 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
834 if (Lex.getKind() != T)
835 return TokError(ErrMsg);
840 /// ParseStringConstant
841 /// ::= StringConstant
842 bool LLParser::ParseStringConstant(std::string &Result) {
843 if (Lex.getKind() != lltok::StringConstant)
844 return TokError("expected string constant");
845 Result = Lex.getStrVal();
852 bool LLParser::ParseUInt32(unsigned &Val) {
853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
854 return TokError("expected integer");
855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
856 if (Val64 != unsigned(Val64))
857 return TokError("expected 32-bit integer (too large)");
864 /// := 'localdynamic'
867 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
868 switch (Lex.getKind()) {
870 return TokError("expected localdynamic, initialexec or localexec");
871 case lltok::kw_localdynamic:
872 TLM = GlobalVariable::LocalDynamicTLSModel;
874 case lltok::kw_initialexec:
875 TLM = GlobalVariable::InitialExecTLSModel;
877 case lltok::kw_localexec:
878 TLM = GlobalVariable::LocalExecTLSModel;
886 /// ParseOptionalThreadLocal
888 /// := 'thread_local'
889 /// := 'thread_local' '(' tlsmodel ')'
890 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
891 TLM = GlobalVariable::NotThreadLocal;
892 if (!EatIfPresent(lltok::kw_thread_local))
895 TLM = GlobalVariable::GeneralDynamicTLSModel;
896 if (Lex.getKind() == lltok::lparen) {
898 return ParseTLSModel(TLM) ||
899 ParseToken(lltok::rparen, "expected ')' after thread local model");
904 /// ParseOptionalAddrSpace
906 /// := 'addrspace' '(' uint32 ')'
907 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
909 if (!EatIfPresent(lltok::kw_addrspace))
911 return ParseToken(lltok::lparen, "expected '(' in address space") ||
912 ParseUInt32(AddrSpace) ||
913 ParseToken(lltok::rparen, "expected ')' in address space");
916 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
917 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
918 /// 2: function attr.
919 bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) {
920 Attrs = Attribute::None;
921 LocTy AttrLoc = Lex.getLoc();
924 switch (Lex.getKind()) {
925 default: // End of attributes.
926 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
927 return Error(AttrLoc, "invalid use of function-only attribute");
929 // As a hack, we allow "align 2" on functions as a synonym for
932 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
933 return Error(AttrLoc, "invalid use of attribute on a function");
935 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
936 return Error(AttrLoc, "invalid use of parameter-only attribute");
939 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
940 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
941 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
942 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
943 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
944 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
945 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
946 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
948 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
949 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
950 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
951 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
952 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
953 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
954 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
955 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
956 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
957 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
958 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
959 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
960 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
961 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
962 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
963 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
964 case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break;
966 case lltok::kw_alignstack: {
968 if (ParseOptionalStackAlignment(Alignment))
970 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
974 case lltok::kw_align: {
976 if (ParseOptionalAlignment(Alignment))
978 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
987 /// ParseOptionalLinkage
990 /// ::= 'linker_private'
991 /// ::= 'linker_private_weak'
992 /// ::= 'linker_private_weak_def_auto'
997 /// ::= 'linkonce_odr'
998 /// ::= 'available_externally'
1003 /// ::= 'extern_weak'
1005 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1007 switch (Lex.getKind()) {
1008 default: Res=GlobalValue::ExternalLinkage; return false;
1009 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1010 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1011 case lltok::kw_linker_private_weak:
1012 Res = GlobalValue::LinkerPrivateWeakLinkage;
1014 case lltok::kw_linker_private_weak_def_auto:
1015 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1017 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1018 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1019 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1020 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1021 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1022 case lltok::kw_available_externally:
1023 Res = GlobalValue::AvailableExternallyLinkage;
1025 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1026 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1027 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1028 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1029 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1030 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1037 /// ParseOptionalVisibility
1043 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1044 switch (Lex.getKind()) {
1045 default: Res = GlobalValue::DefaultVisibility; return false;
1046 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1047 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1048 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1054 /// ParseOptionalCallingConv
1059 /// ::= 'x86_stdcallcc'
1060 /// ::= 'x86_fastcallcc'
1061 /// ::= 'x86_thiscallcc'
1062 /// ::= 'arm_apcscc'
1063 /// ::= 'arm_aapcscc'
1064 /// ::= 'arm_aapcs_vfpcc'
1065 /// ::= 'msp430_intrcc'
1066 /// ::= 'ptx_kernel'
1067 /// ::= 'ptx_device'
1070 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1071 switch (Lex.getKind()) {
1072 default: CC = CallingConv::C; return false;
1073 case lltok::kw_ccc: CC = CallingConv::C; break;
1074 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1075 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1076 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1077 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1078 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1079 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1080 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1081 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1082 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1083 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1084 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1085 case lltok::kw_cc: {
1086 unsigned ArbitraryCC;
1088 if (ParseUInt32(ArbitraryCC))
1090 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1099 /// ParseInstructionMetadata
1100 /// ::= !dbg !42 (',' !dbg !57)*
1101 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1102 PerFunctionState *PFS) {
1104 if (Lex.getKind() != lltok::MetadataVar)
1105 return TokError("expected metadata after comma");
1107 std::string Name = Lex.getStrVal();
1108 unsigned MDK = M->getMDKindID(Name);
1112 SMLoc Loc = Lex.getLoc();
1114 if (ParseToken(lltok::exclaim, "expected '!' here"))
1117 // This code is similar to that of ParseMetadataValue, however it needs to
1118 // have special-case code for a forward reference; see the comments on
1119 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1120 // at the top level here.
1121 if (Lex.getKind() == lltok::lbrace) {
1123 if (ParseMetadataListValue(ID, PFS))
1125 assert(ID.Kind == ValID::t_MDNode);
1126 Inst->setMetadata(MDK, ID.MDNodeVal);
1128 unsigned NodeID = 0;
1129 if (ParseMDNodeID(Node, NodeID))
1132 // If we got the node, add it to the instruction.
1133 Inst->setMetadata(MDK, Node);
1135 MDRef R = { Loc, MDK, NodeID };
1136 // Otherwise, remember that this should be resolved later.
1137 ForwardRefInstMetadata[Inst].push_back(R);
1141 // If this is the end of the list, we're done.
1142 } while (EatIfPresent(lltok::comma));
1146 /// ParseOptionalAlignment
1149 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1151 if (!EatIfPresent(lltok::kw_align))
1153 LocTy AlignLoc = Lex.getLoc();
1154 if (ParseUInt32(Alignment)) return true;
1155 if (!isPowerOf2_32(Alignment))
1156 return Error(AlignLoc, "alignment is not a power of two");
1157 if (Alignment > Value::MaximumAlignment)
1158 return Error(AlignLoc, "huge alignments are not supported yet");
1162 /// ParseOptionalCommaAlign
1166 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1168 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1169 bool &AteExtraComma) {
1170 AteExtraComma = false;
1171 while (EatIfPresent(lltok::comma)) {
1172 // Metadata at the end is an early exit.
1173 if (Lex.getKind() == lltok::MetadataVar) {
1174 AteExtraComma = true;
1178 if (Lex.getKind() != lltok::kw_align)
1179 return Error(Lex.getLoc(), "expected metadata or 'align'");
1181 if (ParseOptionalAlignment(Alignment)) return true;
1187 /// ParseScopeAndOrdering
1188 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1191 /// This sets Scope and Ordering to the parsed values.
1192 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1193 AtomicOrdering &Ordering) {
1197 Scope = CrossThread;
1198 if (EatIfPresent(lltok::kw_singlethread))
1199 Scope = SingleThread;
1200 switch (Lex.getKind()) {
1201 default: return TokError("Expected ordering on atomic instruction");
1202 case lltok::kw_unordered: Ordering = Unordered; break;
1203 case lltok::kw_monotonic: Ordering = Monotonic; break;
1204 case lltok::kw_acquire: Ordering = Acquire; break;
1205 case lltok::kw_release: Ordering = Release; break;
1206 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1207 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1213 /// ParseOptionalStackAlignment
1215 /// ::= 'alignstack' '(' 4 ')'
1216 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1218 if (!EatIfPresent(lltok::kw_alignstack))
1220 LocTy ParenLoc = Lex.getLoc();
1221 if (!EatIfPresent(lltok::lparen))
1222 return Error(ParenLoc, "expected '('");
1223 LocTy AlignLoc = Lex.getLoc();
1224 if (ParseUInt32(Alignment)) return true;
1225 ParenLoc = Lex.getLoc();
1226 if (!EatIfPresent(lltok::rparen))
1227 return Error(ParenLoc, "expected ')'");
1228 if (!isPowerOf2_32(Alignment))
1229 return Error(AlignLoc, "stack alignment is not a power of two");
1233 /// ParseIndexList - This parses the index list for an insert/extractvalue
1234 /// instruction. This sets AteExtraComma in the case where we eat an extra
1235 /// comma at the end of the line and find that it is followed by metadata.
1236 /// Clients that don't allow metadata can call the version of this function that
1237 /// only takes one argument.
1240 /// ::= (',' uint32)+
1242 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1243 bool &AteExtraComma) {
1244 AteExtraComma = false;
1246 if (Lex.getKind() != lltok::comma)
1247 return TokError("expected ',' as start of index list");
1249 while (EatIfPresent(lltok::comma)) {
1250 if (Lex.getKind() == lltok::MetadataVar) {
1251 AteExtraComma = true;
1255 if (ParseUInt32(Idx)) return true;
1256 Indices.push_back(Idx);
1262 //===----------------------------------------------------------------------===//
1264 //===----------------------------------------------------------------------===//
1266 /// ParseType - Parse a type.
1267 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1268 SMLoc TypeLoc = Lex.getLoc();
1269 switch (Lex.getKind()) {
1271 return TokError("expected type");
1273 // Type ::= 'float' | 'void' (etc)
1274 Result = Lex.getTyVal();
1278 // Type ::= StructType
1279 if (ParseAnonStructType(Result, false))
1282 case lltok::lsquare:
1283 // Type ::= '[' ... ']'
1284 Lex.Lex(); // eat the lsquare.
1285 if (ParseArrayVectorType(Result, false))
1288 case lltok::less: // Either vector or packed struct.
1289 // Type ::= '<' ... '>'
1291 if (Lex.getKind() == lltok::lbrace) {
1292 if (ParseAnonStructType(Result, true) ||
1293 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1295 } else if (ParseArrayVectorType(Result, true))
1298 case lltok::LocalVar: {
1300 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1302 // If the type hasn't been defined yet, create a forward definition and
1303 // remember where that forward def'n was seen (in case it never is defined).
1304 if (Entry.first == 0) {
1305 Entry.first = StructType::create(Context, Lex.getStrVal());
1306 Entry.second = Lex.getLoc();
1308 Result = Entry.first;
1313 case lltok::LocalVarID: {
1315 if (Lex.getUIntVal() >= NumberedTypes.size())
1316 NumberedTypes.resize(Lex.getUIntVal()+1);
1317 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1319 // If the type hasn't been defined yet, create a forward definition and
1320 // remember where that forward def'n was seen (in case it never is defined).
1321 if (Entry.first == 0) {
1322 Entry.first = StructType::create(Context);
1323 Entry.second = Lex.getLoc();
1325 Result = Entry.first;
1331 // Parse the type suffixes.
1333 switch (Lex.getKind()) {
1336 if (!AllowVoid && Result->isVoidTy())
1337 return Error(TypeLoc, "void type only allowed for function results");
1340 // Type ::= Type '*'
1342 if (Result->isLabelTy())
1343 return TokError("basic block pointers are invalid");
1344 if (Result->isVoidTy())
1345 return TokError("pointers to void are invalid - use i8* instead");
1346 if (!PointerType::isValidElementType(Result))
1347 return TokError("pointer to this type is invalid");
1348 Result = PointerType::getUnqual(Result);
1352 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1353 case lltok::kw_addrspace: {
1354 if (Result->isLabelTy())
1355 return TokError("basic block pointers are invalid");
1356 if (Result->isVoidTy())
1357 return TokError("pointers to void are invalid; use i8* instead");
1358 if (!PointerType::isValidElementType(Result))
1359 return TokError("pointer to this type is invalid");
1361 if (ParseOptionalAddrSpace(AddrSpace) ||
1362 ParseToken(lltok::star, "expected '*' in address space"))
1365 Result = PointerType::get(Result, AddrSpace);
1369 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1371 if (ParseFunctionType(Result))
1378 /// ParseParameterList
1380 /// ::= '(' Arg (',' Arg)* ')'
1382 /// ::= Type OptionalAttributes Value OptionalAttributes
1383 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1384 PerFunctionState &PFS) {
1385 if (ParseToken(lltok::lparen, "expected '(' in call"))
1388 while (Lex.getKind() != lltok::rparen) {
1389 // If this isn't the first argument, we need a comma.
1390 if (!ArgList.empty() &&
1391 ParseToken(lltok::comma, "expected ',' in argument list"))
1394 // Parse the argument.
1397 Attributes ArgAttrs1;
1398 Attributes ArgAttrs2;
1400 if (ParseType(ArgTy, ArgLoc))
1403 // Otherwise, handle normal operands.
1404 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1406 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1409 Lex.Lex(); // Lex the ')'.
1415 /// ParseArgumentList - Parse the argument list for a function type or function
1417 /// ::= '(' ArgTypeListI ')'
1421 /// ::= ArgTypeList ',' '...'
1422 /// ::= ArgType (',' ArgType)*
1424 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1427 assert(Lex.getKind() == lltok::lparen);
1428 Lex.Lex(); // eat the (.
1430 if (Lex.getKind() == lltok::rparen) {
1432 } else if (Lex.getKind() == lltok::dotdotdot) {
1436 LocTy TypeLoc = Lex.getLoc();
1441 if (ParseType(ArgTy) ||
1442 ParseOptionalAttrs(Attrs, 0)) return true;
1444 if (ArgTy->isVoidTy())
1445 return Error(TypeLoc, "argument can not have void type");
1447 if (Lex.getKind() == lltok::LocalVar) {
1448 Name = Lex.getStrVal();
1452 if (!FunctionType::isValidArgumentType(ArgTy))
1453 return Error(TypeLoc, "invalid type for function argument");
1455 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1457 while (EatIfPresent(lltok::comma)) {
1458 // Handle ... at end of arg list.
1459 if (EatIfPresent(lltok::dotdotdot)) {
1464 // Otherwise must be an argument type.
1465 TypeLoc = Lex.getLoc();
1466 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1468 if (ArgTy->isVoidTy())
1469 return Error(TypeLoc, "argument can not have void type");
1471 if (Lex.getKind() == lltok::LocalVar) {
1472 Name = Lex.getStrVal();
1478 if (!ArgTy->isFirstClassType())
1479 return Error(TypeLoc, "invalid type for function argument");
1481 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1485 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1488 /// ParseFunctionType
1489 /// ::= Type ArgumentList OptionalAttrs
1490 bool LLParser::ParseFunctionType(Type *&Result) {
1491 assert(Lex.getKind() == lltok::lparen);
1493 if (!FunctionType::isValidReturnType(Result))
1494 return TokError("invalid function return type");
1496 SmallVector<ArgInfo, 8> ArgList;
1498 if (ParseArgumentList(ArgList, isVarArg))
1501 // Reject names on the arguments lists.
1502 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1503 if (!ArgList[i].Name.empty())
1504 return Error(ArgList[i].Loc, "argument name invalid in function type");
1505 if (ArgList[i].Attrs)
1506 return Error(ArgList[i].Loc,
1507 "argument attributes invalid in function type");
1510 SmallVector<Type*, 16> ArgListTy;
1511 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1512 ArgListTy.push_back(ArgList[i].Ty);
1514 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1518 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1520 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1521 SmallVector<Type*, 8> Elts;
1522 if (ParseStructBody(Elts)) return true;
1524 Result = StructType::get(Context, Elts, Packed);
1528 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1529 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1530 std::pair<Type*, LocTy> &Entry,
1532 // If the type was already defined, diagnose the redefinition.
1533 if (Entry.first && !Entry.second.isValid())
1534 return Error(TypeLoc, "redefinition of type");
1536 // If we have opaque, just return without filling in the definition for the
1537 // struct. This counts as a definition as far as the .ll file goes.
1538 if (EatIfPresent(lltok::kw_opaque)) {
1539 // This type is being defined, so clear the location to indicate this.
1540 Entry.second = SMLoc();
1542 // If this type number has never been uttered, create it.
1543 if (Entry.first == 0)
1544 Entry.first = StructType::create(Context, Name);
1545 ResultTy = Entry.first;
1549 // If the type starts with '<', then it is either a packed struct or a vector.
1550 bool isPacked = EatIfPresent(lltok::less);
1552 // If we don't have a struct, then we have a random type alias, which we
1553 // accept for compatibility with old files. These types are not allowed to be
1554 // forward referenced and not allowed to be recursive.
1555 if (Lex.getKind() != lltok::lbrace) {
1557 return Error(TypeLoc, "forward references to non-struct type");
1561 return ParseArrayVectorType(ResultTy, true);
1562 return ParseType(ResultTy);
1565 // This type is being defined, so clear the location to indicate this.
1566 Entry.second = SMLoc();
1568 // If this type number has never been uttered, create it.
1569 if (Entry.first == 0)
1570 Entry.first = StructType::create(Context, Name);
1572 StructType *STy = cast<StructType>(Entry.first);
1574 SmallVector<Type*, 8> Body;
1575 if (ParseStructBody(Body) ||
1576 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1579 STy->setBody(Body, isPacked);
1585 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1588 /// ::= '{' Type (',' Type)* '}'
1589 /// ::= '<' '{' '}' '>'
1590 /// ::= '<' '{' Type (',' Type)* '}' '>'
1591 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1592 assert(Lex.getKind() == lltok::lbrace);
1593 Lex.Lex(); // Consume the '{'
1595 // Handle the empty struct.
1596 if (EatIfPresent(lltok::rbrace))
1599 LocTy EltTyLoc = Lex.getLoc();
1601 if (ParseType(Ty)) return true;
1604 if (!StructType::isValidElementType(Ty))
1605 return Error(EltTyLoc, "invalid element type for struct");
1607 while (EatIfPresent(lltok::comma)) {
1608 EltTyLoc = Lex.getLoc();
1609 if (ParseType(Ty)) return true;
1611 if (!StructType::isValidElementType(Ty))
1612 return Error(EltTyLoc, "invalid element type for struct");
1617 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1620 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1621 /// token has already been consumed.
1623 /// ::= '[' APSINTVAL 'x' Types ']'
1624 /// ::= '<' APSINTVAL 'x' Types '>'
1625 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1626 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1627 Lex.getAPSIntVal().getBitWidth() > 64)
1628 return TokError("expected number in address space");
1630 LocTy SizeLoc = Lex.getLoc();
1631 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1634 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1637 LocTy TypeLoc = Lex.getLoc();
1639 if (ParseType(EltTy)) return true;
1641 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1642 "expected end of sequential type"))
1647 return Error(SizeLoc, "zero element vector is illegal");
1648 if ((unsigned)Size != Size)
1649 return Error(SizeLoc, "size too large for vector");
1650 if (!VectorType::isValidElementType(EltTy))
1651 return Error(TypeLoc,
1652 "vector element type must be fp, integer or a pointer to these types");
1653 Result = VectorType::get(EltTy, unsigned(Size));
1655 if (!ArrayType::isValidElementType(EltTy))
1656 return Error(TypeLoc, "invalid array element type");
1657 Result = ArrayType::get(EltTy, Size);
1662 //===----------------------------------------------------------------------===//
1663 // Function Semantic Analysis.
1664 //===----------------------------------------------------------------------===//
1666 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1668 : P(p), F(f), FunctionNumber(functionNumber) {
1670 // Insert unnamed arguments into the NumberedVals list.
1671 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1674 NumberedVals.push_back(AI);
1677 LLParser::PerFunctionState::~PerFunctionState() {
1678 // If there were any forward referenced non-basicblock values, delete them.
1679 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1680 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1681 if (!isa<BasicBlock>(I->second.first)) {
1682 I->second.first->replaceAllUsesWith(
1683 UndefValue::get(I->second.first->getType()));
1684 delete I->second.first;
1685 I->second.first = 0;
1688 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1689 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1690 if (!isa<BasicBlock>(I->second.first)) {
1691 I->second.first->replaceAllUsesWith(
1692 UndefValue::get(I->second.first->getType()));
1693 delete I->second.first;
1694 I->second.first = 0;
1698 bool LLParser::PerFunctionState::FinishFunction() {
1699 // Check to see if someone took the address of labels in this block.
1700 if (!P.ForwardRefBlockAddresses.empty()) {
1702 if (!F.getName().empty()) {
1703 FunctionID.Kind = ValID::t_GlobalName;
1704 FunctionID.StrVal = F.getName();
1706 FunctionID.Kind = ValID::t_GlobalID;
1707 FunctionID.UIntVal = FunctionNumber;
1710 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1711 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1712 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1713 // Resolve all these references.
1714 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1717 P.ForwardRefBlockAddresses.erase(FRBAI);
1721 if (!ForwardRefVals.empty())
1722 return P.Error(ForwardRefVals.begin()->second.second,
1723 "use of undefined value '%" + ForwardRefVals.begin()->first +
1725 if (!ForwardRefValIDs.empty())
1726 return P.Error(ForwardRefValIDs.begin()->second.second,
1727 "use of undefined value '%" +
1728 Twine(ForwardRefValIDs.begin()->first) + "'");
1733 /// GetVal - Get a value with the specified name or ID, creating a
1734 /// forward reference record if needed. This can return null if the value
1735 /// exists but does not have the right type.
1736 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1737 Type *Ty, LocTy Loc) {
1738 // Look this name up in the normal function symbol table.
1739 Value *Val = F.getValueSymbolTable().lookup(Name);
1741 // If this is a forward reference for the value, see if we already created a
1742 // forward ref record.
1744 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1745 I = ForwardRefVals.find(Name);
1746 if (I != ForwardRefVals.end())
1747 Val = I->second.first;
1750 // If we have the value in the symbol table or fwd-ref table, return it.
1752 if (Val->getType() == Ty) return Val;
1753 if (Ty->isLabelTy())
1754 P.Error(Loc, "'%" + Name + "' is not a basic block");
1756 P.Error(Loc, "'%" + Name + "' defined with type '" +
1757 getTypeString(Val->getType()) + "'");
1761 // Don't make placeholders with invalid type.
1762 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1763 P.Error(Loc, "invalid use of a non-first-class type");
1767 // Otherwise, create a new forward reference for this value and remember it.
1769 if (Ty->isLabelTy())
1770 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1772 FwdVal = new Argument(Ty, Name);
1774 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1778 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1780 // Look this name up in the normal function symbol table.
1781 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1783 // If this is a forward reference for the value, see if we already created a
1784 // forward ref record.
1786 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1787 I = ForwardRefValIDs.find(ID);
1788 if (I != ForwardRefValIDs.end())
1789 Val = I->second.first;
1792 // If we have the value in the symbol table or fwd-ref table, return it.
1794 if (Val->getType() == Ty) return Val;
1795 if (Ty->isLabelTy())
1796 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1798 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1799 getTypeString(Val->getType()) + "'");
1803 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1804 P.Error(Loc, "invalid use of a non-first-class type");
1808 // Otherwise, create a new forward reference for this value and remember it.
1810 if (Ty->isLabelTy())
1811 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1813 FwdVal = new Argument(Ty);
1815 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1819 /// SetInstName - After an instruction is parsed and inserted into its
1820 /// basic block, this installs its name.
1821 bool LLParser::PerFunctionState::SetInstName(int NameID,
1822 const std::string &NameStr,
1823 LocTy NameLoc, Instruction *Inst) {
1824 // If this instruction has void type, it cannot have a name or ID specified.
1825 if (Inst->getType()->isVoidTy()) {
1826 if (NameID != -1 || !NameStr.empty())
1827 return P.Error(NameLoc, "instructions returning void cannot have a name");
1831 // If this was a numbered instruction, verify that the instruction is the
1832 // expected value and resolve any forward references.
1833 if (NameStr.empty()) {
1834 // If neither a name nor an ID was specified, just use the next ID.
1836 NameID = NumberedVals.size();
1838 if (unsigned(NameID) != NumberedVals.size())
1839 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1840 Twine(NumberedVals.size()) + "'");
1842 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1843 ForwardRefValIDs.find(NameID);
1844 if (FI != ForwardRefValIDs.end()) {
1845 if (FI->second.first->getType() != Inst->getType())
1846 return P.Error(NameLoc, "instruction forward referenced with type '" +
1847 getTypeString(FI->second.first->getType()) + "'");
1848 FI->second.first->replaceAllUsesWith(Inst);
1849 delete FI->second.first;
1850 ForwardRefValIDs.erase(FI);
1853 NumberedVals.push_back(Inst);
1857 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1858 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1859 FI = ForwardRefVals.find(NameStr);
1860 if (FI != ForwardRefVals.end()) {
1861 if (FI->second.first->getType() != Inst->getType())
1862 return P.Error(NameLoc, "instruction forward referenced with type '" +
1863 getTypeString(FI->second.first->getType()) + "'");
1864 FI->second.first->replaceAllUsesWith(Inst);
1865 delete FI->second.first;
1866 ForwardRefVals.erase(FI);
1869 // Set the name on the instruction.
1870 Inst->setName(NameStr);
1872 if (Inst->getName() != NameStr)
1873 return P.Error(NameLoc, "multiple definition of local value named '" +
1878 /// GetBB - Get a basic block with the specified name or ID, creating a
1879 /// forward reference record if needed.
1880 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1882 return cast_or_null<BasicBlock>(GetVal(Name,
1883 Type::getLabelTy(F.getContext()), Loc));
1886 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1887 return cast_or_null<BasicBlock>(GetVal(ID,
1888 Type::getLabelTy(F.getContext()), Loc));
1891 /// DefineBB - Define the specified basic block, which is either named or
1892 /// unnamed. If there is an error, this returns null otherwise it returns
1893 /// the block being defined.
1894 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1898 BB = GetBB(NumberedVals.size(), Loc);
1900 BB = GetBB(Name, Loc);
1901 if (BB == 0) return 0; // Already diagnosed error.
1903 // Move the block to the end of the function. Forward ref'd blocks are
1904 // inserted wherever they happen to be referenced.
1905 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1907 // Remove the block from forward ref sets.
1909 ForwardRefValIDs.erase(NumberedVals.size());
1910 NumberedVals.push_back(BB);
1912 // BB forward references are already in the function symbol table.
1913 ForwardRefVals.erase(Name);
1919 //===----------------------------------------------------------------------===//
1921 //===----------------------------------------------------------------------===//
1923 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1924 /// type implied. For example, if we parse "4" we don't know what integer type
1925 /// it has. The value will later be combined with its type and checked for
1926 /// sanity. PFS is used to convert function-local operands of metadata (since
1927 /// metadata operands are not just parsed here but also converted to values).
1928 /// PFS can be null when we are not parsing metadata values inside a function.
1929 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1930 ID.Loc = Lex.getLoc();
1931 switch (Lex.getKind()) {
1932 default: return TokError("expected value token");
1933 case lltok::GlobalID: // @42
1934 ID.UIntVal = Lex.getUIntVal();
1935 ID.Kind = ValID::t_GlobalID;
1937 case lltok::GlobalVar: // @foo
1938 ID.StrVal = Lex.getStrVal();
1939 ID.Kind = ValID::t_GlobalName;
1941 case lltok::LocalVarID: // %42
1942 ID.UIntVal = Lex.getUIntVal();
1943 ID.Kind = ValID::t_LocalID;
1945 case lltok::LocalVar: // %foo
1946 ID.StrVal = Lex.getStrVal();
1947 ID.Kind = ValID::t_LocalName;
1949 case lltok::exclaim: // !42, !{...}, or !"foo"
1950 return ParseMetadataValue(ID, PFS);
1952 ID.APSIntVal = Lex.getAPSIntVal();
1953 ID.Kind = ValID::t_APSInt;
1955 case lltok::APFloat:
1956 ID.APFloatVal = Lex.getAPFloatVal();
1957 ID.Kind = ValID::t_APFloat;
1959 case lltok::kw_true:
1960 ID.ConstantVal = ConstantInt::getTrue(Context);
1961 ID.Kind = ValID::t_Constant;
1963 case lltok::kw_false:
1964 ID.ConstantVal = ConstantInt::getFalse(Context);
1965 ID.Kind = ValID::t_Constant;
1967 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1968 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1969 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1971 case lltok::lbrace: {
1972 // ValID ::= '{' ConstVector '}'
1974 SmallVector<Constant*, 16> Elts;
1975 if (ParseGlobalValueVector(Elts) ||
1976 ParseToken(lltok::rbrace, "expected end of struct constant"))
1979 ID.ConstantStructElts = new Constant*[Elts.size()];
1980 ID.UIntVal = Elts.size();
1981 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1982 ID.Kind = ValID::t_ConstantStruct;
1986 // ValID ::= '<' ConstVector '>' --> Vector.
1987 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1989 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1991 SmallVector<Constant*, 16> Elts;
1992 LocTy FirstEltLoc = Lex.getLoc();
1993 if (ParseGlobalValueVector(Elts) ||
1995 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1996 ParseToken(lltok::greater, "expected end of constant"))
1999 if (isPackedStruct) {
2000 ID.ConstantStructElts = new Constant*[Elts.size()];
2001 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2002 ID.UIntVal = Elts.size();
2003 ID.Kind = ValID::t_PackedConstantStruct;
2008 return Error(ID.Loc, "constant vector must not be empty");
2010 if (!Elts[0]->getType()->isIntegerTy() &&
2011 !Elts[0]->getType()->isFloatingPointTy() &&
2012 !Elts[0]->getType()->isPointerTy())
2013 return Error(FirstEltLoc,
2014 "vector elements must have integer, pointer or floating point type");
2016 // Verify that all the vector elements have the same type.
2017 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2018 if (Elts[i]->getType() != Elts[0]->getType())
2019 return Error(FirstEltLoc,
2020 "vector element #" + Twine(i) +
2021 " is not of type '" + getTypeString(Elts[0]->getType()));
2023 ID.ConstantVal = ConstantVector::get(Elts);
2024 ID.Kind = ValID::t_Constant;
2027 case lltok::lsquare: { // Array Constant
2029 SmallVector<Constant*, 16> Elts;
2030 LocTy FirstEltLoc = Lex.getLoc();
2031 if (ParseGlobalValueVector(Elts) ||
2032 ParseToken(lltok::rsquare, "expected end of array constant"))
2035 // Handle empty element.
2037 // Use undef instead of an array because it's inconvenient to determine
2038 // the element type at this point, there being no elements to examine.
2039 ID.Kind = ValID::t_EmptyArray;
2043 if (!Elts[0]->getType()->isFirstClassType())
2044 return Error(FirstEltLoc, "invalid array element type: " +
2045 getTypeString(Elts[0]->getType()));
2047 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2049 // Verify all elements are correct type!
2050 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2051 if (Elts[i]->getType() != Elts[0]->getType())
2052 return Error(FirstEltLoc,
2053 "array element #" + Twine(i) +
2054 " is not of type '" + getTypeString(Elts[0]->getType()));
2057 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2058 ID.Kind = ValID::t_Constant;
2061 case lltok::kw_c: // c "foo"
2063 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2065 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2066 ID.Kind = ValID::t_Constant;
2069 case lltok::kw_asm: {
2070 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2071 bool HasSideEffect, AlignStack;
2073 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2074 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2075 ParseStringConstant(ID.StrVal) ||
2076 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2077 ParseToken(lltok::StringConstant, "expected constraint string"))
2079 ID.StrVal2 = Lex.getStrVal();
2080 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2081 ID.Kind = ValID::t_InlineAsm;
2085 case lltok::kw_blockaddress: {
2086 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2090 LocTy FnLoc, LabelLoc;
2092 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2094 ParseToken(lltok::comma, "expected comma in block address expression")||
2095 ParseValID(Label) ||
2096 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2099 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2100 return Error(Fn.Loc, "expected function name in blockaddress");
2101 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2102 return Error(Label.Loc, "expected basic block name in blockaddress");
2104 // Make a global variable as a placeholder for this reference.
2105 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2106 false, GlobalValue::InternalLinkage,
2108 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2109 ID.ConstantVal = FwdRef;
2110 ID.Kind = ValID::t_Constant;
2114 case lltok::kw_trunc:
2115 case lltok::kw_zext:
2116 case lltok::kw_sext:
2117 case lltok::kw_fptrunc:
2118 case lltok::kw_fpext:
2119 case lltok::kw_bitcast:
2120 case lltok::kw_uitofp:
2121 case lltok::kw_sitofp:
2122 case lltok::kw_fptoui:
2123 case lltok::kw_fptosi:
2124 case lltok::kw_inttoptr:
2125 case lltok::kw_ptrtoint: {
2126 unsigned Opc = Lex.getUIntVal();
2130 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2131 ParseGlobalTypeAndValue(SrcVal) ||
2132 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2133 ParseType(DestTy) ||
2134 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2136 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2137 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2138 getTypeString(SrcVal->getType()) + "' to '" +
2139 getTypeString(DestTy) + "'");
2140 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2142 ID.Kind = ValID::t_Constant;
2145 case lltok::kw_extractvalue: {
2148 SmallVector<unsigned, 4> Indices;
2149 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2150 ParseGlobalTypeAndValue(Val) ||
2151 ParseIndexList(Indices) ||
2152 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2155 if (!Val->getType()->isAggregateType())
2156 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2157 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2158 return Error(ID.Loc, "invalid indices for extractvalue");
2159 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2160 ID.Kind = ValID::t_Constant;
2163 case lltok::kw_insertvalue: {
2165 Constant *Val0, *Val1;
2166 SmallVector<unsigned, 4> Indices;
2167 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2168 ParseGlobalTypeAndValue(Val0) ||
2169 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2170 ParseGlobalTypeAndValue(Val1) ||
2171 ParseIndexList(Indices) ||
2172 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2174 if (!Val0->getType()->isAggregateType())
2175 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2176 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2177 return Error(ID.Loc, "invalid indices for insertvalue");
2178 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2179 ID.Kind = ValID::t_Constant;
2182 case lltok::kw_icmp:
2183 case lltok::kw_fcmp: {
2184 unsigned PredVal, Opc = Lex.getUIntVal();
2185 Constant *Val0, *Val1;
2187 if (ParseCmpPredicate(PredVal, Opc) ||
2188 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2189 ParseGlobalTypeAndValue(Val0) ||
2190 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2191 ParseGlobalTypeAndValue(Val1) ||
2192 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2195 if (Val0->getType() != Val1->getType())
2196 return Error(ID.Loc, "compare operands must have the same type");
2198 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2200 if (Opc == Instruction::FCmp) {
2201 if (!Val0->getType()->isFPOrFPVectorTy())
2202 return Error(ID.Loc, "fcmp requires floating point operands");
2203 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2205 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2206 if (!Val0->getType()->isIntOrIntVectorTy() &&
2207 !Val0->getType()->getScalarType()->isPointerTy())
2208 return Error(ID.Loc, "icmp requires pointer or integer operands");
2209 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2211 ID.Kind = ValID::t_Constant;
2215 // Binary Operators.
2217 case lltok::kw_fadd:
2219 case lltok::kw_fsub:
2221 case lltok::kw_fmul:
2222 case lltok::kw_udiv:
2223 case lltok::kw_sdiv:
2224 case lltok::kw_fdiv:
2225 case lltok::kw_urem:
2226 case lltok::kw_srem:
2227 case lltok::kw_frem:
2229 case lltok::kw_lshr:
2230 case lltok::kw_ashr: {
2234 unsigned Opc = Lex.getUIntVal();
2235 Constant *Val0, *Val1;
2237 LocTy ModifierLoc = Lex.getLoc();
2238 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2239 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2240 if (EatIfPresent(lltok::kw_nuw))
2242 if (EatIfPresent(lltok::kw_nsw)) {
2244 if (EatIfPresent(lltok::kw_nuw))
2247 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2248 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2249 if (EatIfPresent(lltok::kw_exact))
2252 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2253 ParseGlobalTypeAndValue(Val0) ||
2254 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2255 ParseGlobalTypeAndValue(Val1) ||
2256 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2258 if (Val0->getType() != Val1->getType())
2259 return Error(ID.Loc, "operands of constexpr must have same type");
2260 if (!Val0->getType()->isIntOrIntVectorTy()) {
2262 return Error(ModifierLoc, "nuw only applies to integer operations");
2264 return Error(ModifierLoc, "nsw only applies to integer operations");
2266 // Check that the type is valid for the operator.
2268 case Instruction::Add:
2269 case Instruction::Sub:
2270 case Instruction::Mul:
2271 case Instruction::UDiv:
2272 case Instruction::SDiv:
2273 case Instruction::URem:
2274 case Instruction::SRem:
2275 case Instruction::Shl:
2276 case Instruction::AShr:
2277 case Instruction::LShr:
2278 if (!Val0->getType()->isIntOrIntVectorTy())
2279 return Error(ID.Loc, "constexpr requires integer operands");
2281 case Instruction::FAdd:
2282 case Instruction::FSub:
2283 case Instruction::FMul:
2284 case Instruction::FDiv:
2285 case Instruction::FRem:
2286 if (!Val0->getType()->isFPOrFPVectorTy())
2287 return Error(ID.Loc, "constexpr requires fp operands");
2289 default: llvm_unreachable("Unknown binary operator!");
2292 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2293 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2294 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2295 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2297 ID.Kind = ValID::t_Constant;
2301 // Logical Operations
2304 case lltok::kw_xor: {
2305 unsigned Opc = Lex.getUIntVal();
2306 Constant *Val0, *Val1;
2308 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2309 ParseGlobalTypeAndValue(Val0) ||
2310 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2311 ParseGlobalTypeAndValue(Val1) ||
2312 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2314 if (Val0->getType() != Val1->getType())
2315 return Error(ID.Loc, "operands of constexpr must have same type");
2316 if (!Val0->getType()->isIntOrIntVectorTy())
2317 return Error(ID.Loc,
2318 "constexpr requires integer or integer vector operands");
2319 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2320 ID.Kind = ValID::t_Constant;
2324 case lltok::kw_getelementptr:
2325 case lltok::kw_shufflevector:
2326 case lltok::kw_insertelement:
2327 case lltok::kw_extractelement:
2328 case lltok::kw_select: {
2329 unsigned Opc = Lex.getUIntVal();
2330 SmallVector<Constant*, 16> Elts;
2331 bool InBounds = false;
2333 if (Opc == Instruction::GetElementPtr)
2334 InBounds = EatIfPresent(lltok::kw_inbounds);
2335 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2336 ParseGlobalValueVector(Elts) ||
2337 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2340 if (Opc == Instruction::GetElementPtr) {
2341 if (Elts.size() == 0 ||
2342 !Elts[0]->getType()->getScalarType()->isPointerTy())
2343 return Error(ID.Loc, "getelementptr requires pointer operand");
2345 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2346 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2347 return Error(ID.Loc, "invalid indices for getelementptr");
2348 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2350 } else if (Opc == Instruction::Select) {
2351 if (Elts.size() != 3)
2352 return Error(ID.Loc, "expected three operands to select");
2353 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2355 return Error(ID.Loc, Reason);
2356 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2357 } else if (Opc == Instruction::ShuffleVector) {
2358 if (Elts.size() != 3)
2359 return Error(ID.Loc, "expected three operands to shufflevector");
2360 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2361 return Error(ID.Loc, "invalid operands to shufflevector");
2363 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2364 } else if (Opc == Instruction::ExtractElement) {
2365 if (Elts.size() != 2)
2366 return Error(ID.Loc, "expected two operands to extractelement");
2367 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2368 return Error(ID.Loc, "invalid extractelement operands");
2369 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2371 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2372 if (Elts.size() != 3)
2373 return Error(ID.Loc, "expected three operands to insertelement");
2374 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2375 return Error(ID.Loc, "invalid insertelement operands");
2377 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2380 ID.Kind = ValID::t_Constant;
2389 /// ParseGlobalValue - Parse a global value with the specified type.
2390 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2394 bool Parsed = ParseValID(ID) ||
2395 ConvertValIDToValue(Ty, ID, V, NULL);
2396 if (V && !(C = dyn_cast<Constant>(V)))
2397 return Error(ID.Loc, "global values must be constants");
2401 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2403 return ParseType(Ty) ||
2404 ParseGlobalValue(Ty, V);
2407 /// ParseGlobalValueVector
2409 /// ::= TypeAndValue (',' TypeAndValue)*
2410 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2412 if (Lex.getKind() == lltok::rbrace ||
2413 Lex.getKind() == lltok::rsquare ||
2414 Lex.getKind() == lltok::greater ||
2415 Lex.getKind() == lltok::rparen)
2419 if (ParseGlobalTypeAndValue(C)) return true;
2422 while (EatIfPresent(lltok::comma)) {
2423 if (ParseGlobalTypeAndValue(C)) return true;
2430 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2431 assert(Lex.getKind() == lltok::lbrace);
2434 SmallVector<Value*, 16> Elts;
2435 if (ParseMDNodeVector(Elts, PFS) ||
2436 ParseToken(lltok::rbrace, "expected end of metadata node"))
2439 ID.MDNodeVal = MDNode::get(Context, Elts);
2440 ID.Kind = ValID::t_MDNode;
2444 /// ParseMetadataValue
2448 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2449 assert(Lex.getKind() == lltok::exclaim);
2454 if (Lex.getKind() == lltok::lbrace)
2455 return ParseMetadataListValue(ID, PFS);
2457 // Standalone metadata reference
2459 if (Lex.getKind() == lltok::APSInt) {
2460 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2461 ID.Kind = ValID::t_MDNode;
2466 // ::= '!' STRINGCONSTANT
2467 if (ParseMDString(ID.MDStringVal)) return true;
2468 ID.Kind = ValID::t_MDString;
2473 //===----------------------------------------------------------------------===//
2474 // Function Parsing.
2475 //===----------------------------------------------------------------------===//
2477 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2478 PerFunctionState *PFS) {
2479 if (Ty->isFunctionTy())
2480 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2483 case ValID::t_LocalID:
2484 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2485 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2487 case ValID::t_LocalName:
2488 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2489 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2491 case ValID::t_InlineAsm: {
2492 PointerType *PTy = dyn_cast<PointerType>(Ty);
2494 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2495 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2496 return Error(ID.Loc, "invalid type for inline asm constraint string");
2497 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2500 case ValID::t_MDNode:
2501 if (!Ty->isMetadataTy())
2502 return Error(ID.Loc, "metadata value must have metadata type");
2505 case ValID::t_MDString:
2506 if (!Ty->isMetadataTy())
2507 return Error(ID.Loc, "metadata value must have metadata type");
2510 case ValID::t_GlobalName:
2511 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2513 case ValID::t_GlobalID:
2514 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2516 case ValID::t_APSInt:
2517 if (!Ty->isIntegerTy())
2518 return Error(ID.Loc, "integer constant must have integer type");
2519 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2520 V = ConstantInt::get(Context, ID.APSIntVal);
2522 case ValID::t_APFloat:
2523 if (!Ty->isFloatingPointTy() ||
2524 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2525 return Error(ID.Loc, "floating point constant invalid for type");
2527 // The lexer has no type info, so builds all half, float, and double FP
2528 // constants as double. Fix this here. Long double does not need this.
2529 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2532 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2534 else if (Ty->isFloatTy())
2535 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2538 V = ConstantFP::get(Context, ID.APFloatVal);
2540 if (V->getType() != Ty)
2541 return Error(ID.Loc, "floating point constant does not have type '" +
2542 getTypeString(Ty) + "'");
2546 if (!Ty->isPointerTy())
2547 return Error(ID.Loc, "null must be a pointer type");
2548 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2550 case ValID::t_Undef:
2551 // FIXME: LabelTy should not be a first-class type.
2552 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2553 return Error(ID.Loc, "invalid type for undef constant");
2554 V = UndefValue::get(Ty);
2556 case ValID::t_EmptyArray:
2557 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2558 return Error(ID.Loc, "invalid empty array initializer");
2559 V = UndefValue::get(Ty);
2562 // FIXME: LabelTy should not be a first-class type.
2563 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2564 return Error(ID.Loc, "invalid type for null constant");
2565 V = Constant::getNullValue(Ty);
2567 case ValID::t_Constant:
2568 if (ID.ConstantVal->getType() != Ty)
2569 return Error(ID.Loc, "constant expression type mismatch");
2573 case ValID::t_ConstantStruct:
2574 case ValID::t_PackedConstantStruct:
2575 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2576 if (ST->getNumElements() != ID.UIntVal)
2577 return Error(ID.Loc,
2578 "initializer with struct type has wrong # elements");
2579 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2580 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2582 // Verify that the elements are compatible with the structtype.
2583 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2584 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2585 return Error(ID.Loc, "element " + Twine(i) +
2586 " of struct initializer doesn't match struct element type");
2588 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2591 return Error(ID.Loc, "constant expression type mismatch");
2594 llvm_unreachable("Invalid ValID");
2597 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2600 return ParseValID(ID, PFS) ||
2601 ConvertValIDToValue(Ty, ID, V, PFS);
2604 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2606 return ParseType(Ty) ||
2607 ParseValue(Ty, V, PFS);
2610 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2611 PerFunctionState &PFS) {
2614 if (ParseTypeAndValue(V, PFS)) return true;
2615 if (!isa<BasicBlock>(V))
2616 return Error(Loc, "expected a basic block");
2617 BB = cast<BasicBlock>(V);
2623 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2624 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2625 /// OptionalAlign OptGC
2626 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2627 // Parse the linkage.
2628 LocTy LinkageLoc = Lex.getLoc();
2631 unsigned Visibility;
2632 Attributes RetAttrs;
2635 LocTy RetTypeLoc = Lex.getLoc();
2636 if (ParseOptionalLinkage(Linkage) ||
2637 ParseOptionalVisibility(Visibility) ||
2638 ParseOptionalCallingConv(CC) ||
2639 ParseOptionalAttrs(RetAttrs, 1) ||
2640 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2643 // Verify that the linkage is ok.
2644 switch ((GlobalValue::LinkageTypes)Linkage) {
2645 case GlobalValue::ExternalLinkage:
2646 break; // always ok.
2647 case GlobalValue::DLLImportLinkage:
2648 case GlobalValue::ExternalWeakLinkage:
2650 return Error(LinkageLoc, "invalid linkage for function definition");
2652 case GlobalValue::PrivateLinkage:
2653 case GlobalValue::LinkerPrivateLinkage:
2654 case GlobalValue::LinkerPrivateWeakLinkage:
2655 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2656 case GlobalValue::InternalLinkage:
2657 case GlobalValue::AvailableExternallyLinkage:
2658 case GlobalValue::LinkOnceAnyLinkage:
2659 case GlobalValue::LinkOnceODRLinkage:
2660 case GlobalValue::WeakAnyLinkage:
2661 case GlobalValue::WeakODRLinkage:
2662 case GlobalValue::DLLExportLinkage:
2664 return Error(LinkageLoc, "invalid linkage for function declaration");
2666 case GlobalValue::AppendingLinkage:
2667 case GlobalValue::CommonLinkage:
2668 return Error(LinkageLoc, "invalid function linkage type");
2671 if (!FunctionType::isValidReturnType(RetType))
2672 return Error(RetTypeLoc, "invalid function return type");
2674 LocTy NameLoc = Lex.getLoc();
2676 std::string FunctionName;
2677 if (Lex.getKind() == lltok::GlobalVar) {
2678 FunctionName = Lex.getStrVal();
2679 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2680 unsigned NameID = Lex.getUIntVal();
2682 if (NameID != NumberedVals.size())
2683 return TokError("function expected to be numbered '%" +
2684 Twine(NumberedVals.size()) + "'");
2686 return TokError("expected function name");
2691 if (Lex.getKind() != lltok::lparen)
2692 return TokError("expected '(' in function argument list");
2694 SmallVector<ArgInfo, 8> ArgList;
2696 Attributes FuncAttrs;
2697 std::string Section;
2701 LocTy UnnamedAddrLoc;
2703 if (ParseArgumentList(ArgList, isVarArg) ||
2704 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2706 ParseOptionalAttrs(FuncAttrs, 2) ||
2707 (EatIfPresent(lltok::kw_section) &&
2708 ParseStringConstant(Section)) ||
2709 ParseOptionalAlignment(Alignment) ||
2710 (EatIfPresent(lltok::kw_gc) &&
2711 ParseStringConstant(GC)))
2714 // If the alignment was parsed as an attribute, move to the alignment field.
2715 if (FuncAttrs & Attribute::Alignment) {
2716 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2717 FuncAttrs &= ~Attribute::Alignment;
2720 // Okay, if we got here, the function is syntactically valid. Convert types
2721 // and do semantic checks.
2722 std::vector<Type*> ParamTypeList;
2723 SmallVector<AttributeWithIndex, 8> Attrs;
2725 if (RetAttrs != Attribute::None)
2726 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2728 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2729 ParamTypeList.push_back(ArgList[i].Ty);
2730 if (ArgList[i].Attrs != Attribute::None)
2731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2734 if (FuncAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2737 AttrListPtr PAL = AttrListPtr::get(Attrs);
2739 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2740 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2743 FunctionType::get(RetType, ParamTypeList, isVarArg);
2744 PointerType *PFT = PointerType::getUnqual(FT);
2747 if (!FunctionName.empty()) {
2748 // If this was a definition of a forward reference, remove the definition
2749 // from the forward reference table and fill in the forward ref.
2750 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2751 ForwardRefVals.find(FunctionName);
2752 if (FRVI != ForwardRefVals.end()) {
2753 Fn = M->getFunction(FunctionName);
2754 if (Fn->getType() != PFT)
2755 return Error(FRVI->second.second, "invalid forward reference to "
2756 "function '" + FunctionName + "' with wrong type!");
2758 ForwardRefVals.erase(FRVI);
2759 } else if ((Fn = M->getFunction(FunctionName))) {
2760 // Reject redefinitions.
2761 return Error(NameLoc, "invalid redefinition of function '" +
2762 FunctionName + "'");
2763 } else if (M->getNamedValue(FunctionName)) {
2764 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2768 // If this is a definition of a forward referenced function, make sure the
2770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2771 = ForwardRefValIDs.find(NumberedVals.size());
2772 if (I != ForwardRefValIDs.end()) {
2773 Fn = cast<Function>(I->second.first);
2774 if (Fn->getType() != PFT)
2775 return Error(NameLoc, "type of definition and forward reference of '@" +
2776 Twine(NumberedVals.size()) + "' disagree");
2777 ForwardRefValIDs.erase(I);
2782 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2783 else // Move the forward-reference to the correct spot in the module.
2784 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2786 if (FunctionName.empty())
2787 NumberedVals.push_back(Fn);
2789 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2790 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2791 Fn->setCallingConv(CC);
2792 Fn->setAttributes(PAL);
2793 Fn->setUnnamedAddr(UnnamedAddr);
2794 Fn->setAlignment(Alignment);
2795 Fn->setSection(Section);
2796 if (!GC.empty()) Fn->setGC(GC.c_str());
2798 // Add all of the arguments we parsed to the function.
2799 Function::arg_iterator ArgIt = Fn->arg_begin();
2800 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2801 // If the argument has a name, insert it into the argument symbol table.
2802 if (ArgList[i].Name.empty()) continue;
2804 // Set the name, if it conflicted, it will be auto-renamed.
2805 ArgIt->setName(ArgList[i].Name);
2807 if (ArgIt->getName() != ArgList[i].Name)
2808 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2809 ArgList[i].Name + "'");
2816 /// ParseFunctionBody
2817 /// ::= '{' BasicBlock+ '}'
2819 bool LLParser::ParseFunctionBody(Function &Fn) {
2820 if (Lex.getKind() != lltok::lbrace)
2821 return TokError("expected '{' in function body");
2822 Lex.Lex(); // eat the {.
2824 int FunctionNumber = -1;
2825 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2827 PerFunctionState PFS(*this, Fn, FunctionNumber);
2829 // We need at least one basic block.
2830 if (Lex.getKind() == lltok::rbrace)
2831 return TokError("function body requires at least one basic block");
2833 while (Lex.getKind() != lltok::rbrace)
2834 if (ParseBasicBlock(PFS)) return true;
2839 // Verify function is ok.
2840 return PFS.FinishFunction();
2844 /// ::= LabelStr? Instruction*
2845 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2846 // If this basic block starts out with a name, remember it.
2848 LocTy NameLoc = Lex.getLoc();
2849 if (Lex.getKind() == lltok::LabelStr) {
2850 Name = Lex.getStrVal();
2854 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2855 if (BB == 0) return true;
2857 std::string NameStr;
2859 // Parse the instructions in this block until we get a terminator.
2861 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2863 // This instruction may have three possibilities for a name: a) none
2864 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2865 LocTy NameLoc = Lex.getLoc();
2869 if (Lex.getKind() == lltok::LocalVarID) {
2870 NameID = Lex.getUIntVal();
2872 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2874 } else if (Lex.getKind() == lltok::LocalVar) {
2875 NameStr = Lex.getStrVal();
2877 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2881 switch (ParseInstruction(Inst, BB, PFS)) {
2882 default: llvm_unreachable("Unknown ParseInstruction result!");
2883 case InstError: return true;
2885 BB->getInstList().push_back(Inst);
2887 // With a normal result, we check to see if the instruction is followed by
2888 // a comma and metadata.
2889 if (EatIfPresent(lltok::comma))
2890 if (ParseInstructionMetadata(Inst, &PFS))
2893 case InstExtraComma:
2894 BB->getInstList().push_back(Inst);
2896 // If the instruction parser ate an extra comma at the end of it, it
2897 // *must* be followed by metadata.
2898 if (ParseInstructionMetadata(Inst, &PFS))
2903 // Set the name on the instruction.
2904 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2905 } while (!isa<TerminatorInst>(Inst));
2910 //===----------------------------------------------------------------------===//
2911 // Instruction Parsing.
2912 //===----------------------------------------------------------------------===//
2914 /// ParseInstruction - Parse one of the many different instructions.
2916 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2917 PerFunctionState &PFS) {
2918 lltok::Kind Token = Lex.getKind();
2919 if (Token == lltok::Eof)
2920 return TokError("found end of file when expecting more instructions");
2921 LocTy Loc = Lex.getLoc();
2922 unsigned KeywordVal = Lex.getUIntVal();
2923 Lex.Lex(); // Eat the keyword.
2926 default: return Error(Loc, "expected instruction opcode");
2927 // Terminator Instructions.
2928 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2929 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2930 case lltok::kw_br: return ParseBr(Inst, PFS);
2931 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2932 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2933 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2934 case lltok::kw_resume: return ParseResume(Inst, PFS);
2935 // Binary Operators.
2939 case lltok::kw_shl: {
2940 bool NUW = EatIfPresent(lltok::kw_nuw);
2941 bool NSW = EatIfPresent(lltok::kw_nsw);
2942 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2944 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2946 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2947 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2950 case lltok::kw_fadd:
2951 case lltok::kw_fsub:
2952 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2954 case lltok::kw_sdiv:
2955 case lltok::kw_udiv:
2956 case lltok::kw_lshr:
2957 case lltok::kw_ashr: {
2958 bool Exact = EatIfPresent(lltok::kw_exact);
2960 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2961 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2965 case lltok::kw_urem:
2966 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2967 case lltok::kw_fdiv:
2968 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2971 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2972 case lltok::kw_icmp:
2973 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2975 case lltok::kw_trunc:
2976 case lltok::kw_zext:
2977 case lltok::kw_sext:
2978 case lltok::kw_fptrunc:
2979 case lltok::kw_fpext:
2980 case lltok::kw_bitcast:
2981 case lltok::kw_uitofp:
2982 case lltok::kw_sitofp:
2983 case lltok::kw_fptoui:
2984 case lltok::kw_fptosi:
2985 case lltok::kw_inttoptr:
2986 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2988 case lltok::kw_select: return ParseSelect(Inst, PFS);
2989 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2990 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2991 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2992 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2993 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2994 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
2995 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2996 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2998 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2999 case lltok::kw_load: return ParseLoad(Inst, PFS);
3000 case lltok::kw_store: return ParseStore(Inst, PFS);
3001 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3002 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3003 case lltok::kw_fence: return ParseFence(Inst, PFS);
3004 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3005 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3006 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3010 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3011 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3012 if (Opc == Instruction::FCmp) {
3013 switch (Lex.getKind()) {
3014 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3015 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3016 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3017 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3018 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3019 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3020 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3021 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3022 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3023 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3024 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3025 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3026 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3027 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3028 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3029 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3030 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3033 switch (Lex.getKind()) {
3034 default: TokError("expected icmp predicate (e.g. 'eq')");
3035 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3036 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3037 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3038 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3039 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3040 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3041 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3042 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3043 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3044 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3051 //===----------------------------------------------------------------------===//
3052 // Terminator Instructions.
3053 //===----------------------------------------------------------------------===//
3055 /// ParseRet - Parse a return instruction.
3056 /// ::= 'ret' void (',' !dbg, !1)*
3057 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3058 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3059 PerFunctionState &PFS) {
3060 SMLoc TypeLoc = Lex.getLoc();
3062 if (ParseType(Ty, true /*void allowed*/)) return true;
3064 Type *ResType = PFS.getFunction().getReturnType();
3066 if (Ty->isVoidTy()) {
3067 if (!ResType->isVoidTy())
3068 return Error(TypeLoc, "value doesn't match function result type '" +
3069 getTypeString(ResType) + "'");
3071 Inst = ReturnInst::Create(Context);
3076 if (ParseValue(Ty, RV, PFS)) return true;
3078 if (ResType != RV->getType())
3079 return Error(TypeLoc, "value doesn't match function result type '" +
3080 getTypeString(ResType) + "'");
3082 Inst = ReturnInst::Create(Context, RV);
3088 /// ::= 'br' TypeAndValue
3089 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3090 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3093 BasicBlock *Op1, *Op2;
3094 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3096 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3097 Inst = BranchInst::Create(BB);
3101 if (Op0->getType() != Type::getInt1Ty(Context))
3102 return Error(Loc, "branch condition must have 'i1' type");
3104 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3105 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3106 ParseToken(lltok::comma, "expected ',' after true destination") ||
3107 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3110 Inst = BranchInst::Create(Op1, Op2, Op0);
3116 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3118 /// ::= (TypeAndValue ',' TypeAndValue)*
3119 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3120 LocTy CondLoc, BBLoc;
3122 BasicBlock *DefaultBB;
3123 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3124 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3125 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3126 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3129 if (!Cond->getType()->isIntegerTy())
3130 return Error(CondLoc, "switch condition must have integer type");
3132 // Parse the jump table pairs.
3133 SmallPtrSet<Value*, 32> SeenCases;
3134 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3135 while (Lex.getKind() != lltok::rsquare) {
3139 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3140 ParseToken(lltok::comma, "expected ',' after case value") ||
3141 ParseTypeAndBasicBlock(DestBB, PFS))
3144 if (!SeenCases.insert(Constant))
3145 return Error(CondLoc, "duplicate case value in switch");
3146 if (!isa<ConstantInt>(Constant))
3147 return Error(CondLoc, "case value is not a constant integer");
3149 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3152 Lex.Lex(); // Eat the ']'.
3154 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3155 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3156 SI->addCase(Table[i].first, Table[i].second);
3163 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3164 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3167 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3168 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3169 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3172 if (!Address->getType()->isPointerTy())
3173 return Error(AddrLoc, "indirectbr address must have pointer type");
3175 // Parse the destination list.
3176 SmallVector<BasicBlock*, 16> DestList;
3178 if (Lex.getKind() != lltok::rsquare) {
3180 if (ParseTypeAndBasicBlock(DestBB, PFS))
3182 DestList.push_back(DestBB);
3184 while (EatIfPresent(lltok::comma)) {
3185 if (ParseTypeAndBasicBlock(DestBB, PFS))
3187 DestList.push_back(DestBB);
3191 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3194 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3195 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3196 IBI->addDestination(DestList[i]);
3203 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3204 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3205 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3206 LocTy CallLoc = Lex.getLoc();
3207 Attributes RetAttrs, FnAttrs;
3212 SmallVector<ParamInfo, 16> ArgList;
3214 BasicBlock *NormalBB, *UnwindBB;
3215 if (ParseOptionalCallingConv(CC) ||
3216 ParseOptionalAttrs(RetAttrs, 1) ||
3217 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3218 ParseValID(CalleeID) ||
3219 ParseParameterList(ArgList, PFS) ||
3220 ParseOptionalAttrs(FnAttrs, 2) ||
3221 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3222 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3223 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3224 ParseTypeAndBasicBlock(UnwindBB, PFS))
3227 // If RetType is a non-function pointer type, then this is the short syntax
3228 // for the call, which means that RetType is just the return type. Infer the
3229 // rest of the function argument types from the arguments that are present.
3230 PointerType *PFTy = 0;
3231 FunctionType *Ty = 0;
3232 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3233 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3234 // Pull out the types of all of the arguments...
3235 std::vector<Type*> ParamTypes;
3236 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3237 ParamTypes.push_back(ArgList[i].V->getType());
3239 if (!FunctionType::isValidReturnType(RetType))
3240 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3242 Ty = FunctionType::get(RetType, ParamTypes, false);
3243 PFTy = PointerType::getUnqual(Ty);
3246 // Look up the callee.
3248 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3250 // Set up the Attributes for the function.
3251 SmallVector<AttributeWithIndex, 8> Attrs;
3252 if (RetAttrs != Attribute::None)
3253 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3255 SmallVector<Value*, 8> Args;
3257 // Loop through FunctionType's arguments and ensure they are specified
3258 // correctly. Also, gather any parameter attributes.
3259 FunctionType::param_iterator I = Ty->param_begin();
3260 FunctionType::param_iterator E = Ty->param_end();
3261 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3262 Type *ExpectedTy = 0;
3265 } else if (!Ty->isVarArg()) {
3266 return Error(ArgList[i].Loc, "too many arguments specified");
3269 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3270 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3271 getTypeString(ExpectedTy) + "'");
3272 Args.push_back(ArgList[i].V);
3273 if (ArgList[i].Attrs != Attribute::None)
3274 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3278 return Error(CallLoc, "not enough parameters specified for call");
3280 if (FnAttrs != Attribute::None)
3281 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3283 // Finish off the Attributes and check them
3284 AttrListPtr PAL = AttrListPtr::get(Attrs);
3286 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3287 II->setCallingConv(CC);
3288 II->setAttributes(PAL);
3294 /// ::= 'resume' TypeAndValue
3295 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3296 Value *Exn; LocTy ExnLoc;
3297 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3300 ResumeInst *RI = ResumeInst::Create(Exn);
3305 //===----------------------------------------------------------------------===//
3306 // Binary Operators.
3307 //===----------------------------------------------------------------------===//
3310 /// ::= ArithmeticOps TypeAndValue ',' Value
3312 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3313 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3314 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3315 unsigned Opc, unsigned OperandType) {
3316 LocTy Loc; Value *LHS, *RHS;
3317 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3318 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3319 ParseValue(LHS->getType(), RHS, PFS))
3323 switch (OperandType) {
3324 default: llvm_unreachable("Unknown operand type!");
3325 case 0: // int or FP.
3326 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3327 LHS->getType()->isFPOrFPVectorTy();
3329 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3330 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3334 return Error(Loc, "invalid operand type for instruction");
3336 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3341 /// ::= ArithmeticOps TypeAndValue ',' Value {
3342 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3344 LocTy Loc; Value *LHS, *RHS;
3345 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3346 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3347 ParseValue(LHS->getType(), RHS, PFS))
3350 if (!LHS->getType()->isIntOrIntVectorTy())
3351 return Error(Loc,"instruction requires integer or integer vector operands");
3353 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3359 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3360 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3361 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3363 // Parse the integer/fp comparison predicate.
3367 if (ParseCmpPredicate(Pred, Opc) ||
3368 ParseTypeAndValue(LHS, Loc, PFS) ||
3369 ParseToken(lltok::comma, "expected ',' after compare value") ||
3370 ParseValue(LHS->getType(), RHS, PFS))
3373 if (Opc == Instruction::FCmp) {
3374 if (!LHS->getType()->isFPOrFPVectorTy())
3375 return Error(Loc, "fcmp requires floating point operands");
3376 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3378 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3379 if (!LHS->getType()->isIntOrIntVectorTy() &&
3380 !LHS->getType()->getScalarType()->isPointerTy())
3381 return Error(Loc, "icmp requires integer operands");
3382 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3387 //===----------------------------------------------------------------------===//
3388 // Other Instructions.
3389 //===----------------------------------------------------------------------===//
3393 /// ::= CastOpc TypeAndValue 'to' Type
3394 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3399 if (ParseTypeAndValue(Op, Loc, PFS) ||
3400 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3404 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3405 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3406 return Error(Loc, "invalid cast opcode for cast from '" +
3407 getTypeString(Op->getType()) + "' to '" +
3408 getTypeString(DestTy) + "'");
3410 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3415 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3416 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3418 Value *Op0, *Op1, *Op2;
3419 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' after select condition") ||
3421 ParseTypeAndValue(Op1, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after select value") ||
3423 ParseTypeAndValue(Op2, PFS))
3426 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3427 return Error(Loc, Reason);
3429 Inst = SelectInst::Create(Op0, Op1, Op2);
3434 /// ::= 'va_arg' TypeAndValue ',' Type
3435 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3439 if (ParseTypeAndValue(Op, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3441 ParseType(EltTy, TypeLoc))
3444 if (!EltTy->isFirstClassType())
3445 return Error(TypeLoc, "va_arg requires operand with first class type");
3447 Inst = new VAArgInst(Op, EltTy);
3451 /// ParseExtractElement
3452 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3453 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3456 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3457 ParseToken(lltok::comma, "expected ',' after extract value") ||
3458 ParseTypeAndValue(Op1, PFS))
3461 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3462 return Error(Loc, "invalid extractelement operands");
3464 Inst = ExtractElementInst::Create(Op0, Op1);
3468 /// ParseInsertElement
3469 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3470 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3472 Value *Op0, *Op1, *Op2;
3473 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3474 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3475 ParseTypeAndValue(Op1, PFS) ||
3476 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3477 ParseTypeAndValue(Op2, PFS))
3480 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3481 return Error(Loc, "invalid insertelement operands");
3483 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3487 /// ParseShuffleVector
3488 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3489 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3491 Value *Op0, *Op1, *Op2;
3492 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3493 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3494 ParseTypeAndValue(Op1, PFS) ||
3495 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3496 ParseTypeAndValue(Op2, PFS))
3499 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3500 return Error(Loc, "invalid shufflevector operands");
3502 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3507 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3508 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3509 Type *Ty = 0; LocTy TypeLoc;
3512 if (ParseType(Ty, TypeLoc) ||
3513 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3514 ParseValue(Ty, Op0, PFS) ||
3515 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3516 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3517 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3520 bool AteExtraComma = false;
3521 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3523 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3525 if (!EatIfPresent(lltok::comma))
3528 if (Lex.getKind() == lltok::MetadataVar) {
3529 AteExtraComma = true;
3533 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3534 ParseValue(Ty, Op0, PFS) ||
3535 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3536 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3537 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3541 if (!Ty->isFirstClassType())
3542 return Error(TypeLoc, "phi node must have first class type");
3544 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3545 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3546 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3548 return AteExtraComma ? InstExtraComma : InstNormal;
3552 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3554 /// ::= 'catch' TypeAndValue
3556 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3557 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3558 Type *Ty = 0; LocTy TyLoc;
3559 Value *PersFn; LocTy PersFnLoc;
3561 if (ParseType(Ty, TyLoc) ||
3562 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3563 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3566 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3567 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3569 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3570 LandingPadInst::ClauseType CT;
3571 if (EatIfPresent(lltok::kw_catch))
3572 CT = LandingPadInst::Catch;
3573 else if (EatIfPresent(lltok::kw_filter))
3574 CT = LandingPadInst::Filter;
3576 return TokError("expected 'catch' or 'filter' clause type");
3578 Value *V; LocTy VLoc;
3579 if (ParseTypeAndValue(V, VLoc, PFS)) {
3584 // A 'catch' type expects a non-array constant. A filter clause expects an
3586 if (CT == LandingPadInst::Catch) {
3587 if (isa<ArrayType>(V->getType()))
3588 Error(VLoc, "'catch' clause has an invalid type");
3590 if (!isa<ArrayType>(V->getType()))
3591 Error(VLoc, "'filter' clause has an invalid type");
3602 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3603 /// ParameterList OptionalAttrs
3604 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3606 Attributes RetAttrs, FnAttrs;
3611 SmallVector<ParamInfo, 16> ArgList;
3612 LocTy CallLoc = Lex.getLoc();
3614 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3615 ParseOptionalCallingConv(CC) ||
3616 ParseOptionalAttrs(RetAttrs, 1) ||
3617 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3618 ParseValID(CalleeID) ||
3619 ParseParameterList(ArgList, PFS) ||
3620 ParseOptionalAttrs(FnAttrs, 2))
3623 // If RetType is a non-function pointer type, then this is the short syntax
3624 // for the call, which means that RetType is just the return type. Infer the
3625 // rest of the function argument types from the arguments that are present.
3626 PointerType *PFTy = 0;
3627 FunctionType *Ty = 0;
3628 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3629 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3630 // Pull out the types of all of the arguments...
3631 std::vector<Type*> ParamTypes;
3632 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3633 ParamTypes.push_back(ArgList[i].V->getType());
3635 if (!FunctionType::isValidReturnType(RetType))
3636 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3638 Ty = FunctionType::get(RetType, ParamTypes, false);
3639 PFTy = PointerType::getUnqual(Ty);
3642 // Look up the callee.
3644 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3646 // Set up the Attributes for the function.
3647 SmallVector<AttributeWithIndex, 8> Attrs;
3648 if (RetAttrs != Attribute::None)
3649 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3651 SmallVector<Value*, 8> Args;
3653 // Loop through FunctionType's arguments and ensure they are specified
3654 // correctly. Also, gather any parameter attributes.
3655 FunctionType::param_iterator I = Ty->param_begin();
3656 FunctionType::param_iterator E = Ty->param_end();
3657 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3658 Type *ExpectedTy = 0;
3661 } else if (!Ty->isVarArg()) {
3662 return Error(ArgList[i].Loc, "too many arguments specified");
3665 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3666 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3667 getTypeString(ExpectedTy) + "'");
3668 Args.push_back(ArgList[i].V);
3669 if (ArgList[i].Attrs != Attribute::None)
3670 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3674 return Error(CallLoc, "not enough parameters specified for call");
3676 if (FnAttrs != Attribute::None)
3677 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3679 // Finish off the Attributes and check them
3680 AttrListPtr PAL = AttrListPtr::get(Attrs);
3682 CallInst *CI = CallInst::Create(Callee, Args);
3683 CI->setTailCall(isTail);
3684 CI->setCallingConv(CC);
3685 CI->setAttributes(PAL);
3690 //===----------------------------------------------------------------------===//
3691 // Memory Instructions.
3692 //===----------------------------------------------------------------------===//
3695 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3696 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3699 unsigned Alignment = 0;
3701 if (ParseType(Ty)) return true;
3703 bool AteExtraComma = false;
3704 if (EatIfPresent(lltok::comma)) {
3705 if (Lex.getKind() == lltok::kw_align) {
3706 if (ParseOptionalAlignment(Alignment)) return true;
3707 } else if (Lex.getKind() == lltok::MetadataVar) {
3708 AteExtraComma = true;
3710 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3711 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3716 if (Size && !Size->getType()->isIntegerTy())
3717 return Error(SizeLoc, "element count must have integer type");
3719 Inst = new AllocaInst(Ty, Size, Alignment);
3720 return AteExtraComma ? InstExtraComma : InstNormal;
3724 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3725 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3726 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3727 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3728 Value *Val; LocTy Loc;
3729 unsigned Alignment = 0;
3730 bool AteExtraComma = false;
3731 bool isAtomic = false;
3732 AtomicOrdering Ordering = NotAtomic;
3733 SynchronizationScope Scope = CrossThread;
3735 if (Lex.getKind() == lltok::kw_atomic) {
3740 bool isVolatile = false;
3741 if (Lex.getKind() == lltok::kw_volatile) {
3746 if (ParseTypeAndValue(Val, Loc, PFS) ||
3747 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3748 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3751 if (!Val->getType()->isPointerTy() ||
3752 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3753 return Error(Loc, "load operand must be a pointer to a first class type");
3754 if (isAtomic && !Alignment)
3755 return Error(Loc, "atomic load must have explicit non-zero alignment");
3756 if (Ordering == Release || Ordering == AcquireRelease)
3757 return Error(Loc, "atomic load cannot use Release ordering");
3759 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3760 return AteExtraComma ? InstExtraComma : InstNormal;
3765 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3766 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3767 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3768 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3769 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3770 unsigned Alignment = 0;
3771 bool AteExtraComma = false;
3772 bool isAtomic = false;
3773 AtomicOrdering Ordering = NotAtomic;
3774 SynchronizationScope Scope = CrossThread;
3776 if (Lex.getKind() == lltok::kw_atomic) {
3781 bool isVolatile = false;
3782 if (Lex.getKind() == lltok::kw_volatile) {
3787 if (ParseTypeAndValue(Val, Loc, PFS) ||
3788 ParseToken(lltok::comma, "expected ',' after store operand") ||
3789 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3790 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3791 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3794 if (!Ptr->getType()->isPointerTy())
3795 return Error(PtrLoc, "store operand must be a pointer");
3796 if (!Val->getType()->isFirstClassType())
3797 return Error(Loc, "store operand must be a first class value");
3798 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3799 return Error(Loc, "stored value and pointer type do not match");
3800 if (isAtomic && !Alignment)
3801 return Error(Loc, "atomic store must have explicit non-zero alignment");
3802 if (Ordering == Acquire || Ordering == AcquireRelease)
3803 return Error(Loc, "atomic store cannot use Acquire ordering");
3805 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3806 return AteExtraComma ? InstExtraComma : InstNormal;
3810 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3811 /// 'singlethread'? AtomicOrdering
3812 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3813 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3814 bool AteExtraComma = false;
3815 AtomicOrdering Ordering = NotAtomic;
3816 SynchronizationScope Scope = CrossThread;
3817 bool isVolatile = false;
3819 if (EatIfPresent(lltok::kw_volatile))
3822 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3823 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3824 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3825 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3826 ParseTypeAndValue(New, NewLoc, PFS) ||
3827 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3830 if (Ordering == Unordered)
3831 return TokError("cmpxchg cannot be unordered");
3832 if (!Ptr->getType()->isPointerTy())
3833 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3834 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3835 return Error(CmpLoc, "compare value and pointer type do not match");
3836 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3837 return Error(NewLoc, "new value and pointer type do not match");
3838 if (!New->getType()->isIntegerTy())
3839 return Error(NewLoc, "cmpxchg operand must be an integer");
3840 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3841 if (Size < 8 || (Size & (Size - 1)))
3842 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3845 AtomicCmpXchgInst *CXI =
3846 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3847 CXI->setVolatile(isVolatile);
3849 return AteExtraComma ? InstExtraComma : InstNormal;
3853 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3854 /// 'singlethread'? AtomicOrdering
3855 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3856 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3857 bool AteExtraComma = false;
3858 AtomicOrdering Ordering = NotAtomic;
3859 SynchronizationScope Scope = CrossThread;
3860 bool isVolatile = false;
3861 AtomicRMWInst::BinOp Operation;
3863 if (EatIfPresent(lltok::kw_volatile))
3866 switch (Lex.getKind()) {
3867 default: return TokError("expected binary operation in atomicrmw");
3868 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3869 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3870 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3871 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3872 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3873 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3874 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3875 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3876 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3877 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3878 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3880 Lex.Lex(); // Eat the operation.
3882 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3883 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3884 ParseTypeAndValue(Val, ValLoc, PFS) ||
3885 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3888 if (Ordering == Unordered)
3889 return TokError("atomicrmw cannot be unordered");
3890 if (!Ptr->getType()->isPointerTy())
3891 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3892 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3893 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3894 if (!Val->getType()->isIntegerTy())
3895 return Error(ValLoc, "atomicrmw operand must be an integer");
3896 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3897 if (Size < 8 || (Size & (Size - 1)))
3898 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3901 AtomicRMWInst *RMWI =
3902 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3903 RMWI->setVolatile(isVolatile);
3905 return AteExtraComma ? InstExtraComma : InstNormal;
3909 /// ::= 'fence' 'singlethread'? AtomicOrdering
3910 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3911 AtomicOrdering Ordering = NotAtomic;
3912 SynchronizationScope Scope = CrossThread;
3913 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3916 if (Ordering == Unordered)
3917 return TokError("fence cannot be unordered");
3918 if (Ordering == Monotonic)
3919 return TokError("fence cannot be monotonic");
3921 Inst = new FenceInst(Context, Ordering, Scope);
3925 /// ParseGetElementPtr
3926 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3927 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3932 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3934 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3936 if (!Ptr->getType()->getScalarType()->isPointerTy())
3937 return Error(Loc, "base of getelementptr must be a pointer");
3939 SmallVector<Value*, 16> Indices;
3940 bool AteExtraComma = false;
3941 while (EatIfPresent(lltok::comma)) {
3942 if (Lex.getKind() == lltok::MetadataVar) {
3943 AteExtraComma = true;
3946 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3947 if (!Val->getType()->getScalarType()->isIntegerTy())
3948 return Error(EltLoc, "getelementptr index must be an integer");
3949 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
3950 return Error(EltLoc, "getelementptr index type missmatch");
3951 if (Val->getType()->isVectorTy()) {
3952 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
3953 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
3954 if (ValNumEl != PtrNumEl)
3955 return Error(EltLoc,
3956 "getelementptr vector index has a wrong number of elements");
3958 Indices.push_back(Val);
3961 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1)
3962 return Error(EltLoc, "vector getelementptrs must have a single index");
3964 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
3965 return Error(Loc, "invalid getelementptr indices");
3966 Inst = GetElementPtrInst::Create(Ptr, Indices);
3968 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3969 return AteExtraComma ? InstExtraComma : InstNormal;
3972 /// ParseExtractValue
3973 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3974 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3975 Value *Val; LocTy Loc;
3976 SmallVector<unsigned, 4> Indices;
3978 if (ParseTypeAndValue(Val, Loc, PFS) ||
3979 ParseIndexList(Indices, AteExtraComma))
3982 if (!Val->getType()->isAggregateType())
3983 return Error(Loc, "extractvalue operand must be aggregate type");
3985 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3986 return Error(Loc, "invalid indices for extractvalue");
3987 Inst = ExtractValueInst::Create(Val, Indices);
3988 return AteExtraComma ? InstExtraComma : InstNormal;
3991 /// ParseInsertValue
3992 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3993 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3994 Value *Val0, *Val1; LocTy Loc0, Loc1;
3995 SmallVector<unsigned, 4> Indices;
3997 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3998 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3999 ParseTypeAndValue(Val1, Loc1, PFS) ||
4000 ParseIndexList(Indices, AteExtraComma))
4003 if (!Val0->getType()->isAggregateType())
4004 return Error(Loc0, "insertvalue operand must be aggregate type");
4006 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4007 return Error(Loc0, "invalid indices for insertvalue");
4008 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4009 return AteExtraComma ? InstExtraComma : InstNormal;
4012 //===----------------------------------------------------------------------===//
4013 // Embedded metadata.
4014 //===----------------------------------------------------------------------===//
4016 /// ParseMDNodeVector
4017 /// ::= Element (',' Element)*
4019 /// ::= 'null' | TypeAndValue
4020 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4021 PerFunctionState *PFS) {
4022 // Check for an empty list.
4023 if (Lex.getKind() == lltok::rbrace)
4027 // Null is a special case since it is typeless.
4028 if (EatIfPresent(lltok::kw_null)) {
4034 if (ParseTypeAndValue(V, PFS)) return true;
4036 } while (EatIfPresent(lltok::comma));