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/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/ValueSymbolTable.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
187 case lltok::kw_linker_private_weak_def_auto: // 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
636 /// OptionalExternallyInitialized GlobalType Type Const
637 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
638 /// OptionalAddrSpace OptionalUnNammedAddr
639 /// OptionalExternallyInitialized GlobalType Type Const
641 /// Everything through visibility has been parsed already.
643 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
644 unsigned Linkage, bool HasLinkage,
645 unsigned Visibility) {
647 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
648 GlobalVariable::ThreadLocalMode TLM;
649 LocTy UnnamedAddrLoc;
650 LocTy IsExternallyInitializedLoc;
654 if (ParseOptionalThreadLocal(TLM) ||
655 ParseOptionalAddrSpace(AddrSpace) ||
656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
658 ParseOptionalToken(lltok::kw_externally_initialized,
659 IsExternallyInitialized,
660 &IsExternallyInitializedLoc) ||
661 ParseGlobalType(IsConstant) ||
662 ParseType(Ty, TyLoc))
665 // If the linkage is specified and is external, then no initializer is
668 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
669 Linkage != GlobalValue::ExternalWeakLinkage &&
670 Linkage != GlobalValue::ExternalLinkage)) {
671 if (ParseGlobalValue(Ty, Init))
675 if (Ty->isFunctionTy() || Ty->isLabelTy())
676 return Error(TyLoc, "invalid type for global variable");
678 GlobalVariable *GV = 0;
680 // See if the global was forward referenced, if so, use the global.
682 if (GlobalValue *GVal = M->getNamedValue(Name)) {
683 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
684 return Error(NameLoc, "redefinition of global '@" + Name + "'");
685 GV = cast<GlobalVariable>(GVal);
688 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
689 I = ForwardRefValIDs.find(NumberedVals.size());
690 if (I != ForwardRefValIDs.end()) {
691 GV = cast<GlobalVariable>(I->second.first);
692 ForwardRefValIDs.erase(I);
697 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
698 Name, 0, GlobalVariable::NotThreadLocal,
701 if (GV->getType()->getElementType() != Ty)
703 "forward reference and definition of global have different types");
705 // Move the forward-reference to the correct spot in the module.
706 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
710 NumberedVals.push_back(GV);
712 // Set the parsed properties on the global.
714 GV->setInitializer(Init);
715 GV->setConstant(IsConstant);
716 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
717 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
718 GV->setExternallyInitialized(IsExternallyInitialized);
719 GV->setThreadLocalMode(TLM);
720 GV->setUnnamedAddr(UnnamedAddr);
722 // Parse attributes on the global.
723 while (Lex.getKind() == lltok::comma) {
726 if (Lex.getKind() == lltok::kw_section) {
728 GV->setSection(Lex.getStrVal());
729 if (ParseToken(lltok::StringConstant, "expected global section string"))
731 } else if (Lex.getKind() == lltok::kw_align) {
733 if (ParseOptionalAlignment(Alignment)) return true;
734 GV->setAlignment(Alignment);
736 TokError("unknown global variable property!");
744 //===----------------------------------------------------------------------===//
745 // GlobalValue Reference/Resolution Routines.
746 //===----------------------------------------------------------------------===//
748 /// GetGlobalVal - Get a value with the specified name or ID, creating a
749 /// forward reference record if needed. This can return null if the value
750 /// exists but does not have the right type.
751 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
753 PointerType *PTy = dyn_cast<PointerType>(Ty);
755 Error(Loc, "global variable reference must have pointer type");
759 // Look this name up in the normal function symbol table.
761 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
763 // If this is a forward reference for the value, see if we already created a
764 // forward ref record.
766 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
767 I = ForwardRefVals.find(Name);
768 if (I != ForwardRefVals.end())
769 Val = I->second.first;
772 // If we have the value in the symbol table or fwd-ref table, return it.
774 if (Val->getType() == Ty) return Val;
775 Error(Loc, "'@" + Name + "' defined with type '" +
776 getTypeString(Val->getType()) + "'");
780 // Otherwise, create a new forward reference for this value and remember it.
782 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
783 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
785 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
786 GlobalValue::ExternalWeakLinkage, 0, Name,
787 0, GlobalVariable::NotThreadLocal,
788 PTy->getAddressSpace());
790 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
794 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
795 PointerType *PTy = dyn_cast<PointerType>(Ty);
797 Error(Loc, "global variable reference must have pointer type");
801 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
803 // If this is a forward reference for the value, see if we already created a
804 // forward ref record.
806 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
807 I = ForwardRefValIDs.find(ID);
808 if (I != ForwardRefValIDs.end())
809 Val = I->second.first;
812 // If we have the value in the symbol table or fwd-ref table, return it.
814 if (Val->getType() == Ty) return Val;
815 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
816 getTypeString(Val->getType()) + "'");
820 // Otherwise, create a new forward reference for this value and remember it.
822 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
823 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
825 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
826 GlobalValue::ExternalWeakLinkage, 0, "");
828 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
833 //===----------------------------------------------------------------------===//
835 //===----------------------------------------------------------------------===//
837 /// ParseToken - If the current token has the specified kind, eat it and return
838 /// success. Otherwise, emit the specified error and return failure.
839 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
840 if (Lex.getKind() != T)
841 return TokError(ErrMsg);
846 /// ParseStringConstant
847 /// ::= StringConstant
848 bool LLParser::ParseStringConstant(std::string &Result) {
849 if (Lex.getKind() != lltok::StringConstant)
850 return TokError("expected string constant");
851 Result = Lex.getStrVal();
858 bool LLParser::ParseUInt32(unsigned &Val) {
859 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
860 return TokError("expected integer");
861 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
862 if (Val64 != unsigned(Val64))
863 return TokError("expected 32-bit integer (too large)");
870 /// := 'localdynamic'
873 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
874 switch (Lex.getKind()) {
876 return TokError("expected localdynamic, initialexec or localexec");
877 case lltok::kw_localdynamic:
878 TLM = GlobalVariable::LocalDynamicTLSModel;
880 case lltok::kw_initialexec:
881 TLM = GlobalVariable::InitialExecTLSModel;
883 case lltok::kw_localexec:
884 TLM = GlobalVariable::LocalExecTLSModel;
892 /// ParseOptionalThreadLocal
894 /// := 'thread_local'
895 /// := 'thread_local' '(' tlsmodel ')'
896 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
897 TLM = GlobalVariable::NotThreadLocal;
898 if (!EatIfPresent(lltok::kw_thread_local))
901 TLM = GlobalVariable::GeneralDynamicTLSModel;
902 if (Lex.getKind() == lltok::lparen) {
904 return ParseTLSModel(TLM) ||
905 ParseToken(lltok::rparen, "expected ')' after thread local model");
910 /// ParseOptionalAddrSpace
912 /// := 'addrspace' '(' uint32 ')'
913 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
915 if (!EatIfPresent(lltok::kw_addrspace))
917 return ParseToken(lltok::lparen, "expected '(' in address space") ||
918 ParseUInt32(AddrSpace) ||
919 ParseToken(lltok::rparen, "expected ')' in address space");
922 /// ParseOptionalFuncAttrs - Parse a potentially empty list of function attributes.
923 bool LLParser::ParseOptionalFuncAttrs(AttrBuilder &B) {
924 bool HaveError = false;
929 lltok::Kind Token = Lex.getKind();
931 default: // End of attributes.
933 case lltok::kw_alignstack: {
935 if (ParseOptionalStackAlignment(Alignment))
937 B.addStackAlignmentAttr(Alignment);
940 case lltok::kw_align: {
941 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
944 if (ParseOptionalAlignment(Alignment))
946 B.addAlignmentAttr(Alignment);
949 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
950 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
951 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
952 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
953 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
954 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
955 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
956 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
957 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
958 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
959 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
960 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
961 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
962 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
963 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
964 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
965 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
966 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
967 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
968 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
971 case lltok::kw_zeroext:
972 case lltok::kw_signext:
973 case lltok::kw_inreg:
974 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on a function");
976 case lltok::kw_sret: case lltok::kw_noalias:
977 case lltok::kw_nocapture: case lltok::kw_byval:
980 Error(Lex.getLoc(), "invalid use of parameter-only attribute on a function");
988 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
989 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
990 bool HaveError = false;
995 lltok::Kind Token = Lex.getKind();
997 default: // End of attributes.
999 case lltok::kw_align: {
1001 if (ParseOptionalAlignment(Alignment))
1003 B.addAlignmentAttr(Alignment);
1006 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1007 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1008 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1009 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1010 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1011 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1012 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1013 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1015 case lltok::kw_noreturn: case lltok::kw_nounwind:
1016 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1017 case lltok::kw_noinline: case lltok::kw_readnone:
1018 case lltok::kw_readonly: case lltok::kw_inlinehint:
1019 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1020 case lltok::kw_ssp: case lltok::kw_sspreq:
1021 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1022 case lltok::kw_naked: case lltok::kw_nonlazybind:
1023 case lltok::kw_address_safety: case lltok::kw_minsize:
1024 case lltok::kw_alignstack:
1025 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1033 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1034 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1035 bool HaveError = false;
1040 lltok::Kind Token = Lex.getKind();
1042 default: // End of attributes.
1044 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1045 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1046 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1047 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1050 case lltok::kw_sret: case lltok::kw_nocapture:
1051 case lltok::kw_byval: case lltok::kw_nest:
1052 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1055 case lltok::kw_noreturn: case lltok::kw_nounwind:
1056 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1057 case lltok::kw_noinline: case lltok::kw_readnone:
1058 case lltok::kw_readonly: case lltok::kw_inlinehint:
1059 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1060 case lltok::kw_ssp: case lltok::kw_sspreq:
1061 case lltok::kw_sspstrong: case lltok::kw_noimplicitfloat:
1062 case lltok::kw_noredzone: case lltok::kw_naked:
1063 case lltok::kw_nonlazybind: case lltok::kw_address_safety:
1064 case lltok::kw_minsize: case lltok::kw_alignstack:
1065 case lltok::kw_align: case lltok::kw_noduplicate:
1066 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1074 /// ParseOptionalLinkage
1077 /// ::= 'linker_private'
1078 /// ::= 'linker_private_weak'
1083 /// ::= 'linkonce_odr'
1084 /// ::= 'linkonce_odr_auto_hide'
1085 /// ::= 'available_externally'
1090 /// ::= 'extern_weak'
1092 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1094 switch (Lex.getKind()) {
1095 default: Res=GlobalValue::ExternalLinkage; return false;
1096 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1097 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1098 case lltok::kw_linker_private_weak:
1099 Res = GlobalValue::LinkerPrivateWeakLinkage;
1101 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1102 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1103 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1104 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1105 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1106 case lltok::kw_linkonce_odr_auto_hide:
1107 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1108 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1110 case lltok::kw_available_externally:
1111 Res = GlobalValue::AvailableExternallyLinkage;
1113 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1114 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1115 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1116 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1117 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1118 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1125 /// ParseOptionalVisibility
1131 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1132 switch (Lex.getKind()) {
1133 default: Res = GlobalValue::DefaultVisibility; return false;
1134 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1135 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1136 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1142 /// ParseOptionalCallingConv
1146 /// ::= 'kw_intel_ocl_bicc'
1148 /// ::= 'x86_stdcallcc'
1149 /// ::= 'x86_fastcallcc'
1150 /// ::= 'x86_thiscallcc'
1151 /// ::= 'arm_apcscc'
1152 /// ::= 'arm_aapcscc'
1153 /// ::= 'arm_aapcs_vfpcc'
1154 /// ::= 'msp430_intrcc'
1155 /// ::= 'ptx_kernel'
1156 /// ::= 'ptx_device'
1158 /// ::= 'spir_kernel'
1161 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1162 switch (Lex.getKind()) {
1163 default: CC = CallingConv::C; return false;
1164 case lltok::kw_ccc: CC = CallingConv::C; break;
1165 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1166 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1167 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1168 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1169 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1170 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1171 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1172 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1173 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1174 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1175 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1176 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1177 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1178 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1179 case lltok::kw_cc: {
1180 unsigned ArbitraryCC;
1182 if (ParseUInt32(ArbitraryCC))
1184 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1193 /// ParseInstructionMetadata
1194 /// ::= !dbg !42 (',' !dbg !57)*
1195 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1196 PerFunctionState *PFS) {
1198 if (Lex.getKind() != lltok::MetadataVar)
1199 return TokError("expected metadata after comma");
1201 std::string Name = Lex.getStrVal();
1202 unsigned MDK = M->getMDKindID(Name);
1206 SMLoc Loc = Lex.getLoc();
1208 if (ParseToken(lltok::exclaim, "expected '!' here"))
1211 // This code is similar to that of ParseMetadataValue, however it needs to
1212 // have special-case code for a forward reference; see the comments on
1213 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1214 // at the top level here.
1215 if (Lex.getKind() == lltok::lbrace) {
1217 if (ParseMetadataListValue(ID, PFS))
1219 assert(ID.Kind == ValID::t_MDNode);
1220 Inst->setMetadata(MDK, ID.MDNodeVal);
1222 unsigned NodeID = 0;
1223 if (ParseMDNodeID(Node, NodeID))
1226 // If we got the node, add it to the instruction.
1227 Inst->setMetadata(MDK, Node);
1229 MDRef R = { Loc, MDK, NodeID };
1230 // Otherwise, remember that this should be resolved later.
1231 ForwardRefInstMetadata[Inst].push_back(R);
1235 // If this is the end of the list, we're done.
1236 } while (EatIfPresent(lltok::comma));
1240 /// ParseOptionalAlignment
1243 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1245 if (!EatIfPresent(lltok::kw_align))
1247 LocTy AlignLoc = Lex.getLoc();
1248 if (ParseUInt32(Alignment)) return true;
1249 if (!isPowerOf2_32(Alignment))
1250 return Error(AlignLoc, "alignment is not a power of two");
1251 if (Alignment > Value::MaximumAlignment)
1252 return Error(AlignLoc, "huge alignments are not supported yet");
1256 /// ParseOptionalCommaAlign
1260 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1262 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1263 bool &AteExtraComma) {
1264 AteExtraComma = false;
1265 while (EatIfPresent(lltok::comma)) {
1266 // Metadata at the end is an early exit.
1267 if (Lex.getKind() == lltok::MetadataVar) {
1268 AteExtraComma = true;
1272 if (Lex.getKind() != lltok::kw_align)
1273 return Error(Lex.getLoc(), "expected metadata or 'align'");
1275 if (ParseOptionalAlignment(Alignment)) return true;
1281 /// ParseScopeAndOrdering
1282 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1285 /// This sets Scope and Ordering to the parsed values.
1286 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1287 AtomicOrdering &Ordering) {
1291 Scope = CrossThread;
1292 if (EatIfPresent(lltok::kw_singlethread))
1293 Scope = SingleThread;
1294 switch (Lex.getKind()) {
1295 default: return TokError("Expected ordering on atomic instruction");
1296 case lltok::kw_unordered: Ordering = Unordered; break;
1297 case lltok::kw_monotonic: Ordering = Monotonic; break;
1298 case lltok::kw_acquire: Ordering = Acquire; break;
1299 case lltok::kw_release: Ordering = Release; break;
1300 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1301 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1307 /// ParseOptionalStackAlignment
1309 /// ::= 'alignstack' '(' 4 ')'
1310 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1312 if (!EatIfPresent(lltok::kw_alignstack))
1314 LocTy ParenLoc = Lex.getLoc();
1315 if (!EatIfPresent(lltok::lparen))
1316 return Error(ParenLoc, "expected '('");
1317 LocTy AlignLoc = Lex.getLoc();
1318 if (ParseUInt32(Alignment)) return true;
1319 ParenLoc = Lex.getLoc();
1320 if (!EatIfPresent(lltok::rparen))
1321 return Error(ParenLoc, "expected ')'");
1322 if (!isPowerOf2_32(Alignment))
1323 return Error(AlignLoc, "stack alignment is not a power of two");
1327 /// ParseIndexList - This parses the index list for an insert/extractvalue
1328 /// instruction. This sets AteExtraComma in the case where we eat an extra
1329 /// comma at the end of the line and find that it is followed by metadata.
1330 /// Clients that don't allow metadata can call the version of this function that
1331 /// only takes one argument.
1334 /// ::= (',' uint32)+
1336 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1337 bool &AteExtraComma) {
1338 AteExtraComma = false;
1340 if (Lex.getKind() != lltok::comma)
1341 return TokError("expected ',' as start of index list");
1343 while (EatIfPresent(lltok::comma)) {
1344 if (Lex.getKind() == lltok::MetadataVar) {
1345 AteExtraComma = true;
1349 if (ParseUInt32(Idx)) return true;
1350 Indices.push_back(Idx);
1356 //===----------------------------------------------------------------------===//
1358 //===----------------------------------------------------------------------===//
1360 /// ParseType - Parse a type.
1361 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1362 SMLoc TypeLoc = Lex.getLoc();
1363 switch (Lex.getKind()) {
1365 return TokError("expected type");
1367 // Type ::= 'float' | 'void' (etc)
1368 Result = Lex.getTyVal();
1372 // Type ::= StructType
1373 if (ParseAnonStructType(Result, false))
1376 case lltok::lsquare:
1377 // Type ::= '[' ... ']'
1378 Lex.Lex(); // eat the lsquare.
1379 if (ParseArrayVectorType(Result, false))
1382 case lltok::less: // Either vector or packed struct.
1383 // Type ::= '<' ... '>'
1385 if (Lex.getKind() == lltok::lbrace) {
1386 if (ParseAnonStructType(Result, true) ||
1387 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1389 } else if (ParseArrayVectorType(Result, true))
1392 case lltok::LocalVar: {
1394 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1396 // If the type hasn't been defined yet, create a forward definition and
1397 // remember where that forward def'n was seen (in case it never is defined).
1398 if (Entry.first == 0) {
1399 Entry.first = StructType::create(Context, Lex.getStrVal());
1400 Entry.second = Lex.getLoc();
1402 Result = Entry.first;
1407 case lltok::LocalVarID: {
1409 if (Lex.getUIntVal() >= NumberedTypes.size())
1410 NumberedTypes.resize(Lex.getUIntVal()+1);
1411 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1413 // If the type hasn't been defined yet, create a forward definition and
1414 // remember where that forward def'n was seen (in case it never is defined).
1415 if (Entry.first == 0) {
1416 Entry.first = StructType::create(Context);
1417 Entry.second = Lex.getLoc();
1419 Result = Entry.first;
1425 // Parse the type suffixes.
1427 switch (Lex.getKind()) {
1430 if (!AllowVoid && Result->isVoidTy())
1431 return Error(TypeLoc, "void type only allowed for function results");
1434 // Type ::= Type '*'
1436 if (Result->isLabelTy())
1437 return TokError("basic block pointers are invalid");
1438 if (Result->isVoidTy())
1439 return TokError("pointers to void are invalid - use i8* instead");
1440 if (!PointerType::isValidElementType(Result))
1441 return TokError("pointer to this type is invalid");
1442 Result = PointerType::getUnqual(Result);
1446 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1447 case lltok::kw_addrspace: {
1448 if (Result->isLabelTy())
1449 return TokError("basic block pointers are invalid");
1450 if (Result->isVoidTy())
1451 return TokError("pointers to void are invalid; use i8* instead");
1452 if (!PointerType::isValidElementType(Result))
1453 return TokError("pointer to this type is invalid");
1455 if (ParseOptionalAddrSpace(AddrSpace) ||
1456 ParseToken(lltok::star, "expected '*' in address space"))
1459 Result = PointerType::get(Result, AddrSpace);
1463 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1465 if (ParseFunctionType(Result))
1472 /// ParseParameterList
1474 /// ::= '(' Arg (',' Arg)* ')'
1476 /// ::= Type OptionalAttributes Value OptionalAttributes
1477 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1478 PerFunctionState &PFS) {
1479 if (ParseToken(lltok::lparen, "expected '(' in call"))
1482 unsigned AttrIndex = 1;
1483 while (Lex.getKind() != lltok::rparen) {
1484 // If this isn't the first argument, we need a comma.
1485 if (!ArgList.empty() &&
1486 ParseToken(lltok::comma, "expected ',' in argument list"))
1489 // Parse the argument.
1492 AttrBuilder ArgAttrs;
1494 if (ParseType(ArgTy, ArgLoc))
1497 // Otherwise, handle normal operands.
1498 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1500 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1505 Lex.Lex(); // Lex the ')'.
1511 /// ParseArgumentList - Parse the argument list for a function type or function
1513 /// ::= '(' ArgTypeListI ')'
1517 /// ::= ArgTypeList ',' '...'
1518 /// ::= ArgType (',' ArgType)*
1520 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1523 assert(Lex.getKind() == lltok::lparen);
1524 Lex.Lex(); // eat the (.
1526 if (Lex.getKind() == lltok::rparen) {
1528 } else if (Lex.getKind() == lltok::dotdotdot) {
1532 LocTy TypeLoc = Lex.getLoc();
1537 if (ParseType(ArgTy) ||
1538 ParseOptionalParamAttrs(Attrs)) return true;
1540 if (ArgTy->isVoidTy())
1541 return Error(TypeLoc, "argument can not have void type");
1543 if (Lex.getKind() == lltok::LocalVar) {
1544 Name = Lex.getStrVal();
1548 if (!FunctionType::isValidArgumentType(ArgTy))
1549 return Error(TypeLoc, "invalid type for function argument");
1551 unsigned AttrIndex = 1;
1552 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1553 AttributeSet::get(ArgTy->getContext(),
1554 AttrIndex++, Attrs), Name));
1556 while (EatIfPresent(lltok::comma)) {
1557 // Handle ... at end of arg list.
1558 if (EatIfPresent(lltok::dotdotdot)) {
1563 // Otherwise must be an argument type.
1564 TypeLoc = Lex.getLoc();
1565 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1567 if (ArgTy->isVoidTy())
1568 return Error(TypeLoc, "argument can not have void type");
1570 if (Lex.getKind() == lltok::LocalVar) {
1571 Name = Lex.getStrVal();
1577 if (!ArgTy->isFirstClassType())
1578 return Error(TypeLoc, "invalid type for function argument");
1580 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1581 AttributeSet::get(ArgTy->getContext(),
1582 AttrIndex++, Attrs),
1587 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1590 /// ParseFunctionType
1591 /// ::= Type ArgumentList OptionalAttrs
1592 bool LLParser::ParseFunctionType(Type *&Result) {
1593 assert(Lex.getKind() == lltok::lparen);
1595 if (!FunctionType::isValidReturnType(Result))
1596 return TokError("invalid function return type");
1598 SmallVector<ArgInfo, 8> ArgList;
1600 if (ParseArgumentList(ArgList, isVarArg))
1603 // Reject names on the arguments lists.
1604 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1605 if (!ArgList[i].Name.empty())
1606 return Error(ArgList[i].Loc, "argument name invalid in function type");
1607 if (ArgList[i].Attrs.hasAttributes(i + 1))
1608 return Error(ArgList[i].Loc,
1609 "argument attributes invalid in function type");
1612 SmallVector<Type*, 16> ArgListTy;
1613 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1614 ArgListTy.push_back(ArgList[i].Ty);
1616 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1620 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1622 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1623 SmallVector<Type*, 8> Elts;
1624 if (ParseStructBody(Elts)) return true;
1626 Result = StructType::get(Context, Elts, Packed);
1630 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1631 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1632 std::pair<Type*, LocTy> &Entry,
1634 // If the type was already defined, diagnose the redefinition.
1635 if (Entry.first && !Entry.second.isValid())
1636 return Error(TypeLoc, "redefinition of type");
1638 // If we have opaque, just return without filling in the definition for the
1639 // struct. This counts as a definition as far as the .ll file goes.
1640 if (EatIfPresent(lltok::kw_opaque)) {
1641 // This type is being defined, so clear the location to indicate this.
1642 Entry.second = SMLoc();
1644 // If this type number has never been uttered, create it.
1645 if (Entry.first == 0)
1646 Entry.first = StructType::create(Context, Name);
1647 ResultTy = Entry.first;
1651 // If the type starts with '<', then it is either a packed struct or a vector.
1652 bool isPacked = EatIfPresent(lltok::less);
1654 // If we don't have a struct, then we have a random type alias, which we
1655 // accept for compatibility with old files. These types are not allowed to be
1656 // forward referenced and not allowed to be recursive.
1657 if (Lex.getKind() != lltok::lbrace) {
1659 return Error(TypeLoc, "forward references to non-struct type");
1663 return ParseArrayVectorType(ResultTy, true);
1664 return ParseType(ResultTy);
1667 // This type is being defined, so clear the location to indicate this.
1668 Entry.second = SMLoc();
1670 // If this type number has never been uttered, create it.
1671 if (Entry.first == 0)
1672 Entry.first = StructType::create(Context, Name);
1674 StructType *STy = cast<StructType>(Entry.first);
1676 SmallVector<Type*, 8> Body;
1677 if (ParseStructBody(Body) ||
1678 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1681 STy->setBody(Body, isPacked);
1687 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1690 /// ::= '{' Type (',' Type)* '}'
1691 /// ::= '<' '{' '}' '>'
1692 /// ::= '<' '{' Type (',' Type)* '}' '>'
1693 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1694 assert(Lex.getKind() == lltok::lbrace);
1695 Lex.Lex(); // Consume the '{'
1697 // Handle the empty struct.
1698 if (EatIfPresent(lltok::rbrace))
1701 LocTy EltTyLoc = Lex.getLoc();
1703 if (ParseType(Ty)) return true;
1706 if (!StructType::isValidElementType(Ty))
1707 return Error(EltTyLoc, "invalid element type for struct");
1709 while (EatIfPresent(lltok::comma)) {
1710 EltTyLoc = Lex.getLoc();
1711 if (ParseType(Ty)) return true;
1713 if (!StructType::isValidElementType(Ty))
1714 return Error(EltTyLoc, "invalid element type for struct");
1719 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1722 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1723 /// token has already been consumed.
1725 /// ::= '[' APSINTVAL 'x' Types ']'
1726 /// ::= '<' APSINTVAL 'x' Types '>'
1727 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1728 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1729 Lex.getAPSIntVal().getBitWidth() > 64)
1730 return TokError("expected number in address space");
1732 LocTy SizeLoc = Lex.getLoc();
1733 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1736 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1739 LocTy TypeLoc = Lex.getLoc();
1741 if (ParseType(EltTy)) return true;
1743 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1744 "expected end of sequential type"))
1749 return Error(SizeLoc, "zero element vector is illegal");
1750 if ((unsigned)Size != Size)
1751 return Error(SizeLoc, "size too large for vector");
1752 if (!VectorType::isValidElementType(EltTy))
1753 return Error(TypeLoc, "invalid vector element type");
1754 Result = VectorType::get(EltTy, unsigned(Size));
1756 if (!ArrayType::isValidElementType(EltTy))
1757 return Error(TypeLoc, "invalid array element type");
1758 Result = ArrayType::get(EltTy, Size);
1763 //===----------------------------------------------------------------------===//
1764 // Function Semantic Analysis.
1765 //===----------------------------------------------------------------------===//
1767 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1769 : P(p), F(f), FunctionNumber(functionNumber) {
1771 // Insert unnamed arguments into the NumberedVals list.
1772 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1775 NumberedVals.push_back(AI);
1778 LLParser::PerFunctionState::~PerFunctionState() {
1779 // If there were any forward referenced non-basicblock values, delete them.
1780 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1781 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1782 if (!isa<BasicBlock>(I->second.first)) {
1783 I->second.first->replaceAllUsesWith(
1784 UndefValue::get(I->second.first->getType()));
1785 delete I->second.first;
1786 I->second.first = 0;
1789 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1790 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1791 if (!isa<BasicBlock>(I->second.first)) {
1792 I->second.first->replaceAllUsesWith(
1793 UndefValue::get(I->second.first->getType()));
1794 delete I->second.first;
1795 I->second.first = 0;
1799 bool LLParser::PerFunctionState::FinishFunction() {
1800 // Check to see if someone took the address of labels in this block.
1801 if (!P.ForwardRefBlockAddresses.empty()) {
1803 if (!F.getName().empty()) {
1804 FunctionID.Kind = ValID::t_GlobalName;
1805 FunctionID.StrVal = F.getName();
1807 FunctionID.Kind = ValID::t_GlobalID;
1808 FunctionID.UIntVal = FunctionNumber;
1811 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1812 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1813 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1814 // Resolve all these references.
1815 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1818 P.ForwardRefBlockAddresses.erase(FRBAI);
1822 if (!ForwardRefVals.empty())
1823 return P.Error(ForwardRefVals.begin()->second.second,
1824 "use of undefined value '%" + ForwardRefVals.begin()->first +
1826 if (!ForwardRefValIDs.empty())
1827 return P.Error(ForwardRefValIDs.begin()->second.second,
1828 "use of undefined value '%" +
1829 Twine(ForwardRefValIDs.begin()->first) + "'");
1834 /// GetVal - Get a value with the specified name or ID, creating a
1835 /// forward reference record if needed. This can return null if the value
1836 /// exists but does not have the right type.
1837 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1838 Type *Ty, LocTy Loc) {
1839 // Look this name up in the normal function symbol table.
1840 Value *Val = F.getValueSymbolTable().lookup(Name);
1842 // If this is a forward reference for the value, see if we already created a
1843 // forward ref record.
1845 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1846 I = ForwardRefVals.find(Name);
1847 if (I != ForwardRefVals.end())
1848 Val = I->second.first;
1851 // If we have the value in the symbol table or fwd-ref table, return it.
1853 if (Val->getType() == Ty) return Val;
1854 if (Ty->isLabelTy())
1855 P.Error(Loc, "'%" + Name + "' is not a basic block");
1857 P.Error(Loc, "'%" + Name + "' defined with type '" +
1858 getTypeString(Val->getType()) + "'");
1862 // Don't make placeholders with invalid type.
1863 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1864 P.Error(Loc, "invalid use of a non-first-class type");
1868 // Otherwise, create a new forward reference for this value and remember it.
1870 if (Ty->isLabelTy())
1871 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1873 FwdVal = new Argument(Ty, Name);
1875 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1879 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1881 // Look this name up in the normal function symbol table.
1882 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1884 // If this is a forward reference for the value, see if we already created a
1885 // forward ref record.
1887 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1888 I = ForwardRefValIDs.find(ID);
1889 if (I != ForwardRefValIDs.end())
1890 Val = I->second.first;
1893 // If we have the value in the symbol table or fwd-ref table, return it.
1895 if (Val->getType() == Ty) return Val;
1896 if (Ty->isLabelTy())
1897 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1899 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1900 getTypeString(Val->getType()) + "'");
1904 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1905 P.Error(Loc, "invalid use of a non-first-class type");
1909 // Otherwise, create a new forward reference for this value and remember it.
1911 if (Ty->isLabelTy())
1912 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1914 FwdVal = new Argument(Ty);
1916 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1920 /// SetInstName - After an instruction is parsed and inserted into its
1921 /// basic block, this installs its name.
1922 bool LLParser::PerFunctionState::SetInstName(int NameID,
1923 const std::string &NameStr,
1924 LocTy NameLoc, Instruction *Inst) {
1925 // If this instruction has void type, it cannot have a name or ID specified.
1926 if (Inst->getType()->isVoidTy()) {
1927 if (NameID != -1 || !NameStr.empty())
1928 return P.Error(NameLoc, "instructions returning void cannot have a name");
1932 // If this was a numbered instruction, verify that the instruction is the
1933 // expected value and resolve any forward references.
1934 if (NameStr.empty()) {
1935 // If neither a name nor an ID was specified, just use the next ID.
1937 NameID = NumberedVals.size();
1939 if (unsigned(NameID) != NumberedVals.size())
1940 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1941 Twine(NumberedVals.size()) + "'");
1943 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1944 ForwardRefValIDs.find(NameID);
1945 if (FI != ForwardRefValIDs.end()) {
1946 if (FI->second.first->getType() != Inst->getType())
1947 return P.Error(NameLoc, "instruction forward referenced with type '" +
1948 getTypeString(FI->second.first->getType()) + "'");
1949 FI->second.first->replaceAllUsesWith(Inst);
1950 delete FI->second.first;
1951 ForwardRefValIDs.erase(FI);
1954 NumberedVals.push_back(Inst);
1958 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1959 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1960 FI = ForwardRefVals.find(NameStr);
1961 if (FI != ForwardRefVals.end()) {
1962 if (FI->second.first->getType() != Inst->getType())
1963 return P.Error(NameLoc, "instruction forward referenced with type '" +
1964 getTypeString(FI->second.first->getType()) + "'");
1965 FI->second.first->replaceAllUsesWith(Inst);
1966 delete FI->second.first;
1967 ForwardRefVals.erase(FI);
1970 // Set the name on the instruction.
1971 Inst->setName(NameStr);
1973 if (Inst->getName() != NameStr)
1974 return P.Error(NameLoc, "multiple definition of local value named '" +
1979 /// GetBB - Get a basic block with the specified name or ID, creating a
1980 /// forward reference record if needed.
1981 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1983 return cast_or_null<BasicBlock>(GetVal(Name,
1984 Type::getLabelTy(F.getContext()), Loc));
1987 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1988 return cast_or_null<BasicBlock>(GetVal(ID,
1989 Type::getLabelTy(F.getContext()), Loc));
1992 /// DefineBB - Define the specified basic block, which is either named or
1993 /// unnamed. If there is an error, this returns null otherwise it returns
1994 /// the block being defined.
1995 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1999 BB = GetBB(NumberedVals.size(), Loc);
2001 BB = GetBB(Name, Loc);
2002 if (BB == 0) return 0; // Already diagnosed error.
2004 // Move the block to the end of the function. Forward ref'd blocks are
2005 // inserted wherever they happen to be referenced.
2006 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2008 // Remove the block from forward ref sets.
2010 ForwardRefValIDs.erase(NumberedVals.size());
2011 NumberedVals.push_back(BB);
2013 // BB forward references are already in the function symbol table.
2014 ForwardRefVals.erase(Name);
2020 //===----------------------------------------------------------------------===//
2022 //===----------------------------------------------------------------------===//
2024 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2025 /// type implied. For example, if we parse "4" we don't know what integer type
2026 /// it has. The value will later be combined with its type and checked for
2027 /// sanity. PFS is used to convert function-local operands of metadata (since
2028 /// metadata operands are not just parsed here but also converted to values).
2029 /// PFS can be null when we are not parsing metadata values inside a function.
2030 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2031 ID.Loc = Lex.getLoc();
2032 switch (Lex.getKind()) {
2033 default: return TokError("expected value token");
2034 case lltok::GlobalID: // @42
2035 ID.UIntVal = Lex.getUIntVal();
2036 ID.Kind = ValID::t_GlobalID;
2038 case lltok::GlobalVar: // @foo
2039 ID.StrVal = Lex.getStrVal();
2040 ID.Kind = ValID::t_GlobalName;
2042 case lltok::LocalVarID: // %42
2043 ID.UIntVal = Lex.getUIntVal();
2044 ID.Kind = ValID::t_LocalID;
2046 case lltok::LocalVar: // %foo
2047 ID.StrVal = Lex.getStrVal();
2048 ID.Kind = ValID::t_LocalName;
2050 case lltok::exclaim: // !42, !{...}, or !"foo"
2051 return ParseMetadataValue(ID, PFS);
2053 ID.APSIntVal = Lex.getAPSIntVal();
2054 ID.Kind = ValID::t_APSInt;
2056 case lltok::APFloat:
2057 ID.APFloatVal = Lex.getAPFloatVal();
2058 ID.Kind = ValID::t_APFloat;
2060 case lltok::kw_true:
2061 ID.ConstantVal = ConstantInt::getTrue(Context);
2062 ID.Kind = ValID::t_Constant;
2064 case lltok::kw_false:
2065 ID.ConstantVal = ConstantInt::getFalse(Context);
2066 ID.Kind = ValID::t_Constant;
2068 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2069 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2070 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2072 case lltok::lbrace: {
2073 // ValID ::= '{' ConstVector '}'
2075 SmallVector<Constant*, 16> Elts;
2076 if (ParseGlobalValueVector(Elts) ||
2077 ParseToken(lltok::rbrace, "expected end of struct constant"))
2080 ID.ConstantStructElts = new Constant*[Elts.size()];
2081 ID.UIntVal = Elts.size();
2082 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2083 ID.Kind = ValID::t_ConstantStruct;
2087 // ValID ::= '<' ConstVector '>' --> Vector.
2088 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2090 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2092 SmallVector<Constant*, 16> Elts;
2093 LocTy FirstEltLoc = Lex.getLoc();
2094 if (ParseGlobalValueVector(Elts) ||
2096 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2097 ParseToken(lltok::greater, "expected end of constant"))
2100 if (isPackedStruct) {
2101 ID.ConstantStructElts = new Constant*[Elts.size()];
2102 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2103 ID.UIntVal = Elts.size();
2104 ID.Kind = ValID::t_PackedConstantStruct;
2109 return Error(ID.Loc, "constant vector must not be empty");
2111 if (!Elts[0]->getType()->isIntegerTy() &&
2112 !Elts[0]->getType()->isFloatingPointTy() &&
2113 !Elts[0]->getType()->isPointerTy())
2114 return Error(FirstEltLoc,
2115 "vector elements must have integer, pointer or floating point type");
2117 // Verify that all the vector elements have the same type.
2118 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2119 if (Elts[i]->getType() != Elts[0]->getType())
2120 return Error(FirstEltLoc,
2121 "vector element #" + Twine(i) +
2122 " is not of type '" + getTypeString(Elts[0]->getType()));
2124 ID.ConstantVal = ConstantVector::get(Elts);
2125 ID.Kind = ValID::t_Constant;
2128 case lltok::lsquare: { // Array Constant
2130 SmallVector<Constant*, 16> Elts;
2131 LocTy FirstEltLoc = Lex.getLoc();
2132 if (ParseGlobalValueVector(Elts) ||
2133 ParseToken(lltok::rsquare, "expected end of array constant"))
2136 // Handle empty element.
2138 // Use undef instead of an array because it's inconvenient to determine
2139 // the element type at this point, there being no elements to examine.
2140 ID.Kind = ValID::t_EmptyArray;
2144 if (!Elts[0]->getType()->isFirstClassType())
2145 return Error(FirstEltLoc, "invalid array element type: " +
2146 getTypeString(Elts[0]->getType()));
2148 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2150 // Verify all elements are correct type!
2151 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2152 if (Elts[i]->getType() != Elts[0]->getType())
2153 return Error(FirstEltLoc,
2154 "array element #" + Twine(i) +
2155 " is not of type '" + getTypeString(Elts[0]->getType()));
2158 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2159 ID.Kind = ValID::t_Constant;
2162 case lltok::kw_c: // c "foo"
2164 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2166 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2167 ID.Kind = ValID::t_Constant;
2170 case lltok::kw_asm: {
2171 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2172 bool HasSideEffect, AlignStack, AsmDialect;
2174 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2175 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2176 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2177 ParseStringConstant(ID.StrVal) ||
2178 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2179 ParseToken(lltok::StringConstant, "expected constraint string"))
2181 ID.StrVal2 = Lex.getStrVal();
2182 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2183 (unsigned(AsmDialect)<<2);
2184 ID.Kind = ValID::t_InlineAsm;
2188 case lltok::kw_blockaddress: {
2189 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2193 LocTy FnLoc, LabelLoc;
2195 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2197 ParseToken(lltok::comma, "expected comma in block address expression")||
2198 ParseValID(Label) ||
2199 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2202 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2203 return Error(Fn.Loc, "expected function name in blockaddress");
2204 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2205 return Error(Label.Loc, "expected basic block name in blockaddress");
2207 // Make a global variable as a placeholder for this reference.
2208 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2209 false, GlobalValue::InternalLinkage,
2211 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2212 ID.ConstantVal = FwdRef;
2213 ID.Kind = ValID::t_Constant;
2217 case lltok::kw_trunc:
2218 case lltok::kw_zext:
2219 case lltok::kw_sext:
2220 case lltok::kw_fptrunc:
2221 case lltok::kw_fpext:
2222 case lltok::kw_bitcast:
2223 case lltok::kw_uitofp:
2224 case lltok::kw_sitofp:
2225 case lltok::kw_fptoui:
2226 case lltok::kw_fptosi:
2227 case lltok::kw_inttoptr:
2228 case lltok::kw_ptrtoint: {
2229 unsigned Opc = Lex.getUIntVal();
2233 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2234 ParseGlobalTypeAndValue(SrcVal) ||
2235 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2236 ParseType(DestTy) ||
2237 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2239 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2240 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2241 getTypeString(SrcVal->getType()) + "' to '" +
2242 getTypeString(DestTy) + "'");
2243 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2245 ID.Kind = ValID::t_Constant;
2248 case lltok::kw_extractvalue: {
2251 SmallVector<unsigned, 4> Indices;
2252 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2253 ParseGlobalTypeAndValue(Val) ||
2254 ParseIndexList(Indices) ||
2255 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2258 if (!Val->getType()->isAggregateType())
2259 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2260 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2261 return Error(ID.Loc, "invalid indices for extractvalue");
2262 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2263 ID.Kind = ValID::t_Constant;
2266 case lltok::kw_insertvalue: {
2268 Constant *Val0, *Val1;
2269 SmallVector<unsigned, 4> Indices;
2270 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2271 ParseGlobalTypeAndValue(Val0) ||
2272 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2273 ParseGlobalTypeAndValue(Val1) ||
2274 ParseIndexList(Indices) ||
2275 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2277 if (!Val0->getType()->isAggregateType())
2278 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2279 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2280 return Error(ID.Loc, "invalid indices for insertvalue");
2281 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2282 ID.Kind = ValID::t_Constant;
2285 case lltok::kw_icmp:
2286 case lltok::kw_fcmp: {
2287 unsigned PredVal, Opc = Lex.getUIntVal();
2288 Constant *Val0, *Val1;
2290 if (ParseCmpPredicate(PredVal, Opc) ||
2291 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2292 ParseGlobalTypeAndValue(Val0) ||
2293 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2294 ParseGlobalTypeAndValue(Val1) ||
2295 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2298 if (Val0->getType() != Val1->getType())
2299 return Error(ID.Loc, "compare operands must have the same type");
2301 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2303 if (Opc == Instruction::FCmp) {
2304 if (!Val0->getType()->isFPOrFPVectorTy())
2305 return Error(ID.Loc, "fcmp requires floating point operands");
2306 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2308 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2309 if (!Val0->getType()->isIntOrIntVectorTy() &&
2310 !Val0->getType()->getScalarType()->isPointerTy())
2311 return Error(ID.Loc, "icmp requires pointer or integer operands");
2312 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2314 ID.Kind = ValID::t_Constant;
2318 // Binary Operators.
2320 case lltok::kw_fadd:
2322 case lltok::kw_fsub:
2324 case lltok::kw_fmul:
2325 case lltok::kw_udiv:
2326 case lltok::kw_sdiv:
2327 case lltok::kw_fdiv:
2328 case lltok::kw_urem:
2329 case lltok::kw_srem:
2330 case lltok::kw_frem:
2332 case lltok::kw_lshr:
2333 case lltok::kw_ashr: {
2337 unsigned Opc = Lex.getUIntVal();
2338 Constant *Val0, *Val1;
2340 LocTy ModifierLoc = Lex.getLoc();
2341 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2342 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2343 if (EatIfPresent(lltok::kw_nuw))
2345 if (EatIfPresent(lltok::kw_nsw)) {
2347 if (EatIfPresent(lltok::kw_nuw))
2350 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2351 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2352 if (EatIfPresent(lltok::kw_exact))
2355 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2356 ParseGlobalTypeAndValue(Val0) ||
2357 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2358 ParseGlobalTypeAndValue(Val1) ||
2359 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2361 if (Val0->getType() != Val1->getType())
2362 return Error(ID.Loc, "operands of constexpr must have same type");
2363 if (!Val0->getType()->isIntOrIntVectorTy()) {
2365 return Error(ModifierLoc, "nuw only applies to integer operations");
2367 return Error(ModifierLoc, "nsw only applies to integer operations");
2369 // Check that the type is valid for the operator.
2371 case Instruction::Add:
2372 case Instruction::Sub:
2373 case Instruction::Mul:
2374 case Instruction::UDiv:
2375 case Instruction::SDiv:
2376 case Instruction::URem:
2377 case Instruction::SRem:
2378 case Instruction::Shl:
2379 case Instruction::AShr:
2380 case Instruction::LShr:
2381 if (!Val0->getType()->isIntOrIntVectorTy())
2382 return Error(ID.Loc, "constexpr requires integer operands");
2384 case Instruction::FAdd:
2385 case Instruction::FSub:
2386 case Instruction::FMul:
2387 case Instruction::FDiv:
2388 case Instruction::FRem:
2389 if (!Val0->getType()->isFPOrFPVectorTy())
2390 return Error(ID.Loc, "constexpr requires fp operands");
2392 default: llvm_unreachable("Unknown binary operator!");
2395 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2396 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2397 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2398 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2400 ID.Kind = ValID::t_Constant;
2404 // Logical Operations
2407 case lltok::kw_xor: {
2408 unsigned Opc = Lex.getUIntVal();
2409 Constant *Val0, *Val1;
2411 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2412 ParseGlobalTypeAndValue(Val0) ||
2413 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2414 ParseGlobalTypeAndValue(Val1) ||
2415 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2417 if (Val0->getType() != Val1->getType())
2418 return Error(ID.Loc, "operands of constexpr must have same type");
2419 if (!Val0->getType()->isIntOrIntVectorTy())
2420 return Error(ID.Loc,
2421 "constexpr requires integer or integer vector operands");
2422 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2423 ID.Kind = ValID::t_Constant;
2427 case lltok::kw_getelementptr:
2428 case lltok::kw_shufflevector:
2429 case lltok::kw_insertelement:
2430 case lltok::kw_extractelement:
2431 case lltok::kw_select: {
2432 unsigned Opc = Lex.getUIntVal();
2433 SmallVector<Constant*, 16> Elts;
2434 bool InBounds = false;
2436 if (Opc == Instruction::GetElementPtr)
2437 InBounds = EatIfPresent(lltok::kw_inbounds);
2438 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2439 ParseGlobalValueVector(Elts) ||
2440 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2443 if (Opc == Instruction::GetElementPtr) {
2444 if (Elts.size() == 0 ||
2445 !Elts[0]->getType()->getScalarType()->isPointerTy())
2446 return Error(ID.Loc, "getelementptr requires pointer operand");
2448 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2449 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2450 return Error(ID.Loc, "invalid indices for getelementptr");
2451 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2453 } else if (Opc == Instruction::Select) {
2454 if (Elts.size() != 3)
2455 return Error(ID.Loc, "expected three operands to select");
2456 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2458 return Error(ID.Loc, Reason);
2459 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2460 } else if (Opc == Instruction::ShuffleVector) {
2461 if (Elts.size() != 3)
2462 return Error(ID.Loc, "expected three operands to shufflevector");
2463 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2464 return Error(ID.Loc, "invalid operands to shufflevector");
2466 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2467 } else if (Opc == Instruction::ExtractElement) {
2468 if (Elts.size() != 2)
2469 return Error(ID.Loc, "expected two operands to extractelement");
2470 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2471 return Error(ID.Loc, "invalid extractelement operands");
2472 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2474 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2475 if (Elts.size() != 3)
2476 return Error(ID.Loc, "expected three operands to insertelement");
2477 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2478 return Error(ID.Loc, "invalid insertelement operands");
2480 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2483 ID.Kind = ValID::t_Constant;
2492 /// ParseGlobalValue - Parse a global value with the specified type.
2493 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2497 bool Parsed = ParseValID(ID) ||
2498 ConvertValIDToValue(Ty, ID, V, NULL);
2499 if (V && !(C = dyn_cast<Constant>(V)))
2500 return Error(ID.Loc, "global values must be constants");
2504 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2506 return ParseType(Ty) ||
2507 ParseGlobalValue(Ty, V);
2510 /// ParseGlobalValueVector
2512 /// ::= TypeAndValue (',' TypeAndValue)*
2513 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2515 if (Lex.getKind() == lltok::rbrace ||
2516 Lex.getKind() == lltok::rsquare ||
2517 Lex.getKind() == lltok::greater ||
2518 Lex.getKind() == lltok::rparen)
2522 if (ParseGlobalTypeAndValue(C)) return true;
2525 while (EatIfPresent(lltok::comma)) {
2526 if (ParseGlobalTypeAndValue(C)) return true;
2533 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2534 assert(Lex.getKind() == lltok::lbrace);
2537 SmallVector<Value*, 16> Elts;
2538 if (ParseMDNodeVector(Elts, PFS) ||
2539 ParseToken(lltok::rbrace, "expected end of metadata node"))
2542 ID.MDNodeVal = MDNode::get(Context, Elts);
2543 ID.Kind = ValID::t_MDNode;
2547 /// ParseMetadataValue
2551 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2552 assert(Lex.getKind() == lltok::exclaim);
2557 if (Lex.getKind() == lltok::lbrace)
2558 return ParseMetadataListValue(ID, PFS);
2560 // Standalone metadata reference
2562 if (Lex.getKind() == lltok::APSInt) {
2563 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2564 ID.Kind = ValID::t_MDNode;
2569 // ::= '!' STRINGCONSTANT
2570 if (ParseMDString(ID.MDStringVal)) return true;
2571 ID.Kind = ValID::t_MDString;
2576 //===----------------------------------------------------------------------===//
2577 // Function Parsing.
2578 //===----------------------------------------------------------------------===//
2580 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2581 PerFunctionState *PFS) {
2582 if (Ty->isFunctionTy())
2583 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2586 case ValID::t_LocalID:
2587 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2588 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2590 case ValID::t_LocalName:
2591 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2592 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2594 case ValID::t_InlineAsm: {
2595 PointerType *PTy = dyn_cast<PointerType>(Ty);
2597 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2598 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2599 return Error(ID.Loc, "invalid type for inline asm constraint string");
2600 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2601 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2604 case ValID::t_MDNode:
2605 if (!Ty->isMetadataTy())
2606 return Error(ID.Loc, "metadata value must have metadata type");
2609 case ValID::t_MDString:
2610 if (!Ty->isMetadataTy())
2611 return Error(ID.Loc, "metadata value must have metadata type");
2614 case ValID::t_GlobalName:
2615 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2617 case ValID::t_GlobalID:
2618 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2620 case ValID::t_APSInt:
2621 if (!Ty->isIntegerTy())
2622 return Error(ID.Loc, "integer constant must have integer type");
2623 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2624 V = ConstantInt::get(Context, ID.APSIntVal);
2626 case ValID::t_APFloat:
2627 if (!Ty->isFloatingPointTy() ||
2628 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2629 return Error(ID.Loc, "floating point constant invalid for type");
2631 // The lexer has no type info, so builds all half, float, and double FP
2632 // constants as double. Fix this here. Long double does not need this.
2633 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2636 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2638 else if (Ty->isFloatTy())
2639 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2642 V = ConstantFP::get(Context, ID.APFloatVal);
2644 if (V->getType() != Ty)
2645 return Error(ID.Loc, "floating point constant does not have type '" +
2646 getTypeString(Ty) + "'");
2650 if (!Ty->isPointerTy())
2651 return Error(ID.Loc, "null must be a pointer type");
2652 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2654 case ValID::t_Undef:
2655 // FIXME: LabelTy should not be a first-class type.
2656 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2657 return Error(ID.Loc, "invalid type for undef constant");
2658 V = UndefValue::get(Ty);
2660 case ValID::t_EmptyArray:
2661 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2662 return Error(ID.Loc, "invalid empty array initializer");
2663 V = UndefValue::get(Ty);
2666 // FIXME: LabelTy should not be a first-class type.
2667 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2668 return Error(ID.Loc, "invalid type for null constant");
2669 V = Constant::getNullValue(Ty);
2671 case ValID::t_Constant:
2672 if (ID.ConstantVal->getType() != Ty)
2673 return Error(ID.Loc, "constant expression type mismatch");
2677 case ValID::t_ConstantStruct:
2678 case ValID::t_PackedConstantStruct:
2679 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2680 if (ST->getNumElements() != ID.UIntVal)
2681 return Error(ID.Loc,
2682 "initializer with struct type has wrong # elements");
2683 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2684 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2686 // Verify that the elements are compatible with the structtype.
2687 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2688 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2689 return Error(ID.Loc, "element " + Twine(i) +
2690 " of struct initializer doesn't match struct element type");
2692 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2695 return Error(ID.Loc, "constant expression type mismatch");
2698 llvm_unreachable("Invalid ValID");
2701 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2704 return ParseValID(ID, PFS) ||
2705 ConvertValIDToValue(Ty, ID, V, PFS);
2708 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2710 return ParseType(Ty) ||
2711 ParseValue(Ty, V, PFS);
2714 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2715 PerFunctionState &PFS) {
2718 if (ParseTypeAndValue(V, PFS)) return true;
2719 if (!isa<BasicBlock>(V))
2720 return Error(Loc, "expected a basic block");
2721 BB = cast<BasicBlock>(V);
2727 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2728 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2729 /// OptionalAlign OptGC
2730 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2731 // Parse the linkage.
2732 LocTy LinkageLoc = Lex.getLoc();
2735 unsigned Visibility;
2736 AttrBuilder RetAttrs;
2739 LocTy RetTypeLoc = Lex.getLoc();
2740 if (ParseOptionalLinkage(Linkage) ||
2741 ParseOptionalVisibility(Visibility) ||
2742 ParseOptionalCallingConv(CC) ||
2743 ParseOptionalReturnAttrs(RetAttrs) ||
2744 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2747 // Verify that the linkage is ok.
2748 switch ((GlobalValue::LinkageTypes)Linkage) {
2749 case GlobalValue::ExternalLinkage:
2750 break; // always ok.
2751 case GlobalValue::DLLImportLinkage:
2752 case GlobalValue::ExternalWeakLinkage:
2754 return Error(LinkageLoc, "invalid linkage for function definition");
2756 case GlobalValue::PrivateLinkage:
2757 case GlobalValue::LinkerPrivateLinkage:
2758 case GlobalValue::LinkerPrivateWeakLinkage:
2759 case GlobalValue::InternalLinkage:
2760 case GlobalValue::AvailableExternallyLinkage:
2761 case GlobalValue::LinkOnceAnyLinkage:
2762 case GlobalValue::LinkOnceODRLinkage:
2763 case GlobalValue::LinkOnceODRAutoHideLinkage:
2764 case GlobalValue::WeakAnyLinkage:
2765 case GlobalValue::WeakODRLinkage:
2766 case GlobalValue::DLLExportLinkage:
2768 return Error(LinkageLoc, "invalid linkage for function declaration");
2770 case GlobalValue::AppendingLinkage:
2771 case GlobalValue::CommonLinkage:
2772 return Error(LinkageLoc, "invalid function linkage type");
2775 if (!FunctionType::isValidReturnType(RetType))
2776 return Error(RetTypeLoc, "invalid function return type");
2778 LocTy NameLoc = Lex.getLoc();
2780 std::string FunctionName;
2781 if (Lex.getKind() == lltok::GlobalVar) {
2782 FunctionName = Lex.getStrVal();
2783 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2784 unsigned NameID = Lex.getUIntVal();
2786 if (NameID != NumberedVals.size())
2787 return TokError("function expected to be numbered '%" +
2788 Twine(NumberedVals.size()) + "'");
2790 return TokError("expected function name");
2795 if (Lex.getKind() != lltok::lparen)
2796 return TokError("expected '(' in function argument list");
2798 SmallVector<ArgInfo, 8> ArgList;
2800 AttrBuilder FuncAttrs;
2801 std::string Section;
2805 LocTy UnnamedAddrLoc;
2807 if (ParseArgumentList(ArgList, isVarArg) ||
2808 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2810 ParseOptionalFuncAttrs(FuncAttrs) ||
2811 (EatIfPresent(lltok::kw_section) &&
2812 ParseStringConstant(Section)) ||
2813 ParseOptionalAlignment(Alignment) ||
2814 (EatIfPresent(lltok::kw_gc) &&
2815 ParseStringConstant(GC)))
2818 // If the alignment was parsed as an attribute, move to the alignment field.
2819 if (FuncAttrs.hasAlignmentAttr()) {
2820 Alignment = FuncAttrs.getAlignment();
2821 FuncAttrs.removeAttribute(Attribute::Alignment);
2824 // Okay, if we got here, the function is syntactically valid. Convert types
2825 // and do semantic checks.
2826 std::vector<Type*> ParamTypeList;
2827 SmallVector<AttributeSet, 8> Attrs;
2829 if (RetAttrs.hasAttributes())
2830 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2831 AttributeSet::ReturnIndex,
2834 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2835 ParamTypeList.push_back(ArgList[i].Ty);
2836 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
2837 AttrBuilder B(ArgList[i].Attrs, i + 1);
2838 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
2842 if (FuncAttrs.hasAttributes())
2843 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2844 AttributeSet::FunctionIndex,
2847 AttributeSet PAL = AttributeSet::get(Context, Attrs);
2849 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
2850 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2853 FunctionType::get(RetType, ParamTypeList, isVarArg);
2854 PointerType *PFT = PointerType::getUnqual(FT);
2857 if (!FunctionName.empty()) {
2858 // If this was a definition of a forward reference, remove the definition
2859 // from the forward reference table and fill in the forward ref.
2860 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2861 ForwardRefVals.find(FunctionName);
2862 if (FRVI != ForwardRefVals.end()) {
2863 Fn = M->getFunction(FunctionName);
2865 return Error(FRVI->second.second, "invalid forward reference to "
2866 "function as global value!");
2867 if (Fn->getType() != PFT)
2868 return Error(FRVI->second.second, "invalid forward reference to "
2869 "function '" + FunctionName + "' with wrong type!");
2871 ForwardRefVals.erase(FRVI);
2872 } else if ((Fn = M->getFunction(FunctionName))) {
2873 // Reject redefinitions.
2874 return Error(NameLoc, "invalid redefinition of function '" +
2875 FunctionName + "'");
2876 } else if (M->getNamedValue(FunctionName)) {
2877 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2881 // If this is a definition of a forward referenced function, make sure the
2883 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2884 = ForwardRefValIDs.find(NumberedVals.size());
2885 if (I != ForwardRefValIDs.end()) {
2886 Fn = cast<Function>(I->second.first);
2887 if (Fn->getType() != PFT)
2888 return Error(NameLoc, "type of definition and forward reference of '@" +
2889 Twine(NumberedVals.size()) + "' disagree");
2890 ForwardRefValIDs.erase(I);
2895 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2896 else // Move the forward-reference to the correct spot in the module.
2897 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2899 if (FunctionName.empty())
2900 NumberedVals.push_back(Fn);
2902 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2903 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2904 Fn->setCallingConv(CC);
2905 Fn->setAttributes(PAL);
2906 Fn->setUnnamedAddr(UnnamedAddr);
2907 Fn->setAlignment(Alignment);
2908 Fn->setSection(Section);
2909 if (!GC.empty()) Fn->setGC(GC.c_str());
2911 // Add all of the arguments we parsed to the function.
2912 Function::arg_iterator ArgIt = Fn->arg_begin();
2913 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2914 // If the argument has a name, insert it into the argument symbol table.
2915 if (ArgList[i].Name.empty()) continue;
2917 // Set the name, if it conflicted, it will be auto-renamed.
2918 ArgIt->setName(ArgList[i].Name);
2920 if (ArgIt->getName() != ArgList[i].Name)
2921 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2922 ArgList[i].Name + "'");
2929 /// ParseFunctionBody
2930 /// ::= '{' BasicBlock+ '}'
2932 bool LLParser::ParseFunctionBody(Function &Fn) {
2933 if (Lex.getKind() != lltok::lbrace)
2934 return TokError("expected '{' in function body");
2935 Lex.Lex(); // eat the {.
2937 int FunctionNumber = -1;
2938 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2940 PerFunctionState PFS(*this, Fn, FunctionNumber);
2942 // We need at least one basic block.
2943 if (Lex.getKind() == lltok::rbrace)
2944 return TokError("function body requires at least one basic block");
2946 while (Lex.getKind() != lltok::rbrace)
2947 if (ParseBasicBlock(PFS)) return true;
2952 // Verify function is ok.
2953 return PFS.FinishFunction();
2957 /// ::= LabelStr? Instruction*
2958 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2959 // If this basic block starts out with a name, remember it.
2961 LocTy NameLoc = Lex.getLoc();
2962 if (Lex.getKind() == lltok::LabelStr) {
2963 Name = Lex.getStrVal();
2967 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2968 if (BB == 0) return true;
2970 std::string NameStr;
2972 // Parse the instructions in this block until we get a terminator.
2974 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2976 // This instruction may have three possibilities for a name: a) none
2977 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2978 LocTy NameLoc = Lex.getLoc();
2982 if (Lex.getKind() == lltok::LocalVarID) {
2983 NameID = Lex.getUIntVal();
2985 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2987 } else if (Lex.getKind() == lltok::LocalVar) {
2988 NameStr = Lex.getStrVal();
2990 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2994 switch (ParseInstruction(Inst, BB, PFS)) {
2995 default: llvm_unreachable("Unknown ParseInstruction result!");
2996 case InstError: return true;
2998 BB->getInstList().push_back(Inst);
3000 // With a normal result, we check to see if the instruction is followed by
3001 // a comma and metadata.
3002 if (EatIfPresent(lltok::comma))
3003 if (ParseInstructionMetadata(Inst, &PFS))
3006 case InstExtraComma:
3007 BB->getInstList().push_back(Inst);
3009 // If the instruction parser ate an extra comma at the end of it, it
3010 // *must* be followed by metadata.
3011 if (ParseInstructionMetadata(Inst, &PFS))
3016 // Set the name on the instruction.
3017 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3018 } while (!isa<TerminatorInst>(Inst));
3023 //===----------------------------------------------------------------------===//
3024 // Instruction Parsing.
3025 //===----------------------------------------------------------------------===//
3027 /// ParseInstruction - Parse one of the many different instructions.
3029 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3030 PerFunctionState &PFS) {
3031 lltok::Kind Token = Lex.getKind();
3032 if (Token == lltok::Eof)
3033 return TokError("found end of file when expecting more instructions");
3034 LocTy Loc = Lex.getLoc();
3035 unsigned KeywordVal = Lex.getUIntVal();
3036 Lex.Lex(); // Eat the keyword.
3039 default: return Error(Loc, "expected instruction opcode");
3040 // Terminator Instructions.
3041 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3042 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3043 case lltok::kw_br: return ParseBr(Inst, PFS);
3044 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3045 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3046 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3047 case lltok::kw_resume: return ParseResume(Inst, PFS);
3048 // Binary Operators.
3052 case lltok::kw_shl: {
3053 bool NUW = EatIfPresent(lltok::kw_nuw);
3054 bool NSW = EatIfPresent(lltok::kw_nsw);
3055 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3057 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3059 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3060 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3063 case lltok::kw_fadd:
3064 case lltok::kw_fsub:
3065 case lltok::kw_fmul:
3066 case lltok::kw_fdiv:
3067 case lltok::kw_frem: {
3068 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3069 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3073 Inst->setFastMathFlags(FMF);
3077 case lltok::kw_sdiv:
3078 case lltok::kw_udiv:
3079 case lltok::kw_lshr:
3080 case lltok::kw_ashr: {
3081 bool Exact = EatIfPresent(lltok::kw_exact);
3083 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3084 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3088 case lltok::kw_urem:
3089 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3092 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3093 case lltok::kw_icmp:
3094 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3096 case lltok::kw_trunc:
3097 case lltok::kw_zext:
3098 case lltok::kw_sext:
3099 case lltok::kw_fptrunc:
3100 case lltok::kw_fpext:
3101 case lltok::kw_bitcast:
3102 case lltok::kw_uitofp:
3103 case lltok::kw_sitofp:
3104 case lltok::kw_fptoui:
3105 case lltok::kw_fptosi:
3106 case lltok::kw_inttoptr:
3107 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3109 case lltok::kw_select: return ParseSelect(Inst, PFS);
3110 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3111 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3112 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3113 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3114 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3115 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3116 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3117 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3119 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3120 case lltok::kw_load: return ParseLoad(Inst, PFS);
3121 case lltok::kw_store: return ParseStore(Inst, PFS);
3122 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3123 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3124 case lltok::kw_fence: return ParseFence(Inst, PFS);
3125 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3126 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3127 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3131 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3132 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3133 if (Opc == Instruction::FCmp) {
3134 switch (Lex.getKind()) {
3135 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3136 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3137 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3138 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3139 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3140 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3141 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3142 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3143 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3144 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3145 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3146 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3147 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3148 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3149 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3150 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3151 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3154 switch (Lex.getKind()) {
3155 default: return TokError("expected icmp predicate (e.g. 'eq')");
3156 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3157 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3158 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3159 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3160 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3161 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3162 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3163 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3164 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3165 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3172 //===----------------------------------------------------------------------===//
3173 // Terminator Instructions.
3174 //===----------------------------------------------------------------------===//
3176 /// ParseRet - Parse a return instruction.
3177 /// ::= 'ret' void (',' !dbg, !1)*
3178 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3179 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3180 PerFunctionState &PFS) {
3181 SMLoc TypeLoc = Lex.getLoc();
3183 if (ParseType(Ty, true /*void allowed*/)) return true;
3185 Type *ResType = PFS.getFunction().getReturnType();
3187 if (Ty->isVoidTy()) {
3188 if (!ResType->isVoidTy())
3189 return Error(TypeLoc, "value doesn't match function result type '" +
3190 getTypeString(ResType) + "'");
3192 Inst = ReturnInst::Create(Context);
3197 if (ParseValue(Ty, RV, PFS)) return true;
3199 if (ResType != RV->getType())
3200 return Error(TypeLoc, "value doesn't match function result type '" +
3201 getTypeString(ResType) + "'");
3203 Inst = ReturnInst::Create(Context, RV);
3209 /// ::= 'br' TypeAndValue
3210 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3211 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3214 BasicBlock *Op1, *Op2;
3215 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3217 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3218 Inst = BranchInst::Create(BB);
3222 if (Op0->getType() != Type::getInt1Ty(Context))
3223 return Error(Loc, "branch condition must have 'i1' type");
3225 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3226 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3227 ParseToken(lltok::comma, "expected ',' after true destination") ||
3228 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3231 Inst = BranchInst::Create(Op1, Op2, Op0);
3237 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3239 /// ::= (TypeAndValue ',' TypeAndValue)*
3240 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3241 LocTy CondLoc, BBLoc;
3243 BasicBlock *DefaultBB;
3244 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3245 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3246 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3247 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3250 if (!Cond->getType()->isIntegerTy())
3251 return Error(CondLoc, "switch condition must have integer type");
3253 // Parse the jump table pairs.
3254 SmallPtrSet<Value*, 32> SeenCases;
3255 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3256 while (Lex.getKind() != lltok::rsquare) {
3260 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3261 ParseToken(lltok::comma, "expected ',' after case value") ||
3262 ParseTypeAndBasicBlock(DestBB, PFS))
3265 if (!SeenCases.insert(Constant))
3266 return Error(CondLoc, "duplicate case value in switch");
3267 if (!isa<ConstantInt>(Constant))
3268 return Error(CondLoc, "case value is not a constant integer");
3270 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3273 Lex.Lex(); // Eat the ']'.
3275 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3276 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3277 SI->addCase(Table[i].first, Table[i].second);
3284 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3285 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3288 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3289 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3290 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3293 if (!Address->getType()->isPointerTy())
3294 return Error(AddrLoc, "indirectbr address must have pointer type");
3296 // Parse the destination list.
3297 SmallVector<BasicBlock*, 16> DestList;
3299 if (Lex.getKind() != lltok::rsquare) {
3301 if (ParseTypeAndBasicBlock(DestBB, PFS))
3303 DestList.push_back(DestBB);
3305 while (EatIfPresent(lltok::comma)) {
3306 if (ParseTypeAndBasicBlock(DestBB, PFS))
3308 DestList.push_back(DestBB);
3312 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3315 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3316 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3317 IBI->addDestination(DestList[i]);
3324 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3325 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3326 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3327 LocTy CallLoc = Lex.getLoc();
3328 AttrBuilder RetAttrs, FnAttrs;
3333 SmallVector<ParamInfo, 16> ArgList;
3335 BasicBlock *NormalBB, *UnwindBB;
3336 if (ParseOptionalCallingConv(CC) ||
3337 ParseOptionalReturnAttrs(RetAttrs) ||
3338 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3339 ParseValID(CalleeID) ||
3340 ParseParameterList(ArgList, PFS) ||
3341 ParseOptionalFuncAttrs(FnAttrs) ||
3342 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3343 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3344 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3345 ParseTypeAndBasicBlock(UnwindBB, PFS))
3348 // If RetType is a non-function pointer type, then this is the short syntax
3349 // for the call, which means that RetType is just the return type. Infer the
3350 // rest of the function argument types from the arguments that are present.
3351 PointerType *PFTy = 0;
3352 FunctionType *Ty = 0;
3353 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3354 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3355 // Pull out the types of all of the arguments...
3356 std::vector<Type*> ParamTypes;
3357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3358 ParamTypes.push_back(ArgList[i].V->getType());
3360 if (!FunctionType::isValidReturnType(RetType))
3361 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3363 Ty = FunctionType::get(RetType, ParamTypes, false);
3364 PFTy = PointerType::getUnqual(Ty);
3367 // Look up the callee.
3369 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3371 // Set up the Attribute for the function.
3372 SmallVector<AttributeSet, 8> Attrs;
3373 if (RetAttrs.hasAttributes())
3374 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3375 AttributeSet::ReturnIndex,
3378 SmallVector<Value*, 8> Args;
3380 // Loop through FunctionType's arguments and ensure they are specified
3381 // correctly. Also, gather any parameter attributes.
3382 FunctionType::param_iterator I = Ty->param_begin();
3383 FunctionType::param_iterator E = Ty->param_end();
3384 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3385 Type *ExpectedTy = 0;
3388 } else if (!Ty->isVarArg()) {
3389 return Error(ArgList[i].Loc, "too many arguments specified");
3392 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3393 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3394 getTypeString(ExpectedTy) + "'");
3395 Args.push_back(ArgList[i].V);
3396 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3397 AttrBuilder B(ArgList[i].Attrs, i + 1);
3398 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3403 return Error(CallLoc, "not enough parameters specified for call");
3405 if (FnAttrs.hasAttributes())
3406 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3407 AttributeSet::FunctionIndex,
3410 // Finish off the Attribute and check them
3411 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3413 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3414 II->setCallingConv(CC);
3415 II->setAttributes(PAL);
3421 /// ::= 'resume' TypeAndValue
3422 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3423 Value *Exn; LocTy ExnLoc;
3424 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3427 ResumeInst *RI = ResumeInst::Create(Exn);
3432 //===----------------------------------------------------------------------===//
3433 // Binary Operators.
3434 //===----------------------------------------------------------------------===//
3437 /// ::= ArithmeticOps TypeAndValue ',' Value
3439 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3440 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3441 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3442 unsigned Opc, unsigned OperandType) {
3443 LocTy Loc; Value *LHS, *RHS;
3444 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3446 ParseValue(LHS->getType(), RHS, PFS))
3450 switch (OperandType) {
3451 default: llvm_unreachable("Unknown operand type!");
3452 case 0: // int or FP.
3453 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3454 LHS->getType()->isFPOrFPVectorTy();
3456 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3457 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3461 return Error(Loc, "invalid operand type for instruction");
3463 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3468 /// ::= ArithmeticOps TypeAndValue ',' Value {
3469 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3471 LocTy Loc; Value *LHS, *RHS;
3472 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3473 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3474 ParseValue(LHS->getType(), RHS, PFS))
3477 if (!LHS->getType()->isIntOrIntVectorTy())
3478 return Error(Loc,"instruction requires integer or integer vector operands");
3480 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3486 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3487 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3488 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3490 // Parse the integer/fp comparison predicate.
3494 if (ParseCmpPredicate(Pred, Opc) ||
3495 ParseTypeAndValue(LHS, Loc, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after compare value") ||
3497 ParseValue(LHS->getType(), RHS, PFS))
3500 if (Opc == Instruction::FCmp) {
3501 if (!LHS->getType()->isFPOrFPVectorTy())
3502 return Error(Loc, "fcmp requires floating point operands");
3503 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3505 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3506 if (!LHS->getType()->isIntOrIntVectorTy() &&
3507 !LHS->getType()->getScalarType()->isPointerTy())
3508 return Error(Loc, "icmp requires integer operands");
3509 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3514 //===----------------------------------------------------------------------===//
3515 // Other Instructions.
3516 //===----------------------------------------------------------------------===//
3520 /// ::= CastOpc TypeAndValue 'to' Type
3521 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3526 if (ParseTypeAndValue(Op, Loc, PFS) ||
3527 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3531 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3532 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3533 return Error(Loc, "invalid cast opcode for cast from '" +
3534 getTypeString(Op->getType()) + "' to '" +
3535 getTypeString(DestTy) + "'");
3537 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3542 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3543 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3545 Value *Op0, *Op1, *Op2;
3546 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3547 ParseToken(lltok::comma, "expected ',' after select condition") ||
3548 ParseTypeAndValue(Op1, PFS) ||
3549 ParseToken(lltok::comma, "expected ',' after select value") ||
3550 ParseTypeAndValue(Op2, PFS))
3553 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3554 return Error(Loc, Reason);
3556 Inst = SelectInst::Create(Op0, Op1, Op2);
3561 /// ::= 'va_arg' TypeAndValue ',' Type
3562 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3566 if (ParseTypeAndValue(Op, PFS) ||
3567 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3568 ParseType(EltTy, TypeLoc))
3571 if (!EltTy->isFirstClassType())
3572 return Error(TypeLoc, "va_arg requires operand with first class type");
3574 Inst = new VAArgInst(Op, EltTy);
3578 /// ParseExtractElement
3579 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3580 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3583 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' after extract value") ||
3585 ParseTypeAndValue(Op1, PFS))
3588 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3589 return Error(Loc, "invalid extractelement operands");
3591 Inst = ExtractElementInst::Create(Op0, Op1);
3595 /// ParseInsertElement
3596 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3597 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3599 Value *Op0, *Op1, *Op2;
3600 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3601 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3602 ParseTypeAndValue(Op1, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3604 ParseTypeAndValue(Op2, PFS))
3607 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3608 return Error(Loc, "invalid insertelement operands");
3610 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3614 /// ParseShuffleVector
3615 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3616 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3618 Value *Op0, *Op1, *Op2;
3619 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3620 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3621 ParseTypeAndValue(Op1, PFS) ||
3622 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3623 ParseTypeAndValue(Op2, PFS))
3626 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3627 return Error(Loc, "invalid shufflevector operands");
3629 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3634 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3635 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3636 Type *Ty = 0; LocTy TypeLoc;
3639 if (ParseType(Ty, TypeLoc) ||
3640 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3641 ParseValue(Ty, Op0, PFS) ||
3642 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3643 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3644 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3647 bool AteExtraComma = false;
3648 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3650 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3652 if (!EatIfPresent(lltok::comma))
3655 if (Lex.getKind() == lltok::MetadataVar) {
3656 AteExtraComma = true;
3660 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3661 ParseValue(Ty, Op0, PFS) ||
3662 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3663 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3664 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3668 if (!Ty->isFirstClassType())
3669 return Error(TypeLoc, "phi node must have first class type");
3671 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3672 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3673 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3675 return AteExtraComma ? InstExtraComma : InstNormal;
3679 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3681 /// ::= 'catch' TypeAndValue
3683 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3684 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3685 Type *Ty = 0; LocTy TyLoc;
3686 Value *PersFn; LocTy PersFnLoc;
3688 if (ParseType(Ty, TyLoc) ||
3689 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3690 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3693 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3694 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3696 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3697 LandingPadInst::ClauseType CT;
3698 if (EatIfPresent(lltok::kw_catch))
3699 CT = LandingPadInst::Catch;
3700 else if (EatIfPresent(lltok::kw_filter))
3701 CT = LandingPadInst::Filter;
3703 return TokError("expected 'catch' or 'filter' clause type");
3705 Value *V; LocTy VLoc;
3706 if (ParseTypeAndValue(V, VLoc, PFS)) {
3711 // A 'catch' type expects a non-array constant. A filter clause expects an
3713 if (CT == LandingPadInst::Catch) {
3714 if (isa<ArrayType>(V->getType()))
3715 Error(VLoc, "'catch' clause has an invalid type");
3717 if (!isa<ArrayType>(V->getType()))
3718 Error(VLoc, "'filter' clause has an invalid type");
3729 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3730 /// ParameterList OptionalAttrs
3731 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3733 AttrBuilder RetAttrs, FnAttrs;
3738 SmallVector<ParamInfo, 16> ArgList;
3739 LocTy CallLoc = Lex.getLoc();
3741 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3742 ParseOptionalCallingConv(CC) ||
3743 ParseOptionalReturnAttrs(RetAttrs) ||
3744 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3745 ParseValID(CalleeID) ||
3746 ParseParameterList(ArgList, PFS) ||
3747 ParseOptionalFuncAttrs(FnAttrs))
3750 // If RetType is a non-function pointer type, then this is the short syntax
3751 // for the call, which means that RetType is just the return type. Infer the
3752 // rest of the function argument types from the arguments that are present.
3753 PointerType *PFTy = 0;
3754 FunctionType *Ty = 0;
3755 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3756 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3757 // Pull out the types of all of the arguments...
3758 std::vector<Type*> ParamTypes;
3759 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3760 ParamTypes.push_back(ArgList[i].V->getType());
3762 if (!FunctionType::isValidReturnType(RetType))
3763 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3765 Ty = FunctionType::get(RetType, ParamTypes, false);
3766 PFTy = PointerType::getUnqual(Ty);
3769 // Look up the callee.
3771 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3773 // Set up the Attribute for the function.
3774 SmallVector<AttributeSet, 8> Attrs;
3775 if (RetAttrs.hasAttributes())
3776 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3777 AttributeSet::ReturnIndex,
3780 SmallVector<Value*, 8> Args;
3782 // Loop through FunctionType's arguments and ensure they are specified
3783 // correctly. Also, gather any parameter attributes.
3784 FunctionType::param_iterator I = Ty->param_begin();
3785 FunctionType::param_iterator E = Ty->param_end();
3786 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3787 Type *ExpectedTy = 0;
3790 } else if (!Ty->isVarArg()) {
3791 return Error(ArgList[i].Loc, "too many arguments specified");
3794 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3795 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3796 getTypeString(ExpectedTy) + "'");
3797 Args.push_back(ArgList[i].V);
3798 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3799 AttrBuilder B(ArgList[i].Attrs, i + 1);
3800 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3805 return Error(CallLoc, "not enough parameters specified for call");
3807 if (FnAttrs.hasAttributes())
3808 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3809 AttributeSet::FunctionIndex,
3812 // Finish off the Attribute and check them
3813 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3815 CallInst *CI = CallInst::Create(Callee, Args);
3816 CI->setTailCall(isTail);
3817 CI->setCallingConv(CC);
3818 CI->setAttributes(PAL);
3823 //===----------------------------------------------------------------------===//
3824 // Memory Instructions.
3825 //===----------------------------------------------------------------------===//
3828 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3829 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3832 unsigned Alignment = 0;
3834 if (ParseType(Ty)) return true;
3836 bool AteExtraComma = false;
3837 if (EatIfPresent(lltok::comma)) {
3838 if (Lex.getKind() == lltok::kw_align) {
3839 if (ParseOptionalAlignment(Alignment)) return true;
3840 } else if (Lex.getKind() == lltok::MetadataVar) {
3841 AteExtraComma = true;
3843 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3844 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3849 if (Size && !Size->getType()->isIntegerTy())
3850 return Error(SizeLoc, "element count must have integer type");
3852 Inst = new AllocaInst(Ty, Size, Alignment);
3853 return AteExtraComma ? InstExtraComma : InstNormal;
3857 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3858 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3859 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3860 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3861 Value *Val; LocTy Loc;
3862 unsigned Alignment = 0;
3863 bool AteExtraComma = false;
3864 bool isAtomic = false;
3865 AtomicOrdering Ordering = NotAtomic;
3866 SynchronizationScope Scope = CrossThread;
3868 if (Lex.getKind() == lltok::kw_atomic) {
3873 bool isVolatile = false;
3874 if (Lex.getKind() == lltok::kw_volatile) {
3879 if (ParseTypeAndValue(Val, Loc, PFS) ||
3880 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3881 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3884 if (!Val->getType()->isPointerTy() ||
3885 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3886 return Error(Loc, "load operand must be a pointer to a first class type");
3887 if (isAtomic && !Alignment)
3888 return Error(Loc, "atomic load must have explicit non-zero alignment");
3889 if (Ordering == Release || Ordering == AcquireRelease)
3890 return Error(Loc, "atomic load cannot use Release ordering");
3892 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3893 return AteExtraComma ? InstExtraComma : InstNormal;
3898 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3899 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3900 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3901 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3902 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3903 unsigned Alignment = 0;
3904 bool AteExtraComma = false;
3905 bool isAtomic = false;
3906 AtomicOrdering Ordering = NotAtomic;
3907 SynchronizationScope Scope = CrossThread;
3909 if (Lex.getKind() == lltok::kw_atomic) {
3914 bool isVolatile = false;
3915 if (Lex.getKind() == lltok::kw_volatile) {
3920 if (ParseTypeAndValue(Val, Loc, PFS) ||
3921 ParseToken(lltok::comma, "expected ',' after store operand") ||
3922 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3923 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3924 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3927 if (!Ptr->getType()->isPointerTy())
3928 return Error(PtrLoc, "store operand must be a pointer");
3929 if (!Val->getType()->isFirstClassType())
3930 return Error(Loc, "store operand must be a first class value");
3931 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3932 return Error(Loc, "stored value and pointer type do not match");
3933 if (isAtomic && !Alignment)
3934 return Error(Loc, "atomic store must have explicit non-zero alignment");
3935 if (Ordering == Acquire || Ordering == AcquireRelease)
3936 return Error(Loc, "atomic store cannot use Acquire ordering");
3938 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3939 return AteExtraComma ? InstExtraComma : InstNormal;
3943 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3944 /// 'singlethread'? AtomicOrdering
3945 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3946 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3947 bool AteExtraComma = false;
3948 AtomicOrdering Ordering = NotAtomic;
3949 SynchronizationScope Scope = CrossThread;
3950 bool isVolatile = false;
3952 if (EatIfPresent(lltok::kw_volatile))
3955 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3956 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3957 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3958 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3959 ParseTypeAndValue(New, NewLoc, PFS) ||
3960 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3963 if (Ordering == Unordered)
3964 return TokError("cmpxchg cannot be unordered");
3965 if (!Ptr->getType()->isPointerTy())
3966 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3967 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3968 return Error(CmpLoc, "compare value and pointer type do not match");
3969 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3970 return Error(NewLoc, "new value and pointer type do not match");
3971 if (!New->getType()->isIntegerTy())
3972 return Error(NewLoc, "cmpxchg operand must be an integer");
3973 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3974 if (Size < 8 || (Size & (Size - 1)))
3975 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3978 AtomicCmpXchgInst *CXI =
3979 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3980 CXI->setVolatile(isVolatile);
3982 return AteExtraComma ? InstExtraComma : InstNormal;
3986 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3987 /// 'singlethread'? AtomicOrdering
3988 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3989 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3990 bool AteExtraComma = false;
3991 AtomicOrdering Ordering = NotAtomic;
3992 SynchronizationScope Scope = CrossThread;
3993 bool isVolatile = false;
3994 AtomicRMWInst::BinOp Operation;
3996 if (EatIfPresent(lltok::kw_volatile))
3999 switch (Lex.getKind()) {
4000 default: return TokError("expected binary operation in atomicrmw");
4001 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4002 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4003 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4004 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4005 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4006 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4007 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4008 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4009 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4010 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4011 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4013 Lex.Lex(); // Eat the operation.
4015 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4016 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4017 ParseTypeAndValue(Val, ValLoc, PFS) ||
4018 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4021 if (Ordering == Unordered)
4022 return TokError("atomicrmw cannot be unordered");
4023 if (!Ptr->getType()->isPointerTy())
4024 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4025 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4026 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4027 if (!Val->getType()->isIntegerTy())
4028 return Error(ValLoc, "atomicrmw operand must be an integer");
4029 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4030 if (Size < 8 || (Size & (Size - 1)))
4031 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4034 AtomicRMWInst *RMWI =
4035 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4036 RMWI->setVolatile(isVolatile);
4038 return AteExtraComma ? InstExtraComma : InstNormal;
4042 /// ::= 'fence' 'singlethread'? AtomicOrdering
4043 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4044 AtomicOrdering Ordering = NotAtomic;
4045 SynchronizationScope Scope = CrossThread;
4046 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4049 if (Ordering == Unordered)
4050 return TokError("fence cannot be unordered");
4051 if (Ordering == Monotonic)
4052 return TokError("fence cannot be monotonic");
4054 Inst = new FenceInst(Context, Ordering, Scope);
4058 /// ParseGetElementPtr
4059 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4060 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4065 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4067 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4069 if (!Ptr->getType()->getScalarType()->isPointerTy())
4070 return Error(Loc, "base of getelementptr must be a pointer");
4072 SmallVector<Value*, 16> Indices;
4073 bool AteExtraComma = false;
4074 while (EatIfPresent(lltok::comma)) {
4075 if (Lex.getKind() == lltok::MetadataVar) {
4076 AteExtraComma = true;
4079 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4080 if (!Val->getType()->getScalarType()->isIntegerTy())
4081 return Error(EltLoc, "getelementptr index must be an integer");
4082 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4083 return Error(EltLoc, "getelementptr index type missmatch");
4084 if (Val->getType()->isVectorTy()) {
4085 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4086 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4087 if (ValNumEl != PtrNumEl)
4088 return Error(EltLoc,
4089 "getelementptr vector index has a wrong number of elements");
4091 Indices.push_back(Val);
4094 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4095 return Error(Loc, "invalid getelementptr indices");
4096 Inst = GetElementPtrInst::Create(Ptr, Indices);
4098 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4099 return AteExtraComma ? InstExtraComma : InstNormal;
4102 /// ParseExtractValue
4103 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4104 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4105 Value *Val; LocTy Loc;
4106 SmallVector<unsigned, 4> Indices;
4108 if (ParseTypeAndValue(Val, Loc, PFS) ||
4109 ParseIndexList(Indices, AteExtraComma))
4112 if (!Val->getType()->isAggregateType())
4113 return Error(Loc, "extractvalue operand must be aggregate type");
4115 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4116 return Error(Loc, "invalid indices for extractvalue");
4117 Inst = ExtractValueInst::Create(Val, Indices);
4118 return AteExtraComma ? InstExtraComma : InstNormal;
4121 /// ParseInsertValue
4122 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4123 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4124 Value *Val0, *Val1; LocTy Loc0, Loc1;
4125 SmallVector<unsigned, 4> Indices;
4127 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4128 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4129 ParseTypeAndValue(Val1, Loc1, PFS) ||
4130 ParseIndexList(Indices, AteExtraComma))
4133 if (!Val0->getType()->isAggregateType())
4134 return Error(Loc0, "insertvalue operand must be aggregate type");
4136 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4137 return Error(Loc0, "invalid indices for insertvalue");
4138 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4139 return AteExtraComma ? InstExtraComma : InstNormal;
4142 //===----------------------------------------------------------------------===//
4143 // Embedded metadata.
4144 //===----------------------------------------------------------------------===//
4146 /// ParseMDNodeVector
4147 /// ::= Element (',' Element)*
4149 /// ::= 'null' | TypeAndValue
4150 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4151 PerFunctionState *PFS) {
4152 // Check for an empty list.
4153 if (Lex.getKind() == lltok::rbrace)
4157 // Null is a special case since it is typeless.
4158 if (EatIfPresent(lltok::kw_null)) {
4164 if (ParseTypeAndValue(V, PFS)) return true;
4166 } while (EatIfPresent(lltok::comma));