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 /// Run: module ::= toplevelentity*
30 bool LLParser::Run() {
34 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
38 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40 bool LLParser::ValidateEndOfModule() {
41 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata
.empty()) {
43 for (DenseMap
<Instruction
*, std::vector
<MDRef
> >::iterator
44 I
= ForwardRefInstMetadata
.begin(), E
= ForwardRefInstMetadata
.end();
46 Instruction
*Inst
= I
->first
;
47 const std::vector
<MDRef
> &MDList
= I
->second
;
49 for (unsigned i
= 0, e
= MDList
.size(); i
!= e
; ++i
) {
50 unsigned SlotNo
= MDList
[i
].MDSlot
;
52 if (SlotNo
>= NumberedMetadata
.size() || NumberedMetadata
[SlotNo
] == 0)
53 return Error(MDList
[i
].Loc
, "use of undefined metadata '!" +
55 Inst
->setMetadata(MDList
[i
].MDKind
, NumberedMetadata
[SlotNo
]);
58 ForwardRefInstMetadata
.clear();
62 // Update auto-upgraded malloc calls to "malloc".
63 // FIXME: Remove in LLVM 3.0.
65 MallocF
->setName("malloc");
66 // If setName() does not set the name to "malloc", then there is already a
67 // declaration of "malloc". In that case, iterate over all calls to MallocF
68 // and get them to call the declared "malloc" instead.
69 if (MallocF
->getName() != "malloc") {
70 Constant
*RealMallocF
= M
->getFunction("malloc");
71 if (RealMallocF
->getType() != MallocF
->getType())
72 RealMallocF
= ConstantExpr::getBitCast(RealMallocF
, MallocF
->getType());
73 MallocF
->replaceAllUsesWith(RealMallocF
);
74 MallocF
->eraseFromParent();
80 // If there are entries in ForwardRefBlockAddresses at this point, they are
81 // references after the function was defined. Resolve those now.
82 while (!ForwardRefBlockAddresses
.empty()) {
83 // Okay, we are referencing an already-parsed function, resolve them now.
85 const ValID
&Fn
= ForwardRefBlockAddresses
.begin()->first
;
86 if (Fn
.Kind
== ValID::t_GlobalName
)
87 TheFn
= M
->getFunction(Fn
.StrVal
);
88 else if (Fn
.UIntVal
< NumberedVals
.size())
89 TheFn
= dyn_cast
<Function
>(NumberedVals
[Fn
.UIntVal
]);
92 return Error(Fn
.Loc
, "unknown function referenced by blockaddress");
94 // Resolve all these references.
95 if (ResolveForwardRefBlockAddresses(TheFn
,
96 ForwardRefBlockAddresses
.begin()->second
,
100 ForwardRefBlockAddresses
.erase(ForwardRefBlockAddresses
.begin());
104 if (!ForwardRefTypes
.empty())
105 return Error(ForwardRefTypes
.begin()->second
.second
,
106 "use of undefined type named '" +
107 ForwardRefTypes
.begin()->first
+ "'");
108 if (!ForwardRefTypeIDs
.empty())
109 return Error(ForwardRefTypeIDs
.begin()->second
.second
,
110 "use of undefined type '%" +
111 Twine(ForwardRefTypeIDs
.begin()->first
) + "'");
113 if (!ForwardRefVals
.empty())
114 return Error(ForwardRefVals
.begin()->second
.second
,
115 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
118 if (!ForwardRefValIDs
.empty())
119 return Error(ForwardRefValIDs
.begin()->second
.second
,
120 "use of undefined value '@" +
121 Twine(ForwardRefValIDs
.begin()->first
) + "'");
123 if (!ForwardRefMDNodes
.empty())
124 return Error(ForwardRefMDNodes
.begin()->second
.second
,
125 "use of undefined metadata '!" +
126 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
129 // Look for intrinsic functions and CallInst that need to be upgraded
130 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
131 UpgradeCallsToIntrinsic(FI
++); // must be post-increment, as we remove
133 // Check debug info intrinsics.
134 CheckDebugInfoIntrinsics(M
);
138 bool LLParser::ResolveForwardRefBlockAddresses(Function
*TheFn
,
139 std::vector
<std::pair
<ValID
, GlobalValue
*> > &Refs
,
140 PerFunctionState
*PFS
) {
141 // Loop over all the references, resolving them.
142 for (unsigned i
= 0, e
= Refs
.size(); i
!= e
; ++i
) {
145 if (Refs
[i
].first
.Kind
== ValID::t_LocalName
)
146 Res
= PFS
->GetBB(Refs
[i
].first
.StrVal
, Refs
[i
].first
.Loc
);
148 Res
= PFS
->GetBB(Refs
[i
].first
.UIntVal
, Refs
[i
].first
.Loc
);
149 } else if (Refs
[i
].first
.Kind
== ValID::t_LocalID
) {
150 return Error(Refs
[i
].first
.Loc
,
151 "cannot take address of numeric label after the function is defined");
153 Res
= dyn_cast_or_null
<BasicBlock
>(
154 TheFn
->getValueSymbolTable().lookup(Refs
[i
].first
.StrVal
));
158 return Error(Refs
[i
].first
.Loc
,
159 "referenced value is not a basic block");
161 // Get the BlockAddress for this and update references to use it.
162 BlockAddress
*BA
= BlockAddress::get(TheFn
, Res
);
163 Refs
[i
].second
->replaceAllUsesWith(BA
);
164 Refs
[i
].second
->eraseFromParent();
170 //===----------------------------------------------------------------------===//
171 // Top-Level Entities
172 //===----------------------------------------------------------------------===//
174 bool LLParser::ParseTopLevelEntities() {
176 switch (Lex
.getKind()) {
177 default: return TokError("expected top-level entity");
178 case lltok::Eof
: return false;
179 //case lltok::kw_define:
180 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
181 case lltok::kw_define
: if (ParseDefine()) return true; break;
182 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
183 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
184 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
185 case lltok::kw_type
: if (ParseUnnamedType()) return true; break;
186 case lltok::LocalVarID
: if (ParseUnnamedType()) return true; break;
187 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
188 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
189 case lltok::GlobalID
: if (ParseUnnamedGlobal()) return true; break;
190 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
191 case lltok::exclaim
: if (ParseStandaloneMetadata()) return true; break;
192 case lltok::MetadataVar
: if (ParseNamedMetadata()) return true; break;
194 // The Global variable production with no name can have many different
195 // optional leading prefixes, the production is:
196 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
197 // OptionalAddrSpace ('constant'|'global') ...
198 case lltok::kw_private
: // OptionalLinkage
199 case lltok::kw_linker_private
: // OptionalLinkage
200 case lltok::kw_linker_private_weak
: // OptionalLinkage
201 case lltok::kw_linker_private_weak_def_auto
: // OptionalLinkage
202 case lltok::kw_internal
: // OptionalLinkage
203 case lltok::kw_weak
: // OptionalLinkage
204 case lltok::kw_weak_odr
: // OptionalLinkage
205 case lltok::kw_linkonce
: // OptionalLinkage
206 case lltok::kw_linkonce_odr
: // OptionalLinkage
207 case lltok::kw_appending
: // OptionalLinkage
208 case lltok::kw_dllexport
: // OptionalLinkage
209 case lltok::kw_common
: // OptionalLinkage
210 case lltok::kw_dllimport
: // OptionalLinkage
211 case lltok::kw_extern_weak
: // OptionalLinkage
212 case lltok::kw_external
: { // OptionalLinkage
213 unsigned Linkage
, Visibility
;
214 if (ParseOptionalLinkage(Linkage
) ||
215 ParseOptionalVisibility(Visibility
) ||
216 ParseGlobal("", SMLoc(), Linkage
, true, Visibility
))
220 case lltok::kw_default
: // OptionalVisibility
221 case lltok::kw_hidden
: // OptionalVisibility
222 case lltok::kw_protected
: { // OptionalVisibility
224 if (ParseOptionalVisibility(Visibility
) ||
225 ParseGlobal("", SMLoc(), 0, false, Visibility
))
230 case lltok::kw_thread_local
: // OptionalThreadLocal
231 case lltok::kw_addrspace
: // OptionalAddrSpace
232 case lltok::kw_constant
: // GlobalType
233 case lltok::kw_global
: // GlobalType
234 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
242 /// ::= 'module' 'asm' STRINGCONSTANT
243 bool LLParser::ParseModuleAsm() {
244 assert(Lex
.getKind() == lltok::kw_module
);
248 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
249 ParseStringConstant(AsmStr
)) return true;
251 const std::string
&AsmSoFar
= M
->getModuleInlineAsm();
252 if (AsmSoFar
.empty())
253 M
->setModuleInlineAsm(AsmStr
);
255 M
->setModuleInlineAsm(AsmSoFar
+"\n"+AsmStr
);
260 /// ::= 'target' 'triple' '=' STRINGCONSTANT
261 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
262 bool LLParser::ParseTargetDefinition() {
263 assert(Lex
.getKind() == lltok::kw_target
);
266 default: return TokError("unknown target property");
267 case lltok::kw_triple
:
269 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
270 ParseStringConstant(Str
))
272 M
->setTargetTriple(Str
);
274 case lltok::kw_datalayout
:
276 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
277 ParseStringConstant(Str
))
279 M
->setDataLayout(Str
);
285 /// ::= 'deplibs' '=' '[' ']'
286 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
287 bool LLParser::ParseDepLibs() {
288 assert(Lex
.getKind() == lltok::kw_deplibs
);
290 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
291 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
294 if (EatIfPresent(lltok::rsquare
))
298 if (ParseStringConstant(Str
)) return true;
301 while (EatIfPresent(lltok::comma
)) {
302 if (ParseStringConstant(Str
)) return true;
306 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
309 /// ParseUnnamedType:
311 /// ::= LocalVarID '=' 'type' type
312 bool LLParser::ParseUnnamedType() {
313 unsigned TypeID
= NumberedTypes
.size();
315 // Handle the LocalVarID form.
316 if (Lex
.getKind() == lltok::LocalVarID
) {
317 if (Lex
.getUIntVal() != TypeID
)
318 return Error(Lex
.getLoc(), "type expected to be numbered '%" +
319 Twine(TypeID
) + "'");
320 Lex
.Lex(); // eat LocalVarID;
322 if (ParseToken(lltok::equal
, "expected '=' after name"))
326 LocTy TypeLoc
= Lex
.getLoc();
327 if (ParseToken(lltok::kw_type
, "expected 'type' after '='")) return true;
329 PATypeHolder
Ty(Type::getVoidTy(Context
));
330 if (ParseType(Ty
)) return true;
332 // See if this type was previously referenced.
333 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
334 FI
= ForwardRefTypeIDs
.find(TypeID
);
335 if (FI
!= ForwardRefTypeIDs
.end()) {
336 if (FI
->second
.first
.get() == Ty
)
337 return Error(TypeLoc
, "self referential type is invalid");
339 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
340 Ty
= FI
->second
.first
.get();
341 ForwardRefTypeIDs
.erase(FI
);
344 NumberedTypes
.push_back(Ty
);
350 /// ::= LocalVar '=' 'type' type
351 bool LLParser::ParseNamedType() {
352 std::string Name
= Lex
.getStrVal();
353 LocTy NameLoc
= Lex
.getLoc();
354 Lex
.Lex(); // eat LocalVar.
356 PATypeHolder
Ty(Type::getVoidTy(Context
));
358 if (ParseToken(lltok::equal
, "expected '=' after name") ||
359 ParseToken(lltok::kw_type
, "expected 'type' after name") ||
363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists
= M
->addTypeName(Name
, Ty
);
365 if (!AlreadyExists
) return false;
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map
<std::string
, std::pair
<PATypeHolder
, LocTy
> >::iterator
370 FI
= ForwardRefTypes
.find(Name
);
371 if (FI
!= ForwardRefTypes
.end()) {
372 if (FI
->second
.first
.get() == Ty
)
373 return Error(NameLoc
, "self referential type is invalid");
375 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
376 Ty
= FI
->second
.first
.get();
377 ForwardRefTypes
.erase(FI
);
380 // Inserting a name that is already defined, get the existing name.
381 const Type
*Existing
= M
->getTypeByName(Name
);
382 assert(Existing
&& "Conflict but no matching type?!");
384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing
== Ty
) return false;
389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc
, "redefinition of type named '" + Name
+ "' of type '" +
391 Ty
->getDescription() + "'");
396 /// ::= 'declare' FunctionHeader
397 bool LLParser::ParseDeclare() {
398 assert(Lex
.getKind() == lltok::kw_declare
);
402 return ParseFunctionHeader(F
, false);
406 /// ::= 'define' FunctionHeader '{' ...
407 bool LLParser::ParseDefine() {
408 assert(Lex
.getKind() == lltok::kw_define
);
412 return ParseFunctionHeader(F
, true) ||
413 ParseFunctionBody(*F
);
419 bool LLParser::ParseGlobalType(bool &IsConstant
) {
420 if (Lex
.getKind() == lltok::kw_constant
)
422 else if (Lex
.getKind() == lltok::kw_global
)
426 return TokError("expected 'global' or 'constant'");
432 /// ParseUnnamedGlobal:
433 /// OptionalVisibility ALIAS ...
434 /// OptionalLinkage OptionalVisibility ... -> global variable
435 /// GlobalID '=' OptionalVisibility ALIAS ...
436 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437 bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID
= NumberedVals
.size();
440 LocTy NameLoc
= Lex
.getLoc();
442 // Handle the GlobalID form.
443 if (Lex
.getKind() == lltok::GlobalID
) {
444 if (Lex
.getUIntVal() != VarID
)
445 return Error(Lex
.getLoc(), "variable expected to be numbered '%" +
447 Lex
.Lex(); // eat GlobalID;
449 if (ParseToken(lltok::equal
, "expected '=' after name"))
454 unsigned Linkage
, Visibility
;
455 if (ParseOptionalLinkage(Linkage
, HasLinkage
) ||
456 ParseOptionalVisibility(Visibility
))
459 if (HasLinkage
|| Lex
.getKind() != lltok::kw_alias
)
460 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
);
461 return ParseAlias(Name
, NameLoc
, Visibility
);
464 /// ParseNamedGlobal:
465 /// GlobalVar '=' OptionalVisibility ALIAS ...
466 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467 bool LLParser::ParseNamedGlobal() {
468 assert(Lex
.getKind() == lltok::GlobalVar
);
469 LocTy NameLoc
= Lex
.getLoc();
470 std::string Name
= Lex
.getStrVal();
474 unsigned Linkage
, Visibility
;
475 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage
, HasLinkage
) ||
477 ParseOptionalVisibility(Visibility
))
480 if (HasLinkage
|| Lex
.getKind() != lltok::kw_alias
)
481 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
);
482 return ParseAlias(Name
, NameLoc
, Visibility
);
486 // ::= '!' STRINGCONSTANT
487 bool LLParser::ParseMDString(MDString
*&Result
) {
489 if (ParseStringConstant(Str
)) return true;
490 Result
= MDString::get(Context
, Str
);
495 // ::= '!' MDNodeNumber
497 /// This version of ParseMDNodeID returns the slot number and null in the case
498 /// of a forward reference.
499 bool LLParser::ParseMDNodeID(MDNode
*&Result
, unsigned &SlotNo
) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo
)) return true;
503 // Check existing MDNode.
504 if (SlotNo
< NumberedMetadata
.size() && NumberedMetadata
[SlotNo
] != 0)
505 Result
= NumberedMetadata
[SlotNo
];
511 bool LLParser::ParseMDNodeID(MDNode
*&Result
) {
512 // !{ ..., !42, ... }
514 if (ParseMDNodeID(Result
, MID
)) return true;
516 // If not a forward reference, just return it now.
517 if (Result
) return false;
519 // Otherwise, create MDNode forward reference.
520 MDNode
*FwdNode
= MDNode::getTemporary(Context
, 0, 0);
521 ForwardRefMDNodes
[MID
] = std::make_pair(FwdNode
, Lex
.getLoc());
523 if (NumberedMetadata
.size() <= MID
)
524 NumberedMetadata
.resize(MID
+1);
525 NumberedMetadata
[MID
] = FwdNode
;
530 /// ParseNamedMetadata:
531 /// !foo = !{ !1, !2 }
532 bool LLParser::ParseNamedMetadata() {
533 assert(Lex
.getKind() == lltok::MetadataVar
);
534 std::string Name
= Lex
.getStrVal();
537 if (ParseToken(lltok::equal
, "expected '=' here") ||
538 ParseToken(lltok::exclaim
, "Expected '!' here") ||
539 ParseToken(lltok::lbrace
, "Expected '{' here"))
542 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
543 if (Lex
.getKind() != lltok::rbrace
)
545 if (ParseToken(lltok::exclaim
, "Expected '!' here"))
549 if (ParseMDNodeID(N
)) return true;
551 } while (EatIfPresent(lltok::comma
));
553 if (ParseToken(lltok::rbrace
, "expected end of metadata node"))
559 /// ParseStandaloneMetadata:
561 bool LLParser::ParseStandaloneMetadata() {
562 assert(Lex
.getKind() == lltok::exclaim
);
564 unsigned MetadataID
= 0;
567 PATypeHolder
Ty(Type::getVoidTy(Context
));
568 SmallVector
<Value
*, 16> Elts
;
569 if (ParseUInt32(MetadataID
) ||
570 ParseToken(lltok::equal
, "expected '=' here") ||
571 ParseType(Ty
, TyLoc
) ||
572 ParseToken(lltok::exclaim
, "Expected '!' here") ||
573 ParseToken(lltok::lbrace
, "Expected '{' here") ||
574 ParseMDNodeVector(Elts
, NULL
) ||
575 ParseToken(lltok::rbrace
, "expected end of metadata node"))
578 MDNode
*Init
= MDNode::get(Context
, Elts
.data(), Elts
.size());
580 // See if this was forward referenced, if so, handle it.
581 std::map
<unsigned, std::pair
<TrackingVH
<MDNode
>, LocTy
> >::iterator
582 FI
= ForwardRefMDNodes
.find(MetadataID
);
583 if (FI
!= ForwardRefMDNodes
.end()) {
584 MDNode
*Temp
= FI
->second
.first
;
585 Temp
->replaceAllUsesWith(Init
);
586 MDNode::deleteTemporary(Temp
);
587 ForwardRefMDNodes
.erase(FI
);
589 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
591 if (MetadataID
>= NumberedMetadata
.size())
592 NumberedMetadata
.resize(MetadataID
+1);
594 if (NumberedMetadata
[MetadataID
] != 0)
595 return TokError("Metadata id is already used");
596 NumberedMetadata
[MetadataID
] = Init
;
603 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
606 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
607 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
609 /// Everything through visibility has already been parsed.
611 bool LLParser::ParseAlias(const std::string
&Name
, LocTy NameLoc
,
612 unsigned Visibility
) {
613 assert(Lex
.getKind() == lltok::kw_alias
);
616 LocTy LinkageLoc
= Lex
.getLoc();
617 if (ParseOptionalLinkage(Linkage
))
620 if (Linkage
!= GlobalValue::ExternalLinkage
&&
621 Linkage
!= GlobalValue::WeakAnyLinkage
&&
622 Linkage
!= GlobalValue::WeakODRLinkage
&&
623 Linkage
!= GlobalValue::InternalLinkage
&&
624 Linkage
!= GlobalValue::PrivateLinkage
&&
625 Linkage
!= GlobalValue::LinkerPrivateLinkage
&&
626 Linkage
!= GlobalValue::LinkerPrivateWeakLinkage
&&
627 Linkage
!= GlobalValue::LinkerPrivateWeakDefAutoLinkage
)
628 return Error(LinkageLoc
, "invalid linkage type for alias");
631 LocTy AliaseeLoc
= Lex
.getLoc();
632 if (Lex
.getKind() != lltok::kw_bitcast
&&
633 Lex
.getKind() != lltok::kw_getelementptr
) {
634 if (ParseGlobalTypeAndValue(Aliasee
)) return true;
636 // The bitcast dest type is not present, it is implied by the dest type.
638 if (ParseValID(ID
)) return true;
639 if (ID
.Kind
!= ValID::t_Constant
)
640 return Error(AliaseeLoc
, "invalid aliasee");
641 Aliasee
= ID
.ConstantVal
;
644 if (!Aliasee
->getType()->isPointerTy())
645 return Error(AliaseeLoc
, "alias must have pointer type");
647 // Okay, create the alias but do not insert it into the module yet.
648 GlobalAlias
* GA
= new GlobalAlias(Aliasee
->getType(),
649 (GlobalValue::LinkageTypes
)Linkage
, Name
,
651 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
653 // See if this value already exists in the symbol table. If so, it is either
654 // a redefinition or a definition of a forward reference.
655 if (GlobalValue
*Val
= M
->getNamedValue(Name
)) {
656 // See if this was a redefinition. If so, there is no entry in
658 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
659 I
= ForwardRefVals
.find(Name
);
660 if (I
== ForwardRefVals
.end())
661 return Error(NameLoc
, "redefinition of global named '@" + Name
+ "'");
663 // Otherwise, this was a definition of forward ref. Verify that types
665 if (Val
->getType() != GA
->getType())
666 return Error(NameLoc
,
667 "forward reference and definition of alias have different types");
669 // If they agree, just RAUW the old value with the alias and remove the
671 Val
->replaceAllUsesWith(GA
);
672 Val
->eraseFromParent();
673 ForwardRefVals
.erase(I
);
676 // Insert into the module, we know its name won't collide now.
677 M
->getAliasList().push_back(GA
);
678 assert(GA
->getName() == Name
&& "Should not be a name conflict!");
684 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
685 /// OptionalAddrSpace GlobalType Type Const
686 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
687 /// OptionalAddrSpace GlobalType Type Const
689 /// Everything through visibility has been parsed already.
691 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
692 unsigned Linkage
, bool HasLinkage
,
693 unsigned Visibility
) {
695 bool ThreadLocal
, IsConstant
;
698 PATypeHolder
Ty(Type::getVoidTy(Context
));
699 if (ParseOptionalToken(lltok::kw_thread_local
, ThreadLocal
) ||
700 ParseOptionalAddrSpace(AddrSpace
) ||
701 ParseGlobalType(IsConstant
) ||
702 ParseType(Ty
, TyLoc
))
705 // If the linkage is specified and is external, then no initializer is
708 if (!HasLinkage
|| (Linkage
!= GlobalValue::DLLImportLinkage
&&
709 Linkage
!= GlobalValue::ExternalWeakLinkage
&&
710 Linkage
!= GlobalValue::ExternalLinkage
)) {
711 if (ParseGlobalValue(Ty
, Init
))
715 if (Ty
->isFunctionTy() || Ty
->isLabelTy())
716 return Error(TyLoc
, "invalid type for global variable");
718 GlobalVariable
*GV
= 0;
720 // See if the global was forward referenced, if so, use the global.
722 if (GlobalValue
*GVal
= M
->getNamedValue(Name
)) {
723 if (!ForwardRefVals
.erase(Name
) || !isa
<GlobalValue
>(GVal
))
724 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
725 GV
= cast
<GlobalVariable
>(GVal
);
728 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
729 I
= ForwardRefValIDs
.find(NumberedVals
.size());
730 if (I
!= ForwardRefValIDs
.end()) {
731 GV
= cast
<GlobalVariable
>(I
->second
.first
);
732 ForwardRefValIDs
.erase(I
);
737 GV
= new GlobalVariable(*M
, Ty
, false, GlobalValue::ExternalLinkage
, 0,
738 Name
, 0, false, AddrSpace
);
740 if (GV
->getType()->getElementType() != Ty
)
742 "forward reference and definition of global have different types");
744 // Move the forward-reference to the correct spot in the module.
745 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
749 NumberedVals
.push_back(GV
);
751 // Set the parsed properties on the global.
753 GV
->setInitializer(Init
);
754 GV
->setConstant(IsConstant
);
755 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
756 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
757 GV
->setThreadLocal(ThreadLocal
);
759 // Parse attributes on the global.
760 while (Lex
.getKind() == lltok::comma
) {
763 if (Lex
.getKind() == lltok::kw_section
) {
765 GV
->setSection(Lex
.getStrVal());
766 if (ParseToken(lltok::StringConstant
, "expected global section string"))
768 } else if (Lex
.getKind() == lltok::kw_align
) {
770 if (ParseOptionalAlignment(Alignment
)) return true;
771 GV
->setAlignment(Alignment
);
773 TokError("unknown global variable property!");
781 //===----------------------------------------------------------------------===//
782 // GlobalValue Reference/Resolution Routines.
783 //===----------------------------------------------------------------------===//
785 /// GetGlobalVal - Get a value with the specified name or ID, creating a
786 /// forward reference record if needed. This can return null if the value
787 /// exists but does not have the right type.
788 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, const Type
*Ty
,
790 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
792 Error(Loc
, "global variable reference must have pointer type");
796 // Look this name up in the normal function symbol table.
798 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
800 // If this is a forward reference for the value, see if we already created a
801 // forward ref record.
803 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
804 I
= ForwardRefVals
.find(Name
);
805 if (I
!= ForwardRefVals
.end())
806 Val
= I
->second
.first
;
809 // If we have the value in the symbol table or fwd-ref table, return it.
811 if (Val
->getType() == Ty
) return Val
;
812 Error(Loc
, "'@" + Name
+ "' defined with type '" +
813 Val
->getType()->getDescription() + "'");
817 // Otherwise, create a new forward reference for this value and remember it.
819 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
820 // Function types can return opaque but functions can't.
821 if (FT
->getReturnType()->isOpaqueTy()) {
822 Error(Loc
, "function may not return opaque type");
826 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, Name
, M
);
828 FwdVal
= new GlobalVariable(*M
, PTy
->getElementType(), false,
829 GlobalValue::ExternalWeakLinkage
, 0, Name
);
832 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
836 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, const Type
*Ty
, LocTy Loc
) {
837 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
839 Error(Loc
, "global variable reference must have pointer type");
843 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
845 // If this is a forward reference for the value, see if we already created a
846 // forward ref record.
848 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
849 I
= ForwardRefValIDs
.find(ID
);
850 if (I
!= ForwardRefValIDs
.end())
851 Val
= I
->second
.first
;
854 // If we have the value in the symbol table or fwd-ref table, return it.
856 if (Val
->getType() == Ty
) return Val
;
857 Error(Loc
, "'@" + Twine(ID
) + "' defined with type '" +
858 Val
->getType()->getDescription() + "'");
862 // Otherwise, create a new forward reference for this value and remember it.
864 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
865 // Function types can return opaque but functions can't.
866 if (FT
->getReturnType()->isOpaqueTy()) {
867 Error(Loc
, "function may not return opaque type");
870 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, "", M
);
872 FwdVal
= new GlobalVariable(*M
, PTy
->getElementType(), false,
873 GlobalValue::ExternalWeakLinkage
, 0, "");
876 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
881 //===----------------------------------------------------------------------===//
883 //===----------------------------------------------------------------------===//
885 /// ParseToken - If the current token has the specified kind, eat it and return
886 /// success. Otherwise, emit the specified error and return failure.
887 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
888 if (Lex
.getKind() != T
)
889 return TokError(ErrMsg
);
894 /// ParseStringConstant
895 /// ::= StringConstant
896 bool LLParser::ParseStringConstant(std::string
&Result
) {
897 if (Lex
.getKind() != lltok::StringConstant
)
898 return TokError("expected string constant");
899 Result
= Lex
.getStrVal();
906 bool LLParser::ParseUInt32(unsigned &Val
) {
907 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
908 return TokError("expected integer");
909 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
910 if (Val64
!= unsigned(Val64
))
911 return TokError("expected 32-bit integer (too large)");
918 /// ParseOptionalAddrSpace
920 /// := 'addrspace' '(' uint32 ')'
921 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
) {
923 if (!EatIfPresent(lltok::kw_addrspace
))
925 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
926 ParseUInt32(AddrSpace
) ||
927 ParseToken(lltok::rparen
, "expected ')' in address space");
930 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
931 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
932 /// 2: function attr.
933 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
934 bool LLParser::ParseOptionalAttrs(unsigned &Attrs
, unsigned AttrKind
) {
935 Attrs
= Attribute::None
;
936 LocTy AttrLoc
= Lex
.getLoc();
939 switch (Lex
.getKind()) {
942 // Treat these as signext/zeroext if they occur in the argument list after
943 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
944 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
946 // FIXME: REMOVE THIS IN LLVM 3.0
948 if (Lex
.getKind() == lltok::kw_sext
)
949 Attrs
|= Attribute::SExt
;
951 Attrs
|= Attribute::ZExt
;
955 default: // End of attributes.
956 if (AttrKind
!= 2 && (Attrs
& Attribute::FunctionOnly
))
957 return Error(AttrLoc
, "invalid use of function-only attribute");
959 if (AttrKind
!= 0 && AttrKind
!= 3 && (Attrs
& Attribute::ParameterOnly
))
960 return Error(AttrLoc
, "invalid use of parameter-only attribute");
963 case lltok::kw_zeroext
: Attrs
|= Attribute::ZExt
; break;
964 case lltok::kw_signext
: Attrs
|= Attribute::SExt
; break;
965 case lltok::kw_inreg
: Attrs
|= Attribute::InReg
; break;
966 case lltok::kw_sret
: Attrs
|= Attribute::StructRet
; break;
967 case lltok::kw_noalias
: Attrs
|= Attribute::NoAlias
; break;
968 case lltok::kw_nocapture
: Attrs
|= Attribute::NoCapture
; break;
969 case lltok::kw_byval
: Attrs
|= Attribute::ByVal
; break;
970 case lltok::kw_nest
: Attrs
|= Attribute::Nest
; break;
972 case lltok::kw_noreturn
: Attrs
|= Attribute::NoReturn
; break;
973 case lltok::kw_nounwind
: Attrs
|= Attribute::NoUnwind
; break;
974 case lltok::kw_noinline
: Attrs
|= Attribute::NoInline
; break;
975 case lltok::kw_readnone
: Attrs
|= Attribute::ReadNone
; break;
976 case lltok::kw_readonly
: Attrs
|= Attribute::ReadOnly
; break;
977 case lltok::kw_inlinehint
: Attrs
|= Attribute::InlineHint
; break;
978 case lltok::kw_alwaysinline
: Attrs
|= Attribute::AlwaysInline
; break;
979 case lltok::kw_optsize
: Attrs
|= Attribute::OptimizeForSize
; break;
980 case lltok::kw_ssp
: Attrs
|= Attribute::StackProtect
; break;
981 case lltok::kw_sspreq
: Attrs
|= Attribute::StackProtectReq
; break;
982 case lltok::kw_noredzone
: Attrs
|= Attribute::NoRedZone
; break;
983 case lltok::kw_noimplicitfloat
: Attrs
|= Attribute::NoImplicitFloat
; break;
984 case lltok::kw_naked
: Attrs
|= Attribute::Naked
; break;
985 case lltok::kw_hotpatch
: Attrs
|= Attribute::Hotpatch
; break;
987 case lltok::kw_alignstack
: {
989 if (ParseOptionalStackAlignment(Alignment
))
991 Attrs
|= Attribute::constructStackAlignmentFromInt(Alignment
);
995 case lltok::kw_align
: {
997 if (ParseOptionalAlignment(Alignment
))
999 Attrs
|= Attribute::constructAlignmentFromInt(Alignment
);
1008 /// ParseOptionalLinkage
1011 /// ::= 'linker_private'
1012 /// ::= 'linker_private_weak'
1013 /// ::= 'linker_private_weak_def_auto'
1018 /// ::= 'linkonce_odr'
1019 /// ::= 'available_externally'
1024 /// ::= 'extern_weak'
1026 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
) {
1028 switch (Lex
.getKind()) {
1029 default: Res
=GlobalValue::ExternalLinkage
; return false;
1030 case lltok::kw_private
: Res
= GlobalValue::PrivateLinkage
; break;
1031 case lltok::kw_linker_private
: Res
= GlobalValue::LinkerPrivateLinkage
; break;
1032 case lltok::kw_linker_private_weak
:
1033 Res
= GlobalValue::LinkerPrivateWeakLinkage
;
1035 case lltok::kw_linker_private_weak_def_auto
:
1036 Res
= GlobalValue::LinkerPrivateWeakDefAutoLinkage
;
1038 case lltok::kw_internal
: Res
= GlobalValue::InternalLinkage
; break;
1039 case lltok::kw_weak
: Res
= GlobalValue::WeakAnyLinkage
; break;
1040 case lltok::kw_weak_odr
: Res
= GlobalValue::WeakODRLinkage
; break;
1041 case lltok::kw_linkonce
: Res
= GlobalValue::LinkOnceAnyLinkage
; break;
1042 case lltok::kw_linkonce_odr
: Res
= GlobalValue::LinkOnceODRLinkage
; break;
1043 case lltok::kw_available_externally
:
1044 Res
= GlobalValue::AvailableExternallyLinkage
;
1046 case lltok::kw_appending
: Res
= GlobalValue::AppendingLinkage
; break;
1047 case lltok::kw_dllexport
: Res
= GlobalValue::DLLExportLinkage
; break;
1048 case lltok::kw_common
: Res
= GlobalValue::CommonLinkage
; break;
1049 case lltok::kw_dllimport
: Res
= GlobalValue::DLLImportLinkage
; break;
1050 case lltok::kw_extern_weak
: Res
= GlobalValue::ExternalWeakLinkage
; break;
1051 case lltok::kw_external
: Res
= GlobalValue::ExternalLinkage
; break;
1058 /// ParseOptionalVisibility
1064 bool LLParser::ParseOptionalVisibility(unsigned &Res
) {
1065 switch (Lex
.getKind()) {
1066 default: Res
= GlobalValue::DefaultVisibility
; return false;
1067 case lltok::kw_default
: Res
= GlobalValue::DefaultVisibility
; break;
1068 case lltok::kw_hidden
: Res
= GlobalValue::HiddenVisibility
; break;
1069 case lltok::kw_protected
: Res
= GlobalValue::ProtectedVisibility
; break;
1075 /// ParseOptionalCallingConv
1080 /// ::= 'x86_stdcallcc'
1081 /// ::= 'x86_fastcallcc'
1082 /// ::= 'x86_thiscallcc'
1083 /// ::= 'arm_apcscc'
1084 /// ::= 'arm_aapcscc'
1085 /// ::= 'arm_aapcs_vfpcc'
1086 /// ::= 'msp430_intrcc'
1087 /// ::= 'ptx_kernel'
1088 /// ::= 'ptx_device'
1091 bool LLParser::ParseOptionalCallingConv(CallingConv::ID
&CC
) {
1092 switch (Lex
.getKind()) {
1093 default: CC
= CallingConv::C
; return false;
1094 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
1095 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
1096 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
1097 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
1098 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
1099 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
1100 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
1101 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
1102 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
1103 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
1104 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
1105 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
1106 case lltok::kw_cc
: {
1107 unsigned ArbitraryCC
;
1109 if (ParseUInt32(ArbitraryCC
)) {
1112 CC
= static_cast<CallingConv::ID
>(ArbitraryCC
);
1122 /// ParseInstructionMetadata
1123 /// ::= !dbg !42 (',' !dbg !57)*
1124 bool LLParser::ParseInstructionMetadata(Instruction
*Inst
,
1125 PerFunctionState
*PFS
) {
1127 if (Lex
.getKind() != lltok::MetadataVar
)
1128 return TokError("expected metadata after comma");
1130 std::string Name
= Lex
.getStrVal();
1131 unsigned MDK
= M
->getMDKindID(Name
.c_str());
1135 SMLoc Loc
= Lex
.getLoc();
1137 if (ParseToken(lltok::exclaim
, "expected '!' here"))
1140 // This code is similar to that of ParseMetadataValue, however it needs to
1141 // have special-case code for a forward reference; see the comments on
1142 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1143 // at the top level here.
1144 if (Lex
.getKind() == lltok::lbrace
) {
1146 if (ParseMetadataListValue(ID
, PFS
))
1148 assert(ID
.Kind
== ValID::t_MDNode
);
1149 Inst
->setMetadata(MDK
, ID
.MDNodeVal
);
1151 unsigned NodeID
= 0;
1152 if (ParseMDNodeID(Node
, NodeID
))
1155 // If we got the node, add it to the instruction.
1156 Inst
->setMetadata(MDK
, Node
);
1158 MDRef R
= { Loc
, MDK
, NodeID
};
1159 // Otherwise, remember that this should be resolved later.
1160 ForwardRefInstMetadata
[Inst
].push_back(R
);
1164 // If this is the end of the list, we're done.
1165 } while (EatIfPresent(lltok::comma
));
1169 /// ParseOptionalAlignment
1172 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
1174 if (!EatIfPresent(lltok::kw_align
))
1176 LocTy AlignLoc
= Lex
.getLoc();
1177 if (ParseUInt32(Alignment
)) return true;
1178 if (!isPowerOf2_32(Alignment
))
1179 return Error(AlignLoc
, "alignment is not a power of two");
1180 if (Alignment
> Value::MaximumAlignment
)
1181 return Error(AlignLoc
, "huge alignments are not supported yet");
1185 /// ParseOptionalCommaAlign
1189 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1191 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment
,
1192 bool &AteExtraComma
) {
1193 AteExtraComma
= false;
1194 while (EatIfPresent(lltok::comma
)) {
1195 // Metadata at the end is an early exit.
1196 if (Lex
.getKind() == lltok::MetadataVar
) {
1197 AteExtraComma
= true;
1201 if (Lex
.getKind() != lltok::kw_align
)
1202 return Error(Lex
.getLoc(), "expected metadata or 'align'");
1204 if (ParseOptionalAlignment(Alignment
)) return true;
1210 /// ParseOptionalStackAlignment
1212 /// ::= 'alignstack' '(' 4 ')'
1213 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment
) {
1215 if (!EatIfPresent(lltok::kw_alignstack
))
1217 LocTy ParenLoc
= Lex
.getLoc();
1218 if (!EatIfPresent(lltok::lparen
))
1219 return Error(ParenLoc
, "expected '('");
1220 LocTy AlignLoc
= Lex
.getLoc();
1221 if (ParseUInt32(Alignment
)) return true;
1222 ParenLoc
= Lex
.getLoc();
1223 if (!EatIfPresent(lltok::rparen
))
1224 return Error(ParenLoc
, "expected ')'");
1225 if (!isPowerOf2_32(Alignment
))
1226 return Error(AlignLoc
, "stack alignment is not a power of two");
1230 /// ParseIndexList - This parses the index list for an insert/extractvalue
1231 /// instruction. This sets AteExtraComma in the case where we eat an extra
1232 /// comma at the end of the line and find that it is followed by metadata.
1233 /// Clients that don't allow metadata can call the version of this function that
1234 /// only takes one argument.
1237 /// ::= (',' uint32)+
1239 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
,
1240 bool &AteExtraComma
) {
1241 AteExtraComma
= false;
1243 if (Lex
.getKind() != lltok::comma
)
1244 return TokError("expected ',' as start of index list");
1246 while (EatIfPresent(lltok::comma
)) {
1247 if (Lex
.getKind() == lltok::MetadataVar
) {
1248 AteExtraComma
= true;
1252 if (ParseUInt32(Idx
)) return true;
1253 Indices
.push_back(Idx
);
1259 //===----------------------------------------------------------------------===//
1261 //===----------------------------------------------------------------------===//
1263 /// ParseType - Parse and resolve a full type.
1264 bool LLParser::ParseType(PATypeHolder
&Result
, bool AllowVoid
) {
1265 LocTy TypeLoc
= Lex
.getLoc();
1266 if (ParseTypeRec(Result
)) return true;
1268 // Verify no unresolved uprefs.
1269 if (!UpRefs
.empty())
1270 return Error(UpRefs
.back().Loc
, "invalid unresolved type up reference");
1272 if (!AllowVoid
&& Result
.get()->isVoidTy())
1273 return Error(TypeLoc
, "void type only allowed for function results");
1278 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1279 /// called. It loops through the UpRefs vector, which is a list of the
1280 /// currently active types. For each type, if the up-reference is contained in
1281 /// the newly completed type, we decrement the level count. When the level
1282 /// count reaches zero, the up-referenced type is the type that is passed in:
1283 /// thus we can complete the cycle.
1285 PATypeHolder
LLParser::HandleUpRefs(const Type
*ty
) {
1286 // If Ty isn't abstract, or if there are no up-references in it, then there is
1287 // nothing to resolve here.
1288 if (!ty
->isAbstract() || UpRefs
.empty()) return ty
;
1290 PATypeHolder
Ty(ty
);
1292 dbgs() << "Type '" << Ty
->getDescription()
1293 << "' newly formed. Resolving upreferences.\n"
1294 << UpRefs
.size() << " upreferences active!\n";
1297 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1298 // to zero), we resolve them all together before we resolve them to Ty. At
1299 // the end of the loop, if there is anything to resolve to Ty, it will be in
1301 OpaqueType
*TypeToResolve
= 0;
1303 for (unsigned i
= 0; i
!= UpRefs
.size(); ++i
) {
1304 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1306 std::find(Ty
->subtype_begin(), Ty
->subtype_end(),
1307 UpRefs
[i
].LastContainedTy
) != Ty
->subtype_end();
1310 dbgs() << " UR#" << i
<< " - TypeContains(" << Ty
->getDescription() << ", "
1311 << UpRefs
[i
].LastContainedTy
->getDescription() << ") = "
1312 << (ContainsType
? "true" : "false")
1313 << " level=" << UpRefs
[i
].NestingLevel
<< "\n";
1318 // Decrement level of upreference
1319 unsigned Level
= --UpRefs
[i
].NestingLevel
;
1320 UpRefs
[i
].LastContainedTy
= Ty
;
1322 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1327 dbgs() << " * Resolving upreference for " << UpRefs
[i
].UpRefTy
<< "\n";
1330 TypeToResolve
= UpRefs
[i
].UpRefTy
;
1332 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo(TypeToResolve
);
1333 UpRefs
.erase(UpRefs
.begin()+i
); // Remove from upreference list.
1334 --i
; // Do not skip the next element.
1338 TypeToResolve
->refineAbstractTypeTo(Ty
);
1344 /// ParseTypeRec - The recursive function used to process the internal
1345 /// implementation details of types.
1346 bool LLParser::ParseTypeRec(PATypeHolder
&Result
) {
1347 switch (Lex
.getKind()) {
1349 return TokError("expected type");
1351 // TypeRec ::= 'float' | 'void' (etc)
1352 Result
= Lex
.getTyVal();
1355 case lltok::kw_opaque
:
1356 // TypeRec ::= 'opaque'
1357 Result
= OpaqueType::get(Context
);
1361 // TypeRec ::= '{' ... '}'
1362 if (ParseStructType(Result
, false))
1365 case lltok::lsquare
:
1366 // TypeRec ::= '[' ... ']'
1367 Lex
.Lex(); // eat the lsquare.
1368 if (ParseArrayVectorType(Result
, false))
1371 case lltok::less
: // Either vector or packed struct.
1372 // TypeRec ::= '<' ... '>'
1374 if (Lex
.getKind() == lltok::lbrace
) {
1375 if (ParseStructType(Result
, true) ||
1376 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
1378 } else if (ParseArrayVectorType(Result
, true))
1381 case lltok::LocalVar
:
1382 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
1384 if (const Type
*T
= M
->getTypeByName(Lex
.getStrVal())) {
1387 Result
= OpaqueType::get(Context
);
1388 ForwardRefTypes
.insert(std::make_pair(Lex
.getStrVal(),
1389 std::make_pair(Result
,
1391 M
->addTypeName(Lex
.getStrVal(), Result
.get());
1396 case lltok::LocalVarID
:
1398 if (Lex
.getUIntVal() < NumberedTypes
.size())
1399 Result
= NumberedTypes
[Lex
.getUIntVal()];
1401 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
1402 I
= ForwardRefTypeIDs
.find(Lex
.getUIntVal());
1403 if (I
!= ForwardRefTypeIDs
.end())
1404 Result
= I
->second
.first
;
1406 Result
= OpaqueType::get(Context
);
1407 ForwardRefTypeIDs
.insert(std::make_pair(Lex
.getUIntVal(),
1408 std::make_pair(Result
,
1414 case lltok::backslash
: {
1415 // TypeRec ::= '\' 4
1418 if (ParseUInt32(Val
)) return true;
1419 OpaqueType
*OT
= OpaqueType::get(Context
); //Use temporary placeholder.
1420 UpRefs
.push_back(UpRefRecord(Lex
.getLoc(), Val
, OT
));
1426 // Parse the type suffixes.
1428 switch (Lex
.getKind()) {
1430 default: return false;
1432 // TypeRec ::= TypeRec '*'
1434 if (Result
.get()->isLabelTy())
1435 return TokError("basic block pointers are invalid");
1436 if (Result
.get()->isVoidTy())
1437 return TokError("pointers to void are invalid; use i8* instead");
1438 if (!PointerType::isValidElementType(Result
.get()))
1439 return TokError("pointer to this type is invalid");
1440 Result
= HandleUpRefs(PointerType::getUnqual(Result
.get()));
1444 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1445 case lltok::kw_addrspace
: {
1446 if (Result
.get()->isLabelTy())
1447 return TokError("basic block pointers are invalid");
1448 if (Result
.get()->isVoidTy())
1449 return TokError("pointers to void are invalid; use i8* instead");
1450 if (!PointerType::isValidElementType(Result
.get()))
1451 return TokError("pointer to this type is invalid");
1453 if (ParseOptionalAddrSpace(AddrSpace
) ||
1454 ParseToken(lltok::star
, "expected '*' in address space"))
1457 Result
= HandleUpRefs(PointerType::get(Result
.get(), AddrSpace
));
1461 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1463 if (ParseFunctionType(Result
))
1470 /// ParseParameterList
1472 /// ::= '(' Arg (',' Arg)* ')'
1474 /// ::= Type OptionalAttributes Value OptionalAttributes
1475 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
1476 PerFunctionState
&PFS
) {
1477 if (ParseToken(lltok::lparen
, "expected '(' in call"))
1480 while (Lex
.getKind() != lltok::rparen
) {
1481 // If this isn't the first argument, we need a comma.
1482 if (!ArgList
.empty() &&
1483 ParseToken(lltok::comma
, "expected ',' in argument list"))
1486 // Parse the argument.
1488 PATypeHolder
ArgTy(Type::getVoidTy(Context
));
1489 unsigned ArgAttrs1
= Attribute::None
;
1490 unsigned ArgAttrs2
= Attribute::None
;
1492 if (ParseType(ArgTy
, ArgLoc
))
1495 // Otherwise, handle normal operands.
1496 if (ParseOptionalAttrs(ArgAttrs1
, 0) ||
1497 ParseValue(ArgTy
, V
, PFS
) ||
1498 // FIXME: Should not allow attributes after the argument, remove this
1500 ParseOptionalAttrs(ArgAttrs2
, 3))
1502 ArgList
.push_back(ParamInfo(ArgLoc
, V
, ArgAttrs1
|ArgAttrs2
));
1505 Lex
.Lex(); // Lex the ')'.
1511 /// ParseArgumentList - Parse the argument list for a function type or function
1512 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1513 /// ::= '(' ArgTypeListI ')'
1517 /// ::= ArgTypeList ',' '...'
1518 /// ::= ArgType (',' ArgType)*
1520 bool LLParser::ParseArgumentList(std::vector
<ArgInfo
> &ArgList
,
1521 bool &isVarArg
, bool inType
) {
1523 assert(Lex
.getKind() == lltok::lparen
);
1524 Lex
.Lex(); // eat the (.
1526 if (Lex
.getKind() == lltok::rparen
) {
1528 } else if (Lex
.getKind() == lltok::dotdotdot
) {
1532 LocTy TypeLoc
= Lex
.getLoc();
1533 PATypeHolder
ArgTy(Type::getVoidTy(Context
));
1537 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1538 // types (such as a function returning a pointer to itself). If parsing a
1539 // function prototype, we require fully resolved types.
1540 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1541 ParseOptionalAttrs(Attrs
, 0)) return true;
1543 if (ArgTy
->isVoidTy())
1544 return Error(TypeLoc
, "argument can not have void type");
1546 if (Lex
.getKind() == lltok::LocalVar
||
1547 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1548 Name
= Lex
.getStrVal();
1552 if (!FunctionType::isValidArgumentType(ArgTy
))
1553 return Error(TypeLoc
, "invalid type for function argument");
1555 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1557 while (EatIfPresent(lltok::comma
)) {
1558 // Handle ... at end of arg list.
1559 if (EatIfPresent(lltok::dotdotdot
)) {
1564 // Otherwise must be an argument type.
1565 TypeLoc
= Lex
.getLoc();
1566 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1567 ParseOptionalAttrs(Attrs
, 0)) return true;
1569 if (ArgTy
->isVoidTy())
1570 return Error(TypeLoc
, "argument can not have void type");
1572 if (Lex
.getKind() == lltok::LocalVar
||
1573 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1574 Name
= Lex
.getStrVal();
1580 if (!ArgTy
->isFirstClassType() && !ArgTy
->isOpaqueTy())
1581 return Error(TypeLoc
, "invalid type for function argument");
1583 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1587 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
1590 /// ParseFunctionType
1591 /// ::= Type ArgumentList OptionalAttrs
1592 bool LLParser::ParseFunctionType(PATypeHolder
&Result
) {
1593 assert(Lex
.getKind() == lltok::lparen
);
1595 if (!FunctionType::isValidReturnType(Result
))
1596 return TokError("invalid function return type");
1598 std::vector
<ArgInfo
> ArgList
;
1601 if (ParseArgumentList(ArgList
, isVarArg
, true) ||
1602 // FIXME: Allow, but ignore attributes on function types!
1603 // FIXME: Remove in LLVM 3.0
1604 ParseOptionalAttrs(Attrs
, 2))
1607 // Reject names on the arguments lists.
1608 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
1609 if (!ArgList
[i
].Name
.empty())
1610 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
1611 if (!ArgList
[i
].Attrs
!= 0) {
1612 // Allow but ignore attributes on function types; this permits
1614 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1618 std::vector
<const Type
*> ArgListTy
;
1619 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
1620 ArgListTy
.push_back(ArgList
[i
].Type
);
1622 Result
= HandleUpRefs(FunctionType::get(Result
.get(),
1623 ArgListTy
, isVarArg
));
1627 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1630 /// ::= '{' TypeRec (',' TypeRec)* '}'
1631 /// ::= '<' '{' '}' '>'
1632 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1633 bool LLParser::ParseStructType(PATypeHolder
&Result
, bool Packed
) {
1634 assert(Lex
.getKind() == lltok::lbrace
);
1635 Lex
.Lex(); // Consume the '{'
1637 if (EatIfPresent(lltok::rbrace
)) {
1638 Result
= StructType::get(Context
, Packed
);
1642 std::vector
<PATypeHolder
> ParamsList
;
1643 LocTy EltTyLoc
= Lex
.getLoc();
1644 if (ParseTypeRec(Result
)) return true;
1645 ParamsList
.push_back(Result
);
1647 if (Result
->isVoidTy())
1648 return Error(EltTyLoc
, "struct element can not have void type");
1649 if (!StructType::isValidElementType(Result
))
1650 return Error(EltTyLoc
, "invalid element type for struct");
1652 while (EatIfPresent(lltok::comma
)) {
1653 EltTyLoc
= Lex
.getLoc();
1654 if (ParseTypeRec(Result
)) return true;
1656 if (Result
->isVoidTy())
1657 return Error(EltTyLoc
, "struct element can not have void type");
1658 if (!StructType::isValidElementType(Result
))
1659 return Error(EltTyLoc
, "invalid element type for struct");
1661 ParamsList
.push_back(Result
);
1664 if (ParseToken(lltok::rbrace
, "expected '}' at end of struct"))
1667 std::vector
<const Type
*> ParamsListTy
;
1668 for (unsigned i
= 0, e
= ParamsList
.size(); i
!= e
; ++i
)
1669 ParamsListTy
.push_back(ParamsList
[i
].get());
1670 Result
= HandleUpRefs(StructType::get(Context
, ParamsListTy
, Packed
));
1674 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1675 /// token has already been consumed.
1677 /// ::= '[' APSINTVAL 'x' Types ']'
1678 /// ::= '<' APSINTVAL 'x' Types '>'
1679 bool LLParser::ParseArrayVectorType(PATypeHolder
&Result
, bool isVector
) {
1680 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
1681 Lex
.getAPSIntVal().getBitWidth() > 64)
1682 return TokError("expected number in address space");
1684 LocTy SizeLoc
= Lex
.getLoc();
1685 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
1688 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
1691 LocTy TypeLoc
= Lex
.getLoc();
1692 PATypeHolder
EltTy(Type::getVoidTy(Context
));
1693 if (ParseTypeRec(EltTy
)) return true;
1695 if (EltTy
->isVoidTy())
1696 return Error(TypeLoc
, "array and vector element type cannot be void");
1698 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
1699 "expected end of sequential type"))
1704 return Error(SizeLoc
, "zero element vector is illegal");
1705 if ((unsigned)Size
!= Size
)
1706 return Error(SizeLoc
, "size too large for vector");
1707 if (!VectorType::isValidElementType(EltTy
))
1708 return Error(TypeLoc
, "vector element type must be fp or integer");
1709 Result
= VectorType::get(EltTy
, unsigned(Size
));
1711 if (!ArrayType::isValidElementType(EltTy
))
1712 return Error(TypeLoc
, "invalid array element type");
1713 Result
= HandleUpRefs(ArrayType::get(EltTy
, Size
));
1718 //===----------------------------------------------------------------------===//
1719 // Function Semantic Analysis.
1720 //===----------------------------------------------------------------------===//
1722 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
1724 : P(p
), F(f
), FunctionNumber(functionNumber
) {
1726 // Insert unnamed arguments into the NumberedVals list.
1727 for (Function::arg_iterator AI
= F
.arg_begin(), E
= F
.arg_end();
1730 NumberedVals
.push_back(AI
);
1733 LLParser::PerFunctionState::~PerFunctionState() {
1734 // If there were any forward referenced non-basicblock values, delete them.
1735 for (std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1736 I
= ForwardRefVals
.begin(), E
= ForwardRefVals
.end(); I
!= E
; ++I
)
1737 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1738 I
->second
.first
->replaceAllUsesWith(
1739 UndefValue::get(I
->second
.first
->getType()));
1740 delete I
->second
.first
;
1741 I
->second
.first
= 0;
1744 for (std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1745 I
= ForwardRefValIDs
.begin(), E
= ForwardRefValIDs
.end(); I
!= E
; ++I
)
1746 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1747 I
->second
.first
->replaceAllUsesWith(
1748 UndefValue::get(I
->second
.first
->getType()));
1749 delete I
->second
.first
;
1750 I
->second
.first
= 0;
1754 bool LLParser::PerFunctionState::FinishFunction() {
1755 // Check to see if someone took the address of labels in this block.
1756 if (!P
.ForwardRefBlockAddresses
.empty()) {
1758 if (!F
.getName().empty()) {
1759 FunctionID
.Kind
= ValID::t_GlobalName
;
1760 FunctionID
.StrVal
= F
.getName();
1762 FunctionID
.Kind
= ValID::t_GlobalID
;
1763 FunctionID
.UIntVal
= FunctionNumber
;
1766 std::map
<ValID
, std::vector
<std::pair
<ValID
, GlobalValue
*> > >::iterator
1767 FRBAI
= P
.ForwardRefBlockAddresses
.find(FunctionID
);
1768 if (FRBAI
!= P
.ForwardRefBlockAddresses
.end()) {
1769 // Resolve all these references.
1770 if (P
.ResolveForwardRefBlockAddresses(&F
, FRBAI
->second
, this))
1773 P
.ForwardRefBlockAddresses
.erase(FRBAI
);
1777 if (!ForwardRefVals
.empty())
1778 return P
.Error(ForwardRefVals
.begin()->second
.second
,
1779 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
1781 if (!ForwardRefValIDs
.empty())
1782 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
1783 "use of undefined value '%" +
1784 Twine(ForwardRefValIDs
.begin()->first
) + "'");
1789 /// GetVal - Get a value with the specified name or ID, creating a
1790 /// forward reference record if needed. This can return null if the value
1791 /// exists but does not have the right type.
1792 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
,
1793 const Type
*Ty
, LocTy Loc
) {
1794 // Look this name up in the normal function symbol table.
1795 Value
*Val
= F
.getValueSymbolTable().lookup(Name
);
1797 // If this is a forward reference for the value, see if we already created a
1798 // forward ref record.
1800 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1801 I
= ForwardRefVals
.find(Name
);
1802 if (I
!= ForwardRefVals
.end())
1803 Val
= I
->second
.first
;
1806 // If we have the value in the symbol table or fwd-ref table, return it.
1808 if (Val
->getType() == Ty
) return Val
;
1809 if (Ty
->isLabelTy())
1810 P
.Error(Loc
, "'%" + Name
+ "' is not a basic block");
1812 P
.Error(Loc
, "'%" + Name
+ "' defined with type '" +
1813 Val
->getType()->getDescription() + "'");
1817 // Don't make placeholders with invalid type.
1818 if (!Ty
->isFirstClassType() && !Ty
->isOpaqueTy() && !Ty
->isLabelTy()) {
1819 P
.Error(Loc
, "invalid use of a non-first-class type");
1823 // Otherwise, create a new forward reference for this value and remember it.
1825 if (Ty
->isLabelTy())
1826 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
1828 FwdVal
= new Argument(Ty
, Name
);
1830 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1834 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, const Type
*Ty
,
1836 // Look this name up in the normal function symbol table.
1837 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
1839 // If this is a forward reference for the value, see if we already created a
1840 // forward ref record.
1842 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1843 I
= ForwardRefValIDs
.find(ID
);
1844 if (I
!= ForwardRefValIDs
.end())
1845 Val
= I
->second
.first
;
1848 // If we have the value in the symbol table or fwd-ref table, return it.
1850 if (Val
->getType() == Ty
) return Val
;
1851 if (Ty
->isLabelTy())
1852 P
.Error(Loc
, "'%" + Twine(ID
) + "' is not a basic block");
1854 P
.Error(Loc
, "'%" + Twine(ID
) + "' defined with type '" +
1855 Val
->getType()->getDescription() + "'");
1859 if (!Ty
->isFirstClassType() && !Ty
->isOpaqueTy() && !Ty
->isLabelTy()) {
1860 P
.Error(Loc
, "invalid use of a non-first-class type");
1864 // Otherwise, create a new forward reference for this value and remember it.
1866 if (Ty
->isLabelTy())
1867 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
1869 FwdVal
= new Argument(Ty
);
1871 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1875 /// SetInstName - After an instruction is parsed and inserted into its
1876 /// basic block, this installs its name.
1877 bool LLParser::PerFunctionState::SetInstName(int NameID
,
1878 const std::string
&NameStr
,
1879 LocTy NameLoc
, Instruction
*Inst
) {
1880 // If this instruction has void type, it cannot have a name or ID specified.
1881 if (Inst
->getType()->isVoidTy()) {
1882 if (NameID
!= -1 || !NameStr
.empty())
1883 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
1887 // If this was a numbered instruction, verify that the instruction is the
1888 // expected value and resolve any forward references.
1889 if (NameStr
.empty()) {
1890 // If neither a name nor an ID was specified, just use the next ID.
1892 NameID
= NumberedVals
.size();
1894 if (unsigned(NameID
) != NumberedVals
.size())
1895 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
1896 Twine(NumberedVals
.size()) + "'");
1898 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator FI
=
1899 ForwardRefValIDs
.find(NameID
);
1900 if (FI
!= ForwardRefValIDs
.end()) {
1901 if (FI
->second
.first
->getType() != Inst
->getType())
1902 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1903 FI
->second
.first
->getType()->getDescription() + "'");
1904 FI
->second
.first
->replaceAllUsesWith(Inst
);
1905 delete FI
->second
.first
;
1906 ForwardRefValIDs
.erase(FI
);
1909 NumberedVals
.push_back(Inst
);
1913 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1914 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1915 FI
= ForwardRefVals
.find(NameStr
);
1916 if (FI
!= ForwardRefVals
.end()) {
1917 if (FI
->second
.first
->getType() != Inst
->getType())
1918 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1919 FI
->second
.first
->getType()->getDescription() + "'");
1920 FI
->second
.first
->replaceAllUsesWith(Inst
);
1921 delete FI
->second
.first
;
1922 ForwardRefVals
.erase(FI
);
1925 // Set the name on the instruction.
1926 Inst
->setName(NameStr
);
1928 if (Inst
->getName() != NameStr
)
1929 return P
.Error(NameLoc
, "multiple definition of local value named '" +
1934 /// GetBB - Get a basic block with the specified name or ID, creating a
1935 /// forward reference record if needed.
1936 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
1938 return cast_or_null
<BasicBlock
>(GetVal(Name
,
1939 Type::getLabelTy(F
.getContext()), Loc
));
1942 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
1943 return cast_or_null
<BasicBlock
>(GetVal(ID
,
1944 Type::getLabelTy(F
.getContext()), Loc
));
1947 /// DefineBB - Define the specified basic block, which is either named or
1948 /// unnamed. If there is an error, this returns null otherwise it returns
1949 /// the block being defined.
1950 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
1954 BB
= GetBB(NumberedVals
.size(), Loc
);
1956 BB
= GetBB(Name
, Loc
);
1957 if (BB
== 0) return 0; // Already diagnosed error.
1959 // Move the block to the end of the function. Forward ref'd blocks are
1960 // inserted wherever they happen to be referenced.
1961 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
1963 // Remove the block from forward ref sets.
1965 ForwardRefValIDs
.erase(NumberedVals
.size());
1966 NumberedVals
.push_back(BB
);
1968 // BB forward references are already in the function symbol table.
1969 ForwardRefVals
.erase(Name
);
1975 //===----------------------------------------------------------------------===//
1977 //===----------------------------------------------------------------------===//
1979 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1980 /// type implied. For example, if we parse "4" we don't know what integer type
1981 /// it has. The value will later be combined with its type and checked for
1982 /// sanity. PFS is used to convert function-local operands of metadata (since
1983 /// metadata operands are not just parsed here but also converted to values).
1984 /// PFS can be null when we are not parsing metadata values inside a function.
1985 bool LLParser::ParseValID(ValID
&ID
, PerFunctionState
*PFS
) {
1986 ID
.Loc
= Lex
.getLoc();
1987 switch (Lex
.getKind()) {
1988 default: return TokError("expected value token");
1989 case lltok::GlobalID
: // @42
1990 ID
.UIntVal
= Lex
.getUIntVal();
1991 ID
.Kind
= ValID::t_GlobalID
;
1993 case lltok::GlobalVar
: // @foo
1994 ID
.StrVal
= Lex
.getStrVal();
1995 ID
.Kind
= ValID::t_GlobalName
;
1997 case lltok::LocalVarID
: // %42
1998 ID
.UIntVal
= Lex
.getUIntVal();
1999 ID
.Kind
= ValID::t_LocalID
;
2001 case lltok::LocalVar
: // %foo
2002 case lltok::StringConstant
: // "foo" - FIXME: REMOVE IN LLVM 3.0
2003 ID
.StrVal
= Lex
.getStrVal();
2004 ID
.Kind
= ValID::t_LocalName
;
2006 case lltok::exclaim
: // !42, !{...}, or !"foo"
2007 return ParseMetadataValue(ID
, PFS
);
2009 ID
.APSIntVal
= Lex
.getAPSIntVal();
2010 ID
.Kind
= ValID::t_APSInt
;
2012 case lltok::APFloat
:
2013 ID
.APFloatVal
= Lex
.getAPFloatVal();
2014 ID
.Kind
= ValID::t_APFloat
;
2016 case lltok::kw_true
:
2017 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
2018 ID
.Kind
= ValID::t_Constant
;
2020 case lltok::kw_false
:
2021 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
2022 ID
.Kind
= ValID::t_Constant
;
2024 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
2025 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
2026 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
2028 case lltok::lbrace
: {
2029 // ValID ::= '{' ConstVector '}'
2031 SmallVector
<Constant
*, 16> Elts
;
2032 if (ParseGlobalValueVector(Elts
) ||
2033 ParseToken(lltok::rbrace
, "expected end of struct constant"))
2036 ID
.ConstantVal
= ConstantStruct::get(Context
, Elts
.data(),
2037 Elts
.size(), false);
2038 ID
.Kind
= ValID::t_Constant
;
2042 // ValID ::= '<' ConstVector '>' --> Vector.
2043 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2045 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
2047 SmallVector
<Constant
*, 16> Elts
;
2048 LocTy FirstEltLoc
= Lex
.getLoc();
2049 if (ParseGlobalValueVector(Elts
) ||
2051 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
2052 ParseToken(lltok::greater
, "expected end of constant"))
2055 if (isPackedStruct
) {
2057 ConstantStruct::get(Context
, Elts
.data(), Elts
.size(), true);
2058 ID
.Kind
= ValID::t_Constant
;
2063 return Error(ID
.Loc
, "constant vector must not be empty");
2065 if (!Elts
[0]->getType()->isIntegerTy() &&
2066 !Elts
[0]->getType()->isFloatingPointTy())
2067 return Error(FirstEltLoc
,
2068 "vector elements must have integer or floating point type");
2070 // Verify that all the vector elements have the same type.
2071 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
2072 if (Elts
[i
]->getType() != Elts
[0]->getType())
2073 return Error(FirstEltLoc
,
2074 "vector element #" + Twine(i
) +
2075 " is not of type '" + Elts
[0]->getType()->getDescription());
2077 ID
.ConstantVal
= ConstantVector::get(Elts
.data(), Elts
.size());
2078 ID
.Kind
= ValID::t_Constant
;
2081 case lltok::lsquare
: { // Array Constant
2083 SmallVector
<Constant
*, 16> Elts
;
2084 LocTy FirstEltLoc
= Lex
.getLoc();
2085 if (ParseGlobalValueVector(Elts
) ||
2086 ParseToken(lltok::rsquare
, "expected end of array constant"))
2089 // Handle empty element.
2091 // Use undef instead of an array because it's inconvenient to determine
2092 // the element type at this point, there being no elements to examine.
2093 ID
.Kind
= ValID::t_EmptyArray
;
2097 if (!Elts
[0]->getType()->isFirstClassType())
2098 return Error(FirstEltLoc
, "invalid array element type: " +
2099 Elts
[0]->getType()->getDescription());
2101 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
2103 // Verify all elements are correct type!
2104 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
2105 if (Elts
[i
]->getType() != Elts
[0]->getType())
2106 return Error(FirstEltLoc
,
2107 "array element #" + Twine(i
) +
2108 " is not of type '" +Elts
[0]->getType()->getDescription());
2111 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
.data(), Elts
.size());
2112 ID
.Kind
= ValID::t_Constant
;
2115 case lltok::kw_c
: // c "foo"
2117 ID
.ConstantVal
= ConstantArray::get(Context
, Lex
.getStrVal(), false);
2118 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
2119 ID
.Kind
= ValID::t_Constant
;
2122 case lltok::kw_asm
: {
2123 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2124 bool HasSideEffect
, AlignStack
;
2126 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
2127 ParseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
2128 ParseStringConstant(ID
.StrVal
) ||
2129 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
2130 ParseToken(lltok::StringConstant
, "expected constraint string"))
2132 ID
.StrVal2
= Lex
.getStrVal();
2133 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
)<<1);
2134 ID
.Kind
= ValID::t_InlineAsm
;
2138 case lltok::kw_blockaddress
: {
2139 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2143 LocTy FnLoc
, LabelLoc
;
2145 if (ParseToken(lltok::lparen
, "expected '(' in block address expression") ||
2147 ParseToken(lltok::comma
, "expected comma in block address expression")||
2148 ParseValID(Label
) ||
2149 ParseToken(lltok::rparen
, "expected ')' in block address expression"))
2152 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
2153 return Error(Fn
.Loc
, "expected function name in blockaddress");
2154 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
2155 return Error(Label
.Loc
, "expected basic block name in blockaddress");
2157 // Make a global variable as a placeholder for this reference.
2158 GlobalVariable
*FwdRef
= new GlobalVariable(*M
, Type::getInt8Ty(Context
),
2159 false, GlobalValue::InternalLinkage
,
2161 ForwardRefBlockAddresses
[Fn
].push_back(std::make_pair(Label
, FwdRef
));
2162 ID
.ConstantVal
= FwdRef
;
2163 ID
.Kind
= ValID::t_Constant
;
2167 case lltok::kw_trunc
:
2168 case lltok::kw_zext
:
2169 case lltok::kw_sext
:
2170 case lltok::kw_fptrunc
:
2171 case lltok::kw_fpext
:
2172 case lltok::kw_bitcast
:
2173 case lltok::kw_uitofp
:
2174 case lltok::kw_sitofp
:
2175 case lltok::kw_fptoui
:
2176 case lltok::kw_fptosi
:
2177 case lltok::kw_inttoptr
:
2178 case lltok::kw_ptrtoint
: {
2179 unsigned Opc
= Lex
.getUIntVal();
2180 PATypeHolder
DestTy(Type::getVoidTy(Context
));
2183 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
2184 ParseGlobalTypeAndValue(SrcVal
) ||
2185 ParseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
2186 ParseType(DestTy
) ||
2187 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
2189 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
2190 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
2191 SrcVal
->getType()->getDescription() + "' to '" +
2192 DestTy
->getDescription() + "'");
2193 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
2195 ID
.Kind
= ValID::t_Constant
;
2198 case lltok::kw_extractvalue
: {
2201 SmallVector
<unsigned, 4> Indices
;
2202 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
2203 ParseGlobalTypeAndValue(Val
) ||
2204 ParseIndexList(Indices
) ||
2205 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
2208 if (!Val
->getType()->isAggregateType())
2209 return Error(ID
.Loc
, "extractvalue operand must be aggregate type");
2210 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
2212 return Error(ID
.Loc
, "invalid indices for extractvalue");
2214 ConstantExpr::getExtractValue(Val
, Indices
.data(), Indices
.size());
2215 ID
.Kind
= ValID::t_Constant
;
2218 case lltok::kw_insertvalue
: {
2220 Constant
*Val0
, *Val1
;
2221 SmallVector
<unsigned, 4> Indices
;
2222 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
2223 ParseGlobalTypeAndValue(Val0
) ||
2224 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
2225 ParseGlobalTypeAndValue(Val1
) ||
2226 ParseIndexList(Indices
) ||
2227 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
2229 if (!Val0
->getType()->isAggregateType())
2230 return Error(ID
.Loc
, "insertvalue operand must be aggregate type");
2231 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
2233 return Error(ID
.Loc
, "invalid indices for insertvalue");
2234 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
,
2235 Indices
.data(), Indices
.size());
2236 ID
.Kind
= ValID::t_Constant
;
2239 case lltok::kw_icmp
:
2240 case lltok::kw_fcmp
: {
2241 unsigned PredVal
, Opc
= Lex
.getUIntVal();
2242 Constant
*Val0
, *Val1
;
2244 if (ParseCmpPredicate(PredVal
, Opc
) ||
2245 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
2246 ParseGlobalTypeAndValue(Val0
) ||
2247 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
2248 ParseGlobalTypeAndValue(Val1
) ||
2249 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
2252 if (Val0
->getType() != Val1
->getType())
2253 return Error(ID
.Loc
, "compare operands must have the same type");
2255 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
2257 if (Opc
== Instruction::FCmp
) {
2258 if (!Val0
->getType()->isFPOrFPVectorTy())
2259 return Error(ID
.Loc
, "fcmp requires floating point operands");
2260 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
2262 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
2263 if (!Val0
->getType()->isIntOrIntVectorTy() &&
2264 !Val0
->getType()->isPointerTy())
2265 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
2266 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
2268 ID
.Kind
= ValID::t_Constant
;
2272 // Binary Operators.
2274 case lltok::kw_fadd
:
2276 case lltok::kw_fsub
:
2278 case lltok::kw_fmul
:
2279 case lltok::kw_udiv
:
2280 case lltok::kw_sdiv
:
2281 case lltok::kw_fdiv
:
2282 case lltok::kw_urem
:
2283 case lltok::kw_srem
:
2284 case lltok::kw_frem
: {
2288 unsigned Opc
= Lex
.getUIntVal();
2289 Constant
*Val0
, *Val1
;
2291 LocTy ModifierLoc
= Lex
.getLoc();
2292 if (Opc
== Instruction::Add
||
2293 Opc
== Instruction::Sub
||
2294 Opc
== Instruction::Mul
) {
2295 if (EatIfPresent(lltok::kw_nuw
))
2297 if (EatIfPresent(lltok::kw_nsw
)) {
2299 if (EatIfPresent(lltok::kw_nuw
))
2302 } else if (Opc
== Instruction::SDiv
) {
2303 if (EatIfPresent(lltok::kw_exact
))
2306 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
2307 ParseGlobalTypeAndValue(Val0
) ||
2308 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
2309 ParseGlobalTypeAndValue(Val1
) ||
2310 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
2312 if (Val0
->getType() != Val1
->getType())
2313 return Error(ID
.Loc
, "operands of constexpr must have same type");
2314 if (!Val0
->getType()->isIntOrIntVectorTy()) {
2316 return Error(ModifierLoc
, "nuw only applies to integer operations");
2318 return Error(ModifierLoc
, "nsw only applies to integer operations");
2320 // Check that the type is valid for the operator.
2322 case Instruction::Add
:
2323 case Instruction::Sub
:
2324 case Instruction::Mul
:
2325 case Instruction::UDiv
:
2326 case Instruction::SDiv
:
2327 case Instruction::URem
:
2328 case Instruction::SRem
:
2329 if (!Val0
->getType()->isIntOrIntVectorTy())
2330 return Error(ID
.Loc
, "constexpr requires integer operands");
2332 case Instruction::FAdd
:
2333 case Instruction::FSub
:
2334 case Instruction::FMul
:
2335 case Instruction::FDiv
:
2336 case Instruction::FRem
:
2337 if (!Val0
->getType()->isFPOrFPVectorTy())
2338 return Error(ID
.Loc
, "constexpr requires fp operands");
2340 default: llvm_unreachable("Unknown binary operator!");
2343 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
2344 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
2345 if (Exact
) Flags
|= SDivOperator::IsExact
;
2346 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
2348 ID
.Kind
= ValID::t_Constant
;
2352 // Logical Operations
2354 case lltok::kw_lshr
:
2355 case lltok::kw_ashr
:
2358 case lltok::kw_xor
: {
2359 unsigned Opc
= Lex
.getUIntVal();
2360 Constant
*Val0
, *Val1
;
2362 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
2363 ParseGlobalTypeAndValue(Val0
) ||
2364 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
2365 ParseGlobalTypeAndValue(Val1
) ||
2366 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
2368 if (Val0
->getType() != Val1
->getType())
2369 return Error(ID
.Loc
, "operands of constexpr must have same type");
2370 if (!Val0
->getType()->isIntOrIntVectorTy())
2371 return Error(ID
.Loc
,
2372 "constexpr requires integer or integer vector operands");
2373 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
2374 ID
.Kind
= ValID::t_Constant
;
2378 case lltok::kw_getelementptr
:
2379 case lltok::kw_shufflevector
:
2380 case lltok::kw_insertelement
:
2381 case lltok::kw_extractelement
:
2382 case lltok::kw_select
: {
2383 unsigned Opc
= Lex
.getUIntVal();
2384 SmallVector
<Constant
*, 16> Elts
;
2385 bool InBounds
= false;
2387 if (Opc
== Instruction::GetElementPtr
)
2388 InBounds
= EatIfPresent(lltok::kw_inbounds
);
2389 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr") ||
2390 ParseGlobalValueVector(Elts
) ||
2391 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
2394 if (Opc
== Instruction::GetElementPtr
) {
2395 if (Elts
.size() == 0 || !Elts
[0]->getType()->isPointerTy())
2396 return Error(ID
.Loc
, "getelementptr requires pointer operand");
2398 if (!GetElementPtrInst::getIndexedType(Elts
[0]->getType(),
2399 (Value
**)(Elts
.data() + 1),
2401 return Error(ID
.Loc
, "invalid indices for getelementptr");
2402 ID
.ConstantVal
= InBounds
?
2403 ConstantExpr::getInBoundsGetElementPtr(Elts
[0],
2406 ConstantExpr::getGetElementPtr(Elts
[0],
2407 Elts
.data() + 1, Elts
.size() - 1);
2408 } else if (Opc
== Instruction::Select
) {
2409 if (Elts
.size() != 3)
2410 return Error(ID
.Loc
, "expected three operands to select");
2411 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
2413 return Error(ID
.Loc
, Reason
);
2414 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
2415 } else if (Opc
== Instruction::ShuffleVector
) {
2416 if (Elts
.size() != 3)
2417 return Error(ID
.Loc
, "expected three operands to shufflevector");
2418 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
2419 return Error(ID
.Loc
, "invalid operands to shufflevector");
2421 ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
2422 } else if (Opc
== Instruction::ExtractElement
) {
2423 if (Elts
.size() != 2)
2424 return Error(ID
.Loc
, "expected two operands to extractelement");
2425 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
2426 return Error(ID
.Loc
, "invalid extractelement operands");
2427 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
2429 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
2430 if (Elts
.size() != 3)
2431 return Error(ID
.Loc
, "expected three operands to insertelement");
2432 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
2433 return Error(ID
.Loc
, "invalid insertelement operands");
2435 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
2438 ID
.Kind
= ValID::t_Constant
;
2447 /// ParseGlobalValue - Parse a global value with the specified type.
2448 bool LLParser::ParseGlobalValue(const Type
*Ty
, Constant
*&C
) {
2452 bool Parsed
= ParseValID(ID
) ||
2453 ConvertValIDToValue(Ty
, ID
, V
, NULL
);
2454 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
2455 return Error(ID
.Loc
, "global values must be constants");
2459 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
2460 PATypeHolder
Type(Type::getVoidTy(Context
));
2461 return ParseType(Type
) ||
2462 ParseGlobalValue(Type
, V
);
2465 /// ParseGlobalValueVector
2467 /// ::= TypeAndValue (',' TypeAndValue)*
2468 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
) {
2470 if (Lex
.getKind() == lltok::rbrace
||
2471 Lex
.getKind() == lltok::rsquare
||
2472 Lex
.getKind() == lltok::greater
||
2473 Lex
.getKind() == lltok::rparen
)
2477 if (ParseGlobalTypeAndValue(C
)) return true;
2480 while (EatIfPresent(lltok::comma
)) {
2481 if (ParseGlobalTypeAndValue(C
)) return true;
2488 bool LLParser::ParseMetadataListValue(ValID
&ID
, PerFunctionState
*PFS
) {
2489 assert(Lex
.getKind() == lltok::lbrace
);
2492 SmallVector
<Value
*, 16> Elts
;
2493 if (ParseMDNodeVector(Elts
, PFS
) ||
2494 ParseToken(lltok::rbrace
, "expected end of metadata node"))
2497 ID
.MDNodeVal
= MDNode::get(Context
, Elts
.data(), Elts
.size());
2498 ID
.Kind
= ValID::t_MDNode
;
2502 /// ParseMetadataValue
2506 bool LLParser::ParseMetadataValue(ValID
&ID
, PerFunctionState
*PFS
) {
2507 assert(Lex
.getKind() == lltok::exclaim
);
2512 if (Lex
.getKind() == lltok::lbrace
)
2513 return ParseMetadataListValue(ID
, PFS
);
2515 // Standalone metadata reference
2517 if (Lex
.getKind() == lltok::APSInt
) {
2518 if (ParseMDNodeID(ID
.MDNodeVal
)) return true;
2519 ID
.Kind
= ValID::t_MDNode
;
2524 // ::= '!' STRINGCONSTANT
2525 if (ParseMDString(ID
.MDStringVal
)) return true;
2526 ID
.Kind
= ValID::t_MDString
;
2531 //===----------------------------------------------------------------------===//
2532 // Function Parsing.
2533 //===----------------------------------------------------------------------===//
2535 bool LLParser::ConvertValIDToValue(const Type
*Ty
, ValID
&ID
, Value
*&V
,
2536 PerFunctionState
*PFS
) {
2537 if (Ty
->isFunctionTy())
2538 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
2541 default: llvm_unreachable("Unknown ValID!");
2542 case ValID::t_LocalID
:
2543 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
2544 V
= PFS
->GetVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2546 case ValID::t_LocalName
:
2547 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
2548 V
= PFS
->GetVal(ID
.StrVal
, Ty
, ID
.Loc
);
2550 case ValID::t_InlineAsm
: {
2551 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
2552 const FunctionType
*FTy
=
2553 PTy
? dyn_cast
<FunctionType
>(PTy
->getElementType()) : 0;
2554 if (!FTy
|| !InlineAsm::Verify(FTy
, ID
.StrVal2
))
2555 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
2556 V
= InlineAsm::get(FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
&1, ID
.UIntVal
>>1);
2559 case ValID::t_MDNode
:
2560 if (!Ty
->isMetadataTy())
2561 return Error(ID
.Loc
, "metadata value must have metadata type");
2564 case ValID::t_MDString
:
2565 if (!Ty
->isMetadataTy())
2566 return Error(ID
.Loc
, "metadata value must have metadata type");
2569 case ValID::t_GlobalName
:
2570 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
);
2572 case ValID::t_GlobalID
:
2573 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2575 case ValID::t_APSInt
:
2576 if (!Ty
->isIntegerTy())
2577 return Error(ID
.Loc
, "integer constant must have integer type");
2578 ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
2579 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
2581 case ValID::t_APFloat
:
2582 if (!Ty
->isFloatingPointTy() ||
2583 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
2584 return Error(ID
.Loc
, "floating point constant invalid for type");
2586 // The lexer has no type info, so builds all float and double FP constants
2587 // as double. Fix this here. Long double does not need this.
2588 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble
&&
2591 ID
.APFloatVal
.convert(APFloat::IEEEsingle
, APFloat::rmNearestTiesToEven
,
2594 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
2596 if (V
->getType() != Ty
)
2597 return Error(ID
.Loc
, "floating point constant does not have type '" +
2598 Ty
->getDescription() + "'");
2602 if (!Ty
->isPointerTy())
2603 return Error(ID
.Loc
, "null must be a pointer type");
2604 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
2606 case ValID::t_Undef
:
2607 // FIXME: LabelTy should not be a first-class type.
2608 if ((!Ty
->isFirstClassType() || Ty
->isLabelTy()) &&
2610 return Error(ID
.Loc
, "invalid type for undef constant");
2611 V
= UndefValue::get(Ty
);
2613 case ValID::t_EmptyArray
:
2614 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
2615 return Error(ID
.Loc
, "invalid empty array initializer");
2616 V
= UndefValue::get(Ty
);
2619 // FIXME: LabelTy should not be a first-class type.
2620 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
2621 return Error(ID
.Loc
, "invalid type for null constant");
2622 V
= Constant::getNullValue(Ty
);
2624 case ValID::t_Constant
:
2625 if (ID
.ConstantVal
->getType() != Ty
)
2626 return Error(ID
.Loc
, "constant expression type mismatch");
2633 bool LLParser::ParseValue(const Type
*Ty
, Value
*&V
, PerFunctionState
&PFS
) {
2636 return ParseValID(ID
, &PFS
) ||
2637 ConvertValIDToValue(Ty
, ID
, V
, &PFS
);
2640 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
&PFS
) {
2641 PATypeHolder
T(Type::getVoidTy(Context
));
2642 return ParseType(T
) ||
2643 ParseValue(T
, V
, PFS
);
2646 bool LLParser::ParseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
2647 PerFunctionState
&PFS
) {
2650 if (ParseTypeAndValue(V
, PFS
)) return true;
2651 if (!isa
<BasicBlock
>(V
))
2652 return Error(Loc
, "expected a basic block");
2653 BB
= cast
<BasicBlock
>(V
);
2659 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2660 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2661 /// OptionalAlign OptGC
2662 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
2663 // Parse the linkage.
2664 LocTy LinkageLoc
= Lex
.getLoc();
2667 unsigned Visibility
, RetAttrs
;
2669 PATypeHolder
RetType(Type::getVoidTy(Context
));
2670 LocTy RetTypeLoc
= Lex
.getLoc();
2671 if (ParseOptionalLinkage(Linkage
) ||
2672 ParseOptionalVisibility(Visibility
) ||
2673 ParseOptionalCallingConv(CC
) ||
2674 ParseOptionalAttrs(RetAttrs
, 1) ||
2675 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
2678 // Verify that the linkage is ok.
2679 switch ((GlobalValue::LinkageTypes
)Linkage
) {
2680 case GlobalValue::ExternalLinkage
:
2681 break; // always ok.
2682 case GlobalValue::DLLImportLinkage
:
2683 case GlobalValue::ExternalWeakLinkage
:
2685 return Error(LinkageLoc
, "invalid linkage for function definition");
2687 case GlobalValue::PrivateLinkage
:
2688 case GlobalValue::LinkerPrivateLinkage
:
2689 case GlobalValue::LinkerPrivateWeakLinkage
:
2690 case GlobalValue::LinkerPrivateWeakDefAutoLinkage
:
2691 case GlobalValue::InternalLinkage
:
2692 case GlobalValue::AvailableExternallyLinkage
:
2693 case GlobalValue::LinkOnceAnyLinkage
:
2694 case GlobalValue::LinkOnceODRLinkage
:
2695 case GlobalValue::WeakAnyLinkage
:
2696 case GlobalValue::WeakODRLinkage
:
2697 case GlobalValue::DLLExportLinkage
:
2699 return Error(LinkageLoc
, "invalid linkage for function declaration");
2701 case GlobalValue::AppendingLinkage
:
2702 case GlobalValue::CommonLinkage
:
2703 return Error(LinkageLoc
, "invalid function linkage type");
2706 if (!FunctionType::isValidReturnType(RetType
) ||
2707 RetType
->isOpaqueTy())
2708 return Error(RetTypeLoc
, "invalid function return type");
2710 LocTy NameLoc
= Lex
.getLoc();
2712 std::string FunctionName
;
2713 if (Lex
.getKind() == lltok::GlobalVar
) {
2714 FunctionName
= Lex
.getStrVal();
2715 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
2716 unsigned NameID
= Lex
.getUIntVal();
2718 if (NameID
!= NumberedVals
.size())
2719 return TokError("function expected to be numbered '%" +
2720 Twine(NumberedVals
.size()) + "'");
2722 return TokError("expected function name");
2727 if (Lex
.getKind() != lltok::lparen
)
2728 return TokError("expected '(' in function argument list");
2730 std::vector
<ArgInfo
> ArgList
;
2733 std::string Section
;
2737 if (ParseArgumentList(ArgList
, isVarArg
, false) ||
2738 ParseOptionalAttrs(FuncAttrs
, 2) ||
2739 (EatIfPresent(lltok::kw_section
) &&
2740 ParseStringConstant(Section
)) ||
2741 ParseOptionalAlignment(Alignment
) ||
2742 (EatIfPresent(lltok::kw_gc
) &&
2743 ParseStringConstant(GC
)))
2746 // If the alignment was parsed as an attribute, move to the alignment field.
2747 if (FuncAttrs
& Attribute::Alignment
) {
2748 Alignment
= Attribute::getAlignmentFromAttrs(FuncAttrs
);
2749 FuncAttrs
&= ~Attribute::Alignment
;
2752 // Okay, if we got here, the function is syntactically valid. Convert types
2753 // and do semantic checks.
2754 std::vector
<const Type
*> ParamTypeList
;
2755 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2756 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2758 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2759 if (FuncAttrs
& ObsoleteFuncAttrs
) {
2760 RetAttrs
|= FuncAttrs
& ObsoleteFuncAttrs
;
2761 FuncAttrs
&= ~ObsoleteFuncAttrs
;
2764 if (RetAttrs
!= Attribute::None
)
2765 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2767 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2768 ParamTypeList
.push_back(ArgList
[i
].Type
);
2769 if (ArgList
[i
].Attrs
!= Attribute::None
)
2770 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
2773 if (FuncAttrs
!= Attribute::None
)
2774 Attrs
.push_back(AttributeWithIndex::get(~0, FuncAttrs
));
2776 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
2778 if (PAL
.paramHasAttr(1, Attribute::StructRet
) && !RetType
->isVoidTy())
2779 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
2781 const FunctionType
*FT
=
2782 FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
2783 const PointerType
*PFT
= PointerType::getUnqual(FT
);
2786 if (!FunctionName
.empty()) {
2787 // If this was a definition of a forward reference, remove the definition
2788 // from the forward reference table and fill in the forward ref.
2789 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator FRVI
=
2790 ForwardRefVals
.find(FunctionName
);
2791 if (FRVI
!= ForwardRefVals
.end()) {
2792 Fn
= M
->getFunction(FunctionName
);
2793 if (Fn
->getType() != PFT
)
2794 return Error(FRVI
->second
.second
, "invalid forward reference to "
2795 "function '" + FunctionName
+ "' with wrong type!");
2797 ForwardRefVals
.erase(FRVI
);
2798 } else if ((Fn
= M
->getFunction(FunctionName
))) {
2799 // If this function already exists in the symbol table, then it is
2800 // multiply defined. We accept a few cases for old backwards compat.
2801 // FIXME: Remove this stuff for LLVM 3.0.
2802 if (Fn
->getType() != PFT
|| Fn
->getAttributes() != PAL
||
2803 (!Fn
->isDeclaration() && isDefine
)) {
2804 // If the redefinition has different type or different attributes,
2805 // reject it. If both have bodies, reject it.
2806 return Error(NameLoc
, "invalid redefinition of function '" +
2807 FunctionName
+ "'");
2808 } else if (Fn
->isDeclaration()) {
2809 // Make sure to strip off any argument names so we can't get conflicts.
2810 for (Function::arg_iterator AI
= Fn
->arg_begin(), AE
= Fn
->arg_end();
2814 } else if (M
->getNamedValue(FunctionName
)) {
2815 return Error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
2819 // If this is a definition of a forward referenced function, make sure the
2821 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator I
2822 = ForwardRefValIDs
.find(NumberedVals
.size());
2823 if (I
!= ForwardRefValIDs
.end()) {
2824 Fn
= cast
<Function
>(I
->second
.first
);
2825 if (Fn
->getType() != PFT
)
2826 return Error(NameLoc
, "type of definition and forward reference of '@" +
2827 Twine(NumberedVals
.size()) + "' disagree");
2828 ForwardRefValIDs
.erase(I
);
2833 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, FunctionName
, M
);
2834 else // Move the forward-reference to the correct spot in the module.
2835 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
2837 if (FunctionName
.empty())
2838 NumberedVals
.push_back(Fn
);
2840 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
2841 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
2842 Fn
->setCallingConv(CC
);
2843 Fn
->setAttributes(PAL
);
2844 Fn
->setAlignment(Alignment
);
2845 Fn
->setSection(Section
);
2846 if (!GC
.empty()) Fn
->setGC(GC
.c_str());
2848 // Add all of the arguments we parsed to the function.
2849 Function::arg_iterator ArgIt
= Fn
->arg_begin();
2850 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
2851 // If we run out of arguments in the Function prototype, exit early.
2852 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2853 if (ArgIt
== Fn
->arg_end()) break;
2855 // If the argument has a name, insert it into the argument symbol table.
2856 if (ArgList
[i
].Name
.empty()) continue;
2858 // Set the name, if it conflicted, it will be auto-renamed.
2859 ArgIt
->setName(ArgList
[i
].Name
);
2861 if (ArgIt
->getName() != ArgList
[i
].Name
)
2862 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
2863 ArgList
[i
].Name
+ "'");
2870 /// ParseFunctionBody
2871 /// ::= '{' BasicBlock+ '}'
2872 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2874 bool LLParser::ParseFunctionBody(Function
&Fn
) {
2875 if (Lex
.getKind() != lltok::lbrace
&& Lex
.getKind() != lltok::kw_begin
)
2876 return TokError("expected '{' in function body");
2877 Lex
.Lex(); // eat the {.
2879 int FunctionNumber
= -1;
2880 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
2882 PerFunctionState
PFS(*this, Fn
, FunctionNumber
);
2884 // We need at least one basic block.
2885 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_end
)
2886 return TokError("function body requires at least one basic block");
2888 while (Lex
.getKind() != lltok::rbrace
&& Lex
.getKind() != lltok::kw_end
)
2889 if (ParseBasicBlock(PFS
)) return true;
2894 // Verify function is ok.
2895 return PFS
.FinishFunction();
2899 /// ::= LabelStr? Instruction*
2900 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
2901 // If this basic block starts out with a name, remember it.
2903 LocTy NameLoc
= Lex
.getLoc();
2904 if (Lex
.getKind() == lltok::LabelStr
) {
2905 Name
= Lex
.getStrVal();
2909 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameLoc
);
2910 if (BB
== 0) return true;
2912 std::string NameStr
;
2914 // Parse the instructions in this block until we get a terminator.
2916 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MetadataOnInst
;
2918 // This instruction may have three possibilities for a name: a) none
2919 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2920 LocTy NameLoc
= Lex
.getLoc();
2924 if (Lex
.getKind() == lltok::LocalVarID
) {
2925 NameID
= Lex
.getUIntVal();
2927 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
2929 } else if (Lex
.getKind() == lltok::LocalVar
||
2930 // FIXME: REMOVE IN LLVM 3.0
2931 Lex
.getKind() == lltok::StringConstant
) {
2932 NameStr
= Lex
.getStrVal();
2934 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
2938 switch (ParseInstruction(Inst
, BB
, PFS
)) {
2939 default: assert(0 && "Unknown ParseInstruction result!");
2940 case InstError
: return true;
2942 BB
->getInstList().push_back(Inst
);
2944 // With a normal result, we check to see if the instruction is followed by
2945 // a comma and metadata.
2946 if (EatIfPresent(lltok::comma
))
2947 if (ParseInstructionMetadata(Inst
, &PFS
))
2950 case InstExtraComma
:
2951 BB
->getInstList().push_back(Inst
);
2953 // If the instruction parser ate an extra comma at the end of it, it
2954 // *must* be followed by metadata.
2955 if (ParseInstructionMetadata(Inst
, &PFS
))
2960 // Set the name on the instruction.
2961 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
2962 } while (!isa
<TerminatorInst
>(Inst
));
2967 //===----------------------------------------------------------------------===//
2968 // Instruction Parsing.
2969 //===----------------------------------------------------------------------===//
2971 /// ParseInstruction - Parse one of the many different instructions.
2973 int LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
2974 PerFunctionState
&PFS
) {
2975 lltok::Kind Token
= Lex
.getKind();
2976 if (Token
== lltok::Eof
)
2977 return TokError("found end of file when expecting more instructions");
2978 LocTy Loc
= Lex
.getLoc();
2979 unsigned KeywordVal
= Lex
.getUIntVal();
2980 Lex
.Lex(); // Eat the keyword.
2983 default: return Error(Loc
, "expected instruction opcode");
2984 // Terminator Instructions.
2985 case lltok::kw_unwind
: Inst
= new UnwindInst(Context
); return false;
2986 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
2987 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
2988 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
2989 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
2990 case lltok::kw_indirectbr
: return ParseIndirectBr(Inst
, PFS
);
2991 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
2992 // Binary Operators.
2995 case lltok::kw_mul
: {
2998 LocTy ModifierLoc
= Lex
.getLoc();
2999 if (EatIfPresent(lltok::kw_nuw
))
3001 if (EatIfPresent(lltok::kw_nsw
)) {
3003 if (EatIfPresent(lltok::kw_nuw
))
3006 bool Result
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
3008 if (!Inst
->getType()->isIntOrIntVectorTy()) {
3010 return Error(ModifierLoc
, "nuw only applies to integer operations");
3012 return Error(ModifierLoc
, "nsw only applies to integer operations");
3015 cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
3017 cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
3021 case lltok::kw_fadd
:
3022 case lltok::kw_fsub
:
3023 case lltok::kw_fmul
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
3025 case lltok::kw_sdiv
: {
3027 if (EatIfPresent(lltok::kw_exact
))
3029 bool Result
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
3032 cast
<BinaryOperator
>(Inst
)->setIsExact(true);
3036 case lltok::kw_udiv
:
3037 case lltok::kw_urem
:
3038 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
3039 case lltok::kw_fdiv
:
3040 case lltok::kw_frem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
3042 case lltok::kw_lshr
:
3043 case lltok::kw_ashr
:
3046 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
3047 case lltok::kw_icmp
:
3048 case lltok::kw_fcmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
3050 case lltok::kw_trunc
:
3051 case lltok::kw_zext
:
3052 case lltok::kw_sext
:
3053 case lltok::kw_fptrunc
:
3054 case lltok::kw_fpext
:
3055 case lltok::kw_bitcast
:
3056 case lltok::kw_uitofp
:
3057 case lltok::kw_sitofp
:
3058 case lltok::kw_fptoui
:
3059 case lltok::kw_fptosi
:
3060 case lltok::kw_inttoptr
:
3061 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
3063 case lltok::kw_select
: return ParseSelect(Inst
, PFS
);
3064 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
3065 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
3066 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
3067 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
3068 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
3069 case lltok::kw_call
: return ParseCall(Inst
, PFS
, false);
3070 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, true);
3072 case lltok::kw_alloca
: return ParseAlloc(Inst
, PFS
);
3073 case lltok::kw_malloc
: return ParseAlloc(Inst
, PFS
, BB
, false);
3074 case lltok::kw_free
: return ParseFree(Inst
, PFS
, BB
);
3075 case lltok::kw_load
: return ParseLoad(Inst
, PFS
, false);
3076 case lltok::kw_store
: return ParseStore(Inst
, PFS
, false);
3077 case lltok::kw_volatile
:
3078 if (EatIfPresent(lltok::kw_load
))
3079 return ParseLoad(Inst
, PFS
, true);
3080 else if (EatIfPresent(lltok::kw_store
))
3081 return ParseStore(Inst
, PFS
, true);
3083 return TokError("expected 'load' or 'store'");
3084 case lltok::kw_getresult
: return ParseGetResult(Inst
, PFS
);
3085 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
3086 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
3087 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
3091 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3092 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
3093 if (Opc
== Instruction::FCmp
) {
3094 switch (Lex
.getKind()) {
3095 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3096 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
3097 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
3098 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
3099 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
3100 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
3101 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
3102 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
3103 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
3104 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
3105 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
3106 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
3107 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
3108 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
3109 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
3110 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
3111 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
3114 switch (Lex
.getKind()) {
3115 default: TokError("expected icmp predicate (e.g. 'eq')");
3116 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
3117 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
3118 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
3119 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
3120 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
3121 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
3122 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
3123 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
3124 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
3125 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
3132 //===----------------------------------------------------------------------===//
3133 // Terminator Instructions.
3134 //===----------------------------------------------------------------------===//
3136 /// ParseRet - Parse a return instruction.
3137 /// ::= 'ret' void (',' !dbg, !1)*
3138 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3139 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
3140 /// [[obsolete: LLVM 3.0]]
3141 int LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
3142 PerFunctionState
&PFS
) {
3143 PATypeHolder
Ty(Type::getVoidTy(Context
));
3144 if (ParseType(Ty
, true /*void allowed*/)) return true;
3146 if (Ty
->isVoidTy()) {
3147 Inst
= ReturnInst::Create(Context
);
3152 if (ParseValue(Ty
, RV
, PFS
)) return true;
3154 bool ExtraComma
= false;
3155 if (EatIfPresent(lltok::comma
)) {
3156 // Parse optional custom metadata, e.g. !dbg
3157 if (Lex
.getKind() == lltok::MetadataVar
) {
3160 // The normal case is one return value.
3161 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3162 // use of 'ret {i32,i32} {i32 1, i32 2}'
3163 SmallVector
<Value
*, 8> RVs
;
3167 // If optional custom metadata, e.g. !dbg is seen then this is the
3169 if (Lex
.getKind() == lltok::MetadataVar
)
3171 if (ParseTypeAndValue(RV
, PFS
)) return true;
3173 } while (EatIfPresent(lltok::comma
));
3175 RV
= UndefValue::get(PFS
.getFunction().getReturnType());
3176 for (unsigned i
= 0, e
= RVs
.size(); i
!= e
; ++i
) {
3177 Instruction
*I
= InsertValueInst::Create(RV
, RVs
[i
], i
, "mrv");
3178 BB
->getInstList().push_back(I
);
3184 Inst
= ReturnInst::Create(Context
, RV
);
3185 return ExtraComma
? InstExtraComma
: InstNormal
;
3190 /// ::= 'br' TypeAndValue
3191 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3192 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3195 BasicBlock
*Op1
, *Op2
;
3196 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
3198 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
3199 Inst
= BranchInst::Create(BB
);
3203 if (Op0
->getType() != Type::getInt1Ty(Context
))
3204 return Error(Loc
, "branch condition must have 'i1' type");
3206 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
3207 ParseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
3208 ParseToken(lltok::comma
, "expected ',' after true destination") ||
3209 ParseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
3212 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
3218 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3220 /// ::= (TypeAndValue ',' TypeAndValue)*
3221 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3222 LocTy CondLoc
, BBLoc
;
3224 BasicBlock
*DefaultBB
;
3225 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
3226 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
3227 ParseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
3228 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
3231 if (!Cond
->getType()->isIntegerTy())
3232 return Error(CondLoc
, "switch condition must have integer type");
3234 // Parse the jump table pairs.
3235 SmallPtrSet
<Value
*, 32> SeenCases
;
3236 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
3237 while (Lex
.getKind() != lltok::rsquare
) {
3241 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
3242 ParseToken(lltok::comma
, "expected ',' after case value") ||
3243 ParseTypeAndBasicBlock(DestBB
, PFS
))
3246 if (!SeenCases
.insert(Constant
))
3247 return Error(CondLoc
, "duplicate case value in switch");
3248 if (!isa
<ConstantInt
>(Constant
))
3249 return Error(CondLoc
, "case value is not a constant integer");
3251 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
3254 Lex
.Lex(); // Eat the ']'.
3256 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
3257 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
3258 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
3265 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3266 bool LLParser::ParseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3269 if (ParseTypeAndValue(Address
, AddrLoc
, PFS
) ||
3270 ParseToken(lltok::comma
, "expected ',' after indirectbr address") ||
3271 ParseToken(lltok::lsquare
, "expected '[' with indirectbr"))
3274 if (!Address
->getType()->isPointerTy())
3275 return Error(AddrLoc
, "indirectbr address must have pointer type");
3277 // Parse the destination list.
3278 SmallVector
<BasicBlock
*, 16> DestList
;
3280 if (Lex
.getKind() != lltok::rsquare
) {
3282 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
3284 DestList
.push_back(DestBB
);
3286 while (EatIfPresent(lltok::comma
)) {
3287 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
3289 DestList
.push_back(DestBB
);
3293 if (ParseToken(lltok::rsquare
, "expected ']' at end of block list"))
3296 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
3297 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
3298 IBI
->addDestination(DestList
[i
]);
3305 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3306 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3307 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3308 LocTy CallLoc
= Lex
.getLoc();
3309 unsigned RetAttrs
, FnAttrs
;
3311 PATypeHolder
RetType(Type::getVoidTy(Context
));
3314 SmallVector
<ParamInfo
, 16> ArgList
;
3316 BasicBlock
*NormalBB
, *UnwindBB
;
3317 if (ParseOptionalCallingConv(CC
) ||
3318 ParseOptionalAttrs(RetAttrs
, 1) ||
3319 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
3320 ParseValID(CalleeID
) ||
3321 ParseParameterList(ArgList
, PFS
) ||
3322 ParseOptionalAttrs(FnAttrs
, 2) ||
3323 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
3324 ParseTypeAndBasicBlock(NormalBB
, PFS
) ||
3325 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
3326 ParseTypeAndBasicBlock(UnwindBB
, PFS
))
3329 // If RetType is a non-function pointer type, then this is the short syntax
3330 // for the call, which means that RetType is just the return type. Infer the
3331 // rest of the function argument types from the arguments that are present.
3332 const PointerType
*PFTy
= 0;
3333 const FunctionType
*Ty
= 0;
3334 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
3335 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
3336 // Pull out the types of all of the arguments...
3337 std::vector
<const Type
*> ParamTypes
;
3338 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3339 ParamTypes
.push_back(ArgList
[i
].V
->getType());
3341 if (!FunctionType::isValidReturnType(RetType
))
3342 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
3344 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
3345 PFTy
= PointerType::getUnqual(Ty
);
3348 // Look up the callee.
3350 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, &PFS
)) return true;
3352 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3353 // function attributes.
3354 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
3355 if (FnAttrs
& ObsoleteFuncAttrs
) {
3356 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
3357 FnAttrs
&= ~ObsoleteFuncAttrs
;
3360 // Set up the Attributes for the function.
3361 SmallVector
<AttributeWithIndex
, 8> Attrs
;
3362 if (RetAttrs
!= Attribute::None
)
3363 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
3365 SmallVector
<Value
*, 8> Args
;
3367 // Loop through FunctionType's arguments and ensure they are specified
3368 // correctly. Also, gather any parameter attributes.
3369 FunctionType::param_iterator I
= Ty
->param_begin();
3370 FunctionType::param_iterator E
= Ty
->param_end();
3371 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3372 const Type
*ExpectedTy
= 0;
3375 } else if (!Ty
->isVarArg()) {
3376 return Error(ArgList
[i
].Loc
, "too many arguments specified");
3379 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
3380 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
3381 ExpectedTy
->getDescription() + "'");
3382 Args
.push_back(ArgList
[i
].V
);
3383 if (ArgList
[i
].Attrs
!= Attribute::None
)
3384 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
3388 return Error(CallLoc
, "not enough parameters specified for call");
3390 if (FnAttrs
!= Attribute::None
)
3391 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
3393 // Finish off the Attributes and check them
3394 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
3396 InvokeInst
*II
= InvokeInst::Create(Callee
, NormalBB
, UnwindBB
,
3397 Args
.begin(), Args
.end());
3398 II
->setCallingConv(CC
);
3399 II
->setAttributes(PAL
);
3406 //===----------------------------------------------------------------------===//
3407 // Binary Operators.
3408 //===----------------------------------------------------------------------===//
3411 /// ::= ArithmeticOps TypeAndValue ',' Value
3413 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3414 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3415 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
3416 unsigned Opc
, unsigned OperandType
) {
3417 LocTy Loc
; Value
*LHS
, *RHS
;
3418 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3419 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
3420 ParseValue(LHS
->getType(), RHS
, PFS
))
3424 switch (OperandType
) {
3425 default: llvm_unreachable("Unknown operand type!");
3426 case 0: // int or FP.
3427 Valid
= LHS
->getType()->isIntOrIntVectorTy() ||
3428 LHS
->getType()->isFPOrFPVectorTy();
3430 case 1: Valid
= LHS
->getType()->isIntOrIntVectorTy(); break;
3431 case 2: Valid
= LHS
->getType()->isFPOrFPVectorTy(); break;
3435 return Error(Loc
, "invalid operand type for instruction");
3437 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3442 /// ::= ArithmeticOps TypeAndValue ',' Value {
3443 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
3445 LocTy Loc
; Value
*LHS
, *RHS
;
3446 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3447 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
3448 ParseValue(LHS
->getType(), RHS
, PFS
))
3451 if (!LHS
->getType()->isIntOrIntVectorTy())
3452 return Error(Loc
,"instruction requires integer or integer vector operands");
3454 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3460 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3461 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3462 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
3464 // Parse the integer/fp comparison predicate.
3468 if (ParseCmpPredicate(Pred
, Opc
) ||
3469 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3470 ParseToken(lltok::comma
, "expected ',' after compare value") ||
3471 ParseValue(LHS
->getType(), RHS
, PFS
))
3474 if (Opc
== Instruction::FCmp
) {
3475 if (!LHS
->getType()->isFPOrFPVectorTy())
3476 return Error(Loc
, "fcmp requires floating point operands");
3477 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
3479 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
3480 if (!LHS
->getType()->isIntOrIntVectorTy() &&
3481 !LHS
->getType()->isPointerTy())
3482 return Error(Loc
, "icmp requires integer operands");
3483 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
3488 //===----------------------------------------------------------------------===//
3489 // Other Instructions.
3490 //===----------------------------------------------------------------------===//
3494 /// ::= CastOpc TypeAndValue 'to' Type
3495 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
3497 LocTy Loc
; Value
*Op
;
3498 PATypeHolder
DestTy(Type::getVoidTy(Context
));
3499 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
3500 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
3504 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
3505 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
3506 return Error(Loc
, "invalid cast opcode for cast from '" +
3507 Op
->getType()->getDescription() + "' to '" +
3508 DestTy
->getDescription() + "'");
3510 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
3515 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3516 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3518 Value
*Op0
, *Op1
, *Op2
;
3519 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3520 ParseToken(lltok::comma
, "expected ',' after select condition") ||
3521 ParseTypeAndValue(Op1
, PFS
) ||
3522 ParseToken(lltok::comma
, "expected ',' after select value") ||
3523 ParseTypeAndValue(Op2
, PFS
))
3526 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
3527 return Error(Loc
, Reason
);
3529 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
3534 /// ::= 'va_arg' TypeAndValue ',' Type
3535 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3537 PATypeHolder
EltTy(Type::getVoidTy(Context
));
3539 if (ParseTypeAndValue(Op
, PFS
) ||
3540 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
3541 ParseType(EltTy
, TypeLoc
))
3544 if (!EltTy
->isFirstClassType())
3545 return Error(TypeLoc
, "va_arg requires operand with first class type");
3547 Inst
= new VAArgInst(Op
, EltTy
);
3551 /// ParseExtractElement
3552 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3553 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3556 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3557 ParseToken(lltok::comma
, "expected ',' after extract value") ||
3558 ParseTypeAndValue(Op1
, PFS
))
3561 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
3562 return Error(Loc
, "invalid extractelement operands");
3564 Inst
= ExtractElementInst::Create(Op0
, Op1
);
3568 /// ParseInsertElement
3569 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3570 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3572 Value
*Op0
, *Op1
, *Op2
;
3573 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3574 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3575 ParseTypeAndValue(Op1
, PFS
) ||
3576 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3577 ParseTypeAndValue(Op2
, PFS
))
3580 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
3581 return Error(Loc
, "invalid insertelement operands");
3583 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
3587 /// ParseShuffleVector
3588 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3589 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3591 Value
*Op0
, *Op1
, *Op2
;
3592 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3593 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
3594 ParseTypeAndValue(Op1
, PFS
) ||
3595 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
3596 ParseTypeAndValue(Op2
, PFS
))
3599 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
3600 return Error(Loc
, "invalid extractelement operands");
3602 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
3607 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3608 int LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3609 PATypeHolder
Ty(Type::getVoidTy(Context
));
3611 LocTy TypeLoc
= Lex
.getLoc();
3613 if (ParseType(Ty
) ||
3614 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
3615 ParseValue(Ty
, Op0
, PFS
) ||
3616 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3617 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
3618 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
3621 bool AteExtraComma
= false;
3622 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
3624 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
3626 if (!EatIfPresent(lltok::comma
))
3629 if (Lex
.getKind() == lltok::MetadataVar
) {
3630 AteExtraComma
= true;
3634 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
3635 ParseValue(Ty
, Op0
, PFS
) ||
3636 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3637 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
3638 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
3642 if (!Ty
->isFirstClassType())
3643 return Error(TypeLoc
, "phi node must have first class type");
3645 PHINode
*PN
= PHINode::Create(Ty
);
3646 PN
->reserveOperandSpace(PHIVals
.size());
3647 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
3648 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
3650 return AteExtraComma
? InstExtraComma
: InstNormal
;
3654 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3655 /// ParameterList OptionalAttrs
3656 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
3658 unsigned RetAttrs
, FnAttrs
;
3660 PATypeHolder
RetType(Type::getVoidTy(Context
));
3663 SmallVector
<ParamInfo
, 16> ArgList
;
3664 LocTy CallLoc
= Lex
.getLoc();
3666 if ((isTail
&& ParseToken(lltok::kw_call
, "expected 'tail call'")) ||
3667 ParseOptionalCallingConv(CC
) ||
3668 ParseOptionalAttrs(RetAttrs
, 1) ||
3669 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
3670 ParseValID(CalleeID
) ||
3671 ParseParameterList(ArgList
, PFS
) ||
3672 ParseOptionalAttrs(FnAttrs
, 2))
3675 // If RetType is a non-function pointer type, then this is the short syntax
3676 // for the call, which means that RetType is just the return type. Infer the
3677 // rest of the function argument types from the arguments that are present.
3678 const PointerType
*PFTy
= 0;
3679 const FunctionType
*Ty
= 0;
3680 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
3681 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
3682 // Pull out the types of all of the arguments...
3683 std::vector
<const Type
*> ParamTypes
;
3684 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3685 ParamTypes
.push_back(ArgList
[i
].V
->getType());
3687 if (!FunctionType::isValidReturnType(RetType
))
3688 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
3690 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
3691 PFTy
= PointerType::getUnqual(Ty
);
3694 // Look up the callee.
3696 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, &PFS
)) return true;
3698 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3699 // function attributes.
3700 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
3701 if (FnAttrs
& ObsoleteFuncAttrs
) {
3702 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
3703 FnAttrs
&= ~ObsoleteFuncAttrs
;
3706 // Set up the Attributes for the function.
3707 SmallVector
<AttributeWithIndex
, 8> Attrs
;
3708 if (RetAttrs
!= Attribute::None
)
3709 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
3711 SmallVector
<Value
*, 8> Args
;
3713 // Loop through FunctionType's arguments and ensure they are specified
3714 // correctly. Also, gather any parameter attributes.
3715 FunctionType::param_iterator I
= Ty
->param_begin();
3716 FunctionType::param_iterator E
= Ty
->param_end();
3717 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3718 const Type
*ExpectedTy
= 0;
3721 } else if (!Ty
->isVarArg()) {
3722 return Error(ArgList
[i
].Loc
, "too many arguments specified");
3725 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
3726 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
3727 ExpectedTy
->getDescription() + "'");
3728 Args
.push_back(ArgList
[i
].V
);
3729 if (ArgList
[i
].Attrs
!= Attribute::None
)
3730 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
3734 return Error(CallLoc
, "not enough parameters specified for call");
3736 if (FnAttrs
!= Attribute::None
)
3737 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
3739 // Finish off the Attributes and check them
3740 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
3742 CallInst
*CI
= CallInst::Create(Callee
, Args
.begin(), Args
.end());
3743 CI
->setTailCall(isTail
);
3744 CI
->setCallingConv(CC
);
3745 CI
->setAttributes(PAL
);
3750 //===----------------------------------------------------------------------===//
3751 // Memory Instructions.
3752 //===----------------------------------------------------------------------===//
3755 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3756 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3757 int LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
,
3758 BasicBlock
* BB
, bool isAlloca
) {
3759 PATypeHolder
Ty(Type::getVoidTy(Context
));
3762 unsigned Alignment
= 0;
3763 if (ParseType(Ty
)) return true;
3765 bool AteExtraComma
= false;
3766 if (EatIfPresent(lltok::comma
)) {
3767 if (Lex
.getKind() == lltok::kw_align
) {
3768 if (ParseOptionalAlignment(Alignment
)) return true;
3769 } else if (Lex
.getKind() == lltok::MetadataVar
) {
3770 AteExtraComma
= true;
3772 if (ParseTypeAndValue(Size
, SizeLoc
, PFS
) ||
3773 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
3778 if (Size
&& !Size
->getType()->isIntegerTy())
3779 return Error(SizeLoc
, "element count must have integer type");
3782 Inst
= new AllocaInst(Ty
, Size
, Alignment
);
3783 return AteExtraComma
? InstExtraComma
: InstNormal
;
3786 // Autoupgrade old malloc instruction to malloc call.
3787 // FIXME: Remove in LLVM 3.0.
3788 if (Size
&& !Size
->getType()->isIntegerTy(32))
3789 return Error(SizeLoc
, "element count must be i32");
3790 const Type
*IntPtrTy
= Type::getInt32Ty(Context
);
3791 Constant
*AllocSize
= ConstantExpr::getSizeOf(Ty
);
3792 AllocSize
= ConstantExpr::getTruncOrBitCast(AllocSize
, IntPtrTy
);
3794 // Prototype malloc as "void *(int32)".
3795 // This function is renamed as "malloc" in ValidateEndOfModule().
3796 MallocF
= cast
<Function
>(
3797 M
->getOrInsertFunction("", Type::getInt8PtrTy(Context
), IntPtrTy
, NULL
));
3798 Inst
= CallInst::CreateMalloc(BB
, IntPtrTy
, Ty
, AllocSize
, Size
, MallocF
);
3799 return AteExtraComma
? InstExtraComma
: InstNormal
;
3803 /// ::= 'free' TypeAndValue
3804 bool LLParser::ParseFree(Instruction
*&Inst
, PerFunctionState
&PFS
,
3806 Value
*Val
; LocTy Loc
;
3807 if (ParseTypeAndValue(Val
, Loc
, PFS
)) return true;
3808 if (!Val
->getType()->isPointerTy())
3809 return Error(Loc
, "operand to free must be a pointer");
3810 Inst
= CallInst::CreateFree(Val
, BB
);
3815 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3816 int LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
,
3818 Value
*Val
; LocTy Loc
;
3819 unsigned Alignment
= 0;
3820 bool AteExtraComma
= false;
3821 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3822 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
3825 if (!Val
->getType()->isPointerTy() ||
3826 !cast
<PointerType
>(Val
->getType())->getElementType()->isFirstClassType())
3827 return Error(Loc
, "load operand must be a pointer to a first class type");
3829 Inst
= new LoadInst(Val
, "", isVolatile
, Alignment
);
3830 return AteExtraComma
? InstExtraComma
: InstNormal
;
3834 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3835 int LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
,
3837 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
3838 unsigned Alignment
= 0;
3839 bool AteExtraComma
= false;
3840 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3841 ParseToken(lltok::comma
, "expected ',' after store operand") ||
3842 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
3843 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
3846 if (!Ptr
->getType()->isPointerTy())
3847 return Error(PtrLoc
, "store operand must be a pointer");
3848 if (!Val
->getType()->isFirstClassType())
3849 return Error(Loc
, "store operand must be a first class value");
3850 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
3851 return Error(Loc
, "stored value and pointer type do not match");
3853 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
);
3854 return AteExtraComma
? InstExtraComma
: InstNormal
;
3858 /// ::= 'getresult' TypeAndValue ',' i32
3859 /// FIXME: Remove support for getresult in LLVM 3.0
3860 bool LLParser::ParseGetResult(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3861 Value
*Val
; LocTy ValLoc
, EltLoc
;
3863 if (ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
3864 ParseToken(lltok::comma
, "expected ',' after getresult operand") ||
3865 ParseUInt32(Element
, EltLoc
))
3868 if (!Val
->getType()->isStructTy() && !Val
->getType()->isArrayTy())
3869 return Error(ValLoc
, "getresult inst requires an aggregate operand");
3870 if (!ExtractValueInst::getIndexedType(Val
->getType(), Element
))
3871 return Error(EltLoc
, "invalid getresult index for value");
3872 Inst
= ExtractValueInst::Create(Val
, Element
);
3876 /// ParseGetElementPtr
3877 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3878 int LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3879 Value
*Ptr
, *Val
; LocTy Loc
, EltLoc
;
3881 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
3883 if (ParseTypeAndValue(Ptr
, Loc
, PFS
)) return true;
3885 if (!Ptr
->getType()->isPointerTy())
3886 return Error(Loc
, "base of getelementptr must be a pointer");
3888 SmallVector
<Value
*, 16> Indices
;
3889 bool AteExtraComma
= false;
3890 while (EatIfPresent(lltok::comma
)) {
3891 if (Lex
.getKind() == lltok::MetadataVar
) {
3892 AteExtraComma
= true;
3895 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
3896 if (!Val
->getType()->isIntegerTy())
3897 return Error(EltLoc
, "getelementptr index must be an integer");
3898 Indices
.push_back(Val
);
3901 if (!GetElementPtrInst::getIndexedType(Ptr
->getType(),
3902 Indices
.begin(), Indices
.end()))
3903 return Error(Loc
, "invalid getelementptr indices");
3904 Inst
= GetElementPtrInst::Create(Ptr
, Indices
.begin(), Indices
.end());
3906 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
3907 return AteExtraComma
? InstExtraComma
: InstNormal
;
3910 /// ParseExtractValue
3911 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3912 int LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3913 Value
*Val
; LocTy Loc
;
3914 SmallVector
<unsigned, 4> Indices
;
3916 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3917 ParseIndexList(Indices
, AteExtraComma
))
3920 if (!Val
->getType()->isAggregateType())
3921 return Error(Loc
, "extractvalue operand must be aggregate type");
3923 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
3925 return Error(Loc
, "invalid indices for extractvalue");
3926 Inst
= ExtractValueInst::Create(Val
, Indices
.begin(), Indices
.end());
3927 return AteExtraComma
? InstExtraComma
: InstNormal
;
3930 /// ParseInsertValue
3931 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3932 int LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3933 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
3934 SmallVector
<unsigned, 4> Indices
;
3936 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
3937 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
3938 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
3939 ParseIndexList(Indices
, AteExtraComma
))
3942 if (!Val0
->getType()->isAggregateType())
3943 return Error(Loc0
, "insertvalue operand must be aggregate type");
3945 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
3947 return Error(Loc0
, "invalid indices for insertvalue");
3948 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
.begin(), Indices
.end());
3949 return AteExtraComma
? InstExtraComma
: InstNormal
;
3952 //===----------------------------------------------------------------------===//
3953 // Embedded metadata.
3954 //===----------------------------------------------------------------------===//
3956 /// ParseMDNodeVector
3957 /// ::= Element (',' Element)*
3959 /// ::= 'null' | TypeAndValue
3960 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Value
*> &Elts
,
3961 PerFunctionState
*PFS
) {
3962 // Check for an empty list.
3963 if (Lex
.getKind() == lltok::rbrace
)
3967 // Null is a special case since it is typeless.
3968 if (EatIfPresent(lltok::kw_null
)) {
3974 PATypeHolder
Ty(Type::getVoidTy(Context
));
3976 if (ParseType(Ty
) || ParseValID(ID
, PFS
) ||
3977 ConvertValIDToValue(Ty
, ID
, V
, PFS
))
3981 } while (EatIfPresent(lltok::comma
));