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/ADT/SmallPtrSet.h"
16 #include "llvm/AutoUpgrade.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/ValueSymbolTable.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: // FIXME: backwards compat.
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_linkonce_odr_auto_hide: // OptionalLinkage
194 case lltok::kw_appending: // OptionalLinkage
195 case lltok::kw_dllexport: // OptionalLinkage
196 case lltok::kw_common: // OptionalLinkage
197 case lltok::kw_dllimport: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: { // OptionalLinkage
200 unsigned Linkage, Visibility;
201 if (ParseOptionalLinkage(Linkage) ||
202 ParseOptionalVisibility(Visibility) ||
203 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
207 case lltok::kw_default: // OptionalVisibility
208 case lltok::kw_hidden: // OptionalVisibility
209 case lltok::kw_protected: { // OptionalVisibility
211 if (ParseOptionalVisibility(Visibility) ||
212 ParseGlobal("", SMLoc(), 0, false, Visibility))
217 case lltok::kw_thread_local: // OptionalThreadLocal
218 case lltok::kw_addrspace: // OptionalAddrSpace
219 case lltok::kw_constant: // GlobalType
220 case lltok::kw_global: // GlobalType
221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
229 /// ::= 'module' 'asm' STRINGCONSTANT
230 bool LLParser::ParseModuleAsm() {
231 assert(Lex.getKind() == lltok::kw_module);
235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
236 ParseStringConstant(AsmStr)) return true;
238 M->appendModuleInlineAsm(AsmStr);
243 /// ::= 'target' 'triple' '=' STRINGCONSTANT
244 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
245 bool LLParser::ParseTargetDefinition() {
246 assert(Lex.getKind() == lltok::kw_target);
249 default: return TokError("unknown target property");
250 case lltok::kw_triple:
252 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
253 ParseStringConstant(Str))
255 M->setTargetTriple(Str);
257 case lltok::kw_datalayout:
259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
260 ParseStringConstant(Str))
262 M->setDataLayout(Str);
268 /// ::= 'deplibs' '=' '[' ']'
269 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
270 /// FIXME: Remove in 4.0. Currently parse, but ignore.
271 bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
274 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
275 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
278 if (EatIfPresent(lltok::rsquare))
283 if (ParseStringConstant(Str)) return true;
284 } while (EatIfPresent(lltok::comma));
286 return ParseToken(lltok::rsquare, "expected ']' at end of list");
289 /// ParseUnnamedType:
290 /// ::= LocalVarID '=' 'type' type
291 bool LLParser::ParseUnnamedType() {
292 LocTy TypeLoc = Lex.getLoc();
293 unsigned TypeID = Lex.getUIntVal();
294 Lex.Lex(); // eat LocalVarID;
296 if (ParseToken(lltok::equal, "expected '=' after name") ||
297 ParseToken(lltok::kw_type, "expected 'type' after '='"))
300 if (TypeID >= NumberedTypes.size())
301 NumberedTypes.resize(TypeID+1);
304 if (ParseStructDefinition(TypeLoc, "",
305 NumberedTypes[TypeID], Result)) return true;
307 if (!isa<StructType>(Result)) {
308 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
310 return Error(TypeLoc, "non-struct types may not be recursive");
311 Entry.first = Result;
312 Entry.second = SMLoc();
320 /// ::= LocalVar '=' 'type' type
321 bool LLParser::ParseNamedType() {
322 std::string Name = Lex.getStrVal();
323 LocTy NameLoc = Lex.getLoc();
324 Lex.Lex(); // eat LocalVar.
326 if (ParseToken(lltok::equal, "expected '=' after name") ||
327 ParseToken(lltok::kw_type, "expected 'type' after name"))
331 if (ParseStructDefinition(NameLoc, Name,
332 NamedTypes[Name], Result)) return true;
334 if (!isa<StructType>(Result)) {
335 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
337 return Error(NameLoc, "non-struct types may not be recursive");
338 Entry.first = Result;
339 Entry.second = SMLoc();
347 /// ::= 'declare' FunctionHeader
348 bool LLParser::ParseDeclare() {
349 assert(Lex.getKind() == lltok::kw_declare);
353 return ParseFunctionHeader(F, false);
357 /// ::= 'define' FunctionHeader '{' ...
358 bool LLParser::ParseDefine() {
359 assert(Lex.getKind() == lltok::kw_define);
363 return ParseFunctionHeader(F, true) ||
364 ParseFunctionBody(*F);
370 bool LLParser::ParseGlobalType(bool &IsConstant) {
371 if (Lex.getKind() == lltok::kw_constant)
373 else if (Lex.getKind() == lltok::kw_global)
377 return TokError("expected 'global' or 'constant'");
383 /// ParseUnnamedGlobal:
384 /// OptionalVisibility ALIAS ...
385 /// OptionalLinkage OptionalVisibility ... -> global variable
386 /// GlobalID '=' OptionalVisibility ALIAS ...
387 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
388 bool LLParser::ParseUnnamedGlobal() {
389 unsigned VarID = NumberedVals.size();
391 LocTy NameLoc = Lex.getLoc();
393 // Handle the GlobalID form.
394 if (Lex.getKind() == lltok::GlobalID) {
395 if (Lex.getUIntVal() != VarID)
396 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
398 Lex.Lex(); // eat GlobalID;
400 if (ParseToken(lltok::equal, "expected '=' after name"))
405 unsigned Linkage, Visibility;
406 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
407 ParseOptionalVisibility(Visibility))
410 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
411 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
412 return ParseAlias(Name, NameLoc, Visibility);
415 /// ParseNamedGlobal:
416 /// GlobalVar '=' OptionalVisibility ALIAS ...
417 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
418 bool LLParser::ParseNamedGlobal() {
419 assert(Lex.getKind() == lltok::GlobalVar);
420 LocTy NameLoc = Lex.getLoc();
421 std::string Name = Lex.getStrVal();
425 unsigned Linkage, Visibility;
426 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
427 ParseOptionalLinkage(Linkage, HasLinkage) ||
428 ParseOptionalVisibility(Visibility))
431 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
432 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
433 return ParseAlias(Name, NameLoc, Visibility);
437 // ::= '!' STRINGCONSTANT
438 bool LLParser::ParseMDString(MDString *&Result) {
440 if (ParseStringConstant(Str)) return true;
441 Result = MDString::get(Context, Str);
446 // ::= '!' MDNodeNumber
448 /// This version of ParseMDNodeID returns the slot number and null in the case
449 /// of a forward reference.
450 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
451 // !{ ..., !42, ... }
452 if (ParseUInt32(SlotNo)) return true;
454 // Check existing MDNode.
455 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
456 Result = NumberedMetadata[SlotNo];
462 bool LLParser::ParseMDNodeID(MDNode *&Result) {
463 // !{ ..., !42, ... }
465 if (ParseMDNodeID(Result, MID)) return true;
467 // If not a forward reference, just return it now.
468 if (Result) return false;
470 // Otherwise, create MDNode forward reference.
471 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
472 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
474 if (NumberedMetadata.size() <= MID)
475 NumberedMetadata.resize(MID+1);
476 NumberedMetadata[MID] = FwdNode;
481 /// ParseNamedMetadata:
482 /// !foo = !{ !1, !2 }
483 bool LLParser::ParseNamedMetadata() {
484 assert(Lex.getKind() == lltok::MetadataVar);
485 std::string Name = Lex.getStrVal();
488 if (ParseToken(lltok::equal, "expected '=' here") ||
489 ParseToken(lltok::exclaim, "Expected '!' here") ||
490 ParseToken(lltok::lbrace, "Expected '{' here"))
493 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
494 if (Lex.getKind() != lltok::rbrace)
496 if (ParseToken(lltok::exclaim, "Expected '!' here"))
500 if (ParseMDNodeID(N)) return true;
502 } while (EatIfPresent(lltok::comma));
504 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
510 /// ParseStandaloneMetadata:
512 bool LLParser::ParseStandaloneMetadata() {
513 assert(Lex.getKind() == lltok::exclaim);
515 unsigned MetadataID = 0;
519 SmallVector<Value *, 16> Elts;
520 if (ParseUInt32(MetadataID) ||
521 ParseToken(lltok::equal, "expected '=' here") ||
522 ParseType(Ty, TyLoc) ||
523 ParseToken(lltok::exclaim, "Expected '!' here") ||
524 ParseToken(lltok::lbrace, "Expected '{' here") ||
525 ParseMDNodeVector(Elts, NULL) ||
526 ParseToken(lltok::rbrace, "expected end of metadata node"))
529 MDNode *Init = MDNode::get(Context, Elts);
531 // See if this was forward referenced, if so, handle it.
532 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
533 FI = ForwardRefMDNodes.find(MetadataID);
534 if (FI != ForwardRefMDNodes.end()) {
535 MDNode *Temp = FI->second.first;
536 Temp->replaceAllUsesWith(Init);
537 MDNode::deleteTemporary(Temp);
538 ForwardRefMDNodes.erase(FI);
540 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
542 if (MetadataID >= NumberedMetadata.size())
543 NumberedMetadata.resize(MetadataID+1);
545 if (NumberedMetadata[MetadataID] != 0)
546 return TokError("Metadata id is already used");
547 NumberedMetadata[MetadataID] = Init;
554 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
557 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
558 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
560 /// Everything through visibility has already been parsed.
562 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
563 unsigned Visibility) {
564 assert(Lex.getKind() == lltok::kw_alias);
567 LocTy LinkageLoc = Lex.getLoc();
568 if (ParseOptionalLinkage(Linkage))
571 if (Linkage != GlobalValue::ExternalLinkage &&
572 Linkage != GlobalValue::WeakAnyLinkage &&
573 Linkage != GlobalValue::WeakODRLinkage &&
574 Linkage != GlobalValue::InternalLinkage &&
575 Linkage != GlobalValue::PrivateLinkage &&
576 Linkage != GlobalValue::LinkerPrivateLinkage &&
577 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
578 return Error(LinkageLoc, "invalid linkage type for alias");
581 LocTy AliaseeLoc = Lex.getLoc();
582 if (Lex.getKind() != lltok::kw_bitcast &&
583 Lex.getKind() != lltok::kw_getelementptr) {
584 if (ParseGlobalTypeAndValue(Aliasee)) return true;
586 // The bitcast dest type is not present, it is implied by the dest type.
588 if (ParseValID(ID)) return true;
589 if (ID.Kind != ValID::t_Constant)
590 return Error(AliaseeLoc, "invalid aliasee");
591 Aliasee = ID.ConstantVal;
594 if (!Aliasee->getType()->isPointerTy())
595 return Error(AliaseeLoc, "alias must have pointer type");
597 // Okay, create the alias but do not insert it into the module yet.
598 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
599 (GlobalValue::LinkageTypes)Linkage, Name,
601 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
603 // See if this value already exists in the symbol table. If so, it is either
604 // a redefinition or a definition of a forward reference.
605 if (GlobalValue *Val = M->getNamedValue(Name)) {
606 // See if this was a redefinition. If so, there is no entry in
608 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
609 I = ForwardRefVals.find(Name);
610 if (I == ForwardRefVals.end())
611 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
613 // Otherwise, this was a definition of forward ref. Verify that types
615 if (Val->getType() != GA->getType())
616 return Error(NameLoc,
617 "forward reference and definition of alias have different types");
619 // If they agree, just RAUW the old value with the alias and remove the
621 Val->replaceAllUsesWith(GA);
622 Val->eraseFromParent();
623 ForwardRefVals.erase(I);
626 // Insert into the module, we know its name won't collide now.
627 M->getAliasList().push_back(GA);
628 assert(GA->getName() == Name && "Should not be a name conflict!");
634 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
635 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
636 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
637 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
639 /// Everything through visibility has been parsed already.
641 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
642 unsigned Linkage, bool HasLinkage,
643 unsigned Visibility) {
645 bool IsConstant, UnnamedAddr;
646 GlobalVariable::ThreadLocalMode TLM;
647 LocTy UnnamedAddrLoc;
651 if (ParseOptionalThreadLocal(TLM) ||
652 ParseOptionalAddrSpace(AddrSpace) ||
653 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
655 ParseGlobalType(IsConstant) ||
656 ParseType(Ty, TyLoc))
659 // If the linkage is specified and is external, then no initializer is
662 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
663 Linkage != GlobalValue::ExternalWeakLinkage &&
664 Linkage != GlobalValue::ExternalLinkage)) {
665 if (ParseGlobalValue(Ty, Init))
669 if (Ty->isFunctionTy() || Ty->isLabelTy())
670 return Error(TyLoc, "invalid type for global variable");
672 GlobalVariable *GV = 0;
674 // See if the global was forward referenced, if so, use the global.
676 if (GlobalValue *GVal = M->getNamedValue(Name)) {
677 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
678 return Error(NameLoc, "redefinition of global '@" + Name + "'");
679 GV = cast<GlobalVariable>(GVal);
682 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
683 I = ForwardRefValIDs.find(NumberedVals.size());
684 if (I != ForwardRefValIDs.end()) {
685 GV = cast<GlobalVariable>(I->second.first);
686 ForwardRefValIDs.erase(I);
691 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
692 Name, 0, GlobalVariable::NotThreadLocal,
695 if (GV->getType()->getElementType() != Ty)
697 "forward reference and definition of global have different types");
699 // Move the forward-reference to the correct spot in the module.
700 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
704 NumberedVals.push_back(GV);
706 // Set the parsed properties on the global.
708 GV->setInitializer(Init);
709 GV->setConstant(IsConstant);
710 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
711 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
712 GV->setThreadLocalMode(TLM);
713 GV->setUnnamedAddr(UnnamedAddr);
715 // Parse attributes on the global.
716 while (Lex.getKind() == lltok::comma) {
719 if (Lex.getKind() == lltok::kw_section) {
721 GV->setSection(Lex.getStrVal());
722 if (ParseToken(lltok::StringConstant, "expected global section string"))
724 } else if (Lex.getKind() == lltok::kw_align) {
726 if (ParseOptionalAlignment(Alignment)) return true;
727 GV->setAlignment(Alignment);
729 TokError("unknown global variable property!");
737 //===----------------------------------------------------------------------===//
738 // GlobalValue Reference/Resolution Routines.
739 //===----------------------------------------------------------------------===//
741 /// GetGlobalVal - Get a value with the specified name or ID, creating a
742 /// forward reference record if needed. This can return null if the value
743 /// exists but does not have the right type.
744 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
746 PointerType *PTy = dyn_cast<PointerType>(Ty);
748 Error(Loc, "global variable reference must have pointer type");
752 // Look this name up in the normal function symbol table.
754 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
756 // If this is a forward reference for the value, see if we already created a
757 // forward ref record.
759 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
760 I = ForwardRefVals.find(Name);
761 if (I != ForwardRefVals.end())
762 Val = I->second.first;
765 // If we have the value in the symbol table or fwd-ref table, return it.
767 if (Val->getType() == Ty) return Val;
768 Error(Loc, "'@" + Name + "' defined with type '" +
769 getTypeString(Val->getType()) + "'");
773 // Otherwise, create a new forward reference for this value and remember it.
775 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
776 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
778 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
779 GlobalValue::ExternalWeakLinkage, 0, Name,
780 0, GlobalVariable::NotThreadLocal,
781 PTy->getAddressSpace());
783 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
787 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
788 PointerType *PTy = dyn_cast<PointerType>(Ty);
790 Error(Loc, "global variable reference must have pointer type");
794 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
796 // If this is a forward reference for the value, see if we already created a
797 // forward ref record.
799 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
800 I = ForwardRefValIDs.find(ID);
801 if (I != ForwardRefValIDs.end())
802 Val = I->second.first;
805 // If we have the value in the symbol table or fwd-ref table, return it.
807 if (Val->getType() == Ty) return Val;
808 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
809 getTypeString(Val->getType()) + "'");
813 // Otherwise, create a new forward reference for this value and remember it.
815 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
816 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
818 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
819 GlobalValue::ExternalWeakLinkage, 0, "");
821 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
826 //===----------------------------------------------------------------------===//
828 //===----------------------------------------------------------------------===//
830 /// ParseToken - If the current token has the specified kind, eat it and return
831 /// success. Otherwise, emit the specified error and return failure.
832 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
833 if (Lex.getKind() != T)
834 return TokError(ErrMsg);
839 /// ParseStringConstant
840 /// ::= StringConstant
841 bool LLParser::ParseStringConstant(std::string &Result) {
842 if (Lex.getKind() != lltok::StringConstant)
843 return TokError("expected string constant");
844 Result = Lex.getStrVal();
851 bool LLParser::ParseUInt32(unsigned &Val) {
852 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
853 return TokError("expected integer");
854 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
855 if (Val64 != unsigned(Val64))
856 return TokError("expected 32-bit integer (too large)");
863 /// := 'localdynamic'
866 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
867 switch (Lex.getKind()) {
869 return TokError("expected localdynamic, initialexec or localexec");
870 case lltok::kw_localdynamic:
871 TLM = GlobalVariable::LocalDynamicTLSModel;
873 case lltok::kw_initialexec:
874 TLM = GlobalVariable::InitialExecTLSModel;
876 case lltok::kw_localexec:
877 TLM = GlobalVariable::LocalExecTLSModel;
885 /// ParseOptionalThreadLocal
887 /// := 'thread_local'
888 /// := 'thread_local' '(' tlsmodel ')'
889 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
890 TLM = GlobalVariable::NotThreadLocal;
891 if (!EatIfPresent(lltok::kw_thread_local))
894 TLM = GlobalVariable::GeneralDynamicTLSModel;
895 if (Lex.getKind() == lltok::lparen) {
897 return ParseTLSModel(TLM) ||
898 ParseToken(lltok::rparen, "expected ')' after thread local model");
903 /// ParseOptionalAddrSpace
905 /// := 'addrspace' '(' uint32 ')'
906 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
908 if (!EatIfPresent(lltok::kw_addrspace))
910 return ParseToken(lltok::lparen, "expected '(' in address space") ||
911 ParseUInt32(AddrSpace) ||
912 ParseToken(lltok::rparen, "expected ')' in address space");
915 /// ParseOptionalFuncAttrs - Parse a potentially empty list of function attributes.
916 bool LLParser::ParseOptionalFuncAttrs(AttrBuilder &B) {
917 bool HaveError = false;
922 lltok::Kind Token = Lex.getKind();
924 default: // End of attributes.
926 case lltok::kw_alignstack: {
928 if (ParseOptionalStackAlignment(Alignment))
930 B.addStackAlignmentAttr(Alignment);
933 case lltok::kw_align: {
934 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
937 if (ParseOptionalAlignment(Alignment))
939 B.addAlignmentAttr(Alignment);
942 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
943 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
944 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
945 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
946 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
947 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
948 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
949 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
950 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
951 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
952 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
953 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
954 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
955 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
956 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
957 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
958 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
959 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
962 case lltok::kw_zeroext:
963 case lltok::kw_signext:
964 case lltok::kw_inreg:
965 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on a function");
967 case lltok::kw_sret: case lltok::kw_noalias:
968 case lltok::kw_nocapture: case lltok::kw_byval:
971 Error(Lex.getLoc(), "invalid use of parameter-only attribute on a function");
979 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
980 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
981 bool HaveError = false;
986 lltok::Kind Token = Lex.getKind();
988 default: // End of attributes.
990 case lltok::kw_align: {
992 if (ParseOptionalAlignment(Alignment))
994 B.addAlignmentAttr(Alignment);
997 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
998 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
999 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1000 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1001 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1002 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1003 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1004 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1006 case lltok::kw_noreturn: case lltok::kw_nounwind:
1007 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1008 case lltok::kw_noinline: case lltok::kw_readnone:
1009 case lltok::kw_readonly: case lltok::kw_inlinehint:
1010 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1011 case lltok::kw_ssp: case lltok::kw_sspreq:
1012 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1013 case lltok::kw_naked: case lltok::kw_nonlazybind:
1014 case lltok::kw_address_safety: case lltok::kw_minsize:
1015 case lltok::kw_alignstack:
1016 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1024 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1025 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1026 bool HaveError = false;
1031 lltok::Kind Token = Lex.getKind();
1033 default: // End of attributes.
1035 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1036 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1037 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1038 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1041 case lltok::kw_sret: case lltok::kw_nocapture:
1042 case lltok::kw_byval: case lltok::kw_nest:
1043 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1045 case lltok::kw_noreturn: case lltok::kw_nounwind:
1046 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1047 case lltok::kw_noinline: case lltok::kw_readnone:
1048 case lltok::kw_readonly: case lltok::kw_inlinehint:
1049 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1050 case lltok::kw_ssp: case lltok::kw_sspreq:
1051 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1052 case lltok::kw_naked: case lltok::kw_nonlazybind:
1053 case lltok::kw_address_safety: case lltok::kw_minsize:
1054 case lltok::kw_alignstack: case lltok::kw_align:
1055 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1063 /// ParseOptionalLinkage
1066 /// ::= 'linker_private'
1067 /// ::= 'linker_private_weak'
1072 /// ::= 'linkonce_odr'
1073 /// ::= 'linkonce_odr_auto_hide'
1074 /// ::= 'available_externally'
1079 /// ::= 'extern_weak'
1081 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1083 switch (Lex.getKind()) {
1084 default: Res=GlobalValue::ExternalLinkage; return false;
1085 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1086 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1087 case lltok::kw_linker_private_weak:
1088 Res = GlobalValue::LinkerPrivateWeakLinkage;
1090 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1091 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1092 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1093 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1094 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1095 case lltok::kw_linkonce_odr_auto_hide:
1096 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1097 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1099 case lltok::kw_available_externally:
1100 Res = GlobalValue::AvailableExternallyLinkage;
1102 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1103 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1104 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1105 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1106 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1107 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1114 /// ParseOptionalVisibility
1120 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1121 switch (Lex.getKind()) {
1122 default: Res = GlobalValue::DefaultVisibility; return false;
1123 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1124 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1125 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1131 /// ParseOptionalCallingConv
1135 /// ::= 'kw_intel_ocl_bicc'
1137 /// ::= 'x86_stdcallcc'
1138 /// ::= 'x86_fastcallcc'
1139 /// ::= 'x86_thiscallcc'
1140 /// ::= 'arm_apcscc'
1141 /// ::= 'arm_aapcscc'
1142 /// ::= 'arm_aapcs_vfpcc'
1143 /// ::= 'msp430_intrcc'
1144 /// ::= 'ptx_kernel'
1145 /// ::= 'ptx_device'
1147 /// ::= 'spir_kernel'
1150 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1151 switch (Lex.getKind()) {
1152 default: CC = CallingConv::C; return false;
1153 case lltok::kw_ccc: CC = CallingConv::C; break;
1154 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1155 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1156 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1157 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1158 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1159 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1160 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1161 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1162 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1163 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1164 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1165 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1166 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1167 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1168 case lltok::kw_cc: {
1169 unsigned ArbitraryCC;
1171 if (ParseUInt32(ArbitraryCC))
1173 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1182 /// ParseInstructionMetadata
1183 /// ::= !dbg !42 (',' !dbg !57)*
1184 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1185 PerFunctionState *PFS) {
1187 if (Lex.getKind() != lltok::MetadataVar)
1188 return TokError("expected metadata after comma");
1190 std::string Name = Lex.getStrVal();
1191 unsigned MDK = M->getMDKindID(Name);
1195 SMLoc Loc = Lex.getLoc();
1197 if (ParseToken(lltok::exclaim, "expected '!' here"))
1200 // This code is similar to that of ParseMetadataValue, however it needs to
1201 // have special-case code for a forward reference; see the comments on
1202 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1203 // at the top level here.
1204 if (Lex.getKind() == lltok::lbrace) {
1206 if (ParseMetadataListValue(ID, PFS))
1208 assert(ID.Kind == ValID::t_MDNode);
1209 Inst->setMetadata(MDK, ID.MDNodeVal);
1211 unsigned NodeID = 0;
1212 if (ParseMDNodeID(Node, NodeID))
1215 // If we got the node, add it to the instruction.
1216 Inst->setMetadata(MDK, Node);
1218 MDRef R = { Loc, MDK, NodeID };
1219 // Otherwise, remember that this should be resolved later.
1220 ForwardRefInstMetadata[Inst].push_back(R);
1224 // If this is the end of the list, we're done.
1225 } while (EatIfPresent(lltok::comma));
1229 /// ParseOptionalAlignment
1232 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1234 if (!EatIfPresent(lltok::kw_align))
1236 LocTy AlignLoc = Lex.getLoc();
1237 if (ParseUInt32(Alignment)) return true;
1238 if (!isPowerOf2_32(Alignment))
1239 return Error(AlignLoc, "alignment is not a power of two");
1240 if (Alignment > Value::MaximumAlignment)
1241 return Error(AlignLoc, "huge alignments are not supported yet");
1245 /// ParseOptionalCommaAlign
1249 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1251 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1252 bool &AteExtraComma) {
1253 AteExtraComma = false;
1254 while (EatIfPresent(lltok::comma)) {
1255 // Metadata at the end is an early exit.
1256 if (Lex.getKind() == lltok::MetadataVar) {
1257 AteExtraComma = true;
1261 if (Lex.getKind() != lltok::kw_align)
1262 return Error(Lex.getLoc(), "expected metadata or 'align'");
1264 if (ParseOptionalAlignment(Alignment)) return true;
1270 /// ParseScopeAndOrdering
1271 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1274 /// This sets Scope and Ordering to the parsed values.
1275 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1276 AtomicOrdering &Ordering) {
1280 Scope = CrossThread;
1281 if (EatIfPresent(lltok::kw_singlethread))
1282 Scope = SingleThread;
1283 switch (Lex.getKind()) {
1284 default: return TokError("Expected ordering on atomic instruction");
1285 case lltok::kw_unordered: Ordering = Unordered; break;
1286 case lltok::kw_monotonic: Ordering = Monotonic; break;
1287 case lltok::kw_acquire: Ordering = Acquire; break;
1288 case lltok::kw_release: Ordering = Release; break;
1289 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1290 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1296 /// ParseOptionalStackAlignment
1298 /// ::= 'alignstack' '(' 4 ')'
1299 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1301 if (!EatIfPresent(lltok::kw_alignstack))
1303 LocTy ParenLoc = Lex.getLoc();
1304 if (!EatIfPresent(lltok::lparen))
1305 return Error(ParenLoc, "expected '('");
1306 LocTy AlignLoc = Lex.getLoc();
1307 if (ParseUInt32(Alignment)) return true;
1308 ParenLoc = Lex.getLoc();
1309 if (!EatIfPresent(lltok::rparen))
1310 return Error(ParenLoc, "expected ')'");
1311 if (!isPowerOf2_32(Alignment))
1312 return Error(AlignLoc, "stack alignment is not a power of two");
1316 /// ParseIndexList - This parses the index list for an insert/extractvalue
1317 /// instruction. This sets AteExtraComma in the case where we eat an extra
1318 /// comma at the end of the line and find that it is followed by metadata.
1319 /// Clients that don't allow metadata can call the version of this function that
1320 /// only takes one argument.
1323 /// ::= (',' uint32)+
1325 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1326 bool &AteExtraComma) {
1327 AteExtraComma = false;
1329 if (Lex.getKind() != lltok::comma)
1330 return TokError("expected ',' as start of index list");
1332 while (EatIfPresent(lltok::comma)) {
1333 if (Lex.getKind() == lltok::MetadataVar) {
1334 AteExtraComma = true;
1338 if (ParseUInt32(Idx)) return true;
1339 Indices.push_back(Idx);
1345 //===----------------------------------------------------------------------===//
1347 //===----------------------------------------------------------------------===//
1349 /// ParseType - Parse a type.
1350 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1351 SMLoc TypeLoc = Lex.getLoc();
1352 switch (Lex.getKind()) {
1354 return TokError("expected type");
1356 // Type ::= 'float' | 'void' (etc)
1357 Result = Lex.getTyVal();
1361 // Type ::= StructType
1362 if (ParseAnonStructType(Result, false))
1365 case lltok::lsquare:
1366 // Type ::= '[' ... ']'
1367 Lex.Lex(); // eat the lsquare.
1368 if (ParseArrayVectorType(Result, false))
1371 case lltok::less: // Either vector or packed struct.
1372 // Type ::= '<' ... '>'
1374 if (Lex.getKind() == lltok::lbrace) {
1375 if (ParseAnonStructType(Result, true) ||
1376 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1378 } else if (ParseArrayVectorType(Result, true))
1381 case lltok::LocalVar: {
1383 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1385 // If the type hasn't been defined yet, create a forward definition and
1386 // remember where that forward def'n was seen (in case it never is defined).
1387 if (Entry.first == 0) {
1388 Entry.first = StructType::create(Context, Lex.getStrVal());
1389 Entry.second = Lex.getLoc();
1391 Result = Entry.first;
1396 case lltok::LocalVarID: {
1398 if (Lex.getUIntVal() >= NumberedTypes.size())
1399 NumberedTypes.resize(Lex.getUIntVal()+1);
1400 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1402 // If the type hasn't been defined yet, create a forward definition and
1403 // remember where that forward def'n was seen (in case it never is defined).
1404 if (Entry.first == 0) {
1405 Entry.first = StructType::create(Context);
1406 Entry.second = Lex.getLoc();
1408 Result = Entry.first;
1414 // Parse the type suffixes.
1416 switch (Lex.getKind()) {
1419 if (!AllowVoid && Result->isVoidTy())
1420 return Error(TypeLoc, "void type only allowed for function results");
1423 // Type ::= Type '*'
1425 if (Result->isLabelTy())
1426 return TokError("basic block pointers are invalid");
1427 if (Result->isVoidTy())
1428 return TokError("pointers to void are invalid - use i8* instead");
1429 if (!PointerType::isValidElementType(Result))
1430 return TokError("pointer to this type is invalid");
1431 Result = PointerType::getUnqual(Result);
1435 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1436 case lltok::kw_addrspace: {
1437 if (Result->isLabelTy())
1438 return TokError("basic block pointers are invalid");
1439 if (Result->isVoidTy())
1440 return TokError("pointers to void are invalid; use i8* instead");
1441 if (!PointerType::isValidElementType(Result))
1442 return TokError("pointer to this type is invalid");
1444 if (ParseOptionalAddrSpace(AddrSpace) ||
1445 ParseToken(lltok::star, "expected '*' in address space"))
1448 Result = PointerType::get(Result, AddrSpace);
1452 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1454 if (ParseFunctionType(Result))
1461 /// ParseParameterList
1463 /// ::= '(' Arg (',' Arg)* ')'
1465 /// ::= Type OptionalAttributes Value OptionalAttributes
1466 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1467 PerFunctionState &PFS) {
1468 if (ParseToken(lltok::lparen, "expected '(' in call"))
1471 while (Lex.getKind() != lltok::rparen) {
1472 // If this isn't the first argument, we need a comma.
1473 if (!ArgList.empty() &&
1474 ParseToken(lltok::comma, "expected ',' in argument list"))
1477 // Parse the argument.
1480 AttrBuilder ArgAttrs;
1482 if (ParseType(ArgTy, ArgLoc))
1485 // Otherwise, handle normal operands.
1486 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1488 ArgList.push_back(ParamInfo(ArgLoc, V, Attribute::get(V->getContext(),
1492 Lex.Lex(); // Lex the ')'.
1498 /// ParseArgumentList - Parse the argument list for a function type or function
1500 /// ::= '(' ArgTypeListI ')'
1504 /// ::= ArgTypeList ',' '...'
1505 /// ::= ArgType (',' ArgType)*
1507 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1510 assert(Lex.getKind() == lltok::lparen);
1511 Lex.Lex(); // eat the (.
1513 if (Lex.getKind() == lltok::rparen) {
1515 } else if (Lex.getKind() == lltok::dotdotdot) {
1519 LocTy TypeLoc = Lex.getLoc();
1524 if (ParseType(ArgTy) ||
1525 ParseOptionalParamAttrs(Attrs)) return true;
1527 if (ArgTy->isVoidTy())
1528 return Error(TypeLoc, "argument can not have void type");
1530 if (Lex.getKind() == lltok::LocalVar) {
1531 Name = Lex.getStrVal();
1535 if (!FunctionType::isValidArgumentType(ArgTy))
1536 return Error(TypeLoc, "invalid type for function argument");
1538 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1539 Attribute::get(ArgTy->getContext(),
1542 while (EatIfPresent(lltok::comma)) {
1543 // Handle ... at end of arg list.
1544 if (EatIfPresent(lltok::dotdotdot)) {
1549 // Otherwise must be an argument type.
1550 TypeLoc = Lex.getLoc();
1551 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1553 if (ArgTy->isVoidTy())
1554 return Error(TypeLoc, "argument can not have void type");
1556 if (Lex.getKind() == lltok::LocalVar) {
1557 Name = Lex.getStrVal();
1563 if (!ArgTy->isFirstClassType())
1564 return Error(TypeLoc, "invalid type for function argument");
1566 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1567 Attribute::get(ArgTy->getContext(), Attrs),
1572 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1575 /// ParseFunctionType
1576 /// ::= Type ArgumentList OptionalAttrs
1577 bool LLParser::ParseFunctionType(Type *&Result) {
1578 assert(Lex.getKind() == lltok::lparen);
1580 if (!FunctionType::isValidReturnType(Result))
1581 return TokError("invalid function return type");
1583 SmallVector<ArgInfo, 8> ArgList;
1585 if (ParseArgumentList(ArgList, isVarArg))
1588 // Reject names on the arguments lists.
1589 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1590 if (!ArgList[i].Name.empty())
1591 return Error(ArgList[i].Loc, "argument name invalid in function type");
1592 if (ArgList[i].Attrs.hasAttributes())
1593 return Error(ArgList[i].Loc,
1594 "argument attributes invalid in function type");
1597 SmallVector<Type*, 16> ArgListTy;
1598 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1599 ArgListTy.push_back(ArgList[i].Ty);
1601 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1605 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1607 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1608 SmallVector<Type*, 8> Elts;
1609 if (ParseStructBody(Elts)) return true;
1611 Result = StructType::get(Context, Elts, Packed);
1615 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1616 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1617 std::pair<Type*, LocTy> &Entry,
1619 // If the type was already defined, diagnose the redefinition.
1620 if (Entry.first && !Entry.second.isValid())
1621 return Error(TypeLoc, "redefinition of type");
1623 // If we have opaque, just return without filling in the definition for the
1624 // struct. This counts as a definition as far as the .ll file goes.
1625 if (EatIfPresent(lltok::kw_opaque)) {
1626 // This type is being defined, so clear the location to indicate this.
1627 Entry.second = SMLoc();
1629 // If this type number has never been uttered, create it.
1630 if (Entry.first == 0)
1631 Entry.first = StructType::create(Context, Name);
1632 ResultTy = Entry.first;
1636 // If the type starts with '<', then it is either a packed struct or a vector.
1637 bool isPacked = EatIfPresent(lltok::less);
1639 // If we don't have a struct, then we have a random type alias, which we
1640 // accept for compatibility with old files. These types are not allowed to be
1641 // forward referenced and not allowed to be recursive.
1642 if (Lex.getKind() != lltok::lbrace) {
1644 return Error(TypeLoc, "forward references to non-struct type");
1648 return ParseArrayVectorType(ResultTy, true);
1649 return ParseType(ResultTy);
1652 // This type is being defined, so clear the location to indicate this.
1653 Entry.second = SMLoc();
1655 // If this type number has never been uttered, create it.
1656 if (Entry.first == 0)
1657 Entry.first = StructType::create(Context, Name);
1659 StructType *STy = cast<StructType>(Entry.first);
1661 SmallVector<Type*, 8> Body;
1662 if (ParseStructBody(Body) ||
1663 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1666 STy->setBody(Body, isPacked);
1672 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1675 /// ::= '{' Type (',' Type)* '}'
1676 /// ::= '<' '{' '}' '>'
1677 /// ::= '<' '{' Type (',' Type)* '}' '>'
1678 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1679 assert(Lex.getKind() == lltok::lbrace);
1680 Lex.Lex(); // Consume the '{'
1682 // Handle the empty struct.
1683 if (EatIfPresent(lltok::rbrace))
1686 LocTy EltTyLoc = Lex.getLoc();
1688 if (ParseType(Ty)) return true;
1691 if (!StructType::isValidElementType(Ty))
1692 return Error(EltTyLoc, "invalid element type for struct");
1694 while (EatIfPresent(lltok::comma)) {
1695 EltTyLoc = Lex.getLoc();
1696 if (ParseType(Ty)) return true;
1698 if (!StructType::isValidElementType(Ty))
1699 return Error(EltTyLoc, "invalid element type for struct");
1704 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1707 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1708 /// token has already been consumed.
1710 /// ::= '[' APSINTVAL 'x' Types ']'
1711 /// ::= '<' APSINTVAL 'x' Types '>'
1712 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1713 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1714 Lex.getAPSIntVal().getBitWidth() > 64)
1715 return TokError("expected number in address space");
1717 LocTy SizeLoc = Lex.getLoc();
1718 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1721 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1724 LocTy TypeLoc = Lex.getLoc();
1726 if (ParseType(EltTy)) return true;
1728 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1729 "expected end of sequential type"))
1734 return Error(SizeLoc, "zero element vector is illegal");
1735 if ((unsigned)Size != Size)
1736 return Error(SizeLoc, "size too large for vector");
1737 if (!VectorType::isValidElementType(EltTy))
1738 return Error(TypeLoc, "invalid vector element type");
1739 Result = VectorType::get(EltTy, unsigned(Size));
1741 if (!ArrayType::isValidElementType(EltTy))
1742 return Error(TypeLoc, "invalid array element type");
1743 Result = ArrayType::get(EltTy, Size);
1748 //===----------------------------------------------------------------------===//
1749 // Function Semantic Analysis.
1750 //===----------------------------------------------------------------------===//
1752 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1754 : P(p), F(f), FunctionNumber(functionNumber) {
1756 // Insert unnamed arguments into the NumberedVals list.
1757 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1760 NumberedVals.push_back(AI);
1763 LLParser::PerFunctionState::~PerFunctionState() {
1764 // If there were any forward referenced non-basicblock values, delete them.
1765 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1766 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1767 if (!isa<BasicBlock>(I->second.first)) {
1768 I->second.first->replaceAllUsesWith(
1769 UndefValue::get(I->second.first->getType()));
1770 delete I->second.first;
1771 I->second.first = 0;
1774 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1775 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1776 if (!isa<BasicBlock>(I->second.first)) {
1777 I->second.first->replaceAllUsesWith(
1778 UndefValue::get(I->second.first->getType()));
1779 delete I->second.first;
1780 I->second.first = 0;
1784 bool LLParser::PerFunctionState::FinishFunction() {
1785 // Check to see if someone took the address of labels in this block.
1786 if (!P.ForwardRefBlockAddresses.empty()) {
1788 if (!F.getName().empty()) {
1789 FunctionID.Kind = ValID::t_GlobalName;
1790 FunctionID.StrVal = F.getName();
1792 FunctionID.Kind = ValID::t_GlobalID;
1793 FunctionID.UIntVal = FunctionNumber;
1796 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1797 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1798 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1799 // Resolve all these references.
1800 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1803 P.ForwardRefBlockAddresses.erase(FRBAI);
1807 if (!ForwardRefVals.empty())
1808 return P.Error(ForwardRefVals.begin()->second.second,
1809 "use of undefined value '%" + ForwardRefVals.begin()->first +
1811 if (!ForwardRefValIDs.empty())
1812 return P.Error(ForwardRefValIDs.begin()->second.second,
1813 "use of undefined value '%" +
1814 Twine(ForwardRefValIDs.begin()->first) + "'");
1819 /// GetVal - Get a value with the specified name or ID, creating a
1820 /// forward reference record if needed. This can return null if the value
1821 /// exists but does not have the right type.
1822 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1823 Type *Ty, LocTy Loc) {
1824 // Look this name up in the normal function symbol table.
1825 Value *Val = F.getValueSymbolTable().lookup(Name);
1827 // If this is a forward reference for the value, see if we already created a
1828 // forward ref record.
1830 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1831 I = ForwardRefVals.find(Name);
1832 if (I != ForwardRefVals.end())
1833 Val = I->second.first;
1836 // If we have the value in the symbol table or fwd-ref table, return it.
1838 if (Val->getType() == Ty) return Val;
1839 if (Ty->isLabelTy())
1840 P.Error(Loc, "'%" + Name + "' is not a basic block");
1842 P.Error(Loc, "'%" + Name + "' defined with type '" +
1843 getTypeString(Val->getType()) + "'");
1847 // Don't make placeholders with invalid type.
1848 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1849 P.Error(Loc, "invalid use of a non-first-class type");
1853 // Otherwise, create a new forward reference for this value and remember it.
1855 if (Ty->isLabelTy())
1856 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1858 FwdVal = new Argument(Ty, Name);
1860 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1864 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1866 // Look this name up in the normal function symbol table.
1867 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1869 // If this is a forward reference for the value, see if we already created a
1870 // forward ref record.
1872 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1873 I = ForwardRefValIDs.find(ID);
1874 if (I != ForwardRefValIDs.end())
1875 Val = I->second.first;
1878 // If we have the value in the symbol table or fwd-ref table, return it.
1880 if (Val->getType() == Ty) return Val;
1881 if (Ty->isLabelTy())
1882 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1884 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1885 getTypeString(Val->getType()) + "'");
1889 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1890 P.Error(Loc, "invalid use of a non-first-class type");
1894 // Otherwise, create a new forward reference for this value and remember it.
1896 if (Ty->isLabelTy())
1897 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1899 FwdVal = new Argument(Ty);
1901 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1905 /// SetInstName - After an instruction is parsed and inserted into its
1906 /// basic block, this installs its name.
1907 bool LLParser::PerFunctionState::SetInstName(int NameID,
1908 const std::string &NameStr,
1909 LocTy NameLoc, Instruction *Inst) {
1910 // If this instruction has void type, it cannot have a name or ID specified.
1911 if (Inst->getType()->isVoidTy()) {
1912 if (NameID != -1 || !NameStr.empty())
1913 return P.Error(NameLoc, "instructions returning void cannot have a name");
1917 // If this was a numbered instruction, verify that the instruction is the
1918 // expected value and resolve any forward references.
1919 if (NameStr.empty()) {
1920 // If neither a name nor an ID was specified, just use the next ID.
1922 NameID = NumberedVals.size();
1924 if (unsigned(NameID) != NumberedVals.size())
1925 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1926 Twine(NumberedVals.size()) + "'");
1928 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1929 ForwardRefValIDs.find(NameID);
1930 if (FI != ForwardRefValIDs.end()) {
1931 if (FI->second.first->getType() != Inst->getType())
1932 return P.Error(NameLoc, "instruction forward referenced with type '" +
1933 getTypeString(FI->second.first->getType()) + "'");
1934 FI->second.first->replaceAllUsesWith(Inst);
1935 delete FI->second.first;
1936 ForwardRefValIDs.erase(FI);
1939 NumberedVals.push_back(Inst);
1943 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1944 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1945 FI = ForwardRefVals.find(NameStr);
1946 if (FI != ForwardRefVals.end()) {
1947 if (FI->second.first->getType() != Inst->getType())
1948 return P.Error(NameLoc, "instruction forward referenced with type '" +
1949 getTypeString(FI->second.first->getType()) + "'");
1950 FI->second.first->replaceAllUsesWith(Inst);
1951 delete FI->second.first;
1952 ForwardRefVals.erase(FI);
1955 // Set the name on the instruction.
1956 Inst->setName(NameStr);
1958 if (Inst->getName() != NameStr)
1959 return P.Error(NameLoc, "multiple definition of local value named '" +
1964 /// GetBB - Get a basic block with the specified name or ID, creating a
1965 /// forward reference record if needed.
1966 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1968 return cast_or_null<BasicBlock>(GetVal(Name,
1969 Type::getLabelTy(F.getContext()), Loc));
1972 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1973 return cast_or_null<BasicBlock>(GetVal(ID,
1974 Type::getLabelTy(F.getContext()), Loc));
1977 /// DefineBB - Define the specified basic block, which is either named or
1978 /// unnamed. If there is an error, this returns null otherwise it returns
1979 /// the block being defined.
1980 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1984 BB = GetBB(NumberedVals.size(), Loc);
1986 BB = GetBB(Name, Loc);
1987 if (BB == 0) return 0; // Already diagnosed error.
1989 // Move the block to the end of the function. Forward ref'd blocks are
1990 // inserted wherever they happen to be referenced.
1991 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1993 // Remove the block from forward ref sets.
1995 ForwardRefValIDs.erase(NumberedVals.size());
1996 NumberedVals.push_back(BB);
1998 // BB forward references are already in the function symbol table.
1999 ForwardRefVals.erase(Name);
2005 //===----------------------------------------------------------------------===//
2007 //===----------------------------------------------------------------------===//
2009 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2010 /// type implied. For example, if we parse "4" we don't know what integer type
2011 /// it has. The value will later be combined with its type and checked for
2012 /// sanity. PFS is used to convert function-local operands of metadata (since
2013 /// metadata operands are not just parsed here but also converted to values).
2014 /// PFS can be null when we are not parsing metadata values inside a function.
2015 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2016 ID.Loc = Lex.getLoc();
2017 switch (Lex.getKind()) {
2018 default: return TokError("expected value token");
2019 case lltok::GlobalID: // @42
2020 ID.UIntVal = Lex.getUIntVal();
2021 ID.Kind = ValID::t_GlobalID;
2023 case lltok::GlobalVar: // @foo
2024 ID.StrVal = Lex.getStrVal();
2025 ID.Kind = ValID::t_GlobalName;
2027 case lltok::LocalVarID: // %42
2028 ID.UIntVal = Lex.getUIntVal();
2029 ID.Kind = ValID::t_LocalID;
2031 case lltok::LocalVar: // %foo
2032 ID.StrVal = Lex.getStrVal();
2033 ID.Kind = ValID::t_LocalName;
2035 case lltok::exclaim: // !42, !{...}, or !"foo"
2036 return ParseMetadataValue(ID, PFS);
2038 ID.APSIntVal = Lex.getAPSIntVal();
2039 ID.Kind = ValID::t_APSInt;
2041 case lltok::APFloat:
2042 ID.APFloatVal = Lex.getAPFloatVal();
2043 ID.Kind = ValID::t_APFloat;
2045 case lltok::kw_true:
2046 ID.ConstantVal = ConstantInt::getTrue(Context);
2047 ID.Kind = ValID::t_Constant;
2049 case lltok::kw_false:
2050 ID.ConstantVal = ConstantInt::getFalse(Context);
2051 ID.Kind = ValID::t_Constant;
2053 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2054 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2055 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2057 case lltok::lbrace: {
2058 // ValID ::= '{' ConstVector '}'
2060 SmallVector<Constant*, 16> Elts;
2061 if (ParseGlobalValueVector(Elts) ||
2062 ParseToken(lltok::rbrace, "expected end of struct constant"))
2065 ID.ConstantStructElts = new Constant*[Elts.size()];
2066 ID.UIntVal = Elts.size();
2067 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2068 ID.Kind = ValID::t_ConstantStruct;
2072 // ValID ::= '<' ConstVector '>' --> Vector.
2073 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2075 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2077 SmallVector<Constant*, 16> Elts;
2078 LocTy FirstEltLoc = Lex.getLoc();
2079 if (ParseGlobalValueVector(Elts) ||
2081 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2082 ParseToken(lltok::greater, "expected end of constant"))
2085 if (isPackedStruct) {
2086 ID.ConstantStructElts = new Constant*[Elts.size()];
2087 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2088 ID.UIntVal = Elts.size();
2089 ID.Kind = ValID::t_PackedConstantStruct;
2094 return Error(ID.Loc, "constant vector must not be empty");
2096 if (!Elts[0]->getType()->isIntegerTy() &&
2097 !Elts[0]->getType()->isFloatingPointTy() &&
2098 !Elts[0]->getType()->isPointerTy())
2099 return Error(FirstEltLoc,
2100 "vector elements must have integer, pointer or floating point type");
2102 // Verify that all the vector elements have the same type.
2103 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2104 if (Elts[i]->getType() != Elts[0]->getType())
2105 return Error(FirstEltLoc,
2106 "vector element #" + Twine(i) +
2107 " is not of type '" + getTypeString(Elts[0]->getType()));
2109 ID.ConstantVal = ConstantVector::get(Elts);
2110 ID.Kind = ValID::t_Constant;
2113 case lltok::lsquare: { // Array Constant
2115 SmallVector<Constant*, 16> Elts;
2116 LocTy FirstEltLoc = Lex.getLoc();
2117 if (ParseGlobalValueVector(Elts) ||
2118 ParseToken(lltok::rsquare, "expected end of array constant"))
2121 // Handle empty element.
2123 // Use undef instead of an array because it's inconvenient to determine
2124 // the element type at this point, there being no elements to examine.
2125 ID.Kind = ValID::t_EmptyArray;
2129 if (!Elts[0]->getType()->isFirstClassType())
2130 return Error(FirstEltLoc, "invalid array element type: " +
2131 getTypeString(Elts[0]->getType()));
2133 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2135 // Verify all elements are correct type!
2136 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2137 if (Elts[i]->getType() != Elts[0]->getType())
2138 return Error(FirstEltLoc,
2139 "array element #" + Twine(i) +
2140 " is not of type '" + getTypeString(Elts[0]->getType()));
2143 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2144 ID.Kind = ValID::t_Constant;
2147 case lltok::kw_c: // c "foo"
2149 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2151 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2152 ID.Kind = ValID::t_Constant;
2155 case lltok::kw_asm: {
2156 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2157 bool HasSideEffect, AlignStack, AsmDialect;
2159 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2160 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2161 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2162 ParseStringConstant(ID.StrVal) ||
2163 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2164 ParseToken(lltok::StringConstant, "expected constraint string"))
2166 ID.StrVal2 = Lex.getStrVal();
2167 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2168 (unsigned(AsmDialect)<<2);
2169 ID.Kind = ValID::t_InlineAsm;
2173 case lltok::kw_blockaddress: {
2174 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2178 LocTy FnLoc, LabelLoc;
2180 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2182 ParseToken(lltok::comma, "expected comma in block address expression")||
2183 ParseValID(Label) ||
2184 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2187 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2188 return Error(Fn.Loc, "expected function name in blockaddress");
2189 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2190 return Error(Label.Loc, "expected basic block name in blockaddress");
2192 // Make a global variable as a placeholder for this reference.
2193 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2194 false, GlobalValue::InternalLinkage,
2196 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2197 ID.ConstantVal = FwdRef;
2198 ID.Kind = ValID::t_Constant;
2202 case lltok::kw_trunc:
2203 case lltok::kw_zext:
2204 case lltok::kw_sext:
2205 case lltok::kw_fptrunc:
2206 case lltok::kw_fpext:
2207 case lltok::kw_bitcast:
2208 case lltok::kw_uitofp:
2209 case lltok::kw_sitofp:
2210 case lltok::kw_fptoui:
2211 case lltok::kw_fptosi:
2212 case lltok::kw_inttoptr:
2213 case lltok::kw_ptrtoint: {
2214 unsigned Opc = Lex.getUIntVal();
2218 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2219 ParseGlobalTypeAndValue(SrcVal) ||
2220 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2221 ParseType(DestTy) ||
2222 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2224 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2225 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2226 getTypeString(SrcVal->getType()) + "' to '" +
2227 getTypeString(DestTy) + "'");
2228 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2230 ID.Kind = ValID::t_Constant;
2233 case lltok::kw_extractvalue: {
2236 SmallVector<unsigned, 4> Indices;
2237 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2238 ParseGlobalTypeAndValue(Val) ||
2239 ParseIndexList(Indices) ||
2240 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2243 if (!Val->getType()->isAggregateType())
2244 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2245 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2246 return Error(ID.Loc, "invalid indices for extractvalue");
2247 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2248 ID.Kind = ValID::t_Constant;
2251 case lltok::kw_insertvalue: {
2253 Constant *Val0, *Val1;
2254 SmallVector<unsigned, 4> Indices;
2255 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2256 ParseGlobalTypeAndValue(Val0) ||
2257 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2258 ParseGlobalTypeAndValue(Val1) ||
2259 ParseIndexList(Indices) ||
2260 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2262 if (!Val0->getType()->isAggregateType())
2263 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2264 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2265 return Error(ID.Loc, "invalid indices for insertvalue");
2266 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2267 ID.Kind = ValID::t_Constant;
2270 case lltok::kw_icmp:
2271 case lltok::kw_fcmp: {
2272 unsigned PredVal, Opc = Lex.getUIntVal();
2273 Constant *Val0, *Val1;
2275 if (ParseCmpPredicate(PredVal, Opc) ||
2276 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2277 ParseGlobalTypeAndValue(Val0) ||
2278 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2279 ParseGlobalTypeAndValue(Val1) ||
2280 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2283 if (Val0->getType() != Val1->getType())
2284 return Error(ID.Loc, "compare operands must have the same type");
2286 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2288 if (Opc == Instruction::FCmp) {
2289 if (!Val0->getType()->isFPOrFPVectorTy())
2290 return Error(ID.Loc, "fcmp requires floating point operands");
2291 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2293 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2294 if (!Val0->getType()->isIntOrIntVectorTy() &&
2295 !Val0->getType()->getScalarType()->isPointerTy())
2296 return Error(ID.Loc, "icmp requires pointer or integer operands");
2297 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2299 ID.Kind = ValID::t_Constant;
2303 // Binary Operators.
2305 case lltok::kw_fadd:
2307 case lltok::kw_fsub:
2309 case lltok::kw_fmul:
2310 case lltok::kw_udiv:
2311 case lltok::kw_sdiv:
2312 case lltok::kw_fdiv:
2313 case lltok::kw_urem:
2314 case lltok::kw_srem:
2315 case lltok::kw_frem:
2317 case lltok::kw_lshr:
2318 case lltok::kw_ashr: {
2322 unsigned Opc = Lex.getUIntVal();
2323 Constant *Val0, *Val1;
2325 LocTy ModifierLoc = Lex.getLoc();
2326 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2327 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2328 if (EatIfPresent(lltok::kw_nuw))
2330 if (EatIfPresent(lltok::kw_nsw)) {
2332 if (EatIfPresent(lltok::kw_nuw))
2335 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2336 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2337 if (EatIfPresent(lltok::kw_exact))
2340 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2341 ParseGlobalTypeAndValue(Val0) ||
2342 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2343 ParseGlobalTypeAndValue(Val1) ||
2344 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2346 if (Val0->getType() != Val1->getType())
2347 return Error(ID.Loc, "operands of constexpr must have same type");
2348 if (!Val0->getType()->isIntOrIntVectorTy()) {
2350 return Error(ModifierLoc, "nuw only applies to integer operations");
2352 return Error(ModifierLoc, "nsw only applies to integer operations");
2354 // Check that the type is valid for the operator.
2356 case Instruction::Add:
2357 case Instruction::Sub:
2358 case Instruction::Mul:
2359 case Instruction::UDiv:
2360 case Instruction::SDiv:
2361 case Instruction::URem:
2362 case Instruction::SRem:
2363 case Instruction::Shl:
2364 case Instruction::AShr:
2365 case Instruction::LShr:
2366 if (!Val0->getType()->isIntOrIntVectorTy())
2367 return Error(ID.Loc, "constexpr requires integer operands");
2369 case Instruction::FAdd:
2370 case Instruction::FSub:
2371 case Instruction::FMul:
2372 case Instruction::FDiv:
2373 case Instruction::FRem:
2374 if (!Val0->getType()->isFPOrFPVectorTy())
2375 return Error(ID.Loc, "constexpr requires fp operands");
2377 default: llvm_unreachable("Unknown binary operator!");
2380 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2381 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2382 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2383 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2385 ID.Kind = ValID::t_Constant;
2389 // Logical Operations
2392 case lltok::kw_xor: {
2393 unsigned Opc = Lex.getUIntVal();
2394 Constant *Val0, *Val1;
2396 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2397 ParseGlobalTypeAndValue(Val0) ||
2398 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2399 ParseGlobalTypeAndValue(Val1) ||
2400 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2402 if (Val0->getType() != Val1->getType())
2403 return Error(ID.Loc, "operands of constexpr must have same type");
2404 if (!Val0->getType()->isIntOrIntVectorTy())
2405 return Error(ID.Loc,
2406 "constexpr requires integer or integer vector operands");
2407 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2408 ID.Kind = ValID::t_Constant;
2412 case lltok::kw_getelementptr:
2413 case lltok::kw_shufflevector:
2414 case lltok::kw_insertelement:
2415 case lltok::kw_extractelement:
2416 case lltok::kw_select: {
2417 unsigned Opc = Lex.getUIntVal();
2418 SmallVector<Constant*, 16> Elts;
2419 bool InBounds = false;
2421 if (Opc == Instruction::GetElementPtr)
2422 InBounds = EatIfPresent(lltok::kw_inbounds);
2423 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2424 ParseGlobalValueVector(Elts) ||
2425 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2428 if (Opc == Instruction::GetElementPtr) {
2429 if (Elts.size() == 0 ||
2430 !Elts[0]->getType()->getScalarType()->isPointerTy())
2431 return Error(ID.Loc, "getelementptr requires pointer operand");
2433 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2434 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2435 return Error(ID.Loc, "invalid indices for getelementptr");
2436 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2438 } else if (Opc == Instruction::Select) {
2439 if (Elts.size() != 3)
2440 return Error(ID.Loc, "expected three operands to select");
2441 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2443 return Error(ID.Loc, Reason);
2444 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2445 } else if (Opc == Instruction::ShuffleVector) {
2446 if (Elts.size() != 3)
2447 return Error(ID.Loc, "expected three operands to shufflevector");
2448 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2449 return Error(ID.Loc, "invalid operands to shufflevector");
2451 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2452 } else if (Opc == Instruction::ExtractElement) {
2453 if (Elts.size() != 2)
2454 return Error(ID.Loc, "expected two operands to extractelement");
2455 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2456 return Error(ID.Loc, "invalid extractelement operands");
2457 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2459 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2460 if (Elts.size() != 3)
2461 return Error(ID.Loc, "expected three operands to insertelement");
2462 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2463 return Error(ID.Loc, "invalid insertelement operands");
2465 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2468 ID.Kind = ValID::t_Constant;
2477 /// ParseGlobalValue - Parse a global value with the specified type.
2478 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2482 bool Parsed = ParseValID(ID) ||
2483 ConvertValIDToValue(Ty, ID, V, NULL);
2484 if (V && !(C = dyn_cast<Constant>(V)))
2485 return Error(ID.Loc, "global values must be constants");
2489 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2491 return ParseType(Ty) ||
2492 ParseGlobalValue(Ty, V);
2495 /// ParseGlobalValueVector
2497 /// ::= TypeAndValue (',' TypeAndValue)*
2498 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2500 if (Lex.getKind() == lltok::rbrace ||
2501 Lex.getKind() == lltok::rsquare ||
2502 Lex.getKind() == lltok::greater ||
2503 Lex.getKind() == lltok::rparen)
2507 if (ParseGlobalTypeAndValue(C)) return true;
2510 while (EatIfPresent(lltok::comma)) {
2511 if (ParseGlobalTypeAndValue(C)) return true;
2518 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2519 assert(Lex.getKind() == lltok::lbrace);
2522 SmallVector<Value*, 16> Elts;
2523 if (ParseMDNodeVector(Elts, PFS) ||
2524 ParseToken(lltok::rbrace, "expected end of metadata node"))
2527 ID.MDNodeVal = MDNode::get(Context, Elts);
2528 ID.Kind = ValID::t_MDNode;
2532 /// ParseMetadataValue
2536 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2537 assert(Lex.getKind() == lltok::exclaim);
2542 if (Lex.getKind() == lltok::lbrace)
2543 return ParseMetadataListValue(ID, PFS);
2545 // Standalone metadata reference
2547 if (Lex.getKind() == lltok::APSInt) {
2548 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2549 ID.Kind = ValID::t_MDNode;
2554 // ::= '!' STRINGCONSTANT
2555 if (ParseMDString(ID.MDStringVal)) return true;
2556 ID.Kind = ValID::t_MDString;
2561 //===----------------------------------------------------------------------===//
2562 // Function Parsing.
2563 //===----------------------------------------------------------------------===//
2565 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2566 PerFunctionState *PFS) {
2567 if (Ty->isFunctionTy())
2568 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2571 case ValID::t_LocalID:
2572 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2573 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2575 case ValID::t_LocalName:
2576 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2577 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2579 case ValID::t_InlineAsm: {
2580 PointerType *PTy = dyn_cast<PointerType>(Ty);
2582 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2583 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2584 return Error(ID.Loc, "invalid type for inline asm constraint string");
2585 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2586 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2589 case ValID::t_MDNode:
2590 if (!Ty->isMetadataTy())
2591 return Error(ID.Loc, "metadata value must have metadata type");
2594 case ValID::t_MDString:
2595 if (!Ty->isMetadataTy())
2596 return Error(ID.Loc, "metadata value must have metadata type");
2599 case ValID::t_GlobalName:
2600 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2602 case ValID::t_GlobalID:
2603 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2605 case ValID::t_APSInt:
2606 if (!Ty->isIntegerTy())
2607 return Error(ID.Loc, "integer constant must have integer type");
2608 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2609 V = ConstantInt::get(Context, ID.APSIntVal);
2611 case ValID::t_APFloat:
2612 if (!Ty->isFloatingPointTy() ||
2613 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2614 return Error(ID.Loc, "floating point constant invalid for type");
2616 // The lexer has no type info, so builds all half, float, and double FP
2617 // constants as double. Fix this here. Long double does not need this.
2618 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2621 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2623 else if (Ty->isFloatTy())
2624 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2627 V = ConstantFP::get(Context, ID.APFloatVal);
2629 if (V->getType() != Ty)
2630 return Error(ID.Loc, "floating point constant does not have type '" +
2631 getTypeString(Ty) + "'");
2635 if (!Ty->isPointerTy())
2636 return Error(ID.Loc, "null must be a pointer type");
2637 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2639 case ValID::t_Undef:
2640 // FIXME: LabelTy should not be a first-class type.
2641 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2642 return Error(ID.Loc, "invalid type for undef constant");
2643 V = UndefValue::get(Ty);
2645 case ValID::t_EmptyArray:
2646 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2647 return Error(ID.Loc, "invalid empty array initializer");
2648 V = UndefValue::get(Ty);
2651 // FIXME: LabelTy should not be a first-class type.
2652 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2653 return Error(ID.Loc, "invalid type for null constant");
2654 V = Constant::getNullValue(Ty);
2656 case ValID::t_Constant:
2657 if (ID.ConstantVal->getType() != Ty)
2658 return Error(ID.Loc, "constant expression type mismatch");
2662 case ValID::t_ConstantStruct:
2663 case ValID::t_PackedConstantStruct:
2664 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2665 if (ST->getNumElements() != ID.UIntVal)
2666 return Error(ID.Loc,
2667 "initializer with struct type has wrong # elements");
2668 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2669 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2671 // Verify that the elements are compatible with the structtype.
2672 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2673 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2674 return Error(ID.Loc, "element " + Twine(i) +
2675 " of struct initializer doesn't match struct element type");
2677 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2680 return Error(ID.Loc, "constant expression type mismatch");
2683 llvm_unreachable("Invalid ValID");
2686 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2689 return ParseValID(ID, PFS) ||
2690 ConvertValIDToValue(Ty, ID, V, PFS);
2693 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2695 return ParseType(Ty) ||
2696 ParseValue(Ty, V, PFS);
2699 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2700 PerFunctionState &PFS) {
2703 if (ParseTypeAndValue(V, PFS)) return true;
2704 if (!isa<BasicBlock>(V))
2705 return Error(Loc, "expected a basic block");
2706 BB = cast<BasicBlock>(V);
2712 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2713 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2714 /// OptionalAlign OptGC
2715 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2716 // Parse the linkage.
2717 LocTy LinkageLoc = Lex.getLoc();
2720 unsigned Visibility;
2721 AttrBuilder RetAttrs;
2724 LocTy RetTypeLoc = Lex.getLoc();
2725 if (ParseOptionalLinkage(Linkage) ||
2726 ParseOptionalVisibility(Visibility) ||
2727 ParseOptionalCallingConv(CC) ||
2728 ParseOptionalReturnAttrs(RetAttrs) ||
2729 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2732 // Verify that the linkage is ok.
2733 switch ((GlobalValue::LinkageTypes)Linkage) {
2734 case GlobalValue::ExternalLinkage:
2735 break; // always ok.
2736 case GlobalValue::DLLImportLinkage:
2737 case GlobalValue::ExternalWeakLinkage:
2739 return Error(LinkageLoc, "invalid linkage for function definition");
2741 case GlobalValue::PrivateLinkage:
2742 case GlobalValue::LinkerPrivateLinkage:
2743 case GlobalValue::LinkerPrivateWeakLinkage:
2744 case GlobalValue::InternalLinkage:
2745 case GlobalValue::AvailableExternallyLinkage:
2746 case GlobalValue::LinkOnceAnyLinkage:
2747 case GlobalValue::LinkOnceODRLinkage:
2748 case GlobalValue::LinkOnceODRAutoHideLinkage:
2749 case GlobalValue::WeakAnyLinkage:
2750 case GlobalValue::WeakODRLinkage:
2751 case GlobalValue::DLLExportLinkage:
2753 return Error(LinkageLoc, "invalid linkage for function declaration");
2755 case GlobalValue::AppendingLinkage:
2756 case GlobalValue::CommonLinkage:
2757 return Error(LinkageLoc, "invalid function linkage type");
2760 if (!FunctionType::isValidReturnType(RetType))
2761 return Error(RetTypeLoc, "invalid function return type");
2763 LocTy NameLoc = Lex.getLoc();
2765 std::string FunctionName;
2766 if (Lex.getKind() == lltok::GlobalVar) {
2767 FunctionName = Lex.getStrVal();
2768 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2769 unsigned NameID = Lex.getUIntVal();
2771 if (NameID != NumberedVals.size())
2772 return TokError("function expected to be numbered '%" +
2773 Twine(NumberedVals.size()) + "'");
2775 return TokError("expected function name");
2780 if (Lex.getKind() != lltok::lparen)
2781 return TokError("expected '(' in function argument list");
2783 SmallVector<ArgInfo, 8> ArgList;
2785 AttrBuilder FuncAttrs;
2786 std::string Section;
2790 LocTy UnnamedAddrLoc;
2792 if (ParseArgumentList(ArgList, isVarArg) ||
2793 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2795 ParseOptionalFuncAttrs(FuncAttrs) ||
2796 (EatIfPresent(lltok::kw_section) &&
2797 ParseStringConstant(Section)) ||
2798 ParseOptionalAlignment(Alignment) ||
2799 (EatIfPresent(lltok::kw_gc) &&
2800 ParseStringConstant(GC)))
2803 // If the alignment was parsed as an attribute, move to the alignment field.
2804 if (FuncAttrs.hasAlignmentAttr()) {
2805 Alignment = FuncAttrs.getAlignment();
2806 FuncAttrs.removeAttribute(Attribute::Alignment);
2809 // Okay, if we got here, the function is syntactically valid. Convert types
2810 // and do semantic checks.
2811 std::vector<Type*> ParamTypeList;
2812 SmallVector<AttributeWithIndex, 8> Attrs;
2814 if (RetAttrs.hasAttributes())
2816 AttributeWithIndex::get(AttributeSet::ReturnIndex,
2817 Attribute::get(RetType->getContext(),
2820 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2821 ParamTypeList.push_back(ArgList[i].Ty);
2822 if (ArgList[i].Attrs.hasAttributes())
2823 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2826 if (FuncAttrs.hasAttributes())
2828 AttributeWithIndex::get(AttributeSet::FunctionIndex,
2829 Attribute::get(RetType->getContext(),
2832 AttributeSet PAL = AttributeSet::get(Context, Attrs);
2834 if (PAL.getParamAttributes(1).hasAttribute(Attribute::StructRet) &&
2835 !RetType->isVoidTy())
2836 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2839 FunctionType::get(RetType, ParamTypeList, isVarArg);
2840 PointerType *PFT = PointerType::getUnqual(FT);
2843 if (!FunctionName.empty()) {
2844 // If this was a definition of a forward reference, remove the definition
2845 // from the forward reference table and fill in the forward ref.
2846 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2847 ForwardRefVals.find(FunctionName);
2848 if (FRVI != ForwardRefVals.end()) {
2849 Fn = M->getFunction(FunctionName);
2851 return Error(FRVI->second.second, "invalid forward reference to "
2852 "function as global value!");
2853 if (Fn->getType() != PFT)
2854 return Error(FRVI->second.second, "invalid forward reference to "
2855 "function '" + FunctionName + "' with wrong type!");
2857 ForwardRefVals.erase(FRVI);
2858 } else if ((Fn = M->getFunction(FunctionName))) {
2859 // Reject redefinitions.
2860 return Error(NameLoc, "invalid redefinition of function '" +
2861 FunctionName + "'");
2862 } else if (M->getNamedValue(FunctionName)) {
2863 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2867 // If this is a definition of a forward referenced function, make sure the
2869 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2870 = ForwardRefValIDs.find(NumberedVals.size());
2871 if (I != ForwardRefValIDs.end()) {
2872 Fn = cast<Function>(I->second.first);
2873 if (Fn->getType() != PFT)
2874 return Error(NameLoc, "type of definition and forward reference of '@" +
2875 Twine(NumberedVals.size()) + "' disagree");
2876 ForwardRefValIDs.erase(I);
2881 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2882 else // Move the forward-reference to the correct spot in the module.
2883 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2885 if (FunctionName.empty())
2886 NumberedVals.push_back(Fn);
2888 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2889 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2890 Fn->setCallingConv(CC);
2891 Fn->setAttributes(PAL);
2892 Fn->setUnnamedAddr(UnnamedAddr);
2893 Fn->setAlignment(Alignment);
2894 Fn->setSection(Section);
2895 if (!GC.empty()) Fn->setGC(GC.c_str());
2897 // Add all of the arguments we parsed to the function.
2898 Function::arg_iterator ArgIt = Fn->arg_begin();
2899 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2900 // If the argument has a name, insert it into the argument symbol table.
2901 if (ArgList[i].Name.empty()) continue;
2903 // Set the name, if it conflicted, it will be auto-renamed.
2904 ArgIt->setName(ArgList[i].Name);
2906 if (ArgIt->getName() != ArgList[i].Name)
2907 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2908 ArgList[i].Name + "'");
2915 /// ParseFunctionBody
2916 /// ::= '{' BasicBlock+ '}'
2918 bool LLParser::ParseFunctionBody(Function &Fn) {
2919 if (Lex.getKind() != lltok::lbrace)
2920 return TokError("expected '{' in function body");
2921 Lex.Lex(); // eat the {.
2923 int FunctionNumber = -1;
2924 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2926 PerFunctionState PFS(*this, Fn, FunctionNumber);
2928 // We need at least one basic block.
2929 if (Lex.getKind() == lltok::rbrace)
2930 return TokError("function body requires at least one basic block");
2932 while (Lex.getKind() != lltok::rbrace)
2933 if (ParseBasicBlock(PFS)) return true;
2938 // Verify function is ok.
2939 return PFS.FinishFunction();
2943 /// ::= LabelStr? Instruction*
2944 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2945 // If this basic block starts out with a name, remember it.
2947 LocTy NameLoc = Lex.getLoc();
2948 if (Lex.getKind() == lltok::LabelStr) {
2949 Name = Lex.getStrVal();
2953 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2954 if (BB == 0) return true;
2956 std::string NameStr;
2958 // Parse the instructions in this block until we get a terminator.
2960 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2962 // This instruction may have three possibilities for a name: a) none
2963 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2964 LocTy NameLoc = Lex.getLoc();
2968 if (Lex.getKind() == lltok::LocalVarID) {
2969 NameID = Lex.getUIntVal();
2971 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2973 } else if (Lex.getKind() == lltok::LocalVar) {
2974 NameStr = Lex.getStrVal();
2976 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2980 switch (ParseInstruction(Inst, BB, PFS)) {
2981 default: llvm_unreachable("Unknown ParseInstruction result!");
2982 case InstError: return true;
2984 BB->getInstList().push_back(Inst);
2986 // With a normal result, we check to see if the instruction is followed by
2987 // a comma and metadata.
2988 if (EatIfPresent(lltok::comma))
2989 if (ParseInstructionMetadata(Inst, &PFS))
2992 case InstExtraComma:
2993 BB->getInstList().push_back(Inst);
2995 // If the instruction parser ate an extra comma at the end of it, it
2996 // *must* be followed by metadata.
2997 if (ParseInstructionMetadata(Inst, &PFS))
3002 // Set the name on the instruction.
3003 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3004 } while (!isa<TerminatorInst>(Inst));
3009 //===----------------------------------------------------------------------===//
3010 // Instruction Parsing.
3011 //===----------------------------------------------------------------------===//
3013 /// ParseInstruction - Parse one of the many different instructions.
3015 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3016 PerFunctionState &PFS) {
3017 lltok::Kind Token = Lex.getKind();
3018 if (Token == lltok::Eof)
3019 return TokError("found end of file when expecting more instructions");
3020 LocTy Loc = Lex.getLoc();
3021 unsigned KeywordVal = Lex.getUIntVal();
3022 Lex.Lex(); // Eat the keyword.
3025 default: return Error(Loc, "expected instruction opcode");
3026 // Terminator Instructions.
3027 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3028 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3029 case lltok::kw_br: return ParseBr(Inst, PFS);
3030 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3031 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3032 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3033 case lltok::kw_resume: return ParseResume(Inst, PFS);
3034 // Binary Operators.
3038 case lltok::kw_shl: {
3039 bool NUW = EatIfPresent(lltok::kw_nuw);
3040 bool NSW = EatIfPresent(lltok::kw_nsw);
3041 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3043 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3045 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3046 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3049 case lltok::kw_fadd:
3050 case lltok::kw_fsub:
3051 case lltok::kw_fmul:
3052 case lltok::kw_fdiv:
3053 case lltok::kw_frem: {
3054 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3055 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3059 Inst->setFastMathFlags(FMF);
3063 case lltok::kw_sdiv:
3064 case lltok::kw_udiv:
3065 case lltok::kw_lshr:
3066 case lltok::kw_ashr: {
3067 bool Exact = EatIfPresent(lltok::kw_exact);
3069 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3070 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3074 case lltok::kw_urem:
3075 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3078 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3079 case lltok::kw_icmp:
3080 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3082 case lltok::kw_trunc:
3083 case lltok::kw_zext:
3084 case lltok::kw_sext:
3085 case lltok::kw_fptrunc:
3086 case lltok::kw_fpext:
3087 case lltok::kw_bitcast:
3088 case lltok::kw_uitofp:
3089 case lltok::kw_sitofp:
3090 case lltok::kw_fptoui:
3091 case lltok::kw_fptosi:
3092 case lltok::kw_inttoptr:
3093 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3095 case lltok::kw_select: return ParseSelect(Inst, PFS);
3096 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3097 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3098 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3099 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3100 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3101 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3102 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3103 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3105 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3106 case lltok::kw_load: return ParseLoad(Inst, PFS);
3107 case lltok::kw_store: return ParseStore(Inst, PFS);
3108 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3109 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3110 case lltok::kw_fence: return ParseFence(Inst, PFS);
3111 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3112 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3113 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3117 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3118 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3119 if (Opc == Instruction::FCmp) {
3120 switch (Lex.getKind()) {
3121 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3122 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3123 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3124 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3125 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3126 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3127 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3128 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3129 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3130 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3131 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3132 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3133 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3134 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3135 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3136 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3137 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3140 switch (Lex.getKind()) {
3141 default: TokError("expected icmp predicate (e.g. 'eq')");
3142 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3143 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3144 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3145 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3146 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3147 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3148 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3149 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3150 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3151 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3158 //===----------------------------------------------------------------------===//
3159 // Terminator Instructions.
3160 //===----------------------------------------------------------------------===//
3162 /// ParseRet - Parse a return instruction.
3163 /// ::= 'ret' void (',' !dbg, !1)*
3164 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3165 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3166 PerFunctionState &PFS) {
3167 SMLoc TypeLoc = Lex.getLoc();
3169 if (ParseType(Ty, true /*void allowed*/)) return true;
3171 Type *ResType = PFS.getFunction().getReturnType();
3173 if (Ty->isVoidTy()) {
3174 if (!ResType->isVoidTy())
3175 return Error(TypeLoc, "value doesn't match function result type '" +
3176 getTypeString(ResType) + "'");
3178 Inst = ReturnInst::Create(Context);
3183 if (ParseValue(Ty, RV, PFS)) return true;
3185 if (ResType != RV->getType())
3186 return Error(TypeLoc, "value doesn't match function result type '" +
3187 getTypeString(ResType) + "'");
3189 Inst = ReturnInst::Create(Context, RV);
3195 /// ::= 'br' TypeAndValue
3196 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3197 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3200 BasicBlock *Op1, *Op2;
3201 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3203 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3204 Inst = BranchInst::Create(BB);
3208 if (Op0->getType() != Type::getInt1Ty(Context))
3209 return Error(Loc, "branch condition must have 'i1' type");
3211 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3212 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3213 ParseToken(lltok::comma, "expected ',' after true destination") ||
3214 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3217 Inst = BranchInst::Create(Op1, Op2, Op0);
3223 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3225 /// ::= (TypeAndValue ',' TypeAndValue)*
3226 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3227 LocTy CondLoc, BBLoc;
3229 BasicBlock *DefaultBB;
3230 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3231 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3232 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3233 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3236 if (!Cond->getType()->isIntegerTy())
3237 return Error(CondLoc, "switch condition must have integer type");
3239 // Parse the jump table pairs.
3240 SmallPtrSet<Value*, 32> SeenCases;
3241 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3242 while (Lex.getKind() != lltok::rsquare) {
3246 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3247 ParseToken(lltok::comma, "expected ',' after case value") ||
3248 ParseTypeAndBasicBlock(DestBB, PFS))
3251 if (!SeenCases.insert(Constant))
3252 return Error(CondLoc, "duplicate case value in switch");
3253 if (!isa<ConstantInt>(Constant))
3254 return Error(CondLoc, "case value is not a constant integer");
3256 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3259 Lex.Lex(); // Eat the ']'.
3261 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3262 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3263 SI->addCase(Table[i].first, Table[i].second);
3270 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3271 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3274 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3275 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3276 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3279 if (!Address->getType()->isPointerTy())
3280 return Error(AddrLoc, "indirectbr address must have pointer type");
3282 // Parse the destination list.
3283 SmallVector<BasicBlock*, 16> DestList;
3285 if (Lex.getKind() != lltok::rsquare) {
3287 if (ParseTypeAndBasicBlock(DestBB, PFS))
3289 DestList.push_back(DestBB);
3291 while (EatIfPresent(lltok::comma)) {
3292 if (ParseTypeAndBasicBlock(DestBB, PFS))
3294 DestList.push_back(DestBB);
3298 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3301 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3302 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3303 IBI->addDestination(DestList[i]);
3310 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3311 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3312 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3313 LocTy CallLoc = Lex.getLoc();
3314 AttrBuilder RetAttrs, FnAttrs;
3319 SmallVector<ParamInfo, 16> ArgList;
3321 BasicBlock *NormalBB, *UnwindBB;
3322 if (ParseOptionalCallingConv(CC) ||
3323 ParseOptionalReturnAttrs(RetAttrs) ||
3324 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3325 ParseValID(CalleeID) ||
3326 ParseParameterList(ArgList, PFS) ||
3327 ParseOptionalFuncAttrs(FnAttrs) ||
3328 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3329 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3330 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3331 ParseTypeAndBasicBlock(UnwindBB, PFS))
3334 // If RetType is a non-function pointer type, then this is the short syntax
3335 // for the call, which means that RetType is just the return type. Infer the
3336 // rest of the function argument types from the arguments that are present.
3337 PointerType *PFTy = 0;
3338 FunctionType *Ty = 0;
3339 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3340 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3341 // Pull out the types of all of the arguments...
3342 std::vector<Type*> ParamTypes;
3343 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3344 ParamTypes.push_back(ArgList[i].V->getType());
3346 if (!FunctionType::isValidReturnType(RetType))
3347 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3349 Ty = FunctionType::get(RetType, ParamTypes, false);
3350 PFTy = PointerType::getUnqual(Ty);
3353 // Look up the callee.
3355 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3357 // Set up the Attribute for the function.
3358 SmallVector<AttributeWithIndex, 8> Attrs;
3359 if (RetAttrs.hasAttributes())
3361 AttributeWithIndex::get(AttributeSet::ReturnIndex,
3362 Attribute::get(Callee->getContext(),
3365 SmallVector<Value*, 8> Args;
3367 // Loop through FunctionType's arguments and ensure they are specified
3368 // correctly. Also, gather any parameter attributes.
3369 FunctionType::param_iterator I = Ty->param_begin();
3370 FunctionType::param_iterator E = Ty->param_end();
3371 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3372 Type *ExpectedTy = 0;
3375 } else if (!Ty->isVarArg()) {
3376 return Error(ArgList[i].Loc, "too many arguments specified");
3379 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3380 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3381 getTypeString(ExpectedTy) + "'");
3382 Args.push_back(ArgList[i].V);
3383 if (ArgList[i].Attrs.hasAttributes())
3384 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3388 return Error(CallLoc, "not enough parameters specified for call");
3390 if (FnAttrs.hasAttributes())
3392 AttributeWithIndex::get(AttributeSet::FunctionIndex,
3393 Attribute::get(Callee->getContext(),
3396 // Finish off the Attribute and check them
3397 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3399 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3400 II->setCallingConv(CC);
3401 II->setAttributes(PAL);
3407 /// ::= 'resume' TypeAndValue
3408 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3409 Value *Exn; LocTy ExnLoc;
3410 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3413 ResumeInst *RI = ResumeInst::Create(Exn);
3418 //===----------------------------------------------------------------------===//
3419 // Binary Operators.
3420 //===----------------------------------------------------------------------===//
3423 /// ::= ArithmeticOps TypeAndValue ',' Value
3425 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3426 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3427 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3428 unsigned Opc, unsigned OperandType) {
3429 LocTy Loc; Value *LHS, *RHS;
3430 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3431 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3432 ParseValue(LHS->getType(), RHS, PFS))
3436 switch (OperandType) {
3437 default: llvm_unreachable("Unknown operand type!");
3438 case 0: // int or FP.
3439 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3440 LHS->getType()->isFPOrFPVectorTy();
3442 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3443 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3447 return Error(Loc, "invalid operand type for instruction");
3449 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3454 /// ::= ArithmeticOps TypeAndValue ',' Value {
3455 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3457 LocTy Loc; Value *LHS, *RHS;
3458 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3459 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3460 ParseValue(LHS->getType(), RHS, PFS))
3463 if (!LHS->getType()->isIntOrIntVectorTy())
3464 return Error(Loc,"instruction requires integer or integer vector operands");
3466 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3472 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3473 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3474 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3476 // Parse the integer/fp comparison predicate.
3480 if (ParseCmpPredicate(Pred, Opc) ||
3481 ParseTypeAndValue(LHS, Loc, PFS) ||
3482 ParseToken(lltok::comma, "expected ',' after compare value") ||
3483 ParseValue(LHS->getType(), RHS, PFS))
3486 if (Opc == Instruction::FCmp) {
3487 if (!LHS->getType()->isFPOrFPVectorTy())
3488 return Error(Loc, "fcmp requires floating point operands");
3489 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3491 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3492 if (!LHS->getType()->isIntOrIntVectorTy() &&
3493 !LHS->getType()->getScalarType()->isPointerTy())
3494 return Error(Loc, "icmp requires integer operands");
3495 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3500 //===----------------------------------------------------------------------===//
3501 // Other Instructions.
3502 //===----------------------------------------------------------------------===//
3506 /// ::= CastOpc TypeAndValue 'to' Type
3507 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3512 if (ParseTypeAndValue(Op, Loc, PFS) ||
3513 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3517 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3518 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3519 return Error(Loc, "invalid cast opcode for cast from '" +
3520 getTypeString(Op->getType()) + "' to '" +
3521 getTypeString(DestTy) + "'");
3523 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3528 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3529 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3531 Value *Op0, *Op1, *Op2;
3532 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3533 ParseToken(lltok::comma, "expected ',' after select condition") ||
3534 ParseTypeAndValue(Op1, PFS) ||
3535 ParseToken(lltok::comma, "expected ',' after select value") ||
3536 ParseTypeAndValue(Op2, PFS))
3539 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3540 return Error(Loc, Reason);
3542 Inst = SelectInst::Create(Op0, Op1, Op2);
3547 /// ::= 'va_arg' TypeAndValue ',' Type
3548 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3552 if (ParseTypeAndValue(Op, PFS) ||
3553 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3554 ParseType(EltTy, TypeLoc))
3557 if (!EltTy->isFirstClassType())
3558 return Error(TypeLoc, "va_arg requires operand with first class type");
3560 Inst = new VAArgInst(Op, EltTy);
3564 /// ParseExtractElement
3565 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3566 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3569 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3570 ParseToken(lltok::comma, "expected ',' after extract value") ||
3571 ParseTypeAndValue(Op1, PFS))
3574 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3575 return Error(Loc, "invalid extractelement operands");
3577 Inst = ExtractElementInst::Create(Op0, Op1);
3581 /// ParseInsertElement
3582 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3583 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3585 Value *Op0, *Op1, *Op2;
3586 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3587 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3588 ParseTypeAndValue(Op1, PFS) ||
3589 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3590 ParseTypeAndValue(Op2, PFS))
3593 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3594 return Error(Loc, "invalid insertelement operands");
3596 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3600 /// ParseShuffleVector
3601 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3602 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3604 Value *Op0, *Op1, *Op2;
3605 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3606 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3607 ParseTypeAndValue(Op1, PFS) ||
3608 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3609 ParseTypeAndValue(Op2, PFS))
3612 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3613 return Error(Loc, "invalid shufflevector operands");
3615 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3620 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3621 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3622 Type *Ty = 0; LocTy TypeLoc;
3625 if (ParseType(Ty, TypeLoc) ||
3626 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3627 ParseValue(Ty, Op0, PFS) ||
3628 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3629 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3630 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3633 bool AteExtraComma = false;
3634 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3636 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3638 if (!EatIfPresent(lltok::comma))
3641 if (Lex.getKind() == lltok::MetadataVar) {
3642 AteExtraComma = true;
3646 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3647 ParseValue(Ty, Op0, PFS) ||
3648 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3649 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3650 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3654 if (!Ty->isFirstClassType())
3655 return Error(TypeLoc, "phi node must have first class type");
3657 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3658 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3659 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3661 return AteExtraComma ? InstExtraComma : InstNormal;
3665 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3667 /// ::= 'catch' TypeAndValue
3669 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3670 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3671 Type *Ty = 0; LocTy TyLoc;
3672 Value *PersFn; LocTy PersFnLoc;
3674 if (ParseType(Ty, TyLoc) ||
3675 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3676 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3679 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3680 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3682 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3683 LandingPadInst::ClauseType CT;
3684 if (EatIfPresent(lltok::kw_catch))
3685 CT = LandingPadInst::Catch;
3686 else if (EatIfPresent(lltok::kw_filter))
3687 CT = LandingPadInst::Filter;
3689 return TokError("expected 'catch' or 'filter' clause type");
3691 Value *V; LocTy VLoc;
3692 if (ParseTypeAndValue(V, VLoc, PFS)) {
3697 // A 'catch' type expects a non-array constant. A filter clause expects an
3699 if (CT == LandingPadInst::Catch) {
3700 if (isa<ArrayType>(V->getType()))
3701 Error(VLoc, "'catch' clause has an invalid type");
3703 if (!isa<ArrayType>(V->getType()))
3704 Error(VLoc, "'filter' clause has an invalid type");
3715 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3716 /// ParameterList OptionalAttrs
3717 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3719 AttrBuilder RetAttrs, FnAttrs;
3724 SmallVector<ParamInfo, 16> ArgList;
3725 LocTy CallLoc = Lex.getLoc();
3727 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3728 ParseOptionalCallingConv(CC) ||
3729 ParseOptionalReturnAttrs(RetAttrs) ||
3730 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3731 ParseValID(CalleeID) ||
3732 ParseParameterList(ArgList, PFS) ||
3733 ParseOptionalFuncAttrs(FnAttrs))
3736 // If RetType is a non-function pointer type, then this is the short syntax
3737 // for the call, which means that RetType is just the return type. Infer the
3738 // rest of the function argument types from the arguments that are present.
3739 PointerType *PFTy = 0;
3740 FunctionType *Ty = 0;
3741 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3742 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3743 // Pull out the types of all of the arguments...
3744 std::vector<Type*> ParamTypes;
3745 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3746 ParamTypes.push_back(ArgList[i].V->getType());
3748 if (!FunctionType::isValidReturnType(RetType))
3749 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3751 Ty = FunctionType::get(RetType, ParamTypes, false);
3752 PFTy = PointerType::getUnqual(Ty);
3755 // Look up the callee.
3757 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3759 // Set up the Attribute for the function.
3760 SmallVector<AttributeWithIndex, 8> Attrs;
3761 if (RetAttrs.hasAttributes())
3763 AttributeWithIndex::get(AttributeSet::ReturnIndex,
3764 Attribute::get(Callee->getContext(),
3767 SmallVector<Value*, 8> Args;
3769 // Loop through FunctionType's arguments and ensure they are specified
3770 // correctly. Also, gather any parameter attributes.
3771 FunctionType::param_iterator I = Ty->param_begin();
3772 FunctionType::param_iterator E = Ty->param_end();
3773 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3774 Type *ExpectedTy = 0;
3777 } else if (!Ty->isVarArg()) {
3778 return Error(ArgList[i].Loc, "too many arguments specified");
3781 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3782 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3783 getTypeString(ExpectedTy) + "'");
3784 Args.push_back(ArgList[i].V);
3785 if (ArgList[i].Attrs.hasAttributes())
3786 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3790 return Error(CallLoc, "not enough parameters specified for call");
3792 if (FnAttrs.hasAttributes())
3794 AttributeWithIndex::get(AttributeSet::FunctionIndex,
3795 Attribute::get(Callee->getContext(),
3798 // Finish off the Attribute and check them
3799 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3801 CallInst *CI = CallInst::Create(Callee, Args);
3802 CI->setTailCall(isTail);
3803 CI->setCallingConv(CC);
3804 CI->setAttributes(PAL);
3809 //===----------------------------------------------------------------------===//
3810 // Memory Instructions.
3811 //===----------------------------------------------------------------------===//
3814 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3815 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3818 unsigned Alignment = 0;
3820 if (ParseType(Ty)) return true;
3822 bool AteExtraComma = false;
3823 if (EatIfPresent(lltok::comma)) {
3824 if (Lex.getKind() == lltok::kw_align) {
3825 if (ParseOptionalAlignment(Alignment)) return true;
3826 } else if (Lex.getKind() == lltok::MetadataVar) {
3827 AteExtraComma = true;
3829 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3830 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3835 if (Size && !Size->getType()->isIntegerTy())
3836 return Error(SizeLoc, "element count must have integer type");
3838 Inst = new AllocaInst(Ty, Size, Alignment);
3839 return AteExtraComma ? InstExtraComma : InstNormal;
3843 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3844 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3845 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3846 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3847 Value *Val; LocTy Loc;
3848 unsigned Alignment = 0;
3849 bool AteExtraComma = false;
3850 bool isAtomic = false;
3851 AtomicOrdering Ordering = NotAtomic;
3852 SynchronizationScope Scope = CrossThread;
3854 if (Lex.getKind() == lltok::kw_atomic) {
3859 bool isVolatile = false;
3860 if (Lex.getKind() == lltok::kw_volatile) {
3865 if (ParseTypeAndValue(Val, Loc, PFS) ||
3866 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3867 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3870 if (!Val->getType()->isPointerTy() ||
3871 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3872 return Error(Loc, "load operand must be a pointer to a first class type");
3873 if (isAtomic && !Alignment)
3874 return Error(Loc, "atomic load must have explicit non-zero alignment");
3875 if (Ordering == Release || Ordering == AcquireRelease)
3876 return Error(Loc, "atomic load cannot use Release ordering");
3878 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3879 return AteExtraComma ? InstExtraComma : InstNormal;
3884 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3885 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3886 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3887 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3888 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3889 unsigned Alignment = 0;
3890 bool AteExtraComma = false;
3891 bool isAtomic = false;
3892 AtomicOrdering Ordering = NotAtomic;
3893 SynchronizationScope Scope = CrossThread;
3895 if (Lex.getKind() == lltok::kw_atomic) {
3900 bool isVolatile = false;
3901 if (Lex.getKind() == lltok::kw_volatile) {
3906 if (ParseTypeAndValue(Val, Loc, PFS) ||
3907 ParseToken(lltok::comma, "expected ',' after store operand") ||
3908 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3909 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3910 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3913 if (!Ptr->getType()->isPointerTy())
3914 return Error(PtrLoc, "store operand must be a pointer");
3915 if (!Val->getType()->isFirstClassType())
3916 return Error(Loc, "store operand must be a first class value");
3917 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3918 return Error(Loc, "stored value and pointer type do not match");
3919 if (isAtomic && !Alignment)
3920 return Error(Loc, "atomic store must have explicit non-zero alignment");
3921 if (Ordering == Acquire || Ordering == AcquireRelease)
3922 return Error(Loc, "atomic store cannot use Acquire ordering");
3924 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3925 return AteExtraComma ? InstExtraComma : InstNormal;
3929 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3930 /// 'singlethread'? AtomicOrdering
3931 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3932 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3933 bool AteExtraComma = false;
3934 AtomicOrdering Ordering = NotAtomic;
3935 SynchronizationScope Scope = CrossThread;
3936 bool isVolatile = false;
3938 if (EatIfPresent(lltok::kw_volatile))
3941 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3942 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3943 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3944 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3945 ParseTypeAndValue(New, NewLoc, PFS) ||
3946 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3949 if (Ordering == Unordered)
3950 return TokError("cmpxchg cannot be unordered");
3951 if (!Ptr->getType()->isPointerTy())
3952 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3953 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3954 return Error(CmpLoc, "compare value and pointer type do not match");
3955 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3956 return Error(NewLoc, "new value and pointer type do not match");
3957 if (!New->getType()->isIntegerTy())
3958 return Error(NewLoc, "cmpxchg operand must be an integer");
3959 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3960 if (Size < 8 || (Size & (Size - 1)))
3961 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3964 AtomicCmpXchgInst *CXI =
3965 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3966 CXI->setVolatile(isVolatile);
3968 return AteExtraComma ? InstExtraComma : InstNormal;
3972 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3973 /// 'singlethread'? AtomicOrdering
3974 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3975 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3976 bool AteExtraComma = false;
3977 AtomicOrdering Ordering = NotAtomic;
3978 SynchronizationScope Scope = CrossThread;
3979 bool isVolatile = false;
3980 AtomicRMWInst::BinOp Operation;
3982 if (EatIfPresent(lltok::kw_volatile))
3985 switch (Lex.getKind()) {
3986 default: return TokError("expected binary operation in atomicrmw");
3987 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3988 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3989 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3990 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3991 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3992 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3993 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3994 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3995 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3996 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3997 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3999 Lex.Lex(); // Eat the operation.
4001 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4002 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4003 ParseTypeAndValue(Val, ValLoc, PFS) ||
4004 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4007 if (Ordering == Unordered)
4008 return TokError("atomicrmw cannot be unordered");
4009 if (!Ptr->getType()->isPointerTy())
4010 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4011 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4012 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4013 if (!Val->getType()->isIntegerTy())
4014 return Error(ValLoc, "atomicrmw operand must be an integer");
4015 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4016 if (Size < 8 || (Size & (Size - 1)))
4017 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4020 AtomicRMWInst *RMWI =
4021 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4022 RMWI->setVolatile(isVolatile);
4024 return AteExtraComma ? InstExtraComma : InstNormal;
4028 /// ::= 'fence' 'singlethread'? AtomicOrdering
4029 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4030 AtomicOrdering Ordering = NotAtomic;
4031 SynchronizationScope Scope = CrossThread;
4032 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4035 if (Ordering == Unordered)
4036 return TokError("fence cannot be unordered");
4037 if (Ordering == Monotonic)
4038 return TokError("fence cannot be monotonic");
4040 Inst = new FenceInst(Context, Ordering, Scope);
4044 /// ParseGetElementPtr
4045 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4046 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4051 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4053 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4055 if (!Ptr->getType()->getScalarType()->isPointerTy())
4056 return Error(Loc, "base of getelementptr must be a pointer");
4058 SmallVector<Value*, 16> Indices;
4059 bool AteExtraComma = false;
4060 while (EatIfPresent(lltok::comma)) {
4061 if (Lex.getKind() == lltok::MetadataVar) {
4062 AteExtraComma = true;
4065 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4066 if (!Val->getType()->getScalarType()->isIntegerTy())
4067 return Error(EltLoc, "getelementptr index must be an integer");
4068 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4069 return Error(EltLoc, "getelementptr index type missmatch");
4070 if (Val->getType()->isVectorTy()) {
4071 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4072 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4073 if (ValNumEl != PtrNumEl)
4074 return Error(EltLoc,
4075 "getelementptr vector index has a wrong number of elements");
4077 Indices.push_back(Val);
4080 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4081 return Error(Loc, "invalid getelementptr indices");
4082 Inst = GetElementPtrInst::Create(Ptr, Indices);
4084 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4085 return AteExtraComma ? InstExtraComma : InstNormal;
4088 /// ParseExtractValue
4089 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4090 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4091 Value *Val; LocTy Loc;
4092 SmallVector<unsigned, 4> Indices;
4094 if (ParseTypeAndValue(Val, Loc, PFS) ||
4095 ParseIndexList(Indices, AteExtraComma))
4098 if (!Val->getType()->isAggregateType())
4099 return Error(Loc, "extractvalue operand must be aggregate type");
4101 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4102 return Error(Loc, "invalid indices for extractvalue");
4103 Inst = ExtractValueInst::Create(Val, Indices);
4104 return AteExtraComma ? InstExtraComma : InstNormal;
4107 /// ParseInsertValue
4108 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4109 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4110 Value *Val0, *Val1; LocTy Loc0, Loc1;
4111 SmallVector<unsigned, 4> Indices;
4113 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4114 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4115 ParseTypeAndValue(Val1, Loc1, PFS) ||
4116 ParseIndexList(Indices, AteExtraComma))
4119 if (!Val0->getType()->isAggregateType())
4120 return Error(Loc0, "insertvalue operand must be aggregate type");
4122 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4123 return Error(Loc0, "invalid indices for insertvalue");
4124 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4125 return AteExtraComma ? InstExtraComma : InstNormal;
4128 //===----------------------------------------------------------------------===//
4129 // Embedded metadata.
4130 //===----------------------------------------------------------------------===//
4132 /// ParseMDNodeVector
4133 /// ::= Element (',' Element)*
4135 /// ::= 'null' | TypeAndValue
4136 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4137 PerFunctionState *PFS) {
4138 // Check for an empty list.
4139 if (Lex.getKind() == lltok::rbrace)
4143 // Null is a special case since it is typeless.
4144 if (EatIfPresent(lltok::kw_null)) {
4150 if (ParseTypeAndValue(V, PFS)) return true;
4152 } while (EatIfPresent(lltok::comma));