blob: d461a8dcffd2b2ccc5a43d911142c9cdeb7ba066 [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
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"
Owen Andersonfba933c2009-07-01 23:57:11 +000021#include "llvm/LLVMContext.h"
Nick Lewyckycb337992009-05-10 20:57:05 +000022#include "llvm/MDNode.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000024#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000025#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000029#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
Chris Lattnerdf986172009-01-02 07:01:27 +000032namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000033 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000037 struct ValID {
38 enum {
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000043 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000044 t_Constant, // Value in ConstantVal.
45 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
46 } Kind;
47
48 LLParser::LocTy Loc;
49 unsigned UIntVal;
50 std::string StrVal, StrVal2;
51 APSInt APSIntVal;
52 APFloat APFloatVal;
53 Constant *ConstantVal;
54 ValID() : APFloatVal(0.0) {}
55 };
56}
57
Chris Lattner3ed88ef2009-01-02 08:05:26 +000058/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000059bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000060 // Prime the lexer.
61 Lex.Lex();
62
Chris Lattnerad7d1e22009-01-04 20:44:11 +000063 return ParseTopLevelEntities() ||
64 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000065}
66
67/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
68/// module.
69bool LLParser::ValidateEndOfModule() {
70 if (!ForwardRefTypes.empty())
71 return Error(ForwardRefTypes.begin()->second.second,
72 "use of undefined type named '" +
73 ForwardRefTypes.begin()->first + "'");
74 if (!ForwardRefTypeIDs.empty())
75 return Error(ForwardRefTypeIDs.begin()->second.second,
76 "use of undefined type '%" +
77 utostr(ForwardRefTypeIDs.begin()->first) + "'");
78
79 if (!ForwardRefVals.empty())
80 return Error(ForwardRefVals.begin()->second.second,
81 "use of undefined value '@" + ForwardRefVals.begin()->first +
82 "'");
83
84 if (!ForwardRefValIDs.empty())
85 return Error(ForwardRefValIDs.begin()->second.second,
86 "use of undefined value '@" +
87 utostr(ForwardRefValIDs.begin()->first) + "'");
88
Devang Patel1c7eea62009-07-08 19:23:54 +000089 if (!ForwardRefMDNodes.empty())
90 return Error(ForwardRefMDNodes.begin()->second.second,
91 "use of undefined metadata '!" +
92 utostr(ForwardRefMDNodes.begin()->first) + "'");
93
94
Chris Lattnerdf986172009-01-02 07:01:27 +000095 // Look for intrinsic functions and CallInst that need to be upgraded
96 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
97 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
98
99 return false;
100}
101
102//===----------------------------------------------------------------------===//
103// Top-Level Entities
104//===----------------------------------------------------------------------===//
105
106bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000107 while (1) {
108 switch (Lex.getKind()) {
109 default: return TokError("expected top-level entity");
110 case lltok::Eof: return false;
111 //case lltok::kw_define:
112 case lltok::kw_declare: if (ParseDeclare()) return true; break;
113 case lltok::kw_define: if (ParseDefine()) return true; break;
114 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
115 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
116 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
117 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
118 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
119 case lltok::LocalVar: if (ParseNamedType()) return true; break;
120 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000121 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000122
123 // The Global variable production with no name can have many different
124 // optional leading prefixes, the production is:
125 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
126 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000127 case lltok::kw_private : // OptionalLinkage
128 case lltok::kw_linker_private: // OptionalLinkage
129 case lltok::kw_internal: // OptionalLinkage
130 case lltok::kw_weak: // OptionalLinkage
131 case lltok::kw_weak_odr: // OptionalLinkage
132 case lltok::kw_linkonce: // OptionalLinkage
133 case lltok::kw_linkonce_odr: // OptionalLinkage
134 case lltok::kw_appending: // OptionalLinkage
135 case lltok::kw_dllexport: // OptionalLinkage
136 case lltok::kw_common: // OptionalLinkage
137 case lltok::kw_dllimport: // OptionalLinkage
138 case lltok::kw_extern_weak: // OptionalLinkage
139 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000140 unsigned Linkage, Visibility;
141 if (ParseOptionalLinkage(Linkage) ||
142 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000143 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000144 return true;
145 break;
146 }
147 case lltok::kw_default: // OptionalVisibility
148 case lltok::kw_hidden: // OptionalVisibility
149 case lltok::kw_protected: { // OptionalVisibility
150 unsigned Visibility;
151 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000152 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000153 return true;
154 break;
155 }
156
157 case lltok::kw_thread_local: // OptionalThreadLocal
158 case lltok::kw_addrspace: // OptionalAddrSpace
159 case lltok::kw_constant: // GlobalType
160 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000161 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000162 break;
163 }
164 }
165}
166
167
168/// toplevelentity
169/// ::= 'module' 'asm' STRINGCONSTANT
170bool LLParser::ParseModuleAsm() {
171 assert(Lex.getKind() == lltok::kw_module);
172 Lex.Lex();
173
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000174 std::string AsmStr;
175 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
176 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000177
178 const std::string &AsmSoFar = M->getModuleInlineAsm();
179 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000180 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000182 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000183 return false;
184}
185
186/// toplevelentity
187/// ::= 'target' 'triple' '=' STRINGCONSTANT
188/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
189bool LLParser::ParseTargetDefinition() {
190 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000191 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000192 switch (Lex.Lex()) {
193 default: return TokError("unknown target property");
194 case lltok::kw_triple:
195 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000196 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
197 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000199 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000200 return false;
201 case lltok::kw_datalayout:
202 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000203 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
204 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return false;
208 }
209}
210
211/// toplevelentity
212/// ::= 'deplibs' '=' '[' ']'
213/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
214bool LLParser::ParseDepLibs() {
215 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000217 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
218 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
219 return true;
220
221 if (EatIfPresent(lltok::rsquare))
222 return false;
223
224 std::string Str;
225 if (ParseStringConstant(Str)) return true;
226 M->addLibrary(Str);
227
228 while (EatIfPresent(lltok::comma)) {
229 if (ParseStringConstant(Str)) return true;
230 M->addLibrary(Str);
231 }
232
233 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000234}
235
236/// toplevelentity
237/// ::= 'type' type
238bool LLParser::ParseUnnamedType() {
239 assert(Lex.getKind() == lltok::kw_type);
240 LocTy TypeLoc = Lex.getLoc();
241 Lex.Lex(); // eat kw_type
242
243 PATypeHolder Ty(Type::VoidTy);
244 if (ParseType(Ty)) return true;
245
246 unsigned TypeID = NumberedTypes.size();
247
Chris Lattnerdf986172009-01-02 07:01:27 +0000248 // See if this type was previously referenced.
249 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
250 FI = ForwardRefTypeIDs.find(TypeID);
251 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000252 if (FI->second.first.get() == Ty)
253 return Error(TypeLoc, "self referential type is invalid");
254
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
256 Ty = FI->second.first.get();
257 ForwardRefTypeIDs.erase(FI);
258 }
259
260 NumberedTypes.push_back(Ty);
261
262 return false;
263}
264
265/// toplevelentity
266/// ::= LocalVar '=' 'type' type
267bool LLParser::ParseNamedType() {
268 std::string Name = Lex.getStrVal();
269 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000270 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000271
272 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000273
274 if (ParseToken(lltok::equal, "expected '=' after name") ||
275 ParseToken(lltok::kw_type, "expected 'type' after name") ||
276 ParseType(Ty))
277 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000278
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 // Set the type name, checking for conflicts as we do so.
280 bool AlreadyExists = M->addTypeName(Name, Ty);
281 if (!AlreadyExists) return false;
282
283 // See if this type is a forward reference. We need to eagerly resolve
284 // types to allow recursive type redefinitions below.
285 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
286 FI = ForwardRefTypes.find(Name);
287 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000288 if (FI->second.first.get() == Ty)
289 return Error(NameLoc, "self referential type is invalid");
290
Chris Lattnerdf986172009-01-02 07:01:27 +0000291 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
292 Ty = FI->second.first.get();
293 ForwardRefTypes.erase(FI);
294 }
295
296 // Inserting a name that is already defined, get the existing name.
297 const Type *Existing = M->getTypeByName(Name);
298 assert(Existing && "Conflict but no matching type?!");
299
300 // Otherwise, this is an attempt to redefine a type. That's okay if
301 // the redefinition is identical to the original.
302 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
303 if (Existing == Ty) return false;
304
305 // Any other kind of (non-equivalent) redefinition is an error.
306 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
307 Ty->getDescription() + "'");
308}
309
310
311/// toplevelentity
312/// ::= 'declare' FunctionHeader
313bool LLParser::ParseDeclare() {
314 assert(Lex.getKind() == lltok::kw_declare);
315 Lex.Lex();
316
317 Function *F;
318 return ParseFunctionHeader(F, false);
319}
320
321/// toplevelentity
322/// ::= 'define' FunctionHeader '{' ...
323bool LLParser::ParseDefine() {
324 assert(Lex.getKind() == lltok::kw_define);
325 Lex.Lex();
326
327 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000328 return ParseFunctionHeader(F, true) ||
329 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000330}
331
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000332/// ParseGlobalType
333/// ::= 'constant'
334/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000335bool LLParser::ParseGlobalType(bool &IsConstant) {
336 if (Lex.getKind() == lltok::kw_constant)
337 IsConstant = true;
338 else if (Lex.getKind() == lltok::kw_global)
339 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000340 else {
341 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000342 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000343 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 Lex.Lex();
345 return false;
346}
347
348/// ParseNamedGlobal:
349/// GlobalVar '=' OptionalVisibility ALIAS ...
350/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
351bool LLParser::ParseNamedGlobal() {
352 assert(Lex.getKind() == lltok::GlobalVar);
353 LocTy NameLoc = Lex.getLoc();
354 std::string Name = Lex.getStrVal();
355 Lex.Lex();
356
357 bool HasLinkage;
358 unsigned Linkage, Visibility;
359 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
360 ParseOptionalLinkage(Linkage, HasLinkage) ||
361 ParseOptionalVisibility(Visibility))
362 return true;
363
364 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
365 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
366 return ParseAlias(Name, NameLoc, Visibility);
367}
368
Devang Patel256be962009-07-20 19:00:08 +0000369// MDString:
370// ::= '!' STRINGCONSTANT
371bool LLParser::ParseMDString(Constant *&MDS) {
372 std::string Str;
373 if (ParseStringConstant(Str)) return true;
374 MDS = Context.getMDString(Str.data(), Str.data() + Str.size());
375 return false;
376}
377
378// MDNode:
379// ::= '!' MDNodeNumber
380bool LLParser::ParseMDNode(Constant *&Node) {
381 // !{ ..., !42, ... }
382 unsigned MID = 0;
383 if (ParseUInt32(MID)) return true;
384
385 // Check existing MDNode.
386 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
387 if (I != MetadataCache.end()) {
388 Node = I->second;
389 return false;
390 }
391
392 // Check known forward references.
393 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
394 FI = ForwardRefMDNodes.find(MID);
395 if (FI != ForwardRefMDNodes.end()) {
396 Node = FI->second.first;
397 return false;
398 }
399
400 // Create MDNode forward reference
401 SmallVector<Value *, 1> Elts;
402 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
403 Elts.push_back(Context.getMDString(FwdRefName));
404 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
405 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
406 Node = FwdNode;
407 return false;
408}
409
Devang Patel923078c2009-07-01 19:21:12 +0000410/// ParseStandaloneMetadata:
411/// !42 = !{...}
412bool LLParser::ParseStandaloneMetadata() {
413 assert(Lex.getKind() == lltok::Metadata);
414 Lex.Lex();
415 unsigned MetadataID = 0;
416 if (ParseUInt32(MetadataID))
417 return true;
418 if (MetadataCache.find(MetadataID) != MetadataCache.end())
419 return TokError("Metadata id is already used");
420 if (ParseToken(lltok::equal, "expected '=' here"))
421 return true;
422
423 LocTy TyLoc;
Devang Patel923078c2009-07-01 19:21:12 +0000424 PATypeHolder Ty(Type::VoidTy);
Devang Patel2214c942009-07-08 21:57:07 +0000425 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000426 return true;
427
428 Constant *Init = 0;
429 if (ParseGlobalValue(Ty, Init))
430 return true;
431
432 MetadataCache[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000433 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
434 FI = ForwardRefMDNodes.find(MetadataID);
435 if (FI != ForwardRefMDNodes.end()) {
436 Constant *FwdNode = FI->second.first;
437 FwdNode->replaceAllUsesWith(Init);
438 ForwardRefMDNodes.erase(FI);
439 }
440
Devang Patel923078c2009-07-01 19:21:12 +0000441 return false;
442}
443
Chris Lattnerdf986172009-01-02 07:01:27 +0000444/// ParseAlias:
445/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
446/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000447/// ::= TypeAndValue
448/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
449/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000450///
451/// Everything through visibility has already been parsed.
452///
453bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
454 unsigned Visibility) {
455 assert(Lex.getKind() == lltok::kw_alias);
456 Lex.Lex();
457 unsigned Linkage;
458 LocTy LinkageLoc = Lex.getLoc();
459 if (ParseOptionalLinkage(Linkage))
460 return true;
461
462 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000463 Linkage != GlobalValue::WeakAnyLinkage &&
464 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000465 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000466 Linkage != GlobalValue::PrivateLinkage &&
467 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000468 return Error(LinkageLoc, "invalid linkage type for alias");
469
470 Constant *Aliasee;
471 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000472 if (Lex.getKind() != lltok::kw_bitcast &&
473 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000474 if (ParseGlobalTypeAndValue(Aliasee)) return true;
475 } else {
476 // The bitcast dest type is not present, it is implied by the dest type.
477 ValID ID;
478 if (ParseValID(ID)) return true;
479 if (ID.Kind != ValID::t_Constant)
480 return Error(AliaseeLoc, "invalid aliasee");
481 Aliasee = ID.ConstantVal;
482 }
483
484 if (!isa<PointerType>(Aliasee->getType()))
485 return Error(AliaseeLoc, "alias must have pointer type");
486
487 // Okay, create the alias but do not insert it into the module yet.
488 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
489 (GlobalValue::LinkageTypes)Linkage, Name,
490 Aliasee);
491 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
492
493 // See if this value already exists in the symbol table. If so, it is either
494 // a redefinition or a definition of a forward reference.
495 if (GlobalValue *Val =
496 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
497 // See if this was a redefinition. If so, there is no entry in
498 // ForwardRefVals.
499 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
500 I = ForwardRefVals.find(Name);
501 if (I == ForwardRefVals.end())
502 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
503
504 // Otherwise, this was a definition of forward ref. Verify that types
505 // agree.
506 if (Val->getType() != GA->getType())
507 return Error(NameLoc,
508 "forward reference and definition of alias have different types");
509
510 // If they agree, just RAUW the old value with the alias and remove the
511 // forward ref info.
512 Val->replaceAllUsesWith(GA);
513 Val->eraseFromParent();
514 ForwardRefVals.erase(I);
515 }
516
517 // Insert into the module, we know its name won't collide now.
518 M->getAliasList().push_back(GA);
519 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
520
521 return false;
522}
523
524/// ParseGlobal
525/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
526/// OptionalAddrSpace GlobalType Type Const
527/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
528/// OptionalAddrSpace GlobalType Type Const
529///
530/// Everything through visibility has been parsed already.
531///
532bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
533 unsigned Linkage, bool HasLinkage,
534 unsigned Visibility) {
535 unsigned AddrSpace;
536 bool ThreadLocal, IsConstant;
537 LocTy TyLoc;
538
539 PATypeHolder Ty(Type::VoidTy);
540 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
541 ParseOptionalAddrSpace(AddrSpace) ||
542 ParseGlobalType(IsConstant) ||
543 ParseType(Ty, TyLoc))
544 return true;
545
546 // If the linkage is specified and is external, then no initializer is
547 // present.
548 Constant *Init = 0;
549 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000550 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000551 Linkage != GlobalValue::ExternalLinkage)) {
552 if (ParseGlobalValue(Ty, Init))
553 return true;
554 }
555
Chris Lattnera9a9e072009-03-09 04:49:14 +0000556 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000557 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000558
559 GlobalVariable *GV = 0;
560
561 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000562 if (!Name.empty()) {
563 if ((GV = M->getGlobalVariable(Name, true)) &&
564 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000565 return Error(NameLoc, "redefinition of global '@" + Name + "'");
566 } else {
567 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
568 I = ForwardRefValIDs.find(NumberedVals.size());
569 if (I != ForwardRefValIDs.end()) {
570 GV = cast<GlobalVariable>(I->second.first);
571 ForwardRefValIDs.erase(I);
572 }
573 }
574
575 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000576 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
577 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000578 } else {
579 if (GV->getType()->getElementType() != Ty)
580 return Error(TyLoc,
581 "forward reference and definition of global have different types");
582
583 // Move the forward-reference to the correct spot in the module.
584 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
585 }
586
587 if (Name.empty())
588 NumberedVals.push_back(GV);
589
590 // Set the parsed properties on the global.
591 if (Init)
592 GV->setInitializer(Init);
593 GV->setConstant(IsConstant);
594 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
595 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
596 GV->setThreadLocal(ThreadLocal);
597
598 // Parse attributes on the global.
599 while (Lex.getKind() == lltok::comma) {
600 Lex.Lex();
601
602 if (Lex.getKind() == lltok::kw_section) {
603 Lex.Lex();
604 GV->setSection(Lex.getStrVal());
605 if (ParseToken(lltok::StringConstant, "expected global section string"))
606 return true;
607 } else if (Lex.getKind() == lltok::kw_align) {
608 unsigned Alignment;
609 if (ParseOptionalAlignment(Alignment)) return true;
610 GV->setAlignment(Alignment);
611 } else {
612 TokError("unknown global variable property!");
613 }
614 }
615
616 return false;
617}
618
619
620//===----------------------------------------------------------------------===//
621// GlobalValue Reference/Resolution Routines.
622//===----------------------------------------------------------------------===//
623
624/// GetGlobalVal - Get a value with the specified name or ID, creating a
625/// forward reference record if needed. This can return null if the value
626/// exists but does not have the right type.
627GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
628 LocTy Loc) {
629 const PointerType *PTy = dyn_cast<PointerType>(Ty);
630 if (PTy == 0) {
631 Error(Loc, "global variable reference must have pointer type");
632 return 0;
633 }
634
635 // Look this name up in the normal function symbol table.
636 GlobalValue *Val =
637 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
638
639 // If this is a forward reference for the value, see if we already created a
640 // forward ref record.
641 if (Val == 0) {
642 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
643 I = ForwardRefVals.find(Name);
644 if (I != ForwardRefVals.end())
645 Val = I->second.first;
646 }
647
648 // If we have the value in the symbol table or fwd-ref table, return it.
649 if (Val) {
650 if (Val->getType() == Ty) return Val;
651 Error(Loc, "'@" + Name + "' defined with type '" +
652 Val->getType()->getDescription() + "'");
653 return 0;
654 }
655
656 // Otherwise, create a new forward reference for this value and remember it.
657 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000658 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
659 // Function types can return opaque but functions can't.
660 if (isa<OpaqueType>(FT->getReturnType())) {
661 Error(Loc, "function may not return opaque type");
662 return 0;
663 }
664
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000665 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000666 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000667 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
668 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000669 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000670
671 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
672 return FwdVal;
673}
674
675GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
676 const PointerType *PTy = dyn_cast<PointerType>(Ty);
677 if (PTy == 0) {
678 Error(Loc, "global variable reference must have pointer type");
679 return 0;
680 }
681
682 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
683
684 // If this is a forward reference for the value, see if we already created a
685 // forward ref record.
686 if (Val == 0) {
687 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
688 I = ForwardRefValIDs.find(ID);
689 if (I != ForwardRefValIDs.end())
690 Val = I->second.first;
691 }
692
693 // If we have the value in the symbol table or fwd-ref table, return it.
694 if (Val) {
695 if (Val->getType() == Ty) return Val;
696 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
697 Val->getType()->getDescription() + "'");
698 return 0;
699 }
700
701 // Otherwise, create a new forward reference for this value and remember it.
702 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000703 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
704 // Function types can return opaque but functions can't.
705 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000706 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000707 return 0;
708 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000709 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000710 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000711 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
712 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000713 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000714
715 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
716 return FwdVal;
717}
718
719
720//===----------------------------------------------------------------------===//
721// Helper Routines.
722//===----------------------------------------------------------------------===//
723
724/// ParseToken - If the current token has the specified kind, eat it and return
725/// success. Otherwise, emit the specified error and return failure.
726bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
727 if (Lex.getKind() != T)
728 return TokError(ErrMsg);
729 Lex.Lex();
730 return false;
731}
732
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000733/// ParseStringConstant
734/// ::= StringConstant
735bool LLParser::ParseStringConstant(std::string &Result) {
736 if (Lex.getKind() != lltok::StringConstant)
737 return TokError("expected string constant");
738 Result = Lex.getStrVal();
739 Lex.Lex();
740 return false;
741}
742
743/// ParseUInt32
744/// ::= uint32
745bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
747 return TokError("expected integer");
748 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
749 if (Val64 != unsigned(Val64))
750 return TokError("expected 32-bit integer (too large)");
751 Val = Val64;
752 Lex.Lex();
753 return false;
754}
755
756
757/// ParseOptionalAddrSpace
758/// := /*empty*/
759/// := 'addrspace' '(' uint32 ')'
760bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
761 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000762 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000763 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000765 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000766 ParseToken(lltok::rparen, "expected ')' in address space");
767}
768
769/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
770/// indicates what kind of attribute list this is: 0: function arg, 1: result,
771/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000772/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000773bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
774 Attrs = Attribute::None;
775 LocTy AttrLoc = Lex.getLoc();
776
777 while (1) {
778 switch (Lex.getKind()) {
779 case lltok::kw_sext:
780 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000781 // Treat these as signext/zeroext if they occur in the argument list after
782 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
783 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
784 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000786 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000787 if (Lex.getKind() == lltok::kw_sext)
788 Attrs |= Attribute::SExt;
789 else
790 Attrs |= Attribute::ZExt;
791 break;
792 }
793 // FALL THROUGH.
794 default: // End of attributes.
795 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
796 return Error(AttrLoc, "invalid use of function-only attribute");
797
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000798 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 return Error(AttrLoc, "invalid use of parameter-only attribute");
800
801 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000802 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
803 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
804 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
805 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
806 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
807 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
808 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
809 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000810
Devang Patel578efa92009-06-05 21:57:13 +0000811 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
812 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
813 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
814 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
815 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
816 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
817 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
818 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
819 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
820 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
821 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000822 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000823
824 case lltok::kw_align: {
825 unsigned Alignment;
826 if (ParseOptionalAlignment(Alignment))
827 return true;
828 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
829 continue;
830 }
831 }
832 Lex.Lex();
833 }
834}
835
836/// ParseOptionalLinkage
837/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000838/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000839/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000840/// ::= 'internal'
841/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000842/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000843/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000844/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000845/// ::= 'appending'
846/// ::= 'dllexport'
847/// ::= 'common'
848/// ::= 'dllimport'
849/// ::= 'extern_weak'
850/// ::= 'external'
851bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
852 HasLinkage = false;
853 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000854 default: Res=GlobalValue::ExternalLinkage; return false;
855 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
856 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
857 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
858 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
859 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
860 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
861 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000862 case lltok::kw_available_externally:
863 Res = GlobalValue::AvailableExternallyLinkage;
864 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000865 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
866 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
867 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
868 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
869 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
870 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000871 }
872 Lex.Lex();
873 HasLinkage = true;
874 return false;
875}
876
877/// ParseOptionalVisibility
878/// ::= /*empty*/
879/// ::= 'default'
880/// ::= 'hidden'
881/// ::= 'protected'
882///
883bool LLParser::ParseOptionalVisibility(unsigned &Res) {
884 switch (Lex.getKind()) {
885 default: Res = GlobalValue::DefaultVisibility; return false;
886 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
887 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
888 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
889 }
890 Lex.Lex();
891 return false;
892}
893
894/// ParseOptionalCallingConv
895/// ::= /*empty*/
896/// ::= 'ccc'
897/// ::= 'fastcc'
898/// ::= 'coldcc'
899/// ::= 'x86_stdcallcc'
900/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000901/// ::= 'arm_apcscc'
902/// ::= 'arm_aapcscc'
903/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000904/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000905///
Chris Lattnerdf986172009-01-02 07:01:27 +0000906bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
907 switch (Lex.getKind()) {
908 default: CC = CallingConv::C; return false;
909 case lltok::kw_ccc: CC = CallingConv::C; break;
910 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
911 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
912 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
913 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000914 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
915 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
916 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000917 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000918 }
919 Lex.Lex();
920 return false;
921}
922
923/// ParseOptionalAlignment
924/// ::= /* empty */
925/// ::= 'align' 4
926bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
927 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000928 if (!EatIfPresent(lltok::kw_align))
929 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000930 LocTy AlignLoc = Lex.getLoc();
931 if (ParseUInt32(Alignment)) return true;
932 if (!isPowerOf2_32(Alignment))
933 return Error(AlignLoc, "alignment is not a power of two");
934 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000935}
936
937/// ParseOptionalCommaAlignment
938/// ::= /* empty */
939/// ::= ',' 'align' 4
940bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
941 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000942 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000943 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000944 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000945 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000946}
947
948/// ParseIndexList
949/// ::= (',' uint32)+
950bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
951 if (Lex.getKind() != lltok::comma)
952 return TokError("expected ',' as start of index list");
953
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000954 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000955 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000956 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000957 Indices.push_back(Idx);
958 }
959
960 return false;
961}
962
963//===----------------------------------------------------------------------===//
964// Type Parsing.
965//===----------------------------------------------------------------------===//
966
967/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000968bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
969 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000970 if (ParseTypeRec(Result)) return true;
971
972 // Verify no unresolved uprefs.
973 if (!UpRefs.empty())
974 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000975
Chris Lattnera9a9e072009-03-09 04:49:14 +0000976 if (!AllowVoid && Result.get() == Type::VoidTy)
977 return Error(TypeLoc, "void type only allowed for function results");
978
Chris Lattnerdf986172009-01-02 07:01:27 +0000979 return false;
980}
981
982/// HandleUpRefs - Every time we finish a new layer of types, this function is
983/// called. It loops through the UpRefs vector, which is a list of the
984/// currently active types. For each type, if the up-reference is contained in
985/// the newly completed type, we decrement the level count. When the level
986/// count reaches zero, the up-referenced type is the type that is passed in:
987/// thus we can complete the cycle.
988///
989PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
990 // If Ty isn't abstract, or if there are no up-references in it, then there is
991 // nothing to resolve here.
992 if (!ty->isAbstract() || UpRefs.empty()) return ty;
993
994 PATypeHolder Ty(ty);
995#if 0
996 errs() << "Type '" << Ty->getDescription()
997 << "' newly formed. Resolving upreferences.\n"
998 << UpRefs.size() << " upreferences active!\n";
999#endif
1000
1001 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1002 // to zero), we resolve them all together before we resolve them to Ty. At
1003 // the end of the loop, if there is anything to resolve to Ty, it will be in
1004 // this variable.
1005 OpaqueType *TypeToResolve = 0;
1006
1007 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1008 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1009 bool ContainsType =
1010 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1011 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1012
1013#if 0
1014 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1015 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1016 << (ContainsType ? "true" : "false")
1017 << " level=" << UpRefs[i].NestingLevel << "\n";
1018#endif
1019 if (!ContainsType)
1020 continue;
1021
1022 // Decrement level of upreference
1023 unsigned Level = --UpRefs[i].NestingLevel;
1024 UpRefs[i].LastContainedTy = Ty;
1025
1026 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1027 if (Level != 0)
1028 continue;
1029
1030#if 0
1031 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1032#endif
1033 if (!TypeToResolve)
1034 TypeToResolve = UpRefs[i].UpRefTy;
1035 else
1036 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1037 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1038 --i; // Do not skip the next element.
1039 }
1040
1041 if (TypeToResolve)
1042 TypeToResolve->refineAbstractTypeTo(Ty);
1043
1044 return Ty;
1045}
1046
1047
1048/// ParseTypeRec - The recursive function used to process the internal
1049/// implementation details of types.
1050bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1051 switch (Lex.getKind()) {
1052 default:
1053 return TokError("expected type");
1054 case lltok::Type:
1055 // TypeRec ::= 'float' | 'void' (etc)
1056 Result = Lex.getTyVal();
1057 Lex.Lex();
1058 break;
1059 case lltok::kw_opaque:
1060 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001061 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001062 Lex.Lex();
1063 break;
1064 case lltok::lbrace:
1065 // TypeRec ::= '{' ... '}'
1066 if (ParseStructType(Result, false))
1067 return true;
1068 break;
1069 case lltok::lsquare:
1070 // TypeRec ::= '[' ... ']'
1071 Lex.Lex(); // eat the lsquare.
1072 if (ParseArrayVectorType(Result, false))
1073 return true;
1074 break;
1075 case lltok::less: // Either vector or packed struct.
1076 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001077 Lex.Lex();
1078 if (Lex.getKind() == lltok::lbrace) {
1079 if (ParseStructType(Result, true) ||
1080 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001081 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001082 } else if (ParseArrayVectorType(Result, true))
1083 return true;
1084 break;
1085 case lltok::LocalVar:
1086 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1087 // TypeRec ::= %foo
1088 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1089 Result = T;
1090 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001091 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001092 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1093 std::make_pair(Result,
1094 Lex.getLoc())));
1095 M->addTypeName(Lex.getStrVal(), Result.get());
1096 }
1097 Lex.Lex();
1098 break;
1099
1100 case lltok::LocalVarID:
1101 // TypeRec ::= %4
1102 if (Lex.getUIntVal() < NumberedTypes.size())
1103 Result = NumberedTypes[Lex.getUIntVal()];
1104 else {
1105 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1106 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1107 if (I != ForwardRefTypeIDs.end())
1108 Result = I->second.first;
1109 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001110 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001111 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1112 std::make_pair(Result,
1113 Lex.getLoc())));
1114 }
1115 }
1116 Lex.Lex();
1117 break;
1118 case lltok::backslash: {
1119 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001120 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001121 unsigned Val;
1122 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001123 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001124 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1125 Result = OT;
1126 break;
1127 }
1128 }
1129
1130 // Parse the type suffixes.
1131 while (1) {
1132 switch (Lex.getKind()) {
1133 // End of type.
1134 default: return false;
1135
1136 // TypeRec ::= TypeRec '*'
1137 case lltok::star:
1138 if (Result.get() == Type::LabelTy)
1139 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001140 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001141 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001142 if (!PointerType::isValidElementType(Result.get()))
1143 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001144 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001145 Lex.Lex();
1146 break;
1147
1148 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1149 case lltok::kw_addrspace: {
1150 if (Result.get() == Type::LabelTy)
1151 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001152 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001153 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001154 if (!PointerType::isValidElementType(Result.get()))
1155 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 unsigned AddrSpace;
1157 if (ParseOptionalAddrSpace(AddrSpace) ||
1158 ParseToken(lltok::star, "expected '*' in address space"))
1159 return true;
1160
Owen Andersonfba933c2009-07-01 23:57:11 +00001161 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 break;
1163 }
1164
1165 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1166 case lltok::lparen:
1167 if (ParseFunctionType(Result))
1168 return true;
1169 break;
1170 }
1171 }
1172}
1173
1174/// ParseParameterList
1175/// ::= '(' ')'
1176/// ::= '(' Arg (',' Arg)* ')'
1177/// Arg
1178/// ::= Type OptionalAttributes Value OptionalAttributes
1179bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1180 PerFunctionState &PFS) {
1181 if (ParseToken(lltok::lparen, "expected '(' in call"))
1182 return true;
1183
1184 while (Lex.getKind() != lltok::rparen) {
1185 // If this isn't the first argument, we need a comma.
1186 if (!ArgList.empty() &&
1187 ParseToken(lltok::comma, "expected ',' in argument list"))
1188 return true;
1189
1190 // Parse the argument.
1191 LocTy ArgLoc;
1192 PATypeHolder ArgTy(Type::VoidTy);
1193 unsigned ArgAttrs1, ArgAttrs2;
1194 Value *V;
1195 if (ParseType(ArgTy, ArgLoc) ||
1196 ParseOptionalAttrs(ArgAttrs1, 0) ||
1197 ParseValue(ArgTy, V, PFS) ||
1198 // FIXME: Should not allow attributes after the argument, remove this in
1199 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001200 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001201 return true;
1202 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1203 }
1204
1205 Lex.Lex(); // Lex the ')'.
1206 return false;
1207}
1208
1209
1210
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001211/// ParseArgumentList - Parse the argument list for a function type or function
1212/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001213/// ::= '(' ArgTypeListI ')'
1214/// ArgTypeListI
1215/// ::= /*empty*/
1216/// ::= '...'
1217/// ::= ArgTypeList ',' '...'
1218/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001219///
Chris Lattnerdf986172009-01-02 07:01:27 +00001220bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001221 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 isVarArg = false;
1223 assert(Lex.getKind() == lltok::lparen);
1224 Lex.Lex(); // eat the (.
1225
1226 if (Lex.getKind() == lltok::rparen) {
1227 // empty
1228 } else if (Lex.getKind() == lltok::dotdotdot) {
1229 isVarArg = true;
1230 Lex.Lex();
1231 } else {
1232 LocTy TypeLoc = Lex.getLoc();
1233 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001234 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001235 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001236
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001237 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1238 // types (such as a function returning a pointer to itself). If parsing a
1239 // function prototype, we require fully resolved types.
1240 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001241 ParseOptionalAttrs(Attrs, 0)) return true;
1242
Chris Lattnera9a9e072009-03-09 04:49:14 +00001243 if (ArgTy == Type::VoidTy)
1244 return Error(TypeLoc, "argument can not have void type");
1245
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 if (Lex.getKind() == lltok::LocalVar ||
1247 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1248 Name = Lex.getStrVal();
1249 Lex.Lex();
1250 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001251
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001252 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001253 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001254
1255 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1256
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001257 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001258 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001259 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001260 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001261 break;
1262 }
1263
1264 // Otherwise must be an argument type.
1265 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001266 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001267 ParseOptionalAttrs(Attrs, 0)) return true;
1268
Chris Lattnera9a9e072009-03-09 04:49:14 +00001269 if (ArgTy == Type::VoidTy)
1270 return Error(TypeLoc, "argument can not have void type");
1271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 if (Lex.getKind() == lltok::LocalVar ||
1273 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1274 Name = Lex.getStrVal();
1275 Lex.Lex();
1276 } else {
1277 Name = "";
1278 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001279
1280 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1281 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001282
1283 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1284 }
1285 }
1286
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001287 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001288}
1289
1290/// ParseFunctionType
1291/// ::= Type ArgumentList OptionalAttrs
1292bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1293 assert(Lex.getKind() == lltok::lparen);
1294
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001295 if (!FunctionType::isValidReturnType(Result))
1296 return TokError("invalid function return type");
1297
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 std::vector<ArgInfo> ArgList;
1299 bool isVarArg;
1300 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001301 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 // FIXME: Allow, but ignore attributes on function types!
1303 // FIXME: Remove in LLVM 3.0
1304 ParseOptionalAttrs(Attrs, 2))
1305 return true;
1306
1307 // Reject names on the arguments lists.
1308 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1309 if (!ArgList[i].Name.empty())
1310 return Error(ArgList[i].Loc, "argument name invalid in function type");
1311 if (!ArgList[i].Attrs != 0) {
1312 // Allow but ignore attributes on function types; this permits
1313 // auto-upgrade.
1314 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1315 }
1316 }
1317
1318 std::vector<const Type*> ArgListTy;
1319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1320 ArgListTy.push_back(ArgList[i].Type);
1321
Owen Andersonfba933c2009-07-01 23:57:11 +00001322 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1323 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 return false;
1325}
1326
1327/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1328/// TypeRec
1329/// ::= '{' '}'
1330/// ::= '{' TypeRec (',' TypeRec)* '}'
1331/// ::= '<' '{' '}' '>'
1332/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1333bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1334 assert(Lex.getKind() == lltok::lbrace);
1335 Lex.Lex(); // Consume the '{'
1336
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001337 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001338 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 return false;
1340 }
1341
1342 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001343 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001344 if (ParseTypeRec(Result)) return true;
1345 ParamsList.push_back(Result);
1346
Chris Lattnera9a9e072009-03-09 04:49:14 +00001347 if (Result == Type::VoidTy)
1348 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001349 if (!StructType::isValidElementType(Result))
1350 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001351
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001352 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001353 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001355
1356 if (Result == Type::VoidTy)
1357 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001358 if (!StructType::isValidElementType(Result))
1359 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001360
Chris Lattnerdf986172009-01-02 07:01:27 +00001361 ParamsList.push_back(Result);
1362 }
1363
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001364 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1365 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001366
1367 std::vector<const Type*> ParamsListTy;
1368 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1369 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001370 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 return false;
1372}
1373
1374/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1375/// token has already been consumed.
1376/// TypeRec
1377/// ::= '[' APSINTVAL 'x' Types ']'
1378/// ::= '<' APSINTVAL 'x' Types '>'
1379bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1380 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1381 Lex.getAPSIntVal().getBitWidth() > 64)
1382 return TokError("expected number in address space");
1383
1384 LocTy SizeLoc = Lex.getLoc();
1385 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001386 Lex.Lex();
1387
1388 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1389 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001390
1391 LocTy TypeLoc = Lex.getLoc();
1392 PATypeHolder EltTy(Type::VoidTy);
1393 if (ParseTypeRec(EltTy)) return true;
1394
Chris Lattnera9a9e072009-03-09 04:49:14 +00001395 if (EltTy == Type::VoidTy)
1396 return Error(TypeLoc, "array and vector element type cannot be void");
1397
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001398 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1399 "expected end of sequential type"))
1400 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001401
1402 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001403 if (Size == 0)
1404 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001405 if ((unsigned)Size != Size)
1406 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001407 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001409 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001410 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001411 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001412 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001413 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001414 }
1415 return false;
1416}
1417
1418//===----------------------------------------------------------------------===//
1419// Function Semantic Analysis.
1420//===----------------------------------------------------------------------===//
1421
1422LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1423 : P(p), F(f) {
1424
1425 // Insert unnamed arguments into the NumberedVals list.
1426 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1427 AI != E; ++AI)
1428 if (!AI->hasName())
1429 NumberedVals.push_back(AI);
1430}
1431
1432LLParser::PerFunctionState::~PerFunctionState() {
1433 // If there were any forward referenced non-basicblock values, delete them.
1434 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1435 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1436 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001437 I->second.first->replaceAllUsesWith(
1438 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 delete I->second.first;
1440 I->second.first = 0;
1441 }
1442
1443 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1444 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1445 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001446 I->second.first->replaceAllUsesWith(
1447 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 delete I->second.first;
1449 I->second.first = 0;
1450 }
1451}
1452
1453bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1454 if (!ForwardRefVals.empty())
1455 return P.Error(ForwardRefVals.begin()->second.second,
1456 "use of undefined value '%" + ForwardRefVals.begin()->first +
1457 "'");
1458 if (!ForwardRefValIDs.empty())
1459 return P.Error(ForwardRefValIDs.begin()->second.second,
1460 "use of undefined value '%" +
1461 utostr(ForwardRefValIDs.begin()->first) + "'");
1462 return false;
1463}
1464
1465
1466/// GetVal - Get a value with the specified name or ID, creating a
1467/// forward reference record if needed. This can return null if the value
1468/// exists but does not have the right type.
1469Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1470 const Type *Ty, LocTy Loc) {
1471 // Look this name up in the normal function symbol table.
1472 Value *Val = F.getValueSymbolTable().lookup(Name);
1473
1474 // If this is a forward reference for the value, see if we already created a
1475 // forward ref record.
1476 if (Val == 0) {
1477 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1478 I = ForwardRefVals.find(Name);
1479 if (I != ForwardRefVals.end())
1480 Val = I->second.first;
1481 }
1482
1483 // If we have the value in the symbol table or fwd-ref table, return it.
1484 if (Val) {
1485 if (Val->getType() == Ty) return Val;
1486 if (Ty == Type::LabelTy)
1487 P.Error(Loc, "'%" + Name + "' is not a basic block");
1488 else
1489 P.Error(Loc, "'%" + Name + "' defined with type '" +
1490 Val->getType()->getDescription() + "'");
1491 return 0;
1492 }
1493
1494 // Don't make placeholders with invalid type.
1495 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1496 P.Error(Loc, "invalid use of a non-first-class type");
1497 return 0;
1498 }
1499
1500 // Otherwise, create a new forward reference for this value and remember it.
1501 Value *FwdVal;
1502 if (Ty == Type::LabelTy)
1503 FwdVal = BasicBlock::Create(Name, &F);
1504 else
1505 FwdVal = new Argument(Ty, Name);
1506
1507 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1508 return FwdVal;
1509}
1510
1511Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1512 LocTy Loc) {
1513 // Look this name up in the normal function symbol table.
1514 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1515
1516 // If this is a forward reference for the value, see if we already created a
1517 // forward ref record.
1518 if (Val == 0) {
1519 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1520 I = ForwardRefValIDs.find(ID);
1521 if (I != ForwardRefValIDs.end())
1522 Val = I->second.first;
1523 }
1524
1525 // If we have the value in the symbol table or fwd-ref table, return it.
1526 if (Val) {
1527 if (Val->getType() == Ty) return Val;
1528 if (Ty == Type::LabelTy)
1529 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1530 else
1531 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1532 Val->getType()->getDescription() + "'");
1533 return 0;
1534 }
1535
1536 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1537 P.Error(Loc, "invalid use of a non-first-class type");
1538 return 0;
1539 }
1540
1541 // Otherwise, create a new forward reference for this value and remember it.
1542 Value *FwdVal;
1543 if (Ty == Type::LabelTy)
1544 FwdVal = BasicBlock::Create("", &F);
1545 else
1546 FwdVal = new Argument(Ty);
1547
1548 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1549 return FwdVal;
1550}
1551
1552/// SetInstName - After an instruction is parsed and inserted into its
1553/// basic block, this installs its name.
1554bool LLParser::PerFunctionState::SetInstName(int NameID,
1555 const std::string &NameStr,
1556 LocTy NameLoc, Instruction *Inst) {
1557 // If this instruction has void type, it cannot have a name or ID specified.
1558 if (Inst->getType() == Type::VoidTy) {
1559 if (NameID != -1 || !NameStr.empty())
1560 return P.Error(NameLoc, "instructions returning void cannot have a name");
1561 return false;
1562 }
1563
1564 // If this was a numbered instruction, verify that the instruction is the
1565 // expected value and resolve any forward references.
1566 if (NameStr.empty()) {
1567 // If neither a name nor an ID was specified, just use the next ID.
1568 if (NameID == -1)
1569 NameID = NumberedVals.size();
1570
1571 if (unsigned(NameID) != NumberedVals.size())
1572 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1573 utostr(NumberedVals.size()) + "'");
1574
1575 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1576 ForwardRefValIDs.find(NameID);
1577 if (FI != ForwardRefValIDs.end()) {
1578 if (FI->second.first->getType() != Inst->getType())
1579 return P.Error(NameLoc, "instruction forward referenced with type '" +
1580 FI->second.first->getType()->getDescription() + "'");
1581 FI->second.first->replaceAllUsesWith(Inst);
1582 ForwardRefValIDs.erase(FI);
1583 }
1584
1585 NumberedVals.push_back(Inst);
1586 return false;
1587 }
1588
1589 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1590 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1591 FI = ForwardRefVals.find(NameStr);
1592 if (FI != ForwardRefVals.end()) {
1593 if (FI->second.first->getType() != Inst->getType())
1594 return P.Error(NameLoc, "instruction forward referenced with type '" +
1595 FI->second.first->getType()->getDescription() + "'");
1596 FI->second.first->replaceAllUsesWith(Inst);
1597 ForwardRefVals.erase(FI);
1598 }
1599
1600 // Set the name on the instruction.
1601 Inst->setName(NameStr);
1602
1603 if (Inst->getNameStr() != NameStr)
1604 return P.Error(NameLoc, "multiple definition of local value named '" +
1605 NameStr + "'");
1606 return false;
1607}
1608
1609/// GetBB - Get a basic block with the specified name or ID, creating a
1610/// forward reference record if needed.
1611BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1612 LocTy Loc) {
1613 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1614}
1615
1616BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1617 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1618}
1619
1620/// DefineBB - Define the specified basic block, which is either named or
1621/// unnamed. If there is an error, this returns null otherwise it returns
1622/// the block being defined.
1623BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1624 LocTy Loc) {
1625 BasicBlock *BB;
1626 if (Name.empty())
1627 BB = GetBB(NumberedVals.size(), Loc);
1628 else
1629 BB = GetBB(Name, Loc);
1630 if (BB == 0) return 0; // Already diagnosed error.
1631
1632 // Move the block to the end of the function. Forward ref'd blocks are
1633 // inserted wherever they happen to be referenced.
1634 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1635
1636 // Remove the block from forward ref sets.
1637 if (Name.empty()) {
1638 ForwardRefValIDs.erase(NumberedVals.size());
1639 NumberedVals.push_back(BB);
1640 } else {
1641 // BB forward references are already in the function symbol table.
1642 ForwardRefVals.erase(Name);
1643 }
1644
1645 return BB;
1646}
1647
1648//===----------------------------------------------------------------------===//
1649// Constants.
1650//===----------------------------------------------------------------------===//
1651
1652/// ParseValID - Parse an abstract value that doesn't necessarily have a
1653/// type implied. For example, if we parse "4" we don't know what integer type
1654/// it has. The value will later be combined with its type and checked for
1655/// sanity.
1656bool LLParser::ParseValID(ValID &ID) {
1657 ID.Loc = Lex.getLoc();
1658 switch (Lex.getKind()) {
1659 default: return TokError("expected value token");
1660 case lltok::GlobalID: // @42
1661 ID.UIntVal = Lex.getUIntVal();
1662 ID.Kind = ValID::t_GlobalID;
1663 break;
1664 case lltok::GlobalVar: // @foo
1665 ID.StrVal = Lex.getStrVal();
1666 ID.Kind = ValID::t_GlobalName;
1667 break;
1668 case lltok::LocalVarID: // %42
1669 ID.UIntVal = Lex.getUIntVal();
1670 ID.Kind = ValID::t_LocalID;
1671 break;
1672 case lltok::LocalVar: // %foo
1673 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1674 ID.StrVal = Lex.getStrVal();
1675 ID.Kind = ValID::t_LocalName;
1676 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001677 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1678 ID.Kind = ValID::t_Constant;
1679 Lex.Lex();
1680 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001681 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001682 if (ParseMDNodeVector(Elts) ||
1683 ParseToken(lltok::rbrace, "expected end of metadata node"))
1684 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001685
Owen Andersone951bdf2009-07-02 17:20:28 +00001686 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001687 return false;
1688 }
1689
Devang Patel923078c2009-07-01 19:21:12 +00001690 // Standalone metadata reference
1691 // !{ ..., !42, ... }
Devang Patel256be962009-07-20 19:00:08 +00001692 if (!ParseMDNode(ID.ConstantVal))
Devang Patel923078c2009-07-01 19:21:12 +00001693 return false;
Devang Patel256be962009-07-20 19:00:08 +00001694
Nick Lewycky21cc4462009-04-04 07:22:01 +00001695 // MDString:
1696 // ::= '!' STRINGCONSTANT
Devang Patel256be962009-07-20 19:00:08 +00001697 if (ParseMDString(ID.ConstantVal)) return true;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001698 return false;
1699 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001700 case lltok::APSInt:
1701 ID.APSIntVal = Lex.getAPSIntVal();
1702 ID.Kind = ValID::t_APSInt;
1703 break;
1704 case lltok::APFloat:
1705 ID.APFloatVal = Lex.getAPFloatVal();
1706 ID.Kind = ValID::t_APFloat;
1707 break;
1708 case lltok::kw_true:
Owen Andersonb3056fa2009-07-21 18:03:38 +00001709 ID.ConstantVal = Context.getTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 ID.Kind = ValID::t_Constant;
1711 break;
1712 case lltok::kw_false:
Owen Andersonb3056fa2009-07-21 18:03:38 +00001713 ID.ConstantVal = Context.getFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 ID.Kind = ValID::t_Constant;
1715 break;
1716 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1717 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1718 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1719
1720 case lltok::lbrace: {
1721 // ValID ::= '{' ConstVector '}'
1722 Lex.Lex();
1723 SmallVector<Constant*, 16> Elts;
1724 if (ParseGlobalValueVector(Elts) ||
1725 ParseToken(lltok::rbrace, "expected end of struct constant"))
1726 return true;
1727
Owen Andersonfba933c2009-07-01 23:57:11 +00001728 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001729 ID.Kind = ValID::t_Constant;
1730 return false;
1731 }
1732 case lltok::less: {
1733 // ValID ::= '<' ConstVector '>' --> Vector.
1734 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1735 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001736 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001737
1738 SmallVector<Constant*, 16> Elts;
1739 LocTy FirstEltLoc = Lex.getLoc();
1740 if (ParseGlobalValueVector(Elts) ||
1741 (isPackedStruct &&
1742 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1743 ParseToken(lltok::greater, "expected end of constant"))
1744 return true;
1745
1746 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001747 ID.ConstantVal =
1748 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001749 ID.Kind = ValID::t_Constant;
1750 return false;
1751 }
1752
1753 if (Elts.empty())
1754 return Error(ID.Loc, "constant vector must not be empty");
1755
1756 if (!Elts[0]->getType()->isInteger() &&
1757 !Elts[0]->getType()->isFloatingPoint())
1758 return Error(FirstEltLoc,
1759 "vector elements must have integer or floating point type");
1760
1761 // Verify that all the vector elements have the same type.
1762 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1763 if (Elts[i]->getType() != Elts[0]->getType())
1764 return Error(FirstEltLoc,
1765 "vector element #" + utostr(i) +
1766 " is not of type '" + Elts[0]->getType()->getDescription());
1767
Owen Andersonfba933c2009-07-01 23:57:11 +00001768 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 ID.Kind = ValID::t_Constant;
1770 return false;
1771 }
1772 case lltok::lsquare: { // Array Constant
1773 Lex.Lex();
1774 SmallVector<Constant*, 16> Elts;
1775 LocTy FirstEltLoc = Lex.getLoc();
1776 if (ParseGlobalValueVector(Elts) ||
1777 ParseToken(lltok::rsquare, "expected end of array constant"))
1778 return true;
1779
1780 // Handle empty element.
1781 if (Elts.empty()) {
1782 // Use undef instead of an array because it's inconvenient to determine
1783 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001784 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 return false;
1786 }
1787
1788 if (!Elts[0]->getType()->isFirstClassType())
1789 return Error(FirstEltLoc, "invalid array element type: " +
1790 Elts[0]->getType()->getDescription());
1791
Owen Andersonfba933c2009-07-01 23:57:11 +00001792 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001793
1794 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001795 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 if (Elts[i]->getType() != Elts[0]->getType())
1797 return Error(FirstEltLoc,
1798 "array element #" + utostr(i) +
1799 " is not of type '" +Elts[0]->getType()->getDescription());
1800 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001801
Owen Andersonfba933c2009-07-01 23:57:11 +00001802 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001803 ID.Kind = ValID::t_Constant;
1804 return false;
1805 }
1806 case lltok::kw_c: // c "foo"
1807 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001808 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1810 ID.Kind = ValID::t_Constant;
1811 return false;
1812
1813 case lltok::kw_asm: {
1814 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1815 bool HasSideEffect;
1816 Lex.Lex();
1817 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001818 ParseStringConstant(ID.StrVal) ||
1819 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 ParseToken(lltok::StringConstant, "expected constraint string"))
1821 return true;
1822 ID.StrVal2 = Lex.getStrVal();
1823 ID.UIntVal = HasSideEffect;
1824 ID.Kind = ValID::t_InlineAsm;
1825 return false;
1826 }
1827
1828 case lltok::kw_trunc:
1829 case lltok::kw_zext:
1830 case lltok::kw_sext:
1831 case lltok::kw_fptrunc:
1832 case lltok::kw_fpext:
1833 case lltok::kw_bitcast:
1834 case lltok::kw_uitofp:
1835 case lltok::kw_sitofp:
1836 case lltok::kw_fptoui:
1837 case lltok::kw_fptosi:
1838 case lltok::kw_inttoptr:
1839 case lltok::kw_ptrtoint: {
1840 unsigned Opc = Lex.getUIntVal();
1841 PATypeHolder DestTy(Type::VoidTy);
1842 Constant *SrcVal;
1843 Lex.Lex();
1844 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1845 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001846 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 ParseType(DestTy) ||
1848 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1849 return true;
1850 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1851 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1852 SrcVal->getType()->getDescription() + "' to '" +
1853 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001854 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1855 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001856 ID.Kind = ValID::t_Constant;
1857 return false;
1858 }
1859 case lltok::kw_extractvalue: {
1860 Lex.Lex();
1861 Constant *Val;
1862 SmallVector<unsigned, 4> Indices;
1863 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1864 ParseGlobalTypeAndValue(Val) ||
1865 ParseIndexList(Indices) ||
1866 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1867 return true;
1868 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1869 return Error(ID.Loc, "extractvalue operand must be array or struct");
1870 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1871 Indices.end()))
1872 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001873 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001874 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001875 ID.Kind = ValID::t_Constant;
1876 return false;
1877 }
1878 case lltok::kw_insertvalue: {
1879 Lex.Lex();
1880 Constant *Val0, *Val1;
1881 SmallVector<unsigned, 4> Indices;
1882 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1883 ParseGlobalTypeAndValue(Val0) ||
1884 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1885 ParseGlobalTypeAndValue(Val1) ||
1886 ParseIndexList(Indices) ||
1887 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1888 return true;
1889 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1890 return Error(ID.Loc, "extractvalue operand must be array or struct");
1891 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1892 Indices.end()))
1893 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001894 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1895 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001896 ID.Kind = ValID::t_Constant;
1897 return false;
1898 }
1899 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001900 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 unsigned PredVal, Opc = Lex.getUIntVal();
1902 Constant *Val0, *Val1;
1903 Lex.Lex();
1904 if (ParseCmpPredicate(PredVal, Opc) ||
1905 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1906 ParseGlobalTypeAndValue(Val0) ||
1907 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1908 ParseGlobalTypeAndValue(Val1) ||
1909 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1910 return true;
1911
1912 if (Val0->getType() != Val1->getType())
1913 return Error(ID.Loc, "compare operands must have the same type");
1914
1915 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1916
1917 if (Opc == Instruction::FCmp) {
1918 if (!Val0->getType()->isFPOrFPVector())
1919 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001920 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001921 } else {
1922 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001923 if (!Val0->getType()->isIntOrIntVector() &&
1924 !isa<PointerType>(Val0->getType()))
1925 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001926 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001927 }
1928 ID.Kind = ValID::t_Constant;
1929 return false;
1930 }
1931
1932 // Binary Operators.
1933 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001934 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001935 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001936 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001938 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 case lltok::kw_udiv:
1940 case lltok::kw_sdiv:
1941 case lltok::kw_fdiv:
1942 case lltok::kw_urem:
1943 case lltok::kw_srem:
1944 case lltok::kw_frem: {
1945 unsigned Opc = Lex.getUIntVal();
1946 Constant *Val0, *Val1;
1947 Lex.Lex();
1948 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1949 ParseGlobalTypeAndValue(Val0) ||
1950 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1951 ParseGlobalTypeAndValue(Val1) ||
1952 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1953 return true;
1954 if (Val0->getType() != Val1->getType())
1955 return Error(ID.Loc, "operands of constexpr must have same type");
1956 if (!Val0->getType()->isIntOrIntVector() &&
1957 !Val0->getType()->isFPOrFPVector())
1958 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001959 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 ID.Kind = ValID::t_Constant;
1961 return false;
1962 }
1963
1964 // Logical Operations
1965 case lltok::kw_shl:
1966 case lltok::kw_lshr:
1967 case lltok::kw_ashr:
1968 case lltok::kw_and:
1969 case lltok::kw_or:
1970 case lltok::kw_xor: {
1971 unsigned Opc = Lex.getUIntVal();
1972 Constant *Val0, *Val1;
1973 Lex.Lex();
1974 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1975 ParseGlobalTypeAndValue(Val0) ||
1976 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1977 ParseGlobalTypeAndValue(Val1) ||
1978 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1979 return true;
1980 if (Val0->getType() != Val1->getType())
1981 return Error(ID.Loc, "operands of constexpr must have same type");
1982 if (!Val0->getType()->isIntOrIntVector())
1983 return Error(ID.Loc,
1984 "constexpr requires integer or integer vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001985 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001986 ID.Kind = ValID::t_Constant;
1987 return false;
1988 }
1989
1990 case lltok::kw_getelementptr:
1991 case lltok::kw_shufflevector:
1992 case lltok::kw_insertelement:
1993 case lltok::kw_extractelement:
1994 case lltok::kw_select: {
1995 unsigned Opc = Lex.getUIntVal();
1996 SmallVector<Constant*, 16> Elts;
1997 Lex.Lex();
1998 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1999 ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2001 return true;
2002
2003 if (Opc == Instruction::GetElementPtr) {
2004 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2005 return Error(ID.Loc, "getelementptr requires pointer operand");
2006
2007 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2008 (Value**)&Elts[1], Elts.size()-1))
2009 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00002010 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 &Elts[1], Elts.size()-1);
2012 } else if (Opc == Instruction::Select) {
2013 if (Elts.size() != 3)
2014 return Error(ID.Loc, "expected three operands to select");
2015 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2016 Elts[2]))
2017 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00002018 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 } else if (Opc == Instruction::ShuffleVector) {
2020 if (Elts.size() != 3)
2021 return Error(ID.Loc, "expected three operands to shufflevector");
2022 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2023 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002024 ID.ConstantVal =
2025 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002026 } else if (Opc == Instruction::ExtractElement) {
2027 if (Elts.size() != 2)
2028 return Error(ID.Loc, "expected two operands to extractelement");
2029 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2030 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002031 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 } else {
2033 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2034 if (Elts.size() != 3)
2035 return Error(ID.Loc, "expected three operands to insertelement");
2036 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2037 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002038 ID.ConstantVal =
2039 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 }
2041
2042 ID.Kind = ValID::t_Constant;
2043 return false;
2044 }
Dan Gohman1224c382009-07-20 21:19:07 +00002045 case lltok::kw_signed: {
2046 Lex.Lex();
2047 bool AlsoUnsigned = EatIfPresent(lltok::kw_unsigned);
2048 if (Lex.getKind() != lltok::kw_add &&
2049 Lex.getKind() != lltok::kw_sub &&
2050 Lex.getKind() != lltok::kw_mul)
2051 return TokError("expected 'add', 'sub', or 'mul'");
2052 bool Result = LLParser::ParseValID(ID);
2053 if (!Result) {
2054 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2055 ->setHasNoSignedOverflow(true);
2056 if (AlsoUnsigned)
2057 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2058 ->setHasNoUnsignedOverflow(true);
2059 }
2060 return Result;
2061 }
2062 case lltok::kw_unsigned: {
2063 Lex.Lex();
2064 bool AlsoSigned = EatIfPresent(lltok::kw_signed);
2065 if (Lex.getKind() != lltok::kw_add &&
2066 Lex.getKind() != lltok::kw_sub &&
2067 Lex.getKind() != lltok::kw_mul)
2068 return TokError("expected 'add', 'sub', or 'mul'");
2069 bool Result = LLParser::ParseValID(ID);
2070 if (!Result) {
2071 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2072 ->setHasNoUnsignedOverflow(true);
2073 if (AlsoSigned)
2074 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2075 ->setHasNoSignedOverflow(true);
2076 }
2077 return Result;
2078 }
2079 case lltok::kw_exact: {
2080 Lex.Lex();
2081 if (Lex.getKind() != lltok::kw_sdiv)
2082 return TokError("expected 'sdiv'");
2083 bool Result = LLParser::ParseValID(ID);
2084 if (!Result)
2085 cast<SDivOperator>(ID.ConstantVal)->setIsExact(true);
2086 return Result;
2087 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 }
2089
2090 Lex.Lex();
2091 return false;
2092}
2093
2094/// ParseGlobalValue - Parse a global value with the specified type.
2095bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2096 V = 0;
2097 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002098 return ParseValID(ID) ||
2099 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002100}
2101
2102/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2103/// constant.
2104bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2105 Constant *&V) {
2106 if (isa<FunctionType>(Ty))
2107 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2108
2109 switch (ID.Kind) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002110 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002111 case ValID::t_LocalID:
2112 case ValID::t_LocalName:
2113 return Error(ID.Loc, "invalid use of function-local name");
2114 case ValID::t_InlineAsm:
2115 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2116 case ValID::t_GlobalName:
2117 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2118 return V == 0;
2119 case ValID::t_GlobalID:
2120 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2121 return V == 0;
2122 case ValID::t_APSInt:
2123 if (!isa<IntegerType>(Ty))
2124 return Error(ID.Loc, "integer constant must have integer type");
2125 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002126 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002127 return false;
2128 case ValID::t_APFloat:
2129 if (!Ty->isFloatingPoint() ||
2130 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2131 return Error(ID.Loc, "floating point constant invalid for type");
2132
2133 // The lexer has no type info, so builds all float and double FP constants
2134 // as double. Fix this here. Long double does not need this.
2135 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2136 Ty == Type::FloatTy) {
2137 bool Ignored;
2138 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2139 &Ignored);
2140 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002141 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002142
2143 if (V->getType() != Ty)
2144 return Error(ID.Loc, "floating point constant does not have type '" +
2145 Ty->getDescription() + "'");
2146
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 return false;
2148 case ValID::t_Null:
2149 if (!isa<PointerType>(Ty))
2150 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002151 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 return false;
2153 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002154 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002155 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2156 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002157 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002158 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002160 case ValID::t_EmptyArray:
2161 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2162 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002163 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002164 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002166 // FIXME: LabelTy should not be a first-class type.
2167 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002169 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 return false;
2171 case ValID::t_Constant:
2172 if (ID.ConstantVal->getType() != Ty)
2173 return Error(ID.Loc, "constant expression type mismatch");
2174 V = ID.ConstantVal;
2175 return false;
2176 }
2177}
2178
2179bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2180 PATypeHolder Type(Type::VoidTy);
2181 return ParseType(Type) ||
2182 ParseGlobalValue(Type, V);
2183}
2184
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002185/// ParseGlobalValueVector
2186/// ::= /*empty*/
2187/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002188bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2189 // Empty list.
2190 if (Lex.getKind() == lltok::rbrace ||
2191 Lex.getKind() == lltok::rsquare ||
2192 Lex.getKind() == lltok::greater ||
2193 Lex.getKind() == lltok::rparen)
2194 return false;
2195
2196 Constant *C;
2197 if (ParseGlobalTypeAndValue(C)) return true;
2198 Elts.push_back(C);
2199
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002200 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 if (ParseGlobalTypeAndValue(C)) return true;
2202 Elts.push_back(C);
2203 }
2204
2205 return false;
2206}
2207
2208
2209//===----------------------------------------------------------------------===//
2210// Function Parsing.
2211//===----------------------------------------------------------------------===//
2212
2213bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2214 PerFunctionState &PFS) {
2215 if (ID.Kind == ValID::t_LocalID)
2216 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2217 else if (ID.Kind == ValID::t_LocalName)
2218 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002219 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2221 const FunctionType *FTy =
2222 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2223 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2224 return Error(ID.Loc, "invalid type for inline asm constraint string");
2225 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2226 return false;
2227 } else {
2228 Constant *C;
2229 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2230 V = C;
2231 return false;
2232 }
2233
2234 return V == 0;
2235}
2236
2237bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2238 V = 0;
2239 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002240 return ParseValID(ID) ||
2241 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002242}
2243
2244bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2245 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002246 return ParseType(T) ||
2247 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002248}
2249
2250/// FunctionHeader
2251/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2252/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2253/// OptionalAlign OptGC
2254bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2255 // Parse the linkage.
2256 LocTy LinkageLoc = Lex.getLoc();
2257 unsigned Linkage;
2258
2259 unsigned Visibility, CC, RetAttrs;
2260 PATypeHolder RetType(Type::VoidTy);
2261 LocTy RetTypeLoc = Lex.getLoc();
2262 if (ParseOptionalLinkage(Linkage) ||
2263 ParseOptionalVisibility(Visibility) ||
2264 ParseOptionalCallingConv(CC) ||
2265 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002266 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002267 return true;
2268
2269 // Verify that the linkage is ok.
2270 switch ((GlobalValue::LinkageTypes)Linkage) {
2271 case GlobalValue::ExternalLinkage:
2272 break; // always ok.
2273 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002274 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 if (isDefine)
2276 return Error(LinkageLoc, "invalid linkage for function definition");
2277 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002278 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002279 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002281 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002282 case GlobalValue::LinkOnceAnyLinkage:
2283 case GlobalValue::LinkOnceODRLinkage:
2284 case GlobalValue::WeakAnyLinkage:
2285 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002286 case GlobalValue::DLLExportLinkage:
2287 if (!isDefine)
2288 return Error(LinkageLoc, "invalid linkage for function declaration");
2289 break;
2290 case GlobalValue::AppendingLinkage:
2291 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002292 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002293 return Error(LinkageLoc, "invalid function linkage type");
2294 }
2295
Chris Lattner99bb3152009-01-05 08:00:30 +00002296 if (!FunctionType::isValidReturnType(RetType) ||
2297 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002298 return Error(RetTypeLoc, "invalid function return type");
2299
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002301
2302 std::string FunctionName;
2303 if (Lex.getKind() == lltok::GlobalVar) {
2304 FunctionName = Lex.getStrVal();
2305 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2306 unsigned NameID = Lex.getUIntVal();
2307
2308 if (NameID != NumberedVals.size())
2309 return TokError("function expected to be numbered '%" +
2310 utostr(NumberedVals.size()) + "'");
2311 } else {
2312 return TokError("expected function name");
2313 }
2314
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002315 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002316
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002317 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002318 return TokError("expected '(' in function argument list");
2319
2320 std::vector<ArgInfo> ArgList;
2321 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002322 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002324 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002325 std::string GC;
2326
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002327 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002328 ParseOptionalAttrs(FuncAttrs, 2) ||
2329 (EatIfPresent(lltok::kw_section) &&
2330 ParseStringConstant(Section)) ||
2331 ParseOptionalAlignment(Alignment) ||
2332 (EatIfPresent(lltok::kw_gc) &&
2333 ParseStringConstant(GC)))
2334 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002335
2336 // If the alignment was parsed as an attribute, move to the alignment field.
2337 if (FuncAttrs & Attribute::Alignment) {
2338 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2339 FuncAttrs &= ~Attribute::Alignment;
2340 }
2341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 // Okay, if we got here, the function is syntactically valid. Convert types
2343 // and do semantic checks.
2344 std::vector<const Type*> ParamTypeList;
2345 SmallVector<AttributeWithIndex, 8> Attrs;
2346 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2347 // attributes.
2348 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2349 if (FuncAttrs & ObsoleteFuncAttrs) {
2350 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2351 FuncAttrs &= ~ObsoleteFuncAttrs;
2352 }
2353
2354 if (RetAttrs != Attribute::None)
2355 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2356
2357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2358 ParamTypeList.push_back(ArgList[i].Type);
2359 if (ArgList[i].Attrs != Attribute::None)
2360 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2361 }
2362
2363 if (FuncAttrs != Attribute::None)
2364 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2365
2366 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2367
Chris Lattnera9a9e072009-03-09 04:49:14 +00002368 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2369 RetType != Type::VoidTy)
2370 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2371
Owen Andersonfba933c2009-07-01 23:57:11 +00002372 const FunctionType *FT =
2373 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2374 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002375
2376 Fn = 0;
2377 if (!FunctionName.empty()) {
2378 // If this was a definition of a forward reference, remove the definition
2379 // from the forward reference table and fill in the forward ref.
2380 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2381 ForwardRefVals.find(FunctionName);
2382 if (FRVI != ForwardRefVals.end()) {
2383 Fn = M->getFunction(FunctionName);
2384 ForwardRefVals.erase(FRVI);
2385 } else if ((Fn = M->getFunction(FunctionName))) {
2386 // If this function already exists in the symbol table, then it is
2387 // multiply defined. We accept a few cases for old backwards compat.
2388 // FIXME: Remove this stuff for LLVM 3.0.
2389 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2390 (!Fn->isDeclaration() && isDefine)) {
2391 // If the redefinition has different type or different attributes,
2392 // reject it. If both have bodies, reject it.
2393 return Error(NameLoc, "invalid redefinition of function '" +
2394 FunctionName + "'");
2395 } else if (Fn->isDeclaration()) {
2396 // Make sure to strip off any argument names so we can't get conflicts.
2397 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2398 AI != AE; ++AI)
2399 AI->setName("");
2400 }
2401 }
2402
2403 } else if (FunctionName.empty()) {
2404 // If this is a definition of a forward referenced function, make sure the
2405 // types agree.
2406 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2407 = ForwardRefValIDs.find(NumberedVals.size());
2408 if (I != ForwardRefValIDs.end()) {
2409 Fn = cast<Function>(I->second.first);
2410 if (Fn->getType() != PFT)
2411 return Error(NameLoc, "type of definition and forward reference of '@" +
2412 utostr(NumberedVals.size()) +"' disagree");
2413 ForwardRefValIDs.erase(I);
2414 }
2415 }
2416
2417 if (Fn == 0)
2418 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2419 else // Move the forward-reference to the correct spot in the module.
2420 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2421
2422 if (FunctionName.empty())
2423 NumberedVals.push_back(Fn);
2424
2425 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2426 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2427 Fn->setCallingConv(CC);
2428 Fn->setAttributes(PAL);
2429 Fn->setAlignment(Alignment);
2430 Fn->setSection(Section);
2431 if (!GC.empty()) Fn->setGC(GC.c_str());
2432
2433 // Add all of the arguments we parsed to the function.
2434 Function::arg_iterator ArgIt = Fn->arg_begin();
2435 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2436 // If the argument has a name, insert it into the argument symbol table.
2437 if (ArgList[i].Name.empty()) continue;
2438
2439 // Set the name, if it conflicted, it will be auto-renamed.
2440 ArgIt->setName(ArgList[i].Name);
2441
2442 if (ArgIt->getNameStr() != ArgList[i].Name)
2443 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2444 ArgList[i].Name + "'");
2445 }
2446
2447 return false;
2448}
2449
2450
2451/// ParseFunctionBody
2452/// ::= '{' BasicBlock+ '}'
2453/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2454///
2455bool LLParser::ParseFunctionBody(Function &Fn) {
2456 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2457 return TokError("expected '{' in function body");
2458 Lex.Lex(); // eat the {.
2459
2460 PerFunctionState PFS(*this, Fn);
2461
2462 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2463 if (ParseBasicBlock(PFS)) return true;
2464
2465 // Eat the }.
2466 Lex.Lex();
2467
2468 // Verify function is ok.
2469 return PFS.VerifyFunctionComplete();
2470}
2471
2472/// ParseBasicBlock
2473/// ::= LabelStr? Instruction*
2474bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2475 // If this basic block starts out with a name, remember it.
2476 std::string Name;
2477 LocTy NameLoc = Lex.getLoc();
2478 if (Lex.getKind() == lltok::LabelStr) {
2479 Name = Lex.getStrVal();
2480 Lex.Lex();
2481 }
2482
2483 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2484 if (BB == 0) return true;
2485
2486 std::string NameStr;
2487
2488 // Parse the instructions in this block until we get a terminator.
2489 Instruction *Inst;
2490 do {
2491 // This instruction may have three possibilities for a name: a) none
2492 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2493 LocTy NameLoc = Lex.getLoc();
2494 int NameID = -1;
2495 NameStr = "";
2496
2497 if (Lex.getKind() == lltok::LocalVarID) {
2498 NameID = Lex.getUIntVal();
2499 Lex.Lex();
2500 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2501 return true;
2502 } else if (Lex.getKind() == lltok::LocalVar ||
2503 // FIXME: REMOVE IN LLVM 3.0
2504 Lex.getKind() == lltok::StringConstant) {
2505 NameStr = Lex.getStrVal();
2506 Lex.Lex();
2507 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2508 return true;
2509 }
2510
2511 if (ParseInstruction(Inst, BB, PFS)) return true;
2512
2513 BB->getInstList().push_back(Inst);
2514
2515 // Set the name on the instruction.
2516 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2517 } while (!isa<TerminatorInst>(Inst));
2518
2519 return false;
2520}
2521
2522//===----------------------------------------------------------------------===//
2523// Instruction Parsing.
2524//===----------------------------------------------------------------------===//
2525
2526/// ParseInstruction - Parse one of the many different instructions.
2527///
2528bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2529 PerFunctionState &PFS) {
2530 lltok::Kind Token = Lex.getKind();
2531 if (Token == lltok::Eof)
2532 return TokError("found end of file when expecting more instructions");
2533 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002534 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 Lex.Lex(); // Eat the keyword.
2536
2537 switch (Token) {
2538 default: return Error(Loc, "expected instruction opcode");
2539 // Terminator Instructions.
2540 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2541 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2542 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2543 case lltok::kw_br: return ParseBr(Inst, PFS);
2544 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2545 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2546 // Binary Operators.
2547 case lltok::kw_add:
2548 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002549 case lltok::kw_mul:
2550 // API compatibility: Accept either integer or floating-point types.
2551 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2552 case lltok::kw_fadd:
2553 case lltok::kw_fsub:
2554 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2555
Chris Lattnerdf986172009-01-02 07:01:27 +00002556 case lltok::kw_udiv:
2557 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002558 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002559 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002560 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002561 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002562 case lltok::kw_shl:
2563 case lltok::kw_lshr:
2564 case lltok::kw_ashr:
2565 case lltok::kw_and:
2566 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002567 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002568 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002569 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 // Casts.
2571 case lltok::kw_trunc:
2572 case lltok::kw_zext:
2573 case lltok::kw_sext:
2574 case lltok::kw_fptrunc:
2575 case lltok::kw_fpext:
2576 case lltok::kw_bitcast:
2577 case lltok::kw_uitofp:
2578 case lltok::kw_sitofp:
2579 case lltok::kw_fptoui:
2580 case lltok::kw_fptosi:
2581 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002582 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 // Other.
2584 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002585 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2587 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2588 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2589 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2590 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2591 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2592 // Memory.
2593 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002594 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002595 case lltok::kw_free: return ParseFree(Inst, PFS);
2596 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2597 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2598 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002599 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002601 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002603 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002604 return TokError("expected 'load' or 'store'");
Dan Gohman1224c382009-07-20 21:19:07 +00002605 case lltok::kw_signed: {
2606 bool AlsoUnsigned = EatIfPresent(lltok::kw_unsigned);
2607 if (Lex.getKind() == lltok::kw_add ||
2608 Lex.getKind() == lltok::kw_sub ||
2609 Lex.getKind() == lltok::kw_mul) {
2610 Lex.Lex();
2611 KeywordVal = Lex.getUIntVal();
2612 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2613 if (!Result) {
2614 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2615 if (AlsoUnsigned)
2616 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2617 }
2618 return Result;
2619 }
2620 return TokError("expected 'add', 'sub', or 'mul'");
2621 }
2622 case lltok::kw_unsigned: {
2623 bool AlsoSigned = EatIfPresent(lltok::kw_signed);
2624 if (Lex.getKind() == lltok::kw_add ||
2625 Lex.getKind() == lltok::kw_sub ||
2626 Lex.getKind() == lltok::kw_mul) {
2627 Lex.Lex();
2628 KeywordVal = Lex.getUIntVal();
2629 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2630 if (!Result) {
2631 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2632 if (AlsoSigned)
2633 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2634 }
2635 return Result;
2636 }
2637 return TokError("expected 'add', 'sub', or 'mul'");
2638 }
2639 case lltok::kw_exact:
2640 if (Lex.getKind() == lltok::kw_sdiv) {
2641 Lex.Lex();
2642 KeywordVal = Lex.getUIntVal();
2643 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2644 if (!Result)
2645 cast<SDivOperator>(Inst)->setIsExact(true);
2646 return Result;
2647 }
2648 return TokError("expected 'udiv'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002649 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2650 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2651 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2652 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2653 }
2654}
2655
2656/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2657bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002658 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002659 switch (Lex.getKind()) {
2660 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2661 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2662 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2663 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2664 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2665 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2666 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2667 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2668 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2669 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2670 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2671 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2672 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2673 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2674 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2675 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2676 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2677 }
2678 } else {
2679 switch (Lex.getKind()) {
2680 default: TokError("expected icmp predicate (e.g. 'eq')");
2681 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2682 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2683 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2684 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2685 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2686 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2687 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2688 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2689 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2690 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2691 }
2692 }
2693 Lex.Lex();
2694 return false;
2695}
2696
2697//===----------------------------------------------------------------------===//
2698// Terminator Instructions.
2699//===----------------------------------------------------------------------===//
2700
2701/// ParseRet - Parse a return instruction.
2702/// ::= 'ret' void
2703/// ::= 'ret' TypeAndValue
2704/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2705bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2706 PerFunctionState &PFS) {
2707 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002708 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002709
2710 if (Ty == Type::VoidTy) {
2711 Inst = ReturnInst::Create();
2712 return false;
2713 }
2714
2715 Value *RV;
2716 if (ParseValue(Ty, RV, PFS)) return true;
2717
2718 // The normal case is one return value.
2719 if (Lex.getKind() == lltok::comma) {
2720 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2721 // of 'ret {i32,i32} {i32 1, i32 2}'
2722 SmallVector<Value*, 8> RVs;
2723 RVs.push_back(RV);
2724
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002725 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002726 if (ParseTypeAndValue(RV, PFS)) return true;
2727 RVs.push_back(RV);
2728 }
2729
Owen Andersonb43eae72009-07-02 17:04:01 +00002730 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2732 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2733 BB->getInstList().push_back(I);
2734 RV = I;
2735 }
2736 }
2737 Inst = ReturnInst::Create(RV);
2738 return false;
2739}
2740
2741
2742/// ParseBr
2743/// ::= 'br' TypeAndValue
2744/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2745bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2746 LocTy Loc, Loc2;
2747 Value *Op0, *Op1, *Op2;
2748 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2749
2750 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2751 Inst = BranchInst::Create(BB);
2752 return false;
2753 }
2754
2755 if (Op0->getType() != Type::Int1Ty)
2756 return Error(Loc, "branch condition must have 'i1' type");
2757
2758 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2759 ParseTypeAndValue(Op1, Loc, PFS) ||
2760 ParseToken(lltok::comma, "expected ',' after true destination") ||
2761 ParseTypeAndValue(Op2, Loc2, PFS))
2762 return true;
2763
2764 if (!isa<BasicBlock>(Op1))
2765 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 if (!isa<BasicBlock>(Op2))
2767 return Error(Loc2, "true destination of branch must be a basic block");
2768
2769 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2770 return false;
2771}
2772
2773/// ParseSwitch
2774/// Instruction
2775/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2776/// JumpTable
2777/// ::= (TypeAndValue ',' TypeAndValue)*
2778bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2779 LocTy CondLoc, BBLoc;
2780 Value *Cond, *DefaultBB;
2781 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2782 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2783 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2784 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2785 return true;
2786
2787 if (!isa<IntegerType>(Cond->getType()))
2788 return Error(CondLoc, "switch condition must have integer type");
2789 if (!isa<BasicBlock>(DefaultBB))
2790 return Error(BBLoc, "default destination must be a basic block");
2791
2792 // Parse the jump table pairs.
2793 SmallPtrSet<Value*, 32> SeenCases;
2794 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2795 while (Lex.getKind() != lltok::rsquare) {
2796 Value *Constant, *DestBB;
2797
2798 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2799 ParseToken(lltok::comma, "expected ',' after case value") ||
2800 ParseTypeAndValue(DestBB, BBLoc, PFS))
2801 return true;
2802
2803 if (!SeenCases.insert(Constant))
2804 return Error(CondLoc, "duplicate case value in switch");
2805 if (!isa<ConstantInt>(Constant))
2806 return Error(CondLoc, "case value is not a constant integer");
2807 if (!isa<BasicBlock>(DestBB))
2808 return Error(BBLoc, "case destination is not a basic block");
2809
2810 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2811 cast<BasicBlock>(DestBB)));
2812 }
2813
2814 Lex.Lex(); // Eat the ']'.
2815
2816 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2817 Table.size());
2818 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2819 SI->addCase(Table[i].first, Table[i].second);
2820 Inst = SI;
2821 return false;
2822}
2823
2824/// ParseInvoke
2825/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2826/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2827bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2828 LocTy CallLoc = Lex.getLoc();
2829 unsigned CC, RetAttrs, FnAttrs;
2830 PATypeHolder RetType(Type::VoidTy);
2831 LocTy RetTypeLoc;
2832 ValID CalleeID;
2833 SmallVector<ParamInfo, 16> ArgList;
2834
2835 Value *NormalBB, *UnwindBB;
2836 if (ParseOptionalCallingConv(CC) ||
2837 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002838 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002839 ParseValID(CalleeID) ||
2840 ParseParameterList(ArgList, PFS) ||
2841 ParseOptionalAttrs(FnAttrs, 2) ||
2842 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2843 ParseTypeAndValue(NormalBB, PFS) ||
2844 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2845 ParseTypeAndValue(UnwindBB, PFS))
2846 return true;
2847
2848 if (!isa<BasicBlock>(NormalBB))
2849 return Error(CallLoc, "normal destination is not a basic block");
2850 if (!isa<BasicBlock>(UnwindBB))
2851 return Error(CallLoc, "unwind destination is not a basic block");
2852
2853 // If RetType is a non-function pointer type, then this is the short syntax
2854 // for the call, which means that RetType is just the return type. Infer the
2855 // rest of the function argument types from the arguments that are present.
2856 const PointerType *PFTy = 0;
2857 const FunctionType *Ty = 0;
2858 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2859 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2860 // Pull out the types of all of the arguments...
2861 std::vector<const Type*> ParamTypes;
2862 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2863 ParamTypes.push_back(ArgList[i].V->getType());
2864
2865 if (!FunctionType::isValidReturnType(RetType))
2866 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2867
Owen Andersonfba933c2009-07-01 23:57:11 +00002868 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2869 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002870 }
2871
2872 // Look up the callee.
2873 Value *Callee;
2874 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2875
2876 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2877 // function attributes.
2878 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2879 if (FnAttrs & ObsoleteFuncAttrs) {
2880 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2881 FnAttrs &= ~ObsoleteFuncAttrs;
2882 }
2883
2884 // Set up the Attributes for the function.
2885 SmallVector<AttributeWithIndex, 8> Attrs;
2886 if (RetAttrs != Attribute::None)
2887 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2888
2889 SmallVector<Value*, 8> Args;
2890
2891 // Loop through FunctionType's arguments and ensure they are specified
2892 // correctly. Also, gather any parameter attributes.
2893 FunctionType::param_iterator I = Ty->param_begin();
2894 FunctionType::param_iterator E = Ty->param_end();
2895 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2896 const Type *ExpectedTy = 0;
2897 if (I != E) {
2898 ExpectedTy = *I++;
2899 } else if (!Ty->isVarArg()) {
2900 return Error(ArgList[i].Loc, "too many arguments specified");
2901 }
2902
2903 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2904 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2905 ExpectedTy->getDescription() + "'");
2906 Args.push_back(ArgList[i].V);
2907 if (ArgList[i].Attrs != Attribute::None)
2908 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2909 }
2910
2911 if (I != E)
2912 return Error(CallLoc, "not enough parameters specified for call");
2913
2914 if (FnAttrs != Attribute::None)
2915 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2916
2917 // Finish off the Attributes and check them
2918 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2919
2920 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2921 cast<BasicBlock>(UnwindBB),
2922 Args.begin(), Args.end());
2923 II->setCallingConv(CC);
2924 II->setAttributes(PAL);
2925 Inst = II;
2926 return false;
2927}
2928
2929
2930
2931//===----------------------------------------------------------------------===//
2932// Binary Operators.
2933//===----------------------------------------------------------------------===//
2934
2935/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002936/// ::= ArithmeticOps TypeAndValue ',' Value
2937///
2938/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2939/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002940bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002941 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 LocTy Loc; Value *LHS, *RHS;
2943 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2944 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2945 ParseValue(LHS->getType(), RHS, PFS))
2946 return true;
2947
Chris Lattnere914b592009-01-05 08:24:46 +00002948 bool Valid;
2949 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002950 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00002951 case 0: // int or FP.
2952 Valid = LHS->getType()->isIntOrIntVector() ||
2953 LHS->getType()->isFPOrFPVector();
2954 break;
2955 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2956 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2957 }
2958
2959 if (!Valid)
2960 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002961
2962 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2963 return false;
2964}
2965
2966/// ParseLogical
2967/// ::= ArithmeticOps TypeAndValue ',' Value {
2968bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2969 unsigned Opc) {
2970 LocTy Loc; Value *LHS, *RHS;
2971 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2972 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2973 ParseValue(LHS->getType(), RHS, PFS))
2974 return true;
2975
2976 if (!LHS->getType()->isIntOrIntVector())
2977 return Error(Loc,"instruction requires integer or integer vector operands");
2978
2979 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2980 return false;
2981}
2982
2983
2984/// ParseCompare
2985/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2986/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00002987bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2988 unsigned Opc) {
2989 // Parse the integer/fp comparison predicate.
2990 LocTy Loc;
2991 unsigned Pred;
2992 Value *LHS, *RHS;
2993 if (ParseCmpPredicate(Pred, Opc) ||
2994 ParseTypeAndValue(LHS, Loc, PFS) ||
2995 ParseToken(lltok::comma, "expected ',' after compare value") ||
2996 ParseValue(LHS->getType(), RHS, PFS))
2997 return true;
2998
2999 if (Opc == Instruction::FCmp) {
3000 if (!LHS->getType()->isFPOrFPVector())
3001 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003002 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003003 } else {
3004 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003005 if (!LHS->getType()->isIntOrIntVector() &&
3006 !isa<PointerType>(LHS->getType()))
3007 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003008 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003009 }
3010 return false;
3011}
3012
3013//===----------------------------------------------------------------------===//
3014// Other Instructions.
3015//===----------------------------------------------------------------------===//
3016
3017
3018/// ParseCast
3019/// ::= CastOpc TypeAndValue 'to' Type
3020bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3021 unsigned Opc) {
3022 LocTy Loc; Value *Op;
3023 PATypeHolder DestTy(Type::VoidTy);
3024 if (ParseTypeAndValue(Op, Loc, PFS) ||
3025 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3026 ParseType(DestTy))
3027 return true;
3028
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003029 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3030 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003031 return Error(Loc, "invalid cast opcode for cast from '" +
3032 Op->getType()->getDescription() + "' to '" +
3033 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003034 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3036 return false;
3037}
3038
3039/// ParseSelect
3040/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3041bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3042 LocTy Loc;
3043 Value *Op0, *Op1, *Op2;
3044 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3045 ParseToken(lltok::comma, "expected ',' after select condition") ||
3046 ParseTypeAndValue(Op1, PFS) ||
3047 ParseToken(lltok::comma, "expected ',' after select value") ||
3048 ParseTypeAndValue(Op2, PFS))
3049 return true;
3050
3051 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3052 return Error(Loc, Reason);
3053
3054 Inst = SelectInst::Create(Op0, Op1, Op2);
3055 return false;
3056}
3057
Chris Lattner0088a5c2009-01-05 08:18:44 +00003058/// ParseVA_Arg
3059/// ::= 'va_arg' TypeAndValue ',' Type
3060bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 Value *Op;
3062 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003063 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003064 if (ParseTypeAndValue(Op, PFS) ||
3065 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003066 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003068
3069 if (!EltTy->isFirstClassType())
3070 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003071
3072 Inst = new VAArgInst(Op, EltTy);
3073 return false;
3074}
3075
3076/// ParseExtractElement
3077/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3078bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3079 LocTy Loc;
3080 Value *Op0, *Op1;
3081 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3082 ParseToken(lltok::comma, "expected ',' after extract value") ||
3083 ParseTypeAndValue(Op1, PFS))
3084 return true;
3085
3086 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3087 return Error(Loc, "invalid extractelement operands");
3088
3089 Inst = new ExtractElementInst(Op0, Op1);
3090 return false;
3091}
3092
3093/// ParseInsertElement
3094/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3095bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3096 LocTy Loc;
3097 Value *Op0, *Op1, *Op2;
3098 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3099 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3100 ParseTypeAndValue(Op1, PFS) ||
3101 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3102 ParseTypeAndValue(Op2, PFS))
3103 return true;
3104
3105 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3106 return Error(Loc, "invalid extractelement operands");
3107
3108 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3109 return false;
3110}
3111
3112/// ParseShuffleVector
3113/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3114bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3115 LocTy Loc;
3116 Value *Op0, *Op1, *Op2;
3117 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3118 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3119 ParseTypeAndValue(Op1, PFS) ||
3120 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3121 ParseTypeAndValue(Op2, PFS))
3122 return true;
3123
3124 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3125 return Error(Loc, "invalid extractelement operands");
3126
3127 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3128 return false;
3129}
3130
3131/// ParsePHI
3132/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3133bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3134 PATypeHolder Ty(Type::VoidTy);
3135 Value *Op0, *Op1;
3136 LocTy TypeLoc = Lex.getLoc();
3137
3138 if (ParseType(Ty) ||
3139 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3140 ParseValue(Ty, Op0, PFS) ||
3141 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3142 ParseValue(Type::LabelTy, Op1, PFS) ||
3143 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3144 return true;
3145
3146 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3147 while (1) {
3148 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3149
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003150 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 break;
3152
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003153 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003154 ParseValue(Ty, Op0, PFS) ||
3155 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3156 ParseValue(Type::LabelTy, Op1, PFS) ||
3157 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3158 return true;
3159 }
3160
3161 if (!Ty->isFirstClassType())
3162 return Error(TypeLoc, "phi node must have first class type");
3163
3164 PHINode *PN = PHINode::Create(Ty);
3165 PN->reserveOperandSpace(PHIVals.size());
3166 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3167 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3168 Inst = PN;
3169 return false;
3170}
3171
3172/// ParseCall
3173/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3174/// ParameterList OptionalAttrs
3175bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3176 bool isTail) {
3177 unsigned CC, RetAttrs, FnAttrs;
3178 PATypeHolder RetType(Type::VoidTy);
3179 LocTy RetTypeLoc;
3180 ValID CalleeID;
3181 SmallVector<ParamInfo, 16> ArgList;
3182 LocTy CallLoc = Lex.getLoc();
3183
3184 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3185 ParseOptionalCallingConv(CC) ||
3186 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003187 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003188 ParseValID(CalleeID) ||
3189 ParseParameterList(ArgList, PFS) ||
3190 ParseOptionalAttrs(FnAttrs, 2))
3191 return true;
3192
3193 // If RetType is a non-function pointer type, then this is the short syntax
3194 // for the call, which means that RetType is just the return type. Infer the
3195 // rest of the function argument types from the arguments that are present.
3196 const PointerType *PFTy = 0;
3197 const FunctionType *Ty = 0;
3198 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3199 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3200 // Pull out the types of all of the arguments...
3201 std::vector<const Type*> ParamTypes;
3202 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3203 ParamTypes.push_back(ArgList[i].V->getType());
3204
3205 if (!FunctionType::isValidReturnType(RetType))
3206 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3207
Owen Andersonfba933c2009-07-01 23:57:11 +00003208 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3209 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 }
3211
3212 // Look up the callee.
3213 Value *Callee;
3214 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3215
Chris Lattnerdf986172009-01-02 07:01:27 +00003216 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3217 // function attributes.
3218 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3219 if (FnAttrs & ObsoleteFuncAttrs) {
3220 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3221 FnAttrs &= ~ObsoleteFuncAttrs;
3222 }
3223
3224 // Set up the Attributes for the function.
3225 SmallVector<AttributeWithIndex, 8> Attrs;
3226 if (RetAttrs != Attribute::None)
3227 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3228
3229 SmallVector<Value*, 8> Args;
3230
3231 // Loop through FunctionType's arguments and ensure they are specified
3232 // correctly. Also, gather any parameter attributes.
3233 FunctionType::param_iterator I = Ty->param_begin();
3234 FunctionType::param_iterator E = Ty->param_end();
3235 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3236 const Type *ExpectedTy = 0;
3237 if (I != E) {
3238 ExpectedTy = *I++;
3239 } else if (!Ty->isVarArg()) {
3240 return Error(ArgList[i].Loc, "too many arguments specified");
3241 }
3242
3243 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3244 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3245 ExpectedTy->getDescription() + "'");
3246 Args.push_back(ArgList[i].V);
3247 if (ArgList[i].Attrs != Attribute::None)
3248 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3249 }
3250
3251 if (I != E)
3252 return Error(CallLoc, "not enough parameters specified for call");
3253
3254 if (FnAttrs != Attribute::None)
3255 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3256
3257 // Finish off the Attributes and check them
3258 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3259
3260 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3261 CI->setTailCall(isTail);
3262 CI->setCallingConv(CC);
3263 CI->setAttributes(PAL);
3264 Inst = CI;
3265 return false;
3266}
3267
3268//===----------------------------------------------------------------------===//
3269// Memory Instructions.
3270//===----------------------------------------------------------------------===//
3271
3272/// ParseAlloc
3273/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3274/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3275bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3276 unsigned Opc) {
3277 PATypeHolder Ty(Type::VoidTy);
3278 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003279 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003280 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003281 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003282
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003283 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003284 if (Lex.getKind() == lltok::kw_align) {
3285 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003286 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3287 ParseOptionalCommaAlignment(Alignment)) {
3288 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003289 }
3290 }
3291
3292 if (Size && Size->getType() != Type::Int32Ty)
3293 return Error(SizeLoc, "element count must be i32");
3294
3295 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003296 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003297 else
Owen Anderson50dead02009-07-15 23:53:25 +00003298 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003299 return false;
3300}
3301
3302/// ParseFree
3303/// ::= 'free' TypeAndValue
3304bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3305 Value *Val; LocTy Loc;
3306 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3307 if (!isa<PointerType>(Val->getType()))
3308 return Error(Loc, "operand to free must be a pointer");
3309 Inst = new FreeInst(Val);
3310 return false;
3311}
3312
3313/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003314/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003315bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3316 bool isVolatile) {
3317 Value *Val; LocTy Loc;
3318 unsigned Alignment;
3319 if (ParseTypeAndValue(Val, Loc, PFS) ||
3320 ParseOptionalCommaAlignment(Alignment))
3321 return true;
3322
3323 if (!isa<PointerType>(Val->getType()) ||
3324 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3325 return Error(Loc, "load operand must be a pointer to a first class type");
3326
3327 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3328 return false;
3329}
3330
3331/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003332/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003333bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3334 bool isVolatile) {
3335 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3336 unsigned Alignment;
3337 if (ParseTypeAndValue(Val, Loc, PFS) ||
3338 ParseToken(lltok::comma, "expected ',' after store operand") ||
3339 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3340 ParseOptionalCommaAlignment(Alignment))
3341 return true;
3342
3343 if (!isa<PointerType>(Ptr->getType()))
3344 return Error(PtrLoc, "store operand must be a pointer");
3345 if (!Val->getType()->isFirstClassType())
3346 return Error(Loc, "store operand must be a first class value");
3347 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3348 return Error(Loc, "stored value and pointer type do not match");
3349
3350 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3351 return false;
3352}
3353
3354/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003355/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003356/// FIXME: Remove support for getresult in LLVM 3.0
3357bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3358 Value *Val; LocTy ValLoc, EltLoc;
3359 unsigned Element;
3360 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3361 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003362 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003363 return true;
3364
3365 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3366 return Error(ValLoc, "getresult inst requires an aggregate operand");
3367 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3368 return Error(EltLoc, "invalid getresult index for value");
3369 Inst = ExtractValueInst::Create(Val, Element);
3370 return false;
3371}
3372
3373/// ParseGetElementPtr
3374/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3375bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3376 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003377 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003378
3379 if (!isa<PointerType>(Ptr->getType()))
3380 return Error(Loc, "base of getelementptr must be a pointer");
3381
3382 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003383 while (EatIfPresent(lltok::comma)) {
3384 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 if (!isa<IntegerType>(Val->getType()))
3386 return Error(EltLoc, "getelementptr index must be an integer");
3387 Indices.push_back(Val);
3388 }
3389
3390 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3391 Indices.begin(), Indices.end()))
3392 return Error(Loc, "invalid getelementptr indices");
3393 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3394 return false;
3395}
3396
3397/// ParseExtractValue
3398/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3399bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3400 Value *Val; LocTy Loc;
3401 SmallVector<unsigned, 4> Indices;
3402 if (ParseTypeAndValue(Val, Loc, PFS) ||
3403 ParseIndexList(Indices))
3404 return true;
3405
3406 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3407 return Error(Loc, "extractvalue operand must be array or struct");
3408
3409 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3410 Indices.end()))
3411 return Error(Loc, "invalid indices for extractvalue");
3412 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3413 return false;
3414}
3415
3416/// ParseInsertValue
3417/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3418bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3419 Value *Val0, *Val1; LocTy Loc0, Loc1;
3420 SmallVector<unsigned, 4> Indices;
3421 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3422 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3423 ParseTypeAndValue(Val1, Loc1, PFS) ||
3424 ParseIndexList(Indices))
3425 return true;
3426
3427 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3428 return Error(Loc0, "extractvalue operand must be array or struct");
3429
3430 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3431 Indices.end()))
3432 return Error(Loc0, "invalid indices for insertvalue");
3433 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3434 return false;
3435}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003436
3437//===----------------------------------------------------------------------===//
3438// Embedded metadata.
3439//===----------------------------------------------------------------------===//
3440
3441/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003442/// ::= Element (',' Element)*
3443/// Element
3444/// ::= 'null' | TypeAndValue
3445bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003446 assert(Lex.getKind() == lltok::lbrace);
3447 Lex.Lex();
3448 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003449 Value *V;
3450 if (Lex.getKind() == lltok::kw_null) {
3451 Lex.Lex();
3452 V = 0;
3453 } else {
3454 Constant *C;
3455 if (ParseGlobalTypeAndValue(C)) return true;
3456 V = C;
3457 }
3458 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003459 } while (EatIfPresent(lltok::comma));
3460
3461 return false;
3462}