1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(const 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());
93 if (!ForwardRefTypes.empty())
94 return Error(ForwardRefTypes.begin()->second.second,
95 "use of undefined type named '" +
96 ForwardRefTypes.begin()->first + "'");
97 if (!ForwardRefTypeIDs.empty())
98 return Error(ForwardRefTypeIDs.begin()->second.second,
99 "use of undefined type '%" +
100 Twine(ForwardRefTypeIDs.begin()->first) + "'");
102 if (!ForwardRefVals.empty())
103 return Error(ForwardRefVals.begin()->second.second,
104 "use of undefined value '@" + ForwardRefVals.begin()->first +
107 if (!ForwardRefValIDs.empty())
108 return Error(ForwardRefValIDs.begin()->second.second,
109 "use of undefined value '@" +
110 Twine(ForwardRefValIDs.begin()->first) + "'");
112 if (!ForwardRefMDNodes.empty())
113 return Error(ForwardRefMDNodes.begin()->second.second,
114 "use of undefined metadata '!" +
115 Twine(ForwardRefMDNodes.begin()->first) + "'");
118 // Look for intrinsic functions and CallInst that need to be upgraded
119 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
120 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
122 // Check debug info intrinsics.
123 CheckDebugInfoIntrinsics(M);
127 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
128 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
129 PerFunctionState *PFS) {
130 // Loop over all the references, resolving them.
131 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
134 if (Refs[i].first.Kind == ValID::t_LocalName)
135 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
137 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
138 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
139 return Error(Refs[i].first.Loc,
140 "cannot take address of numeric label after the function is defined");
142 Res = dyn_cast_or_null<BasicBlock>(
143 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
147 return Error(Refs[i].first.Loc,
148 "referenced value is not a basic block");
150 // Get the BlockAddress for this and update references to use it.
151 BlockAddress *BA = BlockAddress::get(TheFn, Res);
152 Refs[i].second->replaceAllUsesWith(BA);
153 Refs[i].second->eraseFromParent();
159 //===----------------------------------------------------------------------===//
160 // Top-Level Entities
161 //===----------------------------------------------------------------------===//
163 bool LLParser::ParseTopLevelEntities() {
165 switch (Lex.getKind()) {
166 default: return TokError("expected top-level entity");
167 case lltok::Eof: return false;
168 case lltok::kw_declare: if (ParseDeclare()) return true; break;
169 case lltok::kw_define: if (ParseDefine()) return true; break;
170 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
171 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
172 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
173 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
174 case lltok::LocalVar: if (ParseNamedType()) return true; break;
175 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
176 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
177 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
178 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
180 // The Global variable production with no name can have many different
181 // optional leading prefixes, the production is:
182 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
183 // OptionalAddrSpace OptionalUnNammedAddr
184 // ('constant'|'global') ...
185 case lltok::kw_private: // OptionalLinkage
186 case lltok::kw_linker_private: // OptionalLinkage
187 case lltok::kw_linker_private_weak: // OptionalLinkage
188 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
189 case lltok::kw_internal: // OptionalLinkage
190 case lltok::kw_weak: // OptionalLinkage
191 case lltok::kw_weak_odr: // OptionalLinkage
192 case lltok::kw_linkonce: // OptionalLinkage
193 case lltok::kw_linkonce_odr: // 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 bool LLParser::ParseDepLibs() {
271 assert(Lex.getKind() == lltok::kw_deplibs);
273 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
274 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
277 if (EatIfPresent(lltok::rsquare))
281 if (ParseStringConstant(Str)) return true;
284 while (EatIfPresent(lltok::comma)) {
285 if (ParseStringConstant(Str)) return true;
289 return ParseToken(lltok::rsquare, "expected ']' at end of list");
292 /// ParseUnnamedType:
293 /// ::= LocalVarID '=' 'type' type
294 bool LLParser::ParseUnnamedType() {
295 LocTy TypeLoc = Lex.getLoc();
296 unsigned TypeID = NumberedTypes.size();
297 if (Lex.getUIntVal() != TypeID)
298 return Error(Lex.getLoc(), "type expected to be numbered '%" +
299 Twine(TypeID) + "'");
300 Lex.Lex(); // eat LocalVarID;
302 if (ParseToken(lltok::equal, "expected '=' after name") ||
303 ParseToken(lltok::kw_type, "expected 'type' after '='"))
306 PATypeHolder Ty(Type::getVoidTy(Context));
307 if (ParseType(Ty)) return true;
309 // See if this type was previously referenced.
310 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
311 FI = ForwardRefTypeIDs.find(TypeID);
312 if (FI != ForwardRefTypeIDs.end()) {
313 if (FI->second.first.get() == Ty)
314 return Error(TypeLoc, "self referential type is invalid");
316 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
317 Ty = FI->second.first.get();
318 ForwardRefTypeIDs.erase(FI);
321 NumberedTypes.push_back(Ty);
327 /// ::= LocalVar '=' 'type' type
328 bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
331 Lex.Lex(); // eat LocalVar.
333 PATypeHolder Ty(Type::getVoidTy(Context));
335 if (ParseToken(lltok::equal, "expected '=' after name") ||
336 ParseToken(lltok::kw_type, "expected 'type' after name") ||
340 // Set the type name, checking for conflicts as we do so.
341 bool AlreadyExists = M->addTypeName(Name, Ty);
342 if (!AlreadyExists) return false;
344 // See if this type is a forward reference. We need to eagerly resolve
345 // types to allow recursive type redefinitions below.
346 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
347 FI = ForwardRefTypes.find(Name);
348 if (FI != ForwardRefTypes.end()) {
349 if (FI->second.first.get() == Ty)
350 return Error(NameLoc, "self referential type is invalid");
352 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
353 Ty = FI->second.first.get();
354 ForwardRefTypes.erase(FI);
358 // Inserting a name that is already defined, get the existing name.
359 assert(M->getTypeByName(Name) && "Conflict but no matching type?!");
361 // Otherwise, this is an attempt to redefine a type, report the error.
362 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
363 getTypeString(Ty) + "'");
368 /// ::= 'declare' FunctionHeader
369 bool LLParser::ParseDeclare() {
370 assert(Lex.getKind() == lltok::kw_declare);
374 return ParseFunctionHeader(F, false);
378 /// ::= 'define' FunctionHeader '{' ...
379 bool LLParser::ParseDefine() {
380 assert(Lex.getKind() == lltok::kw_define);
384 return ParseFunctionHeader(F, true) ||
385 ParseFunctionBody(*F);
391 bool LLParser::ParseGlobalType(bool &IsConstant) {
392 if (Lex.getKind() == lltok::kw_constant)
394 else if (Lex.getKind() == lltok::kw_global)
398 return TokError("expected 'global' or 'constant'");
404 /// ParseUnnamedGlobal:
405 /// OptionalVisibility ALIAS ...
406 /// OptionalLinkage OptionalVisibility ... -> global variable
407 /// GlobalID '=' OptionalVisibility ALIAS ...
408 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
409 bool LLParser::ParseUnnamedGlobal() {
410 unsigned VarID = NumberedVals.size();
412 LocTy NameLoc = Lex.getLoc();
414 // Handle the GlobalID form.
415 if (Lex.getKind() == lltok::GlobalID) {
416 if (Lex.getUIntVal() != VarID)
417 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
419 Lex.Lex(); // eat GlobalID;
421 if (ParseToken(lltok::equal, "expected '=' after name"))
426 unsigned Linkage, Visibility;
427 if (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);
436 /// ParseNamedGlobal:
437 /// GlobalVar '=' OptionalVisibility ALIAS ...
438 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
439 bool LLParser::ParseNamedGlobal() {
440 assert(Lex.getKind() == lltok::GlobalVar);
441 LocTy NameLoc = Lex.getLoc();
442 std::string Name = Lex.getStrVal();
446 unsigned Linkage, Visibility;
447 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
448 ParseOptionalLinkage(Linkage, HasLinkage) ||
449 ParseOptionalVisibility(Visibility))
452 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
454 return ParseAlias(Name, NameLoc, Visibility);
458 // ::= '!' STRINGCONSTANT
459 bool LLParser::ParseMDString(MDString *&Result) {
461 if (ParseStringConstant(Str)) return true;
462 Result = MDString::get(Context, Str);
467 // ::= '!' MDNodeNumber
469 /// This version of ParseMDNodeID returns the slot number and null in the case
470 /// of a forward reference.
471 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
472 // !{ ..., !42, ... }
473 if (ParseUInt32(SlotNo)) return true;
475 // Check existing MDNode.
476 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
477 Result = NumberedMetadata[SlotNo];
483 bool LLParser::ParseMDNodeID(MDNode *&Result) {
484 // !{ ..., !42, ... }
486 if (ParseMDNodeID(Result, MID)) return true;
488 // If not a forward reference, just return it now.
489 if (Result) return false;
491 // Otherwise, create MDNode forward reference.
492 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
493 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
495 if (NumberedMetadata.size() <= MID)
496 NumberedMetadata.resize(MID+1);
497 NumberedMetadata[MID] = FwdNode;
502 /// ParseNamedMetadata:
503 /// !foo = !{ !1, !2 }
504 bool LLParser::ParseNamedMetadata() {
505 assert(Lex.getKind() == lltok::MetadataVar);
506 std::string Name = Lex.getStrVal();
509 if (ParseToken(lltok::equal, "expected '=' here") ||
510 ParseToken(lltok::exclaim, "Expected '!' here") ||
511 ParseToken(lltok::lbrace, "Expected '{' here"))
514 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
515 if (Lex.getKind() != lltok::rbrace)
517 if (ParseToken(lltok::exclaim, "Expected '!' here"))
521 if (ParseMDNodeID(N)) return true;
523 } while (EatIfPresent(lltok::comma));
525 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
531 /// ParseStandaloneMetadata:
533 bool LLParser::ParseStandaloneMetadata() {
534 assert(Lex.getKind() == lltok::exclaim);
536 unsigned MetadataID = 0;
539 PATypeHolder Ty(Type::getVoidTy(Context));
540 SmallVector<Value *, 16> Elts;
541 if (ParseUInt32(MetadataID) ||
542 ParseToken(lltok::equal, "expected '=' here") ||
543 ParseType(Ty, TyLoc) ||
544 ParseToken(lltok::exclaim, "Expected '!' here") ||
545 ParseToken(lltok::lbrace, "Expected '{' here") ||
546 ParseMDNodeVector(Elts, NULL) ||
547 ParseToken(lltok::rbrace, "expected end of metadata node"))
550 MDNode *Init = MDNode::get(Context, Elts);
552 // See if this was forward referenced, if so, handle it.
553 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
554 FI = ForwardRefMDNodes.find(MetadataID);
555 if (FI != ForwardRefMDNodes.end()) {
556 MDNode *Temp = FI->second.first;
557 Temp->replaceAllUsesWith(Init);
558 MDNode::deleteTemporary(Temp);
559 ForwardRefMDNodes.erase(FI);
561 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
563 if (MetadataID >= NumberedMetadata.size())
564 NumberedMetadata.resize(MetadataID+1);
566 if (NumberedMetadata[MetadataID] != 0)
567 return TokError("Metadata id is already used");
568 NumberedMetadata[MetadataID] = Init;
575 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
578 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
579 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
581 /// Everything through visibility has already been parsed.
583 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
584 unsigned Visibility) {
585 assert(Lex.getKind() == lltok::kw_alias);
588 LocTy LinkageLoc = Lex.getLoc();
589 if (ParseOptionalLinkage(Linkage))
592 if (Linkage != GlobalValue::ExternalLinkage &&
593 Linkage != GlobalValue::WeakAnyLinkage &&
594 Linkage != GlobalValue::WeakODRLinkage &&
595 Linkage != GlobalValue::InternalLinkage &&
596 Linkage != GlobalValue::PrivateLinkage &&
597 Linkage != GlobalValue::LinkerPrivateLinkage &&
598 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
599 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
600 return Error(LinkageLoc, "invalid linkage type for alias");
603 LocTy AliaseeLoc = Lex.getLoc();
604 if (Lex.getKind() != lltok::kw_bitcast &&
605 Lex.getKind() != lltok::kw_getelementptr) {
606 if (ParseGlobalTypeAndValue(Aliasee)) return true;
608 // The bitcast dest type is not present, it is implied by the dest type.
610 if (ParseValID(ID)) return true;
611 if (ID.Kind != ValID::t_Constant)
612 return Error(AliaseeLoc, "invalid aliasee");
613 Aliasee = ID.ConstantVal;
616 if (!Aliasee->getType()->isPointerTy())
617 return Error(AliaseeLoc, "alias must have pointer type");
619 // Okay, create the alias but do not insert it into the module yet.
620 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
621 (GlobalValue::LinkageTypes)Linkage, Name,
623 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
625 // See if this value already exists in the symbol table. If so, it is either
626 // a redefinition or a definition of a forward reference.
627 if (GlobalValue *Val = M->getNamedValue(Name)) {
628 // See if this was a redefinition. If so, there is no entry in
630 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
631 I = ForwardRefVals.find(Name);
632 if (I == ForwardRefVals.end())
633 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
635 // Otherwise, this was a definition of forward ref. Verify that types
637 if (Val->getType() != GA->getType())
638 return Error(NameLoc,
639 "forward reference and definition of alias have different types");
641 // If they agree, just RAUW the old value with the alias and remove the
643 Val->replaceAllUsesWith(GA);
644 Val->eraseFromParent();
645 ForwardRefVals.erase(I);
648 // Insert into the module, we know its name won't collide now.
649 M->getAliasList().push_back(GA);
650 assert(GA->getName() == Name && "Should not be a name conflict!");
656 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
657 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
658 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
659 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
661 /// Everything through visibility has been parsed already.
663 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
664 unsigned Linkage, bool HasLinkage,
665 unsigned Visibility) {
667 bool ThreadLocal, IsConstant, UnnamedAddr;
668 LocTy UnnamedAddrLoc;
671 PATypeHolder Ty(Type::getVoidTy(Context));
672 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
673 ParseOptionalAddrSpace(AddrSpace) ||
674 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
676 ParseGlobalType(IsConstant) ||
677 ParseType(Ty, TyLoc))
680 // If the linkage is specified and is external, then no initializer is
683 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
684 Linkage != GlobalValue::ExternalWeakLinkage &&
685 Linkage != GlobalValue::ExternalLinkage)) {
686 if (ParseGlobalValue(Ty, Init))
690 if (Ty->isFunctionTy() || Ty->isLabelTy())
691 return Error(TyLoc, "invalid type for global variable");
693 GlobalVariable *GV = 0;
695 // See if the global was forward referenced, if so, use the global.
697 if (GlobalValue *GVal = M->getNamedValue(Name)) {
698 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
699 return Error(NameLoc, "redefinition of global '@" + Name + "'");
700 GV = cast<GlobalVariable>(GVal);
703 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
704 I = ForwardRefValIDs.find(NumberedVals.size());
705 if (I != ForwardRefValIDs.end()) {
706 GV = cast<GlobalVariable>(I->second.first);
707 ForwardRefValIDs.erase(I);
712 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
713 Name, 0, false, AddrSpace);
715 if (GV->getType()->getElementType() != Ty)
717 "forward reference and definition of global have different types");
719 // Move the forward-reference to the correct spot in the module.
720 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
724 NumberedVals.push_back(GV);
726 // Set the parsed properties on the global.
728 GV->setInitializer(Init);
729 GV->setConstant(IsConstant);
730 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
731 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
732 GV->setThreadLocal(ThreadLocal);
733 GV->setUnnamedAddr(UnnamedAddr);
735 // Parse attributes on the global.
736 while (Lex.getKind() == lltok::comma) {
739 if (Lex.getKind() == lltok::kw_section) {
741 GV->setSection(Lex.getStrVal());
742 if (ParseToken(lltok::StringConstant, "expected global section string"))
744 } else if (Lex.getKind() == lltok::kw_align) {
746 if (ParseOptionalAlignment(Alignment)) return true;
747 GV->setAlignment(Alignment);
749 TokError("unknown global variable property!");
757 //===----------------------------------------------------------------------===//
758 // GlobalValue Reference/Resolution Routines.
759 //===----------------------------------------------------------------------===//
761 /// GetGlobalVal - Get a value with the specified name or ID, creating a
762 /// forward reference record if needed. This can return null if the value
763 /// exists but does not have the right type.
764 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
766 const PointerType *PTy = dyn_cast<PointerType>(Ty);
768 Error(Loc, "global variable reference must have pointer type");
772 // Look this name up in the normal function symbol table.
774 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
776 // If this is a forward reference for the value, see if we already created a
777 // forward ref record.
779 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
780 I = ForwardRefVals.find(Name);
781 if (I != ForwardRefVals.end())
782 Val = I->second.first;
785 // If we have the value in the symbol table or fwd-ref table, return it.
787 if (Val->getType() == Ty) return Val;
788 Error(Loc, "'@" + Name + "' defined with type '" +
789 getTypeString(Val->getType()) + "'");
793 // Otherwise, create a new forward reference for this value and remember it.
795 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
796 // Function types can return opaque but functions can't.
797 if (FT->getReturnType()->isOpaqueTy()) {
798 Error(Loc, "function may not return opaque type");
802 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
804 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
805 GlobalValue::ExternalWeakLinkage, 0, Name);
808 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
812 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
813 const PointerType *PTy = dyn_cast<PointerType>(Ty);
815 Error(Loc, "global variable reference must have pointer type");
819 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
821 // If this is a forward reference for the value, see if we already created a
822 // forward ref record.
824 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
825 I = ForwardRefValIDs.find(ID);
826 if (I != ForwardRefValIDs.end())
827 Val = I->second.first;
830 // If we have the value in the symbol table or fwd-ref table, return it.
832 if (Val->getType() == Ty) return Val;
833 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
834 getTypeString(Val->getType()) + "'");
838 // Otherwise, create a new forward reference for this value and remember it.
840 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
841 // Function types can return opaque but functions can't.
842 if (FT->getReturnType()->isOpaqueTy()) {
843 Error(Loc, "function may not return opaque type");
846 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
848 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
849 GlobalValue::ExternalWeakLinkage, 0, "");
852 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
857 //===----------------------------------------------------------------------===//
859 //===----------------------------------------------------------------------===//
861 /// ParseToken - If the current token has the specified kind, eat it and return
862 /// success. Otherwise, emit the specified error and return failure.
863 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
864 if (Lex.getKind() != T)
865 return TokError(ErrMsg);
870 /// ParseStringConstant
871 /// ::= StringConstant
872 bool LLParser::ParseStringConstant(std::string &Result) {
873 if (Lex.getKind() != lltok::StringConstant)
874 return TokError("expected string constant");
875 Result = Lex.getStrVal();
882 bool LLParser::ParseUInt32(unsigned &Val) {
883 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
884 return TokError("expected integer");
885 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
886 if (Val64 != unsigned(Val64))
887 return TokError("expected 32-bit integer (too large)");
894 /// ParseOptionalAddrSpace
896 /// := 'addrspace' '(' uint32 ')'
897 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
899 if (!EatIfPresent(lltok::kw_addrspace))
901 return ParseToken(lltok::lparen, "expected '(' in address space") ||
902 ParseUInt32(AddrSpace) ||
903 ParseToken(lltok::rparen, "expected ')' in address space");
906 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
907 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
908 /// 2: function attr.
909 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
910 Attrs = Attribute::None;
911 LocTy AttrLoc = Lex.getLoc();
914 switch (Lex.getKind()) {
915 default: // End of attributes.
916 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
917 return Error(AttrLoc, "invalid use of function-only attribute");
919 // As a hack, we allow "align 2" on functions as a synonym for
922 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
923 return Error(AttrLoc, "invalid use of attribute on a function");
925 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
926 return Error(AttrLoc, "invalid use of parameter-only attribute");
929 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
930 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
931 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
932 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
933 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
934 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
935 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
936 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
938 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
939 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
940 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
941 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
942 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
943 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
944 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
945 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
946 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
947 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
948 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
949 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
950 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
951 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
952 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
953 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
955 case lltok::kw_alignstack: {
957 if (ParseOptionalStackAlignment(Alignment))
959 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
963 case lltok::kw_align: {
965 if (ParseOptionalAlignment(Alignment))
967 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
976 /// ParseOptionalLinkage
979 /// ::= 'linker_private'
980 /// ::= 'linker_private_weak'
981 /// ::= 'linker_private_weak_def_auto'
986 /// ::= 'linkonce_odr'
987 /// ::= 'available_externally'
992 /// ::= 'extern_weak'
994 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
996 switch (Lex.getKind()) {
997 default: Res=GlobalValue::ExternalLinkage; return false;
998 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
999 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1000 case lltok::kw_linker_private_weak:
1001 Res = GlobalValue::LinkerPrivateWeakLinkage;
1003 case lltok::kw_linker_private_weak_def_auto:
1004 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1006 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1007 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1008 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1009 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1010 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1011 case lltok::kw_available_externally:
1012 Res = GlobalValue::AvailableExternallyLinkage;
1014 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1015 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1016 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1017 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1018 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1019 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1026 /// ParseOptionalVisibility
1032 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1033 switch (Lex.getKind()) {
1034 default: Res = GlobalValue::DefaultVisibility; return false;
1035 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1036 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1037 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1043 /// ParseOptionalCallingConv
1048 /// ::= 'x86_stdcallcc'
1049 /// ::= 'x86_fastcallcc'
1050 /// ::= 'x86_thiscallcc'
1051 /// ::= 'arm_apcscc'
1052 /// ::= 'arm_aapcscc'
1053 /// ::= 'arm_aapcs_vfpcc'
1054 /// ::= 'msp430_intrcc'
1055 /// ::= 'ptx_kernel'
1056 /// ::= 'ptx_device'
1059 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1060 switch (Lex.getKind()) {
1061 default: CC = CallingConv::C; return false;
1062 case lltok::kw_ccc: CC = CallingConv::C; break;
1063 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1064 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1065 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1066 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1067 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1068 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1069 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1070 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1071 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1072 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1073 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1074 case lltok::kw_cc: {
1075 unsigned ArbitraryCC;
1077 if (ParseUInt32(ArbitraryCC)) {
1080 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1090 /// ParseInstructionMetadata
1091 /// ::= !dbg !42 (',' !dbg !57)*
1092 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1093 PerFunctionState *PFS) {
1095 if (Lex.getKind() != lltok::MetadataVar)
1096 return TokError("expected metadata after comma");
1098 std::string Name = Lex.getStrVal();
1099 unsigned MDK = M->getMDKindID(Name.c_str());
1103 SMLoc Loc = Lex.getLoc();
1105 if (ParseToken(lltok::exclaim, "expected '!' here"))
1108 // This code is similar to that of ParseMetadataValue, however it needs to
1109 // have special-case code for a forward reference; see the comments on
1110 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1111 // at the top level here.
1112 if (Lex.getKind() == lltok::lbrace) {
1114 if (ParseMetadataListValue(ID, PFS))
1116 assert(ID.Kind == ValID::t_MDNode);
1117 Inst->setMetadata(MDK, ID.MDNodeVal);
1119 unsigned NodeID = 0;
1120 if (ParseMDNodeID(Node, NodeID))
1123 // If we got the node, add it to the instruction.
1124 Inst->setMetadata(MDK, Node);
1126 MDRef R = { Loc, MDK, NodeID };
1127 // Otherwise, remember that this should be resolved later.
1128 ForwardRefInstMetadata[Inst].push_back(R);
1132 // If this is the end of the list, we're done.
1133 } while (EatIfPresent(lltok::comma));
1137 /// ParseOptionalAlignment
1140 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1142 if (!EatIfPresent(lltok::kw_align))
1144 LocTy AlignLoc = Lex.getLoc();
1145 if (ParseUInt32(Alignment)) return true;
1146 if (!isPowerOf2_32(Alignment))
1147 return Error(AlignLoc, "alignment is not a power of two");
1148 if (Alignment > Value::MaximumAlignment)
1149 return Error(AlignLoc, "huge alignments are not supported yet");
1153 /// ParseOptionalCommaAlign
1157 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1159 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1160 bool &AteExtraComma) {
1161 AteExtraComma = false;
1162 while (EatIfPresent(lltok::comma)) {
1163 // Metadata at the end is an early exit.
1164 if (Lex.getKind() == lltok::MetadataVar) {
1165 AteExtraComma = true;
1169 if (Lex.getKind() != lltok::kw_align)
1170 return Error(Lex.getLoc(), "expected metadata or 'align'");
1172 if (ParseOptionalAlignment(Alignment)) return true;
1178 /// ParseOptionalStackAlignment
1180 /// ::= 'alignstack' '(' 4 ')'
1181 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1183 if (!EatIfPresent(lltok::kw_alignstack))
1185 LocTy ParenLoc = Lex.getLoc();
1186 if (!EatIfPresent(lltok::lparen))
1187 return Error(ParenLoc, "expected '('");
1188 LocTy AlignLoc = Lex.getLoc();
1189 if (ParseUInt32(Alignment)) return true;
1190 ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::rparen))
1192 return Error(ParenLoc, "expected ')'");
1193 if (!isPowerOf2_32(Alignment))
1194 return Error(AlignLoc, "stack alignment is not a power of two");
1198 /// ParseIndexList - This parses the index list for an insert/extractvalue
1199 /// instruction. This sets AteExtraComma in the case where we eat an extra
1200 /// comma at the end of the line and find that it is followed by metadata.
1201 /// Clients that don't allow metadata can call the version of this function that
1202 /// only takes one argument.
1205 /// ::= (',' uint32)+
1207 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1208 bool &AteExtraComma) {
1209 AteExtraComma = false;
1211 if (Lex.getKind() != lltok::comma)
1212 return TokError("expected ',' as start of index list");
1214 while (EatIfPresent(lltok::comma)) {
1215 if (Lex.getKind() == lltok::MetadataVar) {
1216 AteExtraComma = true;
1220 if (ParseUInt32(Idx)) return true;
1221 Indices.push_back(Idx);
1227 //===----------------------------------------------------------------------===//
1229 //===----------------------------------------------------------------------===//
1231 /// ParseType - Parse and resolve a full type.
1232 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1233 LocTy TypeLoc = Lex.getLoc();
1234 if (ParseTypeRec(Result)) return true;
1236 // Verify no unresolved uprefs.
1237 if (!UpRefs.empty())
1238 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1240 if (!AllowVoid && Result.get()->isVoidTy())
1241 return Error(TypeLoc, "void type only allowed for function results");
1246 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1247 /// called. It loops through the UpRefs vector, which is a list of the
1248 /// currently active types. For each type, if the up-reference is contained in
1249 /// the newly completed type, we decrement the level count. When the level
1250 /// count reaches zero, the up-referenced type is the type that is passed in:
1251 /// thus we can complete the cycle.
1253 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1254 // If Ty isn't abstract, or if there are no up-references in it, then there is
1255 // nothing to resolve here.
1256 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1258 PATypeHolder Ty(ty);
1260 dbgs() << "Type '" << *Ty
1261 << "' newly formed. Resolving upreferences.\n"
1262 << UpRefs.size() << " upreferences active!\n";
1265 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1266 // to zero), we resolve them all together before we resolve them to Ty. At
1267 // the end of the loop, if there is anything to resolve to Ty, it will be in
1269 OpaqueType *TypeToResolve = 0;
1271 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1272 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1274 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1275 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1278 dbgs() << " UR#" << i << " - TypeContains(" << *Ty << ", "
1279 << *UpRefs[i].LastContainedTy << ") = "
1280 << (ContainsType ? "true" : "false")
1281 << " level=" << UpRefs[i].NestingLevel << "\n";
1286 // Decrement level of upreference
1287 unsigned Level = --UpRefs[i].NestingLevel;
1288 UpRefs[i].LastContainedTy = Ty;
1290 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1295 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1298 TypeToResolve = UpRefs[i].UpRefTy;
1300 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1301 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1302 --i; // Do not skip the next element.
1306 TypeToResolve->refineAbstractTypeTo(Ty);
1312 /// ParseTypeRec - The recursive function used to process the internal
1313 /// implementation details of types.
1314 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1315 switch (Lex.getKind()) {
1317 return TokError("expected type");
1319 // TypeRec ::= 'float' | 'void' (etc)
1320 Result = Lex.getTyVal();
1323 case lltok::kw_opaque:
1324 // TypeRec ::= 'opaque'
1325 Result = OpaqueType::get(Context);
1329 // TypeRec ::= '{' ... '}'
1330 if (ParseStructType(Result, false))
1333 case lltok::lsquare:
1334 // TypeRec ::= '[' ... ']'
1335 Lex.Lex(); // eat the lsquare.
1336 if (ParseArrayVectorType(Result, false))
1339 case lltok::less: // Either vector or packed struct.
1340 // TypeRec ::= '<' ... '>'
1342 if (Lex.getKind() == lltok::lbrace) {
1343 if (ParseStructType(Result, true) ||
1344 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1346 } else if (ParseArrayVectorType(Result, true))
1349 case lltok::LocalVar:
1351 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1354 Result = OpaqueType::get(Context);
1355 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1356 std::make_pair(Result,
1358 M->addTypeName(Lex.getStrVal(), Result.get());
1363 case lltok::LocalVarID:
1365 if (Lex.getUIntVal() < NumberedTypes.size())
1366 Result = NumberedTypes[Lex.getUIntVal()];
1368 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1369 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1370 if (I != ForwardRefTypeIDs.end())
1371 Result = I->second.first;
1373 Result = OpaqueType::get(Context);
1374 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1375 std::make_pair(Result,
1381 case lltok::backslash: {
1382 // TypeRec ::= '\' 4
1385 if (ParseUInt32(Val)) return true;
1386 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1387 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1393 // Parse the type suffixes.
1395 switch (Lex.getKind()) {
1397 default: return false;
1399 // TypeRec ::= TypeRec '*'
1401 if (Result.get()->isLabelTy())
1402 return TokError("basic block pointers are invalid");
1403 if (Result.get()->isVoidTy())
1404 return TokError("pointers to void are invalid; use i8* instead");
1405 if (!PointerType::isValidElementType(Result.get()))
1406 return TokError("pointer to this type is invalid");
1407 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1411 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1412 case lltok::kw_addrspace: {
1413 if (Result.get()->isLabelTy())
1414 return TokError("basic block pointers are invalid");
1415 if (Result.get()->isVoidTy())
1416 return TokError("pointers to void are invalid; use i8* instead");
1417 if (!PointerType::isValidElementType(Result.get()))
1418 return TokError("pointer to this type is invalid");
1420 if (ParseOptionalAddrSpace(AddrSpace) ||
1421 ParseToken(lltok::star, "expected '*' in address space"))
1424 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1428 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1430 if (ParseFunctionType(Result))
1437 /// ParseParameterList
1439 /// ::= '(' Arg (',' Arg)* ')'
1441 /// ::= Type OptionalAttributes Value OptionalAttributes
1442 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1443 PerFunctionState &PFS) {
1444 if (ParseToken(lltok::lparen, "expected '(' in call"))
1447 while (Lex.getKind() != lltok::rparen) {
1448 // If this isn't the first argument, we need a comma.
1449 if (!ArgList.empty() &&
1450 ParseToken(lltok::comma, "expected ',' in argument list"))
1453 // Parse the argument.
1455 PATypeHolder ArgTy(Type::getVoidTy(Context));
1456 unsigned ArgAttrs1 = Attribute::None;
1457 unsigned ArgAttrs2 = Attribute::None;
1459 if (ParseType(ArgTy, ArgLoc))
1462 // Otherwise, handle normal operands.
1463 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1465 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1468 Lex.Lex(); // Lex the ')'.
1474 /// ParseArgumentList - Parse the argument list for a function type or function
1475 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1476 /// ::= '(' ArgTypeListI ')'
1480 /// ::= ArgTypeList ',' '...'
1481 /// ::= ArgType (',' ArgType)*
1483 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1484 bool &isVarArg, bool inType) {
1486 assert(Lex.getKind() == lltok::lparen);
1487 Lex.Lex(); // eat the (.
1489 if (Lex.getKind() == lltok::rparen) {
1491 } else if (Lex.getKind() == lltok::dotdotdot) {
1495 LocTy TypeLoc = Lex.getLoc();
1496 PATypeHolder ArgTy(Type::getVoidTy(Context));
1500 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1501 // types (such as a function returning a pointer to itself). If parsing a
1502 // function prototype, we require fully resolved types.
1503 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1504 ParseOptionalAttrs(Attrs, 0)) return true;
1506 if (ArgTy->isVoidTy())
1507 return Error(TypeLoc, "argument can not have void type");
1509 if (Lex.getKind() == lltok::LocalVar) {
1510 Name = Lex.getStrVal();
1514 if (!FunctionType::isValidArgumentType(ArgTy))
1515 return Error(TypeLoc, "invalid type for function argument");
1517 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1519 while (EatIfPresent(lltok::comma)) {
1520 // Handle ... at end of arg list.
1521 if (EatIfPresent(lltok::dotdotdot)) {
1526 // Otherwise must be an argument type.
1527 TypeLoc = Lex.getLoc();
1528 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1529 ParseOptionalAttrs(Attrs, 0)) return true;
1531 if (ArgTy->isVoidTy())
1532 return Error(TypeLoc, "argument can not have void type");
1534 if (Lex.getKind() == lltok::LocalVar) {
1535 Name = Lex.getStrVal();
1541 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1542 return Error(TypeLoc, "invalid type for function argument");
1544 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1548 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1551 /// ParseFunctionType
1552 /// ::= Type ArgumentList OptionalAttrs
1553 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1554 assert(Lex.getKind() == lltok::lparen);
1556 if (!FunctionType::isValidReturnType(Result))
1557 return TokError("invalid function return type");
1559 std::vector<ArgInfo> ArgList;
1561 if (ParseArgumentList(ArgList, isVarArg, true))
1564 // Reject names on the arguments lists.
1565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1566 if (!ArgList[i].Name.empty())
1567 return Error(ArgList[i].Loc, "argument name invalid in function type");
1568 if (ArgList[i].Attrs != 0)
1569 return Error(ArgList[i].Loc,
1570 "argument attributes invalid in function type");
1573 std::vector<const Type*> ArgListTy;
1574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1575 ArgListTy.push_back(ArgList[i].Type);
1577 Result = HandleUpRefs(FunctionType::get(Result.get(),
1578 ArgListTy, isVarArg));
1582 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1585 /// ::= '{' TypeRec (',' TypeRec)* '}'
1586 /// ::= '<' '{' '}' '>'
1587 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1588 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1589 assert(Lex.getKind() == lltok::lbrace);
1590 Lex.Lex(); // Consume the '{'
1592 if (EatIfPresent(lltok::rbrace)) {
1593 Result = StructType::get(Context, Packed);
1597 std::vector<PATypeHolder> ParamsList;
1598 LocTy EltTyLoc = Lex.getLoc();
1599 if (ParseTypeRec(Result)) return true;
1600 ParamsList.push_back(Result);
1602 if (Result->isVoidTy())
1603 return Error(EltTyLoc, "struct element can not have void type");
1604 if (!StructType::isValidElementType(Result))
1605 return Error(EltTyLoc, "invalid element type for struct");
1607 while (EatIfPresent(lltok::comma)) {
1608 EltTyLoc = Lex.getLoc();
1609 if (ParseTypeRec(Result)) return true;
1611 if (Result->isVoidTy())
1612 return Error(EltTyLoc, "struct element can not have void type");
1613 if (!StructType::isValidElementType(Result))
1614 return Error(EltTyLoc, "invalid element type for struct");
1616 ParamsList.push_back(Result);
1619 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1622 std::vector<const Type*> ParamsListTy;
1623 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1624 ParamsListTy.push_back(ParamsList[i].get());
1625 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1629 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1630 /// token has already been consumed.
1632 /// ::= '[' APSINTVAL 'x' Types ']'
1633 /// ::= '<' APSINTVAL 'x' Types '>'
1634 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1635 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1636 Lex.getAPSIntVal().getBitWidth() > 64)
1637 return TokError("expected number in address space");
1639 LocTy SizeLoc = Lex.getLoc();
1640 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1643 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1646 LocTy TypeLoc = Lex.getLoc();
1647 PATypeHolder EltTy(Type::getVoidTy(Context));
1648 if (ParseTypeRec(EltTy)) return true;
1650 if (EltTy->isVoidTy())
1651 return Error(TypeLoc, "array and vector element type cannot be void");
1653 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1654 "expected end of sequential type"))
1659 return Error(SizeLoc, "zero element vector is illegal");
1660 if ((unsigned)Size != Size)
1661 return Error(SizeLoc, "size too large for vector");
1662 if (!VectorType::isValidElementType(EltTy))
1663 return Error(TypeLoc, "vector element type must be fp or integer");
1664 Result = VectorType::get(EltTy, unsigned(Size));
1666 if (!ArrayType::isValidElementType(EltTy))
1667 return Error(TypeLoc, "invalid array element type");
1668 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1673 //===----------------------------------------------------------------------===//
1674 // Function Semantic Analysis.
1675 //===----------------------------------------------------------------------===//
1677 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1679 : P(p), F(f), FunctionNumber(functionNumber) {
1681 // Insert unnamed arguments into the NumberedVals list.
1682 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1685 NumberedVals.push_back(AI);
1688 LLParser::PerFunctionState::~PerFunctionState() {
1689 // If there were any forward referenced non-basicblock values, delete them.
1690 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1691 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1692 if (!isa<BasicBlock>(I->second.first)) {
1693 I->second.first->replaceAllUsesWith(
1694 UndefValue::get(I->second.first->getType()));
1695 delete I->second.first;
1696 I->second.first = 0;
1699 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1700 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1701 if (!isa<BasicBlock>(I->second.first)) {
1702 I->second.first->replaceAllUsesWith(
1703 UndefValue::get(I->second.first->getType()));
1704 delete I->second.first;
1705 I->second.first = 0;
1709 bool LLParser::PerFunctionState::FinishFunction() {
1710 // Check to see if someone took the address of labels in this block.
1711 if (!P.ForwardRefBlockAddresses.empty()) {
1713 if (!F.getName().empty()) {
1714 FunctionID.Kind = ValID::t_GlobalName;
1715 FunctionID.StrVal = F.getName();
1717 FunctionID.Kind = ValID::t_GlobalID;
1718 FunctionID.UIntVal = FunctionNumber;
1721 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1722 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1723 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1724 // Resolve all these references.
1725 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1728 P.ForwardRefBlockAddresses.erase(FRBAI);
1732 if (!ForwardRefVals.empty())
1733 return P.Error(ForwardRefVals.begin()->second.second,
1734 "use of undefined value '%" + ForwardRefVals.begin()->first +
1736 if (!ForwardRefValIDs.empty())
1737 return P.Error(ForwardRefValIDs.begin()->second.second,
1738 "use of undefined value '%" +
1739 Twine(ForwardRefValIDs.begin()->first) + "'");
1744 /// GetVal - Get a value with the specified name or ID, creating a
1745 /// forward reference record if needed. This can return null if the value
1746 /// exists but does not have the right type.
1747 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1748 const Type *Ty, LocTy Loc) {
1749 // Look this name up in the normal function symbol table.
1750 Value *Val = F.getValueSymbolTable().lookup(Name);
1752 // If this is a forward reference for the value, see if we already created a
1753 // forward ref record.
1755 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1756 I = ForwardRefVals.find(Name);
1757 if (I != ForwardRefVals.end())
1758 Val = I->second.first;
1761 // If we have the value in the symbol table or fwd-ref table, return it.
1763 if (Val->getType() == Ty) return Val;
1764 if (Ty->isLabelTy())
1765 P.Error(Loc, "'%" + Name + "' is not a basic block");
1767 P.Error(Loc, "'%" + Name + "' defined with type '" +
1768 getTypeString(Val->getType()) + "'");
1772 // Don't make placeholders with invalid type.
1773 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1774 P.Error(Loc, "invalid use of a non-first-class type");
1778 // Otherwise, create a new forward reference for this value and remember it.
1780 if (Ty->isLabelTy())
1781 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1783 FwdVal = new Argument(Ty, Name);
1785 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1789 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1791 // Look this name up in the normal function symbol table.
1792 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1794 // If this is a forward reference for the value, see if we already created a
1795 // forward ref record.
1797 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1798 I = ForwardRefValIDs.find(ID);
1799 if (I != ForwardRefValIDs.end())
1800 Val = I->second.first;
1803 // If we have the value in the symbol table or fwd-ref table, return it.
1805 if (Val->getType() == Ty) return Val;
1806 if (Ty->isLabelTy())
1807 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1809 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1810 getTypeString(Val->getType()) + "'");
1814 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1815 P.Error(Loc, "invalid use of a non-first-class type");
1819 // Otherwise, create a new forward reference for this value and remember it.
1821 if (Ty->isLabelTy())
1822 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1824 FwdVal = new Argument(Ty);
1826 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1830 /// SetInstName - After an instruction is parsed and inserted into its
1831 /// basic block, this installs its name.
1832 bool LLParser::PerFunctionState::SetInstName(int NameID,
1833 const std::string &NameStr,
1834 LocTy NameLoc, Instruction *Inst) {
1835 // If this instruction has void type, it cannot have a name or ID specified.
1836 if (Inst->getType()->isVoidTy()) {
1837 if (NameID != -1 || !NameStr.empty())
1838 return P.Error(NameLoc, "instructions returning void cannot have a name");
1842 // If this was a numbered instruction, verify that the instruction is the
1843 // expected value and resolve any forward references.
1844 if (NameStr.empty()) {
1845 // If neither a name nor an ID was specified, just use the next ID.
1847 NameID = NumberedVals.size();
1849 if (unsigned(NameID) != NumberedVals.size())
1850 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1851 Twine(NumberedVals.size()) + "'");
1853 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1854 ForwardRefValIDs.find(NameID);
1855 if (FI != ForwardRefValIDs.end()) {
1856 if (FI->second.first->getType() != Inst->getType())
1857 return P.Error(NameLoc, "instruction forward referenced with type '" +
1858 getTypeString(FI->second.first->getType()) + "'");
1859 FI->second.first->replaceAllUsesWith(Inst);
1860 delete FI->second.first;
1861 ForwardRefValIDs.erase(FI);
1864 NumberedVals.push_back(Inst);
1868 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1869 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1870 FI = ForwardRefVals.find(NameStr);
1871 if (FI != ForwardRefVals.end()) {
1872 if (FI->second.first->getType() != Inst->getType())
1873 return P.Error(NameLoc, "instruction forward referenced with type '" +
1874 getTypeString(FI->second.first->getType()) + "'");
1875 FI->second.first->replaceAllUsesWith(Inst);
1876 delete FI->second.first;
1877 ForwardRefVals.erase(FI);
1880 // Set the name on the instruction.
1881 Inst->setName(NameStr);
1883 if (Inst->getName() != NameStr)
1884 return P.Error(NameLoc, "multiple definition of local value named '" +
1889 /// GetBB - Get a basic block with the specified name or ID, creating a
1890 /// forward reference record if needed.
1891 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1893 return cast_or_null<BasicBlock>(GetVal(Name,
1894 Type::getLabelTy(F.getContext()), Loc));
1897 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1898 return cast_or_null<BasicBlock>(GetVal(ID,
1899 Type::getLabelTy(F.getContext()), Loc));
1902 /// DefineBB - Define the specified basic block, which is either named or
1903 /// unnamed. If there is an error, this returns null otherwise it returns
1904 /// the block being defined.
1905 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1909 BB = GetBB(NumberedVals.size(), Loc);
1911 BB = GetBB(Name, Loc);
1912 if (BB == 0) return 0; // Already diagnosed error.
1914 // Move the block to the end of the function. Forward ref'd blocks are
1915 // inserted wherever they happen to be referenced.
1916 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1918 // Remove the block from forward ref sets.
1920 ForwardRefValIDs.erase(NumberedVals.size());
1921 NumberedVals.push_back(BB);
1923 // BB forward references are already in the function symbol table.
1924 ForwardRefVals.erase(Name);
1930 //===----------------------------------------------------------------------===//
1932 //===----------------------------------------------------------------------===//
1934 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1935 /// type implied. For example, if we parse "4" we don't know what integer type
1936 /// it has. The value will later be combined with its type and checked for
1937 /// sanity. PFS is used to convert function-local operands of metadata (since
1938 /// metadata operands are not just parsed here but also converted to values).
1939 /// PFS can be null when we are not parsing metadata values inside a function.
1940 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1941 ID.Loc = Lex.getLoc();
1942 switch (Lex.getKind()) {
1943 default: return TokError("expected value token");
1944 case lltok::GlobalID: // @42
1945 ID.UIntVal = Lex.getUIntVal();
1946 ID.Kind = ValID::t_GlobalID;
1948 case lltok::GlobalVar: // @foo
1949 ID.StrVal = Lex.getStrVal();
1950 ID.Kind = ValID::t_GlobalName;
1952 case lltok::LocalVarID: // %42
1953 ID.UIntVal = Lex.getUIntVal();
1954 ID.Kind = ValID::t_LocalID;
1956 case lltok::LocalVar: // %foo
1957 ID.StrVal = Lex.getStrVal();
1958 ID.Kind = ValID::t_LocalName;
1960 case lltok::exclaim: // !42, !{...}, or !"foo"
1961 return ParseMetadataValue(ID, PFS);
1963 ID.APSIntVal = Lex.getAPSIntVal();
1964 ID.Kind = ValID::t_APSInt;
1966 case lltok::APFloat:
1967 ID.APFloatVal = Lex.getAPFloatVal();
1968 ID.Kind = ValID::t_APFloat;
1970 case lltok::kw_true:
1971 ID.ConstantVal = ConstantInt::getTrue(Context);
1972 ID.Kind = ValID::t_Constant;
1974 case lltok::kw_false:
1975 ID.ConstantVal = ConstantInt::getFalse(Context);
1976 ID.Kind = ValID::t_Constant;
1978 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1979 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1980 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1982 case lltok::lbrace: {
1983 // ValID ::= '{' ConstVector '}'
1985 SmallVector<Constant*, 16> Elts;
1986 if (ParseGlobalValueVector(Elts) ||
1987 ParseToken(lltok::rbrace, "expected end of struct constant"))
1990 // FIXME: Get this type from context instead of reconstructing it!
1991 ID.ConstantVal = ConstantStruct::getAnon(Context, Elts);
1992 ID.Kind = ValID::t_Constant;
1996 // ValID ::= '<' ConstVector '>' --> Vector.
1997 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1999 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2001 SmallVector<Constant*, 16> Elts;
2002 LocTy FirstEltLoc = Lex.getLoc();
2003 if (ParseGlobalValueVector(Elts) ||
2005 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2006 ParseToken(lltok::greater, "expected end of constant"))
2009 if (isPackedStruct) {
2010 // FIXME: Get this type from context instead of reconstructing it!
2011 ID.ConstantVal = ConstantStruct::getAnon(Context, Elts, true);
2012 ID.Kind = ValID::t_Constant;
2017 return Error(ID.Loc, "constant vector must not be empty");
2019 if (!Elts[0]->getType()->isIntegerTy() &&
2020 !Elts[0]->getType()->isFloatingPointTy())
2021 return Error(FirstEltLoc,
2022 "vector elements must have integer or floating point type");
2024 // Verify that all the vector elements have the same type.
2025 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2026 if (Elts[i]->getType() != Elts[0]->getType())
2027 return Error(FirstEltLoc,
2028 "vector element #" + Twine(i) +
2029 " is not of type '" + getTypeString(Elts[0]->getType()));
2031 ID.ConstantVal = ConstantVector::get(Elts);
2032 ID.Kind = ValID::t_Constant;
2035 case lltok::lsquare: { // Array Constant
2037 SmallVector<Constant*, 16> Elts;
2038 LocTy FirstEltLoc = Lex.getLoc();
2039 if (ParseGlobalValueVector(Elts) ||
2040 ParseToken(lltok::rsquare, "expected end of array constant"))
2043 // Handle empty element.
2045 // Use undef instead of an array because it's inconvenient to determine
2046 // the element type at this point, there being no elements to examine.
2047 ID.Kind = ValID::t_EmptyArray;
2051 if (!Elts[0]->getType()->isFirstClassType())
2052 return Error(FirstEltLoc, "invalid array element type: " +
2053 getTypeString(Elts[0]->getType()));
2055 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2057 // Verify all elements are correct type!
2058 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2059 if (Elts[i]->getType() != Elts[0]->getType())
2060 return Error(FirstEltLoc,
2061 "array element #" + Twine(i) +
2062 " is not of type '" + getTypeString(Elts[0]->getType()));
2065 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2066 ID.Kind = ValID::t_Constant;
2069 case lltok::kw_c: // c "foo"
2071 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2072 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2073 ID.Kind = ValID::t_Constant;
2076 case lltok::kw_asm: {
2077 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2078 bool HasSideEffect, AlignStack;
2080 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2081 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2082 ParseStringConstant(ID.StrVal) ||
2083 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2084 ParseToken(lltok::StringConstant, "expected constraint string"))
2086 ID.StrVal2 = Lex.getStrVal();
2087 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2088 ID.Kind = ValID::t_InlineAsm;
2092 case lltok::kw_blockaddress: {
2093 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2097 LocTy FnLoc, LabelLoc;
2099 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2101 ParseToken(lltok::comma, "expected comma in block address expression")||
2102 ParseValID(Label) ||
2103 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2106 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2107 return Error(Fn.Loc, "expected function name in blockaddress");
2108 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2109 return Error(Label.Loc, "expected basic block name in blockaddress");
2111 // Make a global variable as a placeholder for this reference.
2112 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2113 false, GlobalValue::InternalLinkage,
2115 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2116 ID.ConstantVal = FwdRef;
2117 ID.Kind = ValID::t_Constant;
2121 case lltok::kw_trunc:
2122 case lltok::kw_zext:
2123 case lltok::kw_sext:
2124 case lltok::kw_fptrunc:
2125 case lltok::kw_fpext:
2126 case lltok::kw_bitcast:
2127 case lltok::kw_uitofp:
2128 case lltok::kw_sitofp:
2129 case lltok::kw_fptoui:
2130 case lltok::kw_fptosi:
2131 case lltok::kw_inttoptr:
2132 case lltok::kw_ptrtoint: {
2133 unsigned Opc = Lex.getUIntVal();
2134 PATypeHolder DestTy(Type::getVoidTy(Context));
2137 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2138 ParseGlobalTypeAndValue(SrcVal) ||
2139 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2140 ParseType(DestTy) ||
2141 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2143 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2144 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2145 getTypeString(SrcVal->getType()) + "' to '" +
2146 getTypeString(DestTy) + "'");
2147 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2149 ID.Kind = ValID::t_Constant;
2152 case lltok::kw_extractvalue: {
2155 SmallVector<unsigned, 4> Indices;
2156 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2157 ParseGlobalTypeAndValue(Val) ||
2158 ParseIndexList(Indices) ||
2159 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2162 if (!Val->getType()->isAggregateType())
2163 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2164 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2166 return Error(ID.Loc, "invalid indices for extractvalue");
2168 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2169 ID.Kind = ValID::t_Constant;
2172 case lltok::kw_insertvalue: {
2174 Constant *Val0, *Val1;
2175 SmallVector<unsigned, 4> Indices;
2176 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2177 ParseGlobalTypeAndValue(Val0) ||
2178 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2179 ParseGlobalTypeAndValue(Val1) ||
2180 ParseIndexList(Indices) ||
2181 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2183 if (!Val0->getType()->isAggregateType())
2184 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2185 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2187 return Error(ID.Loc, "invalid indices for insertvalue");
2188 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2189 Indices.data(), Indices.size());
2190 ID.Kind = ValID::t_Constant;
2193 case lltok::kw_icmp:
2194 case lltok::kw_fcmp: {
2195 unsigned PredVal, Opc = Lex.getUIntVal();
2196 Constant *Val0, *Val1;
2198 if (ParseCmpPredicate(PredVal, Opc) ||
2199 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2200 ParseGlobalTypeAndValue(Val0) ||
2201 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2202 ParseGlobalTypeAndValue(Val1) ||
2203 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2206 if (Val0->getType() != Val1->getType())
2207 return Error(ID.Loc, "compare operands must have the same type");
2209 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2211 if (Opc == Instruction::FCmp) {
2212 if (!Val0->getType()->isFPOrFPVectorTy())
2213 return Error(ID.Loc, "fcmp requires floating point operands");
2214 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2216 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2217 if (!Val0->getType()->isIntOrIntVectorTy() &&
2218 !Val0->getType()->isPointerTy())
2219 return Error(ID.Loc, "icmp requires pointer or integer operands");
2220 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2222 ID.Kind = ValID::t_Constant;
2226 // Binary Operators.
2228 case lltok::kw_fadd:
2230 case lltok::kw_fsub:
2232 case lltok::kw_fmul:
2233 case lltok::kw_udiv:
2234 case lltok::kw_sdiv:
2235 case lltok::kw_fdiv:
2236 case lltok::kw_urem:
2237 case lltok::kw_srem:
2238 case lltok::kw_frem:
2240 case lltok::kw_lshr:
2241 case lltok::kw_ashr: {
2245 unsigned Opc = Lex.getUIntVal();
2246 Constant *Val0, *Val1;
2248 LocTy ModifierLoc = Lex.getLoc();
2249 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2250 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2251 if (EatIfPresent(lltok::kw_nuw))
2253 if (EatIfPresent(lltok::kw_nsw)) {
2255 if (EatIfPresent(lltok::kw_nuw))
2258 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2259 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2260 if (EatIfPresent(lltok::kw_exact))
2263 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2264 ParseGlobalTypeAndValue(Val0) ||
2265 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2266 ParseGlobalTypeAndValue(Val1) ||
2267 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2269 if (Val0->getType() != Val1->getType())
2270 return Error(ID.Loc, "operands of constexpr must have same type");
2271 if (!Val0->getType()->isIntOrIntVectorTy()) {
2273 return Error(ModifierLoc, "nuw only applies to integer operations");
2275 return Error(ModifierLoc, "nsw only applies to integer operations");
2277 // Check that the type is valid for the operator.
2279 case Instruction::Add:
2280 case Instruction::Sub:
2281 case Instruction::Mul:
2282 case Instruction::UDiv:
2283 case Instruction::SDiv:
2284 case Instruction::URem:
2285 case Instruction::SRem:
2286 case Instruction::Shl:
2287 case Instruction::AShr:
2288 case Instruction::LShr:
2289 if (!Val0->getType()->isIntOrIntVectorTy())
2290 return Error(ID.Loc, "constexpr requires integer operands");
2292 case Instruction::FAdd:
2293 case Instruction::FSub:
2294 case Instruction::FMul:
2295 case Instruction::FDiv:
2296 case Instruction::FRem:
2297 if (!Val0->getType()->isFPOrFPVectorTy())
2298 return Error(ID.Loc, "constexpr requires fp operands");
2300 default: llvm_unreachable("Unknown binary operator!");
2303 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2304 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2305 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2306 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2308 ID.Kind = ValID::t_Constant;
2312 // Logical Operations
2315 case lltok::kw_xor: {
2316 unsigned Opc = Lex.getUIntVal();
2317 Constant *Val0, *Val1;
2319 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2320 ParseGlobalTypeAndValue(Val0) ||
2321 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2322 ParseGlobalTypeAndValue(Val1) ||
2323 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2325 if (Val0->getType() != Val1->getType())
2326 return Error(ID.Loc, "operands of constexpr must have same type");
2327 if (!Val0->getType()->isIntOrIntVectorTy())
2328 return Error(ID.Loc,
2329 "constexpr requires integer or integer vector operands");
2330 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2331 ID.Kind = ValID::t_Constant;
2335 case lltok::kw_getelementptr:
2336 case lltok::kw_shufflevector:
2337 case lltok::kw_insertelement:
2338 case lltok::kw_extractelement:
2339 case lltok::kw_select: {
2340 unsigned Opc = Lex.getUIntVal();
2341 SmallVector<Constant*, 16> Elts;
2342 bool InBounds = false;
2344 if (Opc == Instruction::GetElementPtr)
2345 InBounds = EatIfPresent(lltok::kw_inbounds);
2346 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2347 ParseGlobalValueVector(Elts) ||
2348 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2351 if (Opc == Instruction::GetElementPtr) {
2352 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2353 return Error(ID.Loc, "getelementptr requires pointer operand");
2355 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2356 (Value**)(Elts.data() + 1),
2358 return Error(ID.Loc, "invalid indices for getelementptr");
2359 ID.ConstantVal = InBounds ?
2360 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2363 ConstantExpr::getGetElementPtr(Elts[0],
2364 Elts.data() + 1, Elts.size() - 1);
2365 } else if (Opc == Instruction::Select) {
2366 if (Elts.size() != 3)
2367 return Error(ID.Loc, "expected three operands to select");
2368 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2370 return Error(ID.Loc, Reason);
2371 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2372 } else if (Opc == Instruction::ShuffleVector) {
2373 if (Elts.size() != 3)
2374 return Error(ID.Loc, "expected three operands to shufflevector");
2375 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2376 return Error(ID.Loc, "invalid operands to shufflevector");
2378 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2379 } else if (Opc == Instruction::ExtractElement) {
2380 if (Elts.size() != 2)
2381 return Error(ID.Loc, "expected two operands to extractelement");
2382 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2383 return Error(ID.Loc, "invalid extractelement operands");
2384 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2386 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2387 if (Elts.size() != 3)
2388 return Error(ID.Loc, "expected three operands to insertelement");
2389 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2390 return Error(ID.Loc, "invalid insertelement operands");
2392 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2395 ID.Kind = ValID::t_Constant;
2404 /// ParseGlobalValue - Parse a global value with the specified type.
2405 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2409 bool Parsed = ParseValID(ID) ||
2410 ConvertValIDToValue(Ty, ID, V, NULL);
2411 if (V && !(C = dyn_cast<Constant>(V)))
2412 return Error(ID.Loc, "global values must be constants");
2416 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2417 PATypeHolder Type(Type::getVoidTy(Context));
2418 return ParseType(Type) ||
2419 ParseGlobalValue(Type, V);
2422 /// ParseGlobalValueVector
2424 /// ::= TypeAndValue (',' TypeAndValue)*
2425 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2427 if (Lex.getKind() == lltok::rbrace ||
2428 Lex.getKind() == lltok::rsquare ||
2429 Lex.getKind() == lltok::greater ||
2430 Lex.getKind() == lltok::rparen)
2434 if (ParseGlobalTypeAndValue(C)) return true;
2437 while (EatIfPresent(lltok::comma)) {
2438 if (ParseGlobalTypeAndValue(C)) return true;
2445 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2446 assert(Lex.getKind() == lltok::lbrace);
2449 SmallVector<Value*, 16> Elts;
2450 if (ParseMDNodeVector(Elts, PFS) ||
2451 ParseToken(lltok::rbrace, "expected end of metadata node"))
2454 ID.MDNodeVal = MDNode::get(Context, Elts);
2455 ID.Kind = ValID::t_MDNode;
2459 /// ParseMetadataValue
2463 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2464 assert(Lex.getKind() == lltok::exclaim);
2469 if (Lex.getKind() == lltok::lbrace)
2470 return ParseMetadataListValue(ID, PFS);
2472 // Standalone metadata reference
2474 if (Lex.getKind() == lltok::APSInt) {
2475 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2476 ID.Kind = ValID::t_MDNode;
2481 // ::= '!' STRINGCONSTANT
2482 if (ParseMDString(ID.MDStringVal)) return true;
2483 ID.Kind = ValID::t_MDString;
2488 //===----------------------------------------------------------------------===//
2489 // Function Parsing.
2490 //===----------------------------------------------------------------------===//
2492 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2493 PerFunctionState *PFS) {
2494 if (Ty->isFunctionTy())
2495 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2498 default: llvm_unreachable("Unknown ValID!");
2499 case ValID::t_LocalID:
2500 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2501 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2503 case ValID::t_LocalName:
2504 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2505 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2507 case ValID::t_InlineAsm: {
2508 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2509 const FunctionType *FTy =
2510 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2511 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2512 return Error(ID.Loc, "invalid type for inline asm constraint string");
2513 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2516 case ValID::t_MDNode:
2517 if (!Ty->isMetadataTy())
2518 return Error(ID.Loc, "metadata value must have metadata type");
2521 case ValID::t_MDString:
2522 if (!Ty->isMetadataTy())
2523 return Error(ID.Loc, "metadata value must have metadata type");
2526 case ValID::t_GlobalName:
2527 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2529 case ValID::t_GlobalID:
2530 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2532 case ValID::t_APSInt:
2533 if (!Ty->isIntegerTy())
2534 return Error(ID.Loc, "integer constant must have integer type");
2535 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2536 V = ConstantInt::get(Context, ID.APSIntVal);
2538 case ValID::t_APFloat:
2539 if (!Ty->isFloatingPointTy() ||
2540 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2541 return Error(ID.Loc, "floating point constant invalid for type");
2543 // The lexer has no type info, so builds all float and double FP constants
2544 // as double. Fix this here. Long double does not need this.
2545 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2548 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2551 V = ConstantFP::get(Context, ID.APFloatVal);
2553 if (V->getType() != Ty)
2554 return Error(ID.Loc, "floating point constant does not have type '" +
2555 getTypeString(Ty) + "'");
2559 if (!Ty->isPointerTy())
2560 return Error(ID.Loc, "null must be a pointer type");
2561 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2563 case ValID::t_Undef:
2564 // FIXME: LabelTy should not be a first-class type.
2565 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2567 return Error(ID.Loc, "invalid type for undef constant");
2568 V = UndefValue::get(Ty);
2570 case ValID::t_EmptyArray:
2571 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2572 return Error(ID.Loc, "invalid empty array initializer");
2573 V = UndefValue::get(Ty);
2576 // FIXME: LabelTy should not be a first-class type.
2577 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2578 return Error(ID.Loc, "invalid type for null constant");
2579 V = Constant::getNullValue(Ty);
2581 case ValID::t_Constant:
2582 if (ID.ConstantVal->getType() != Ty)
2583 return Error(ID.Loc, "constant expression type mismatch");
2590 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2593 return ParseValID(ID, &PFS) ||
2594 ConvertValIDToValue(Ty, ID, V, &PFS);
2597 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2598 PATypeHolder T(Type::getVoidTy(Context));
2599 return ParseType(T) ||
2600 ParseValue(T, V, PFS);
2603 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2604 PerFunctionState &PFS) {
2607 if (ParseTypeAndValue(V, PFS)) return true;
2608 if (!isa<BasicBlock>(V))
2609 return Error(Loc, "expected a basic block");
2610 BB = cast<BasicBlock>(V);
2616 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2617 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2618 /// OptionalAlign OptGC
2619 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2620 // Parse the linkage.
2621 LocTy LinkageLoc = Lex.getLoc();
2624 unsigned Visibility, RetAttrs;
2626 PATypeHolder RetType(Type::getVoidTy(Context));
2627 LocTy RetTypeLoc = Lex.getLoc();
2628 if (ParseOptionalLinkage(Linkage) ||
2629 ParseOptionalVisibility(Visibility) ||
2630 ParseOptionalCallingConv(CC) ||
2631 ParseOptionalAttrs(RetAttrs, 1) ||
2632 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2635 // Verify that the linkage is ok.
2636 switch ((GlobalValue::LinkageTypes)Linkage) {
2637 case GlobalValue::ExternalLinkage:
2638 break; // always ok.
2639 case GlobalValue::DLLImportLinkage:
2640 case GlobalValue::ExternalWeakLinkage:
2642 return Error(LinkageLoc, "invalid linkage for function definition");
2644 case GlobalValue::PrivateLinkage:
2645 case GlobalValue::LinkerPrivateLinkage:
2646 case GlobalValue::LinkerPrivateWeakLinkage:
2647 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2648 case GlobalValue::InternalLinkage:
2649 case GlobalValue::AvailableExternallyLinkage:
2650 case GlobalValue::LinkOnceAnyLinkage:
2651 case GlobalValue::LinkOnceODRLinkage:
2652 case GlobalValue::WeakAnyLinkage:
2653 case GlobalValue::WeakODRLinkage:
2654 case GlobalValue::DLLExportLinkage:
2656 return Error(LinkageLoc, "invalid linkage for function declaration");
2658 case GlobalValue::AppendingLinkage:
2659 case GlobalValue::CommonLinkage:
2660 return Error(LinkageLoc, "invalid function linkage type");
2663 if (!FunctionType::isValidReturnType(RetType) ||
2664 RetType->isOpaqueTy())
2665 return Error(RetTypeLoc, "invalid function return type");
2667 LocTy NameLoc = Lex.getLoc();
2669 std::string FunctionName;
2670 if (Lex.getKind() == lltok::GlobalVar) {
2671 FunctionName = Lex.getStrVal();
2672 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2673 unsigned NameID = Lex.getUIntVal();
2675 if (NameID != NumberedVals.size())
2676 return TokError("function expected to be numbered '%" +
2677 Twine(NumberedVals.size()) + "'");
2679 return TokError("expected function name");
2684 if (Lex.getKind() != lltok::lparen)
2685 return TokError("expected '(' in function argument list");
2687 std::vector<ArgInfo> ArgList;
2690 std::string Section;
2694 LocTy UnnamedAddrLoc;
2696 if (ParseArgumentList(ArgList, isVarArg, false) ||
2697 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2699 ParseOptionalAttrs(FuncAttrs, 2) ||
2700 (EatIfPresent(lltok::kw_section) &&
2701 ParseStringConstant(Section)) ||
2702 ParseOptionalAlignment(Alignment) ||
2703 (EatIfPresent(lltok::kw_gc) &&
2704 ParseStringConstant(GC)))
2707 // If the alignment was parsed as an attribute, move to the alignment field.
2708 if (FuncAttrs & Attribute::Alignment) {
2709 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2710 FuncAttrs &= ~Attribute::Alignment;
2713 // Okay, if we got here, the function is syntactically valid. Convert types
2714 // and do semantic checks.
2715 std::vector<const Type*> ParamTypeList;
2716 SmallVector<AttributeWithIndex, 8> Attrs;
2718 if (RetAttrs != Attribute::None)
2719 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2721 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2722 ParamTypeList.push_back(ArgList[i].Type);
2723 if (ArgList[i].Attrs != Attribute::None)
2724 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2727 if (FuncAttrs != Attribute::None)
2728 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2730 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2732 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2733 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2735 const FunctionType *FT =
2736 FunctionType::get(RetType, ParamTypeList, isVarArg);
2737 const PointerType *PFT = PointerType::getUnqual(FT);
2740 if (!FunctionName.empty()) {
2741 // If this was a definition of a forward reference, remove the definition
2742 // from the forward reference table and fill in the forward ref.
2743 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2744 ForwardRefVals.find(FunctionName);
2745 if (FRVI != ForwardRefVals.end()) {
2746 Fn = M->getFunction(FunctionName);
2747 if (Fn->getType() != PFT)
2748 return Error(FRVI->second.second, "invalid forward reference to "
2749 "function '" + FunctionName + "' with wrong type!");
2751 ForwardRefVals.erase(FRVI);
2752 } else if ((Fn = M->getFunction(FunctionName))) {
2753 // Reject redefinitions.
2754 return Error(NameLoc, "invalid redefinition of function '" +
2755 FunctionName + "'");
2756 } else if (M->getNamedValue(FunctionName)) {
2757 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2761 // If this is a definition of a forward referenced function, make sure the
2763 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2764 = ForwardRefValIDs.find(NumberedVals.size());
2765 if (I != ForwardRefValIDs.end()) {
2766 Fn = cast<Function>(I->second.first);
2767 if (Fn->getType() != PFT)
2768 return Error(NameLoc, "type of definition and forward reference of '@" +
2769 Twine(NumberedVals.size()) + "' disagree");
2770 ForwardRefValIDs.erase(I);
2775 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2776 else // Move the forward-reference to the correct spot in the module.
2777 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2779 if (FunctionName.empty())
2780 NumberedVals.push_back(Fn);
2782 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2783 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2784 Fn->setCallingConv(CC);
2785 Fn->setAttributes(PAL);
2786 Fn->setUnnamedAddr(UnnamedAddr);
2787 Fn->setAlignment(Alignment);
2788 Fn->setSection(Section);
2789 if (!GC.empty()) Fn->setGC(GC.c_str());
2791 // Add all of the arguments we parsed to the function.
2792 Function::arg_iterator ArgIt = Fn->arg_begin();
2793 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2794 // If the argument has a name, insert it into the argument symbol table.
2795 if (ArgList[i].Name.empty()) continue;
2797 // Set the name, if it conflicted, it will be auto-renamed.
2798 ArgIt->setName(ArgList[i].Name);
2800 if (ArgIt->getName() != ArgList[i].Name)
2801 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2802 ArgList[i].Name + "'");
2809 /// ParseFunctionBody
2810 /// ::= '{' BasicBlock+ '}'
2812 bool LLParser::ParseFunctionBody(Function &Fn) {
2813 if (Lex.getKind() != lltok::lbrace)
2814 return TokError("expected '{' in function body");
2815 Lex.Lex(); // eat the {.
2817 int FunctionNumber = -1;
2818 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2820 PerFunctionState PFS(*this, Fn, FunctionNumber);
2822 // We need at least one basic block.
2823 if (Lex.getKind() == lltok::rbrace)
2824 return TokError("function body requires at least one basic block");
2826 while (Lex.getKind() != lltok::rbrace)
2827 if (ParseBasicBlock(PFS)) return true;
2832 // Verify function is ok.
2833 return PFS.FinishFunction();
2837 /// ::= LabelStr? Instruction*
2838 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2839 // If this basic block starts out with a name, remember it.
2841 LocTy NameLoc = Lex.getLoc();
2842 if (Lex.getKind() == lltok::LabelStr) {
2843 Name = Lex.getStrVal();
2847 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2848 if (BB == 0) return true;
2850 std::string NameStr;
2852 // Parse the instructions in this block until we get a terminator.
2854 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2856 // This instruction may have three possibilities for a name: a) none
2857 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2858 LocTy NameLoc = Lex.getLoc();
2862 if (Lex.getKind() == lltok::LocalVarID) {
2863 NameID = Lex.getUIntVal();
2865 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2867 } else if (Lex.getKind() == lltok::LocalVar) {
2868 NameStr = Lex.getStrVal();
2870 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2874 switch (ParseInstruction(Inst, BB, PFS)) {
2875 default: assert(0 && "Unknown ParseInstruction result!");
2876 case InstError: return true;
2878 BB->getInstList().push_back(Inst);
2880 // With a normal result, we check to see if the instruction is followed by
2881 // a comma and metadata.
2882 if (EatIfPresent(lltok::comma))
2883 if (ParseInstructionMetadata(Inst, &PFS))
2886 case InstExtraComma:
2887 BB->getInstList().push_back(Inst);
2889 // If the instruction parser ate an extra comma at the end of it, it
2890 // *must* be followed by metadata.
2891 if (ParseInstructionMetadata(Inst, &PFS))
2896 // Set the name on the instruction.
2897 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2898 } while (!isa<TerminatorInst>(Inst));
2903 //===----------------------------------------------------------------------===//
2904 // Instruction Parsing.
2905 //===----------------------------------------------------------------------===//
2907 /// ParseInstruction - Parse one of the many different instructions.
2909 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2910 PerFunctionState &PFS) {
2911 lltok::Kind Token = Lex.getKind();
2912 if (Token == lltok::Eof)
2913 return TokError("found end of file when expecting more instructions");
2914 LocTy Loc = Lex.getLoc();
2915 unsigned KeywordVal = Lex.getUIntVal();
2916 Lex.Lex(); // Eat the keyword.
2919 default: return Error(Loc, "expected instruction opcode");
2920 // Terminator Instructions.
2921 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2922 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2923 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2924 case lltok::kw_br: return ParseBr(Inst, PFS);
2925 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2926 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2927 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2928 // Binary Operators.
2932 case lltok::kw_shl: {
2933 bool NUW = EatIfPresent(lltok::kw_nuw);
2934 bool NSW = EatIfPresent(lltok::kw_nsw);
2935 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2937 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2939 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2940 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2943 case lltok::kw_fadd:
2944 case lltok::kw_fsub:
2945 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2947 case lltok::kw_sdiv:
2948 case lltok::kw_udiv:
2949 case lltok::kw_lshr:
2950 case lltok::kw_ashr: {
2951 bool Exact = EatIfPresent(lltok::kw_exact);
2953 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2954 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2958 case lltok::kw_urem:
2959 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2960 case lltok::kw_fdiv:
2961 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2964 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2965 case lltok::kw_icmp:
2966 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2968 case lltok::kw_trunc:
2969 case lltok::kw_zext:
2970 case lltok::kw_sext:
2971 case lltok::kw_fptrunc:
2972 case lltok::kw_fpext:
2973 case lltok::kw_bitcast:
2974 case lltok::kw_uitofp:
2975 case lltok::kw_sitofp:
2976 case lltok::kw_fptoui:
2977 case lltok::kw_fptosi:
2978 case lltok::kw_inttoptr:
2979 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2981 case lltok::kw_select: return ParseSelect(Inst, PFS);
2982 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2983 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2984 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2985 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2986 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2987 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2988 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2990 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2991 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2992 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2993 case lltok::kw_volatile:
2994 if (EatIfPresent(lltok::kw_load))
2995 return ParseLoad(Inst, PFS, true);
2996 else if (EatIfPresent(lltok::kw_store))
2997 return ParseStore(Inst, PFS, true);
2999 return TokError("expected 'load' or 'store'");
3000 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3001 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3002 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3006 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3007 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3008 if (Opc == Instruction::FCmp) {
3009 switch (Lex.getKind()) {
3010 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3011 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3012 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3013 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3014 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3015 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3016 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3017 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3018 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3019 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3020 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3021 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3022 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3023 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3024 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3025 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3026 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3029 switch (Lex.getKind()) {
3030 default: TokError("expected icmp predicate (e.g. 'eq')");
3031 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3032 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3033 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3034 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3035 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3036 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3037 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3038 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3039 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3040 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3047 //===----------------------------------------------------------------------===//
3048 // Terminator Instructions.
3049 //===----------------------------------------------------------------------===//
3051 /// ParseRet - Parse a return instruction.
3052 /// ::= 'ret' void (',' !dbg, !1)*
3053 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3054 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3055 PerFunctionState &PFS) {
3056 PATypeHolder Ty(Type::getVoidTy(Context));
3057 if (ParseType(Ty, true /*void allowed*/)) return true;
3059 if (Ty->isVoidTy()) {
3060 Inst = ReturnInst::Create(Context);
3065 if (ParseValue(Ty, RV, PFS)) return true;
3067 Inst = ReturnInst::Create(Context, RV);
3073 /// ::= 'br' TypeAndValue
3074 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3075 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3078 BasicBlock *Op1, *Op2;
3079 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3081 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3082 Inst = BranchInst::Create(BB);
3086 if (Op0->getType() != Type::getInt1Ty(Context))
3087 return Error(Loc, "branch condition must have 'i1' type");
3089 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3090 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3091 ParseToken(lltok::comma, "expected ',' after true destination") ||
3092 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3095 Inst = BranchInst::Create(Op1, Op2, Op0);
3101 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3103 /// ::= (TypeAndValue ',' TypeAndValue)*
3104 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3105 LocTy CondLoc, BBLoc;
3107 BasicBlock *DefaultBB;
3108 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3109 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3110 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3111 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3114 if (!Cond->getType()->isIntegerTy())
3115 return Error(CondLoc, "switch condition must have integer type");
3117 // Parse the jump table pairs.
3118 SmallPtrSet<Value*, 32> SeenCases;
3119 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3120 while (Lex.getKind() != lltok::rsquare) {
3124 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3125 ParseToken(lltok::comma, "expected ',' after case value") ||
3126 ParseTypeAndBasicBlock(DestBB, PFS))
3129 if (!SeenCases.insert(Constant))
3130 return Error(CondLoc, "duplicate case value in switch");
3131 if (!isa<ConstantInt>(Constant))
3132 return Error(CondLoc, "case value is not a constant integer");
3134 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3137 Lex.Lex(); // Eat the ']'.
3139 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3140 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3141 SI->addCase(Table[i].first, Table[i].second);
3148 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3149 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3152 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3154 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3157 if (!Address->getType()->isPointerTy())
3158 return Error(AddrLoc, "indirectbr address must have pointer type");
3160 // Parse the destination list.
3161 SmallVector<BasicBlock*, 16> DestList;
3163 if (Lex.getKind() != lltok::rsquare) {
3165 if (ParseTypeAndBasicBlock(DestBB, PFS))
3167 DestList.push_back(DestBB);
3169 while (EatIfPresent(lltok::comma)) {
3170 if (ParseTypeAndBasicBlock(DestBB, PFS))
3172 DestList.push_back(DestBB);
3176 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3179 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3180 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3181 IBI->addDestination(DestList[i]);
3188 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3189 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3190 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3191 LocTy CallLoc = Lex.getLoc();
3192 unsigned RetAttrs, FnAttrs;
3194 PATypeHolder RetType(Type::getVoidTy(Context));
3197 SmallVector<ParamInfo, 16> ArgList;
3199 BasicBlock *NormalBB, *UnwindBB;
3200 if (ParseOptionalCallingConv(CC) ||
3201 ParseOptionalAttrs(RetAttrs, 1) ||
3202 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3203 ParseValID(CalleeID) ||
3204 ParseParameterList(ArgList, PFS) ||
3205 ParseOptionalAttrs(FnAttrs, 2) ||
3206 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3207 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3208 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3209 ParseTypeAndBasicBlock(UnwindBB, PFS))
3212 // If RetType is a non-function pointer type, then this is the short syntax
3213 // for the call, which means that RetType is just the return type. Infer the
3214 // rest of the function argument types from the arguments that are present.
3215 const PointerType *PFTy = 0;
3216 const FunctionType *Ty = 0;
3217 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3218 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3219 // Pull out the types of all of the arguments...
3220 std::vector<const Type*> ParamTypes;
3221 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3222 ParamTypes.push_back(ArgList[i].V->getType());
3224 if (!FunctionType::isValidReturnType(RetType))
3225 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3227 Ty = FunctionType::get(RetType, ParamTypes, false);
3228 PFTy = PointerType::getUnqual(Ty);
3231 // Look up the callee.
3233 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3235 // Set up the Attributes for the function.
3236 SmallVector<AttributeWithIndex, 8> Attrs;
3237 if (RetAttrs != Attribute::None)
3238 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3240 SmallVector<Value*, 8> Args;
3242 // Loop through FunctionType's arguments and ensure they are specified
3243 // correctly. Also, gather any parameter attributes.
3244 FunctionType::param_iterator I = Ty->param_begin();
3245 FunctionType::param_iterator E = Ty->param_end();
3246 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3247 const Type *ExpectedTy = 0;
3250 } else if (!Ty->isVarArg()) {
3251 return Error(ArgList[i].Loc, "too many arguments specified");
3254 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3255 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3256 getTypeString(ExpectedTy) + "'");
3257 Args.push_back(ArgList[i].V);
3258 if (ArgList[i].Attrs != Attribute::None)
3259 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3263 return Error(CallLoc, "not enough parameters specified for call");
3265 if (FnAttrs != Attribute::None)
3266 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3268 // Finish off the Attributes and check them
3269 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3271 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3272 Args.begin(), Args.end());
3273 II->setCallingConv(CC);
3274 II->setAttributes(PAL);
3281 //===----------------------------------------------------------------------===//
3282 // Binary Operators.
3283 //===----------------------------------------------------------------------===//
3286 /// ::= ArithmeticOps TypeAndValue ',' Value
3288 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3289 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3290 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3291 unsigned Opc, unsigned OperandType) {
3292 LocTy Loc; Value *LHS, *RHS;
3293 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3294 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3295 ParseValue(LHS->getType(), RHS, PFS))
3299 switch (OperandType) {
3300 default: llvm_unreachable("Unknown operand type!");
3301 case 0: // int or FP.
3302 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3303 LHS->getType()->isFPOrFPVectorTy();
3305 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3306 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3310 return Error(Loc, "invalid operand type for instruction");
3312 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3317 /// ::= ArithmeticOps TypeAndValue ',' Value {
3318 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3320 LocTy Loc; Value *LHS, *RHS;
3321 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3322 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3323 ParseValue(LHS->getType(), RHS, PFS))
3326 if (!LHS->getType()->isIntOrIntVectorTy())
3327 return Error(Loc,"instruction requires integer or integer vector operands");
3329 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3335 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3336 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3337 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3339 // Parse the integer/fp comparison predicate.
3343 if (ParseCmpPredicate(Pred, Opc) ||
3344 ParseTypeAndValue(LHS, Loc, PFS) ||
3345 ParseToken(lltok::comma, "expected ',' after compare value") ||
3346 ParseValue(LHS->getType(), RHS, PFS))
3349 if (Opc == Instruction::FCmp) {
3350 if (!LHS->getType()->isFPOrFPVectorTy())
3351 return Error(Loc, "fcmp requires floating point operands");
3352 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3354 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3355 if (!LHS->getType()->isIntOrIntVectorTy() &&
3356 !LHS->getType()->isPointerTy())
3357 return Error(Loc, "icmp requires integer operands");
3358 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3363 //===----------------------------------------------------------------------===//
3364 // Other Instructions.
3365 //===----------------------------------------------------------------------===//
3369 /// ::= CastOpc TypeAndValue 'to' Type
3370 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3372 LocTy Loc; Value *Op;
3373 PATypeHolder DestTy(Type::getVoidTy(Context));
3374 if (ParseTypeAndValue(Op, Loc, PFS) ||
3375 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3379 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3380 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3381 return Error(Loc, "invalid cast opcode for cast from '" +
3382 getTypeString(Op->getType()) + "' to '" +
3383 getTypeString(DestTy) + "'");
3385 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3390 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3391 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3393 Value *Op0, *Op1, *Op2;
3394 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3395 ParseToken(lltok::comma, "expected ',' after select condition") ||
3396 ParseTypeAndValue(Op1, PFS) ||
3397 ParseToken(lltok::comma, "expected ',' after select value") ||
3398 ParseTypeAndValue(Op2, PFS))
3401 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3402 return Error(Loc, Reason);
3404 Inst = SelectInst::Create(Op0, Op1, Op2);
3409 /// ::= 'va_arg' TypeAndValue ',' Type
3410 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3412 PATypeHolder EltTy(Type::getVoidTy(Context));
3414 if (ParseTypeAndValue(Op, PFS) ||
3415 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3416 ParseType(EltTy, TypeLoc))
3419 if (!EltTy->isFirstClassType())
3420 return Error(TypeLoc, "va_arg requires operand with first class type");
3422 Inst = new VAArgInst(Op, EltTy);
3426 /// ParseExtractElement
3427 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3428 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3431 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3432 ParseToken(lltok::comma, "expected ',' after extract value") ||
3433 ParseTypeAndValue(Op1, PFS))
3436 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3437 return Error(Loc, "invalid extractelement operands");
3439 Inst = ExtractElementInst::Create(Op0, Op1);
3443 /// ParseInsertElement
3444 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3445 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3447 Value *Op0, *Op1, *Op2;
3448 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3449 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3450 ParseTypeAndValue(Op1, PFS) ||
3451 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3452 ParseTypeAndValue(Op2, PFS))
3455 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3456 return Error(Loc, "invalid insertelement operands");
3458 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3462 /// ParseShuffleVector
3463 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3464 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3466 Value *Op0, *Op1, *Op2;
3467 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3468 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3469 ParseTypeAndValue(Op1, PFS) ||
3470 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3471 ParseTypeAndValue(Op2, PFS))
3474 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3475 return Error(Loc, "invalid extractelement operands");
3477 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3482 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3483 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3484 PATypeHolder Ty(Type::getVoidTy(Context));
3486 LocTy TypeLoc = Lex.getLoc();
3488 if (ParseType(Ty) ||
3489 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3490 ParseValue(Ty, Op0, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3492 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3493 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3496 bool AteExtraComma = false;
3497 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3499 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3501 if (!EatIfPresent(lltok::comma))
3504 if (Lex.getKind() == lltok::MetadataVar) {
3505 AteExtraComma = true;
3509 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3510 ParseValue(Ty, Op0, PFS) ||
3511 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3512 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3513 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3517 if (!Ty->isFirstClassType())
3518 return Error(TypeLoc, "phi node must have first class type");
3520 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3521 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3522 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3524 return AteExtraComma ? InstExtraComma : InstNormal;
3528 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3529 /// ParameterList OptionalAttrs
3530 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3532 unsigned RetAttrs, FnAttrs;
3534 PATypeHolder RetType(Type::getVoidTy(Context));
3537 SmallVector<ParamInfo, 16> ArgList;
3538 LocTy CallLoc = Lex.getLoc();
3540 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3541 ParseOptionalCallingConv(CC) ||
3542 ParseOptionalAttrs(RetAttrs, 1) ||
3543 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3544 ParseValID(CalleeID) ||
3545 ParseParameterList(ArgList, PFS) ||
3546 ParseOptionalAttrs(FnAttrs, 2))
3549 // If RetType is a non-function pointer type, then this is the short syntax
3550 // for the call, which means that RetType is just the return type. Infer the
3551 // rest of the function argument types from the arguments that are present.
3552 const PointerType *PFTy = 0;
3553 const FunctionType *Ty = 0;
3554 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3555 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3556 // Pull out the types of all of the arguments...
3557 std::vector<const Type*> ParamTypes;
3558 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3559 ParamTypes.push_back(ArgList[i].V->getType());
3561 if (!FunctionType::isValidReturnType(RetType))
3562 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3564 Ty = FunctionType::get(RetType, ParamTypes, false);
3565 PFTy = PointerType::getUnqual(Ty);
3568 // Look up the callee.
3570 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3572 // Set up the Attributes for the function.
3573 SmallVector<AttributeWithIndex, 8> Attrs;
3574 if (RetAttrs != Attribute::None)
3575 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3577 SmallVector<Value*, 8> Args;
3579 // Loop through FunctionType's arguments and ensure they are specified
3580 // correctly. Also, gather any parameter attributes.
3581 FunctionType::param_iterator I = Ty->param_begin();
3582 FunctionType::param_iterator E = Ty->param_end();
3583 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3584 const Type *ExpectedTy = 0;
3587 } else if (!Ty->isVarArg()) {
3588 return Error(ArgList[i].Loc, "too many arguments specified");
3591 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3592 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3593 getTypeString(ExpectedTy) + "'");
3594 Args.push_back(ArgList[i].V);
3595 if (ArgList[i].Attrs != Attribute::None)
3596 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3600 return Error(CallLoc, "not enough parameters specified for call");
3602 if (FnAttrs != Attribute::None)
3603 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3605 // Finish off the Attributes and check them
3606 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3608 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3609 CI->setTailCall(isTail);
3610 CI->setCallingConv(CC);
3611 CI->setAttributes(PAL);
3616 //===----------------------------------------------------------------------===//
3617 // Memory Instructions.
3618 //===----------------------------------------------------------------------===//
3621 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3622 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3623 PATypeHolder Ty(Type::getVoidTy(Context));
3626 unsigned Alignment = 0;
3627 if (ParseType(Ty)) return true;
3629 bool AteExtraComma = false;
3630 if (EatIfPresent(lltok::comma)) {
3631 if (Lex.getKind() == lltok::kw_align) {
3632 if (ParseOptionalAlignment(Alignment)) return true;
3633 } else if (Lex.getKind() == lltok::MetadataVar) {
3634 AteExtraComma = true;
3636 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3637 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3642 if (Size && !Size->getType()->isIntegerTy())
3643 return Error(SizeLoc, "element count must have integer type");
3645 Inst = new AllocaInst(Ty, Size, Alignment);
3646 return AteExtraComma ? InstExtraComma : InstNormal;
3650 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3651 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3653 Value *Val; LocTy Loc;
3654 unsigned Alignment = 0;
3655 bool AteExtraComma = false;
3656 if (ParseTypeAndValue(Val, Loc, PFS) ||
3657 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3660 if (!Val->getType()->isPointerTy() ||
3661 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3662 return Error(Loc, "load operand must be a pointer to a first class type");
3664 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3665 return AteExtraComma ? InstExtraComma : InstNormal;
3669 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3670 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3672 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3673 unsigned Alignment = 0;
3674 bool AteExtraComma = false;
3675 if (ParseTypeAndValue(Val, Loc, PFS) ||
3676 ParseToken(lltok::comma, "expected ',' after store operand") ||
3677 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3678 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3681 if (!Ptr->getType()->isPointerTy())
3682 return Error(PtrLoc, "store operand must be a pointer");
3683 if (!Val->getType()->isFirstClassType())
3684 return Error(Loc, "store operand must be a first class value");
3685 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3686 return Error(Loc, "stored value and pointer type do not match");
3688 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3689 return AteExtraComma ? InstExtraComma : InstNormal;
3692 /// ParseGetElementPtr
3693 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3694 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3695 Value *Ptr, *Val; LocTy Loc, EltLoc;
3697 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3699 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3701 if (!Ptr->getType()->isPointerTy())
3702 return Error(Loc, "base of getelementptr must be a pointer");
3704 SmallVector<Value*, 16> Indices;
3705 bool AteExtraComma = false;
3706 while (EatIfPresent(lltok::comma)) {
3707 if (Lex.getKind() == lltok::MetadataVar) {
3708 AteExtraComma = true;
3711 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3712 if (!Val->getType()->isIntegerTy())
3713 return Error(EltLoc, "getelementptr index must be an integer");
3714 Indices.push_back(Val);
3717 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3718 Indices.begin(), Indices.end()))
3719 return Error(Loc, "invalid getelementptr indices");
3720 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3722 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3723 return AteExtraComma ? InstExtraComma : InstNormal;
3726 /// ParseExtractValue
3727 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3728 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3729 Value *Val; LocTy Loc;
3730 SmallVector<unsigned, 4> Indices;
3732 if (ParseTypeAndValue(Val, Loc, PFS) ||
3733 ParseIndexList(Indices, AteExtraComma))
3736 if (!Val->getType()->isAggregateType())
3737 return Error(Loc, "extractvalue operand must be aggregate type");
3739 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3741 return Error(Loc, "invalid indices for extractvalue");
3742 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3743 return AteExtraComma ? InstExtraComma : InstNormal;
3746 /// ParseInsertValue
3747 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3748 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3749 Value *Val0, *Val1; LocTy Loc0, Loc1;
3750 SmallVector<unsigned, 4> Indices;
3752 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3753 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3754 ParseTypeAndValue(Val1, Loc1, PFS) ||
3755 ParseIndexList(Indices, AteExtraComma))
3758 if (!Val0->getType()->isAggregateType())
3759 return Error(Loc0, "insertvalue operand must be aggregate type");
3761 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3763 return Error(Loc0, "invalid indices for insertvalue");
3764 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3765 return AteExtraComma ? InstExtraComma : InstNormal;
3768 //===----------------------------------------------------------------------===//
3769 // Embedded metadata.
3770 //===----------------------------------------------------------------------===//
3772 /// ParseMDNodeVector
3773 /// ::= Element (',' Element)*
3775 /// ::= 'null' | TypeAndValue
3776 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3777 PerFunctionState *PFS) {
3778 // Check for an empty list.
3779 if (Lex.getKind() == lltok::rbrace)
3783 // Null is a special case since it is typeless.
3784 if (EatIfPresent(lltok::kw_null)) {
3790 PATypeHolder Ty(Type::getVoidTy(Context));
3792 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3793 ConvertValIDToValue(Ty, ID, V, PFS))
3797 } while (EatIfPresent(lltok::comma));