blob: 3927cf1e9e98792bba061e4ed6e3d48ad675d2f7 [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"
24#include "llvm/ValueSymbolTable.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattnerdf986172009-01-02 07:01:27 +000030namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000031 /// ValID - Represents a reference of a definition of some sort with no type.
32 /// There are several cases where we have to parse the value but where the
33 /// type can depend on later context. This may either be a numeric reference
34 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000035 struct ValID {
36 enum {
37 t_LocalID, t_GlobalID, // ID in UIntVal.
38 t_LocalName, t_GlobalName, // Name in StrVal.
39 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
40 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000041 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000042 t_Constant, // Value in ConstantVal.
43 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
44 } Kind;
45
46 LLParser::LocTy Loc;
47 unsigned UIntVal;
48 std::string StrVal, StrVal2;
49 APSInt APSIntVal;
50 APFloat APFloatVal;
51 Constant *ConstantVal;
52 ValID() : APFloatVal(0.0) {}
53 };
54}
55
Chris Lattner3ed88ef2009-01-02 08:05:26 +000056/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000057bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000058 // Prime the lexer.
59 Lex.Lex();
60
Chris Lattnerad7d1e22009-01-04 20:44:11 +000061 return ParseTopLevelEntities() ||
62 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000063}
64
65/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
66/// module.
67bool LLParser::ValidateEndOfModule() {
68 if (!ForwardRefTypes.empty())
69 return Error(ForwardRefTypes.begin()->second.second,
70 "use of undefined type named '" +
71 ForwardRefTypes.begin()->first + "'");
72 if (!ForwardRefTypeIDs.empty())
73 return Error(ForwardRefTypeIDs.begin()->second.second,
74 "use of undefined type '%" +
75 utostr(ForwardRefTypeIDs.begin()->first) + "'");
76
77 if (!ForwardRefVals.empty())
78 return Error(ForwardRefVals.begin()->second.second,
79 "use of undefined value '@" + ForwardRefVals.begin()->first +
80 "'");
81
82 if (!ForwardRefValIDs.empty())
83 return Error(ForwardRefValIDs.begin()->second.second,
84 "use of undefined value '@" +
85 utostr(ForwardRefValIDs.begin()->first) + "'");
86
87 // Look for intrinsic functions and CallInst that need to be upgraded
88 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
89 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
90
91 return false;
92}
93
94//===----------------------------------------------------------------------===//
95// Top-Level Entities
96//===----------------------------------------------------------------------===//
97
98bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000099 while (1) {
100 switch (Lex.getKind()) {
101 default: return TokError("expected top-level entity");
102 case lltok::Eof: return false;
103 //case lltok::kw_define:
104 case lltok::kw_declare: if (ParseDeclare()) return true; break;
105 case lltok::kw_define: if (ParseDefine()) return true; break;
106 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
107 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
108 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
109 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
110 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
111 case lltok::LocalVar: if (ParseNamedType()) return true; break;
112 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000113 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000114
115 // The Global variable production with no name can have many different
116 // optional leading prefixes, the production is:
117 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
118 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000119 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 case lltok::kw_internal: // OptionalLinkage
121 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000122 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000124 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000125 case lltok::kw_appending: // OptionalLinkage
126 case lltok::kw_dllexport: // OptionalLinkage
127 case lltok::kw_common: // OptionalLinkage
128 case lltok::kw_dllimport: // OptionalLinkage
129 case lltok::kw_extern_weak: // OptionalLinkage
130 case lltok::kw_external: { // OptionalLinkage
131 unsigned Linkage, Visibility;
132 if (ParseOptionalLinkage(Linkage) ||
133 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000134 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000135 return true;
136 break;
137 }
138 case lltok::kw_default: // OptionalVisibility
139 case lltok::kw_hidden: // OptionalVisibility
140 case lltok::kw_protected: { // OptionalVisibility
141 unsigned Visibility;
142 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000143 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000144 return true;
145 break;
146 }
147
148 case lltok::kw_thread_local: // OptionalThreadLocal
149 case lltok::kw_addrspace: // OptionalAddrSpace
150 case lltok::kw_constant: // GlobalType
151 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000152 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000153 break;
154 }
155 }
156}
157
158
159/// toplevelentity
160/// ::= 'module' 'asm' STRINGCONSTANT
161bool LLParser::ParseModuleAsm() {
162 assert(Lex.getKind() == lltok::kw_module);
163 Lex.Lex();
164
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000165 std::string AsmStr;
166 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
167 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000168
169 const std::string &AsmSoFar = M->getModuleInlineAsm();
170 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000171 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000172 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000173 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000174 return false;
175}
176
177/// toplevelentity
178/// ::= 'target' 'triple' '=' STRINGCONSTANT
179/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
180bool LLParser::ParseTargetDefinition() {
181 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000182 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000183 switch (Lex.Lex()) {
184 default: return TokError("unknown target property");
185 case lltok::kw_triple:
186 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
188 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000189 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000190 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 return false;
192 case lltok::kw_datalayout:
193 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000194 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
195 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000196 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000197 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 return false;
199 }
200}
201
202/// toplevelentity
203/// ::= 'deplibs' '=' '[' ']'
204/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
205bool LLParser::ParseDepLibs() {
206 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000208 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
209 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
210 return true;
211
212 if (EatIfPresent(lltok::rsquare))
213 return false;
214
215 std::string Str;
216 if (ParseStringConstant(Str)) return true;
217 M->addLibrary(Str);
218
219 while (EatIfPresent(lltok::comma)) {
220 if (ParseStringConstant(Str)) return true;
221 M->addLibrary(Str);
222 }
223
224 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000225}
226
227/// toplevelentity
228/// ::= 'type' type
229bool LLParser::ParseUnnamedType() {
230 assert(Lex.getKind() == lltok::kw_type);
231 LocTy TypeLoc = Lex.getLoc();
232 Lex.Lex(); // eat kw_type
233
234 PATypeHolder Ty(Type::VoidTy);
235 if (ParseType(Ty)) return true;
236
237 unsigned TypeID = NumberedTypes.size();
238
Chris Lattnerdf986172009-01-02 07:01:27 +0000239 // See if this type was previously referenced.
240 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
241 FI = ForwardRefTypeIDs.find(TypeID);
242 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000243 if (FI->second.first.get() == Ty)
244 return Error(TypeLoc, "self referential type is invalid");
245
Chris Lattnerdf986172009-01-02 07:01:27 +0000246 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
247 Ty = FI->second.first.get();
248 ForwardRefTypeIDs.erase(FI);
249 }
250
251 NumberedTypes.push_back(Ty);
252
253 return false;
254}
255
256/// toplevelentity
257/// ::= LocalVar '=' 'type' type
258bool LLParser::ParseNamedType() {
259 std::string Name = Lex.getStrVal();
260 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000262
263 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000264
265 if (ParseToken(lltok::equal, "expected '=' after name") ||
266 ParseToken(lltok::kw_type, "expected 'type' after name") ||
267 ParseType(Ty))
268 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000269
Chris Lattnerdf986172009-01-02 07:01:27 +0000270 // Set the type name, checking for conflicts as we do so.
271 bool AlreadyExists = M->addTypeName(Name, Ty);
272 if (!AlreadyExists) return false;
273
274 // See if this type is a forward reference. We need to eagerly resolve
275 // types to allow recursive type redefinitions below.
276 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
277 FI = ForwardRefTypes.find(Name);
278 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000279 if (FI->second.first.get() == Ty)
280 return Error(NameLoc, "self referential type is invalid");
281
Chris Lattnerdf986172009-01-02 07:01:27 +0000282 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
283 Ty = FI->second.first.get();
284 ForwardRefTypes.erase(FI);
285 }
286
287 // Inserting a name that is already defined, get the existing name.
288 const Type *Existing = M->getTypeByName(Name);
289 assert(Existing && "Conflict but no matching type?!");
290
291 // Otherwise, this is an attempt to redefine a type. That's okay if
292 // the redefinition is identical to the original.
293 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
294 if (Existing == Ty) return false;
295
296 // Any other kind of (non-equivalent) redefinition is an error.
297 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
298 Ty->getDescription() + "'");
299}
300
301
302/// toplevelentity
303/// ::= 'declare' FunctionHeader
304bool LLParser::ParseDeclare() {
305 assert(Lex.getKind() == lltok::kw_declare);
306 Lex.Lex();
307
308 Function *F;
309 return ParseFunctionHeader(F, false);
310}
311
312/// toplevelentity
313/// ::= 'define' FunctionHeader '{' ...
314bool LLParser::ParseDefine() {
315 assert(Lex.getKind() == lltok::kw_define);
316 Lex.Lex();
317
318 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000319 return ParseFunctionHeader(F, true) ||
320 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000321}
322
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000323/// ParseGlobalType
324/// ::= 'constant'
325/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000326bool LLParser::ParseGlobalType(bool &IsConstant) {
327 if (Lex.getKind() == lltok::kw_constant)
328 IsConstant = true;
329 else if (Lex.getKind() == lltok::kw_global)
330 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000331 else {
332 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000334 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000335 Lex.Lex();
336 return false;
337}
338
339/// ParseNamedGlobal:
340/// GlobalVar '=' OptionalVisibility ALIAS ...
341/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
346 Lex.Lex();
347
348 bool HasLinkage;
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
353 return true;
354
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
358}
359
Devang Patel923078c2009-07-01 19:21:12 +0000360/// ParseStandaloneMetadata:
361/// !42 = !{...}
362bool LLParser::ParseStandaloneMetadata() {
363 assert(Lex.getKind() == lltok::Metadata);
364 Lex.Lex();
365 unsigned MetadataID = 0;
366 if (ParseUInt32(MetadataID))
367 return true;
368 if (MetadataCache.find(MetadataID) != MetadataCache.end())
369 return TokError("Metadata id is already used");
370 if (ParseToken(lltok::equal, "expected '=' here"))
371 return true;
372
373 LocTy TyLoc;
374 bool IsConstant;
375 PATypeHolder Ty(Type::VoidTy);
376 if (ParseGlobalType(IsConstant) ||
377 ParseType(Ty, TyLoc))
378 return true;
379
380 Constant *Init = 0;
381 if (ParseGlobalValue(Ty, Init))
382 return true;
383
384 MetadataCache[MetadataID] = Init;
385 return false;
386}
387
Chris Lattnerdf986172009-01-02 07:01:27 +0000388/// ParseAlias:
389/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
390/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000391/// ::= TypeAndValue
392/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
393/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000394///
395/// Everything through visibility has already been parsed.
396///
397bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
398 unsigned Visibility) {
399 assert(Lex.getKind() == lltok::kw_alias);
400 Lex.Lex();
401 unsigned Linkage;
402 LocTy LinkageLoc = Lex.getLoc();
403 if (ParseOptionalLinkage(Linkage))
404 return true;
405
406 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000407 Linkage != GlobalValue::WeakAnyLinkage &&
408 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000409 Linkage != GlobalValue::InternalLinkage &&
410 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 return Error(LinkageLoc, "invalid linkage type for alias");
412
413 Constant *Aliasee;
414 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000415 if (Lex.getKind() != lltok::kw_bitcast &&
416 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000417 if (ParseGlobalTypeAndValue(Aliasee)) return true;
418 } else {
419 // The bitcast dest type is not present, it is implied by the dest type.
420 ValID ID;
421 if (ParseValID(ID)) return true;
422 if (ID.Kind != ValID::t_Constant)
423 return Error(AliaseeLoc, "invalid aliasee");
424 Aliasee = ID.ConstantVal;
425 }
426
427 if (!isa<PointerType>(Aliasee->getType()))
428 return Error(AliaseeLoc, "alias must have pointer type");
429
430 // Okay, create the alias but do not insert it into the module yet.
431 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
432 (GlobalValue::LinkageTypes)Linkage, Name,
433 Aliasee);
434 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
435
436 // See if this value already exists in the symbol table. If so, it is either
437 // a redefinition or a definition of a forward reference.
438 if (GlobalValue *Val =
439 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
440 // See if this was a redefinition. If so, there is no entry in
441 // ForwardRefVals.
442 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
443 I = ForwardRefVals.find(Name);
444 if (I == ForwardRefVals.end())
445 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
446
447 // Otherwise, this was a definition of forward ref. Verify that types
448 // agree.
449 if (Val->getType() != GA->getType())
450 return Error(NameLoc,
451 "forward reference and definition of alias have different types");
452
453 // If they agree, just RAUW the old value with the alias and remove the
454 // forward ref info.
455 Val->replaceAllUsesWith(GA);
456 Val->eraseFromParent();
457 ForwardRefVals.erase(I);
458 }
459
460 // Insert into the module, we know its name won't collide now.
461 M->getAliasList().push_back(GA);
462 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
463
464 return false;
465}
466
467/// ParseGlobal
468/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
469/// OptionalAddrSpace GlobalType Type Const
470/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
471/// OptionalAddrSpace GlobalType Type Const
472///
473/// Everything through visibility has been parsed already.
474///
475bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
476 unsigned Linkage, bool HasLinkage,
477 unsigned Visibility) {
478 unsigned AddrSpace;
479 bool ThreadLocal, IsConstant;
480 LocTy TyLoc;
481
482 PATypeHolder Ty(Type::VoidTy);
483 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
484 ParseOptionalAddrSpace(AddrSpace) ||
485 ParseGlobalType(IsConstant) ||
486 ParseType(Ty, TyLoc))
487 return true;
488
489 // If the linkage is specified and is external, then no initializer is
490 // present.
491 Constant *Init = 0;
492 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000493 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000494 Linkage != GlobalValue::ExternalLinkage)) {
495 if (ParseGlobalValue(Ty, Init))
496 return true;
497 }
498
Chris Lattnera9a9e072009-03-09 04:49:14 +0000499 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000500 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000501
502 GlobalVariable *GV = 0;
503
504 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000505 if (!Name.empty()) {
506 if ((GV = M->getGlobalVariable(Name, true)) &&
507 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000508 return Error(NameLoc, "redefinition of global '@" + Name + "'");
509 } else {
510 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
511 I = ForwardRefValIDs.find(NumberedVals.size());
512 if (I != ForwardRefValIDs.end()) {
513 GV = cast<GlobalVariable>(I->second.first);
514 ForwardRefValIDs.erase(I);
515 }
516 }
517
518 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000519 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
520 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000521 } else {
522 if (GV->getType()->getElementType() != Ty)
523 return Error(TyLoc,
524 "forward reference and definition of global have different types");
525
526 // Move the forward-reference to the correct spot in the module.
527 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
528 }
529
530 if (Name.empty())
531 NumberedVals.push_back(GV);
532
533 // Set the parsed properties on the global.
534 if (Init)
535 GV->setInitializer(Init);
536 GV->setConstant(IsConstant);
537 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
538 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
539 GV->setThreadLocal(ThreadLocal);
540
541 // Parse attributes on the global.
542 while (Lex.getKind() == lltok::comma) {
543 Lex.Lex();
544
545 if (Lex.getKind() == lltok::kw_section) {
546 Lex.Lex();
547 GV->setSection(Lex.getStrVal());
548 if (ParseToken(lltok::StringConstant, "expected global section string"))
549 return true;
550 } else if (Lex.getKind() == lltok::kw_align) {
551 unsigned Alignment;
552 if (ParseOptionalAlignment(Alignment)) return true;
553 GV->setAlignment(Alignment);
554 } else {
555 TokError("unknown global variable property!");
556 }
557 }
558
559 return false;
560}
561
562
563//===----------------------------------------------------------------------===//
564// GlobalValue Reference/Resolution Routines.
565//===----------------------------------------------------------------------===//
566
567/// GetGlobalVal - Get a value with the specified name or ID, creating a
568/// forward reference record if needed. This can return null if the value
569/// exists but does not have the right type.
570GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
571 LocTy Loc) {
572 const PointerType *PTy = dyn_cast<PointerType>(Ty);
573 if (PTy == 0) {
574 Error(Loc, "global variable reference must have pointer type");
575 return 0;
576 }
577
578 // Look this name up in the normal function symbol table.
579 GlobalValue *Val =
580 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
581
582 // If this is a forward reference for the value, see if we already created a
583 // forward ref record.
584 if (Val == 0) {
585 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
586 I = ForwardRefVals.find(Name);
587 if (I != ForwardRefVals.end())
588 Val = I->second.first;
589 }
590
591 // If we have the value in the symbol table or fwd-ref table, return it.
592 if (Val) {
593 if (Val->getType() == Ty) return Val;
594 Error(Loc, "'@" + Name + "' defined with type '" +
595 Val->getType()->getDescription() + "'");
596 return 0;
597 }
598
599 // Otherwise, create a new forward reference for this value and remember it.
600 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000601 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
602 // Function types can return opaque but functions can't.
603 if (isa<OpaqueType>(FT->getReturnType())) {
604 Error(Loc, "function may not return opaque type");
605 return 0;
606 }
607
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000608 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000609 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000610 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
611 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000612 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000613
614 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
615 return FwdVal;
616}
617
618GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
619 const PointerType *PTy = dyn_cast<PointerType>(Ty);
620 if (PTy == 0) {
621 Error(Loc, "global variable reference must have pointer type");
622 return 0;
623 }
624
625 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
626
627 // If this is a forward reference for the value, see if we already created a
628 // forward ref record.
629 if (Val == 0) {
630 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
631 I = ForwardRefValIDs.find(ID);
632 if (I != ForwardRefValIDs.end())
633 Val = I->second.first;
634 }
635
636 // If we have the value in the symbol table or fwd-ref table, return it.
637 if (Val) {
638 if (Val->getType() == Ty) return Val;
639 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
640 Val->getType()->getDescription() + "'");
641 return 0;
642 }
643
644 // Otherwise, create a new forward reference for this value and remember it.
645 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000646 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
647 // Function types can return opaque but functions can't.
648 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000649 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000650 return 0;
651 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000652 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000653 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000654 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
655 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000656 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000657
658 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
659 return FwdVal;
660}
661
662
663//===----------------------------------------------------------------------===//
664// Helper Routines.
665//===----------------------------------------------------------------------===//
666
667/// ParseToken - If the current token has the specified kind, eat it and return
668/// success. Otherwise, emit the specified error and return failure.
669bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
670 if (Lex.getKind() != T)
671 return TokError(ErrMsg);
672 Lex.Lex();
673 return false;
674}
675
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000676/// ParseStringConstant
677/// ::= StringConstant
678bool LLParser::ParseStringConstant(std::string &Result) {
679 if (Lex.getKind() != lltok::StringConstant)
680 return TokError("expected string constant");
681 Result = Lex.getStrVal();
682 Lex.Lex();
683 return false;
684}
685
686/// ParseUInt32
687/// ::= uint32
688bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000689 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
690 return TokError("expected integer");
691 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
692 if (Val64 != unsigned(Val64))
693 return TokError("expected 32-bit integer (too large)");
694 Val = Val64;
695 Lex.Lex();
696 return false;
697}
698
699
700/// ParseOptionalAddrSpace
701/// := /*empty*/
702/// := 'addrspace' '(' uint32 ')'
703bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
704 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000705 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000707 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000708 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 ParseToken(lltok::rparen, "expected ')' in address space");
710}
711
712/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
713/// indicates what kind of attribute list this is: 0: function arg, 1: result,
714/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000715/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000716bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
717 Attrs = Attribute::None;
718 LocTy AttrLoc = Lex.getLoc();
719
720 while (1) {
721 switch (Lex.getKind()) {
722 case lltok::kw_sext:
723 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000724 // Treat these as signext/zeroext if they occur in the argument list after
725 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
726 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
727 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000728 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000729 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000730 if (Lex.getKind() == lltok::kw_sext)
731 Attrs |= Attribute::SExt;
732 else
733 Attrs |= Attribute::ZExt;
734 break;
735 }
736 // FALL THROUGH.
737 default: // End of attributes.
738 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
739 return Error(AttrLoc, "invalid use of function-only attribute");
740
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000741 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000742 return Error(AttrLoc, "invalid use of parameter-only attribute");
743
744 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000745 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
746 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
747 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
748 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
749 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
750 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
751 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
752 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000753
Devang Patel578efa92009-06-05 21:57:13 +0000754 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
755 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
756 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
757 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
758 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
759 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
760 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
761 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
762 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
763 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
764 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000765
766 case lltok::kw_align: {
767 unsigned Alignment;
768 if (ParseOptionalAlignment(Alignment))
769 return true;
770 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
771 continue;
772 }
773 }
774 Lex.Lex();
775 }
776}
777
778/// ParseOptionalLinkage
779/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000780/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000781/// ::= 'internal'
782/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000783/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000784/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000785/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000786/// ::= 'appending'
787/// ::= 'dllexport'
788/// ::= 'common'
789/// ::= 'dllimport'
790/// ::= 'extern_weak'
791/// ::= 'external'
792bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
793 HasLinkage = false;
794 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000795 default: Res = GlobalValue::ExternalLinkage; return false;
796 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
797 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
798 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
799 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
800 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
801 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000802 case lltok::kw_available_externally:
803 Res = GlobalValue::AvailableExternallyLinkage;
804 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000805 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
806 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000807 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000808 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000809 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000810 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000811 }
812 Lex.Lex();
813 HasLinkage = true;
814 return false;
815}
816
817/// ParseOptionalVisibility
818/// ::= /*empty*/
819/// ::= 'default'
820/// ::= 'hidden'
821/// ::= 'protected'
822///
823bool LLParser::ParseOptionalVisibility(unsigned &Res) {
824 switch (Lex.getKind()) {
825 default: Res = GlobalValue::DefaultVisibility; return false;
826 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
827 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
828 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
829 }
830 Lex.Lex();
831 return false;
832}
833
834/// ParseOptionalCallingConv
835/// ::= /*empty*/
836/// ::= 'ccc'
837/// ::= 'fastcc'
838/// ::= 'coldcc'
839/// ::= 'x86_stdcallcc'
840/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000841/// ::= 'arm_apcscc'
842/// ::= 'arm_aapcscc'
843/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000844/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000845///
Chris Lattnerdf986172009-01-02 07:01:27 +0000846bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
847 switch (Lex.getKind()) {
848 default: CC = CallingConv::C; return false;
849 case lltok::kw_ccc: CC = CallingConv::C; break;
850 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
851 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
852 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
853 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000854 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
855 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
856 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000857 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 }
859 Lex.Lex();
860 return false;
861}
862
863/// ParseOptionalAlignment
864/// ::= /* empty */
865/// ::= 'align' 4
866bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
867 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000868 if (!EatIfPresent(lltok::kw_align))
869 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000870 LocTy AlignLoc = Lex.getLoc();
871 if (ParseUInt32(Alignment)) return true;
872 if (!isPowerOf2_32(Alignment))
873 return Error(AlignLoc, "alignment is not a power of two");
874 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000875}
876
877/// ParseOptionalCommaAlignment
878/// ::= /* empty */
879/// ::= ',' 'align' 4
880bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
881 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000882 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000884 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000885 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000886}
887
888/// ParseIndexList
889/// ::= (',' uint32)+
890bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
891 if (Lex.getKind() != lltok::comma)
892 return TokError("expected ',' as start of index list");
893
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000894 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000895 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000896 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000897 Indices.push_back(Idx);
898 }
899
900 return false;
901}
902
903//===----------------------------------------------------------------------===//
904// Type Parsing.
905//===----------------------------------------------------------------------===//
906
907/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000908bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
909 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 if (ParseTypeRec(Result)) return true;
911
912 // Verify no unresolved uprefs.
913 if (!UpRefs.empty())
914 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000915
Chris Lattnera9a9e072009-03-09 04:49:14 +0000916 if (!AllowVoid && Result.get() == Type::VoidTy)
917 return Error(TypeLoc, "void type only allowed for function results");
918
Chris Lattnerdf986172009-01-02 07:01:27 +0000919 return false;
920}
921
922/// HandleUpRefs - Every time we finish a new layer of types, this function is
923/// called. It loops through the UpRefs vector, which is a list of the
924/// currently active types. For each type, if the up-reference is contained in
925/// the newly completed type, we decrement the level count. When the level
926/// count reaches zero, the up-referenced type is the type that is passed in:
927/// thus we can complete the cycle.
928///
929PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
930 // If Ty isn't abstract, or if there are no up-references in it, then there is
931 // nothing to resolve here.
932 if (!ty->isAbstract() || UpRefs.empty()) return ty;
933
934 PATypeHolder Ty(ty);
935#if 0
936 errs() << "Type '" << Ty->getDescription()
937 << "' newly formed. Resolving upreferences.\n"
938 << UpRefs.size() << " upreferences active!\n";
939#endif
940
941 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
942 // to zero), we resolve them all together before we resolve them to Ty. At
943 // the end of the loop, if there is anything to resolve to Ty, it will be in
944 // this variable.
945 OpaqueType *TypeToResolve = 0;
946
947 for (unsigned i = 0; i != UpRefs.size(); ++i) {
948 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
949 bool ContainsType =
950 std::find(Ty->subtype_begin(), Ty->subtype_end(),
951 UpRefs[i].LastContainedTy) != Ty->subtype_end();
952
953#if 0
954 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
955 << UpRefs[i].LastContainedTy->getDescription() << ") = "
956 << (ContainsType ? "true" : "false")
957 << " level=" << UpRefs[i].NestingLevel << "\n";
958#endif
959 if (!ContainsType)
960 continue;
961
962 // Decrement level of upreference
963 unsigned Level = --UpRefs[i].NestingLevel;
964 UpRefs[i].LastContainedTy = Ty;
965
966 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
967 if (Level != 0)
968 continue;
969
970#if 0
971 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
972#endif
973 if (!TypeToResolve)
974 TypeToResolve = UpRefs[i].UpRefTy;
975 else
976 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
977 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
978 --i; // Do not skip the next element.
979 }
980
981 if (TypeToResolve)
982 TypeToResolve->refineAbstractTypeTo(Ty);
983
984 return Ty;
985}
986
987
988/// ParseTypeRec - The recursive function used to process the internal
989/// implementation details of types.
990bool LLParser::ParseTypeRec(PATypeHolder &Result) {
991 switch (Lex.getKind()) {
992 default:
993 return TokError("expected type");
994 case lltok::Type:
995 // TypeRec ::= 'float' | 'void' (etc)
996 Result = Lex.getTyVal();
997 Lex.Lex();
998 break;
999 case lltok::kw_opaque:
1000 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001001 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001002 Lex.Lex();
1003 break;
1004 case lltok::lbrace:
1005 // TypeRec ::= '{' ... '}'
1006 if (ParseStructType(Result, false))
1007 return true;
1008 break;
1009 case lltok::lsquare:
1010 // TypeRec ::= '[' ... ']'
1011 Lex.Lex(); // eat the lsquare.
1012 if (ParseArrayVectorType(Result, false))
1013 return true;
1014 break;
1015 case lltok::less: // Either vector or packed struct.
1016 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001017 Lex.Lex();
1018 if (Lex.getKind() == lltok::lbrace) {
1019 if (ParseStructType(Result, true) ||
1020 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001021 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001022 } else if (ParseArrayVectorType(Result, true))
1023 return true;
1024 break;
1025 case lltok::LocalVar:
1026 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1027 // TypeRec ::= %foo
1028 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1029 Result = T;
1030 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001031 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001032 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1033 std::make_pair(Result,
1034 Lex.getLoc())));
1035 M->addTypeName(Lex.getStrVal(), Result.get());
1036 }
1037 Lex.Lex();
1038 break;
1039
1040 case lltok::LocalVarID:
1041 // TypeRec ::= %4
1042 if (Lex.getUIntVal() < NumberedTypes.size())
1043 Result = NumberedTypes[Lex.getUIntVal()];
1044 else {
1045 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1046 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1047 if (I != ForwardRefTypeIDs.end())
1048 Result = I->second.first;
1049 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001050 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001051 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1052 std::make_pair(Result,
1053 Lex.getLoc())));
1054 }
1055 }
1056 Lex.Lex();
1057 break;
1058 case lltok::backslash: {
1059 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001061 unsigned Val;
1062 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001063 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001064 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1065 Result = OT;
1066 break;
1067 }
1068 }
1069
1070 // Parse the type suffixes.
1071 while (1) {
1072 switch (Lex.getKind()) {
1073 // End of type.
1074 default: return false;
1075
1076 // TypeRec ::= TypeRec '*'
1077 case lltok::star:
1078 if (Result.get() == Type::LabelTy)
1079 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001080 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001081 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001082 if (!PointerType::isValidElementType(Result.get()))
1083 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001084 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001085 Lex.Lex();
1086 break;
1087
1088 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1089 case lltok::kw_addrspace: {
1090 if (Result.get() == Type::LabelTy)
1091 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001092 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001093 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001094 if (!PointerType::isValidElementType(Result.get()))
1095 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001096 unsigned AddrSpace;
1097 if (ParseOptionalAddrSpace(AddrSpace) ||
1098 ParseToken(lltok::star, "expected '*' in address space"))
1099 return true;
1100
Owen Andersonfba933c2009-07-01 23:57:11 +00001101 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001102 break;
1103 }
1104
1105 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1106 case lltok::lparen:
1107 if (ParseFunctionType(Result))
1108 return true;
1109 break;
1110 }
1111 }
1112}
1113
1114/// ParseParameterList
1115/// ::= '(' ')'
1116/// ::= '(' Arg (',' Arg)* ')'
1117/// Arg
1118/// ::= Type OptionalAttributes Value OptionalAttributes
1119bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1120 PerFunctionState &PFS) {
1121 if (ParseToken(lltok::lparen, "expected '(' in call"))
1122 return true;
1123
1124 while (Lex.getKind() != lltok::rparen) {
1125 // If this isn't the first argument, we need a comma.
1126 if (!ArgList.empty() &&
1127 ParseToken(lltok::comma, "expected ',' in argument list"))
1128 return true;
1129
1130 // Parse the argument.
1131 LocTy ArgLoc;
1132 PATypeHolder ArgTy(Type::VoidTy);
1133 unsigned ArgAttrs1, ArgAttrs2;
1134 Value *V;
1135 if (ParseType(ArgTy, ArgLoc) ||
1136 ParseOptionalAttrs(ArgAttrs1, 0) ||
1137 ParseValue(ArgTy, V, PFS) ||
1138 // FIXME: Should not allow attributes after the argument, remove this in
1139 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001140 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 return true;
1142 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1143 }
1144
1145 Lex.Lex(); // Lex the ')'.
1146 return false;
1147}
1148
1149
1150
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001151/// ParseArgumentList - Parse the argument list for a function type or function
1152/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001153/// ::= '(' ArgTypeListI ')'
1154/// ArgTypeListI
1155/// ::= /*empty*/
1156/// ::= '...'
1157/// ::= ArgTypeList ',' '...'
1158/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001159///
Chris Lattnerdf986172009-01-02 07:01:27 +00001160bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001161 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 isVarArg = false;
1163 assert(Lex.getKind() == lltok::lparen);
1164 Lex.Lex(); // eat the (.
1165
1166 if (Lex.getKind() == lltok::rparen) {
1167 // empty
1168 } else if (Lex.getKind() == lltok::dotdotdot) {
1169 isVarArg = true;
1170 Lex.Lex();
1171 } else {
1172 LocTy TypeLoc = Lex.getLoc();
1173 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001176
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001177 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1178 // types (such as a function returning a pointer to itself). If parsing a
1179 // function prototype, we require fully resolved types.
1180 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001181 ParseOptionalAttrs(Attrs, 0)) return true;
1182
Chris Lattnera9a9e072009-03-09 04:49:14 +00001183 if (ArgTy == Type::VoidTy)
1184 return Error(TypeLoc, "argument can not have void type");
1185
Chris Lattnerdf986172009-01-02 07:01:27 +00001186 if (Lex.getKind() == lltok::LocalVar ||
1187 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1188 Name = Lex.getStrVal();
1189 Lex.Lex();
1190 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001191
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001192 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001193 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001194
1195 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1196
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001197 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001198 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001199 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001200 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001201 break;
1202 }
1203
1204 // Otherwise must be an argument type.
1205 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001206 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001207 ParseOptionalAttrs(Attrs, 0)) return true;
1208
Chris Lattnera9a9e072009-03-09 04:49:14 +00001209 if (ArgTy == Type::VoidTy)
1210 return Error(TypeLoc, "argument can not have void type");
1211
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 if (Lex.getKind() == lltok::LocalVar ||
1213 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1214 Name = Lex.getStrVal();
1215 Lex.Lex();
1216 } else {
1217 Name = "";
1218 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001219
1220 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1221 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001222
1223 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1224 }
1225 }
1226
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001227 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001228}
1229
1230/// ParseFunctionType
1231/// ::= Type ArgumentList OptionalAttrs
1232bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1233 assert(Lex.getKind() == lltok::lparen);
1234
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001235 if (!FunctionType::isValidReturnType(Result))
1236 return TokError("invalid function return type");
1237
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 std::vector<ArgInfo> ArgList;
1239 bool isVarArg;
1240 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001241 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 // FIXME: Allow, but ignore attributes on function types!
1243 // FIXME: Remove in LLVM 3.0
1244 ParseOptionalAttrs(Attrs, 2))
1245 return true;
1246
1247 // Reject names on the arguments lists.
1248 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1249 if (!ArgList[i].Name.empty())
1250 return Error(ArgList[i].Loc, "argument name invalid in function type");
1251 if (!ArgList[i].Attrs != 0) {
1252 // Allow but ignore attributes on function types; this permits
1253 // auto-upgrade.
1254 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1255 }
1256 }
1257
1258 std::vector<const Type*> ArgListTy;
1259 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1260 ArgListTy.push_back(ArgList[i].Type);
1261
Owen Andersonfba933c2009-07-01 23:57:11 +00001262 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1263 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001264 return false;
1265}
1266
1267/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1268/// TypeRec
1269/// ::= '{' '}'
1270/// ::= '{' TypeRec (',' TypeRec)* '}'
1271/// ::= '<' '{' '}' '>'
1272/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1273bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1274 assert(Lex.getKind() == lltok::lbrace);
1275 Lex.Lex(); // Consume the '{'
1276
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001277 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001278 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001279 return false;
1280 }
1281
1282 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001283 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 if (ParseTypeRec(Result)) return true;
1285 ParamsList.push_back(Result);
1286
Chris Lattnera9a9e072009-03-09 04:49:14 +00001287 if (Result == Type::VoidTy)
1288 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001289 if (!StructType::isValidElementType(Result))
1290 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001291
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001292 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001293 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001295
1296 if (Result == Type::VoidTy)
1297 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001298 if (!StructType::isValidElementType(Result))
1299 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001300
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 ParamsList.push_back(Result);
1302 }
1303
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001304 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1305 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001306
1307 std::vector<const Type*> ParamsListTy;
1308 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1309 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001310 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 return false;
1312}
1313
1314/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1315/// token has already been consumed.
1316/// TypeRec
1317/// ::= '[' APSINTVAL 'x' Types ']'
1318/// ::= '<' APSINTVAL 'x' Types '>'
1319bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1320 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1321 Lex.getAPSIntVal().getBitWidth() > 64)
1322 return TokError("expected number in address space");
1323
1324 LocTy SizeLoc = Lex.getLoc();
1325 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001326 Lex.Lex();
1327
1328 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1329 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001330
1331 LocTy TypeLoc = Lex.getLoc();
1332 PATypeHolder EltTy(Type::VoidTy);
1333 if (ParseTypeRec(EltTy)) return true;
1334
Chris Lattnera9a9e072009-03-09 04:49:14 +00001335 if (EltTy == Type::VoidTy)
1336 return Error(TypeLoc, "array and vector element type cannot be void");
1337
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001338 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1339 "expected end of sequential type"))
1340 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001341
1342 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001343 if (Size == 0)
1344 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 if ((unsigned)Size != Size)
1346 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001347 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001348 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001349 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001351 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001353 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 }
1355 return false;
1356}
1357
1358//===----------------------------------------------------------------------===//
1359// Function Semantic Analysis.
1360//===----------------------------------------------------------------------===//
1361
1362LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1363 : P(p), F(f) {
1364
1365 // Insert unnamed arguments into the NumberedVals list.
1366 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1367 AI != E; ++AI)
1368 if (!AI->hasName())
1369 NumberedVals.push_back(AI);
1370}
1371
1372LLParser::PerFunctionState::~PerFunctionState() {
1373 // If there were any forward referenced non-basicblock values, delete them.
1374 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1375 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1376 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001377 I->second.first->replaceAllUsesWith(
1378 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001379 delete I->second.first;
1380 I->second.first = 0;
1381 }
1382
1383 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1384 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1385 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001386 I->second.first->replaceAllUsesWith(
1387 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 delete I->second.first;
1389 I->second.first = 0;
1390 }
1391}
1392
1393bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1394 if (!ForwardRefVals.empty())
1395 return P.Error(ForwardRefVals.begin()->second.second,
1396 "use of undefined value '%" + ForwardRefVals.begin()->first +
1397 "'");
1398 if (!ForwardRefValIDs.empty())
1399 return P.Error(ForwardRefValIDs.begin()->second.second,
1400 "use of undefined value '%" +
1401 utostr(ForwardRefValIDs.begin()->first) + "'");
1402 return false;
1403}
1404
1405
1406/// GetVal - Get a value with the specified name or ID, creating a
1407/// forward reference record if needed. This can return null if the value
1408/// exists but does not have the right type.
1409Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1410 const Type *Ty, LocTy Loc) {
1411 // Look this name up in the normal function symbol table.
1412 Value *Val = F.getValueSymbolTable().lookup(Name);
1413
1414 // If this is a forward reference for the value, see if we already created a
1415 // forward ref record.
1416 if (Val == 0) {
1417 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1418 I = ForwardRefVals.find(Name);
1419 if (I != ForwardRefVals.end())
1420 Val = I->second.first;
1421 }
1422
1423 // If we have the value in the symbol table or fwd-ref table, return it.
1424 if (Val) {
1425 if (Val->getType() == Ty) return Val;
1426 if (Ty == Type::LabelTy)
1427 P.Error(Loc, "'%" + Name + "' is not a basic block");
1428 else
1429 P.Error(Loc, "'%" + Name + "' defined with type '" +
1430 Val->getType()->getDescription() + "'");
1431 return 0;
1432 }
1433
1434 // Don't make placeholders with invalid type.
1435 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1436 P.Error(Loc, "invalid use of a non-first-class type");
1437 return 0;
1438 }
1439
1440 // Otherwise, create a new forward reference for this value and remember it.
1441 Value *FwdVal;
1442 if (Ty == Type::LabelTy)
1443 FwdVal = BasicBlock::Create(Name, &F);
1444 else
1445 FwdVal = new Argument(Ty, Name);
1446
1447 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1448 return FwdVal;
1449}
1450
1451Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1452 LocTy Loc) {
1453 // Look this name up in the normal function symbol table.
1454 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1455
1456 // If this is a forward reference for the value, see if we already created a
1457 // forward ref record.
1458 if (Val == 0) {
1459 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1460 I = ForwardRefValIDs.find(ID);
1461 if (I != ForwardRefValIDs.end())
1462 Val = I->second.first;
1463 }
1464
1465 // If we have the value in the symbol table or fwd-ref table, return it.
1466 if (Val) {
1467 if (Val->getType() == Ty) return Val;
1468 if (Ty == Type::LabelTy)
1469 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1470 else
1471 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1472 Val->getType()->getDescription() + "'");
1473 return 0;
1474 }
1475
1476 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1477 P.Error(Loc, "invalid use of a non-first-class type");
1478 return 0;
1479 }
1480
1481 // Otherwise, create a new forward reference for this value and remember it.
1482 Value *FwdVal;
1483 if (Ty == Type::LabelTy)
1484 FwdVal = BasicBlock::Create("", &F);
1485 else
1486 FwdVal = new Argument(Ty);
1487
1488 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1489 return FwdVal;
1490}
1491
1492/// SetInstName - After an instruction is parsed and inserted into its
1493/// basic block, this installs its name.
1494bool LLParser::PerFunctionState::SetInstName(int NameID,
1495 const std::string &NameStr,
1496 LocTy NameLoc, Instruction *Inst) {
1497 // If this instruction has void type, it cannot have a name or ID specified.
1498 if (Inst->getType() == Type::VoidTy) {
1499 if (NameID != -1 || !NameStr.empty())
1500 return P.Error(NameLoc, "instructions returning void cannot have a name");
1501 return false;
1502 }
1503
1504 // If this was a numbered instruction, verify that the instruction is the
1505 // expected value and resolve any forward references.
1506 if (NameStr.empty()) {
1507 // If neither a name nor an ID was specified, just use the next ID.
1508 if (NameID == -1)
1509 NameID = NumberedVals.size();
1510
1511 if (unsigned(NameID) != NumberedVals.size())
1512 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1513 utostr(NumberedVals.size()) + "'");
1514
1515 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1516 ForwardRefValIDs.find(NameID);
1517 if (FI != ForwardRefValIDs.end()) {
1518 if (FI->second.first->getType() != Inst->getType())
1519 return P.Error(NameLoc, "instruction forward referenced with type '" +
1520 FI->second.first->getType()->getDescription() + "'");
1521 FI->second.first->replaceAllUsesWith(Inst);
1522 ForwardRefValIDs.erase(FI);
1523 }
1524
1525 NumberedVals.push_back(Inst);
1526 return false;
1527 }
1528
1529 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1530 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1531 FI = ForwardRefVals.find(NameStr);
1532 if (FI != ForwardRefVals.end()) {
1533 if (FI->second.first->getType() != Inst->getType())
1534 return P.Error(NameLoc, "instruction forward referenced with type '" +
1535 FI->second.first->getType()->getDescription() + "'");
1536 FI->second.first->replaceAllUsesWith(Inst);
1537 ForwardRefVals.erase(FI);
1538 }
1539
1540 // Set the name on the instruction.
1541 Inst->setName(NameStr);
1542
1543 if (Inst->getNameStr() != NameStr)
1544 return P.Error(NameLoc, "multiple definition of local value named '" +
1545 NameStr + "'");
1546 return false;
1547}
1548
1549/// GetBB - Get a basic block with the specified name or ID, creating a
1550/// forward reference record if needed.
1551BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1552 LocTy Loc) {
1553 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1554}
1555
1556BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1557 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1558}
1559
1560/// DefineBB - Define the specified basic block, which is either named or
1561/// unnamed. If there is an error, this returns null otherwise it returns
1562/// the block being defined.
1563BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1564 LocTy Loc) {
1565 BasicBlock *BB;
1566 if (Name.empty())
1567 BB = GetBB(NumberedVals.size(), Loc);
1568 else
1569 BB = GetBB(Name, Loc);
1570 if (BB == 0) return 0; // Already diagnosed error.
1571
1572 // Move the block to the end of the function. Forward ref'd blocks are
1573 // inserted wherever they happen to be referenced.
1574 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1575
1576 // Remove the block from forward ref sets.
1577 if (Name.empty()) {
1578 ForwardRefValIDs.erase(NumberedVals.size());
1579 NumberedVals.push_back(BB);
1580 } else {
1581 // BB forward references are already in the function symbol table.
1582 ForwardRefVals.erase(Name);
1583 }
1584
1585 return BB;
1586}
1587
1588//===----------------------------------------------------------------------===//
1589// Constants.
1590//===----------------------------------------------------------------------===//
1591
1592/// ParseValID - Parse an abstract value that doesn't necessarily have a
1593/// type implied. For example, if we parse "4" we don't know what integer type
1594/// it has. The value will later be combined with its type and checked for
1595/// sanity.
1596bool LLParser::ParseValID(ValID &ID) {
1597 ID.Loc = Lex.getLoc();
1598 switch (Lex.getKind()) {
1599 default: return TokError("expected value token");
1600 case lltok::GlobalID: // @42
1601 ID.UIntVal = Lex.getUIntVal();
1602 ID.Kind = ValID::t_GlobalID;
1603 break;
1604 case lltok::GlobalVar: // @foo
1605 ID.StrVal = Lex.getStrVal();
1606 ID.Kind = ValID::t_GlobalName;
1607 break;
1608 case lltok::LocalVarID: // %42
1609 ID.UIntVal = Lex.getUIntVal();
1610 ID.Kind = ValID::t_LocalID;
1611 break;
1612 case lltok::LocalVar: // %foo
1613 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1614 ID.StrVal = Lex.getStrVal();
1615 ID.Kind = ValID::t_LocalName;
1616 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001617 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1618 ID.Kind = ValID::t_Constant;
1619 Lex.Lex();
1620 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001621 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001622 if (ParseMDNodeVector(Elts) ||
1623 ParseToken(lltok::rbrace, "expected end of metadata node"))
1624 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001625
Owen Andersone951bdf2009-07-02 17:20:28 +00001626 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001627 return false;
1628 }
1629
Devang Patel923078c2009-07-01 19:21:12 +00001630 // Standalone metadata reference
1631 // !{ ..., !42, ... }
1632 unsigned MID = 0;
1633 if (!ParseUInt32(MID)) {
1634 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1635 if (I == MetadataCache.end())
1636 return TokError("Unknown metadata reference");
1637 ID.ConstantVal = I->second;
1638 return false;
1639 }
1640
Nick Lewycky21cc4462009-04-04 07:22:01 +00001641 // MDString:
1642 // ::= '!' STRINGCONSTANT
1643 std::string Str;
1644 if (ParseStringConstant(Str)) return true;
1645
Owen Anderson12c99d82009-07-02 17:28:30 +00001646 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001647 return false;
1648 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 case lltok::APSInt:
1650 ID.APSIntVal = Lex.getAPSIntVal();
1651 ID.Kind = ValID::t_APSInt;
1652 break;
1653 case lltok::APFloat:
1654 ID.APFloatVal = Lex.getAPFloatVal();
1655 ID.Kind = ValID::t_APFloat;
1656 break;
1657 case lltok::kw_true:
Owen Andersonfba933c2009-07-01 23:57:11 +00001658 ID.ConstantVal = Context.getConstantIntTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001659 ID.Kind = ValID::t_Constant;
1660 break;
1661 case lltok::kw_false:
Owen Andersonfba933c2009-07-01 23:57:11 +00001662 ID.ConstantVal = Context.getConstantIntFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 ID.Kind = ValID::t_Constant;
1664 break;
1665 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1666 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1667 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1668
1669 case lltok::lbrace: {
1670 // ValID ::= '{' ConstVector '}'
1671 Lex.Lex();
1672 SmallVector<Constant*, 16> Elts;
1673 if (ParseGlobalValueVector(Elts) ||
1674 ParseToken(lltok::rbrace, "expected end of struct constant"))
1675 return true;
1676
Owen Andersonfba933c2009-07-01 23:57:11 +00001677 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001678 ID.Kind = ValID::t_Constant;
1679 return false;
1680 }
1681 case lltok::less: {
1682 // ValID ::= '<' ConstVector '>' --> Vector.
1683 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1684 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001685 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001686
1687 SmallVector<Constant*, 16> Elts;
1688 LocTy FirstEltLoc = Lex.getLoc();
1689 if (ParseGlobalValueVector(Elts) ||
1690 (isPackedStruct &&
1691 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1692 ParseToken(lltok::greater, "expected end of constant"))
1693 return true;
1694
1695 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001696 ID.ConstantVal =
1697 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001698 ID.Kind = ValID::t_Constant;
1699 return false;
1700 }
1701
1702 if (Elts.empty())
1703 return Error(ID.Loc, "constant vector must not be empty");
1704
1705 if (!Elts[0]->getType()->isInteger() &&
1706 !Elts[0]->getType()->isFloatingPoint())
1707 return Error(FirstEltLoc,
1708 "vector elements must have integer or floating point type");
1709
1710 // Verify that all the vector elements have the same type.
1711 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1712 if (Elts[i]->getType() != Elts[0]->getType())
1713 return Error(FirstEltLoc,
1714 "vector element #" + utostr(i) +
1715 " is not of type '" + Elts[0]->getType()->getDescription());
1716
Owen Andersonfba933c2009-07-01 23:57:11 +00001717 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 ID.Kind = ValID::t_Constant;
1719 return false;
1720 }
1721 case lltok::lsquare: { // Array Constant
1722 Lex.Lex();
1723 SmallVector<Constant*, 16> Elts;
1724 LocTy FirstEltLoc = Lex.getLoc();
1725 if (ParseGlobalValueVector(Elts) ||
1726 ParseToken(lltok::rsquare, "expected end of array constant"))
1727 return true;
1728
1729 // Handle empty element.
1730 if (Elts.empty()) {
1731 // Use undef instead of an array because it's inconvenient to determine
1732 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001733 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 return false;
1735 }
1736
1737 if (!Elts[0]->getType()->isFirstClassType())
1738 return Error(FirstEltLoc, "invalid array element type: " +
1739 Elts[0]->getType()->getDescription());
1740
Owen Andersonfba933c2009-07-01 23:57:11 +00001741 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001742
1743 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001744 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001745 if (Elts[i]->getType() != Elts[0]->getType())
1746 return Error(FirstEltLoc,
1747 "array element #" + utostr(i) +
1748 " is not of type '" +Elts[0]->getType()->getDescription());
1749 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001750
Owen Andersonfba933c2009-07-01 23:57:11 +00001751 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 ID.Kind = ValID::t_Constant;
1753 return false;
1754 }
1755 case lltok::kw_c: // c "foo"
1756 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001757 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1759 ID.Kind = ValID::t_Constant;
1760 return false;
1761
1762 case lltok::kw_asm: {
1763 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1764 bool HasSideEffect;
1765 Lex.Lex();
1766 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001767 ParseStringConstant(ID.StrVal) ||
1768 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 ParseToken(lltok::StringConstant, "expected constraint string"))
1770 return true;
1771 ID.StrVal2 = Lex.getStrVal();
1772 ID.UIntVal = HasSideEffect;
1773 ID.Kind = ValID::t_InlineAsm;
1774 return false;
1775 }
1776
1777 case lltok::kw_trunc:
1778 case lltok::kw_zext:
1779 case lltok::kw_sext:
1780 case lltok::kw_fptrunc:
1781 case lltok::kw_fpext:
1782 case lltok::kw_bitcast:
1783 case lltok::kw_uitofp:
1784 case lltok::kw_sitofp:
1785 case lltok::kw_fptoui:
1786 case lltok::kw_fptosi:
1787 case lltok::kw_inttoptr:
1788 case lltok::kw_ptrtoint: {
1789 unsigned Opc = Lex.getUIntVal();
1790 PATypeHolder DestTy(Type::VoidTy);
1791 Constant *SrcVal;
1792 Lex.Lex();
1793 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1794 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001795 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 ParseType(DestTy) ||
1797 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1798 return true;
1799 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1800 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1801 SrcVal->getType()->getDescription() + "' to '" +
1802 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001803 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1804 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001805 ID.Kind = ValID::t_Constant;
1806 return false;
1807 }
1808 case lltok::kw_extractvalue: {
1809 Lex.Lex();
1810 Constant *Val;
1811 SmallVector<unsigned, 4> Indices;
1812 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1813 ParseGlobalTypeAndValue(Val) ||
1814 ParseIndexList(Indices) ||
1815 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1816 return true;
1817 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1818 return Error(ID.Loc, "extractvalue operand must be array or struct");
1819 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1820 Indices.end()))
1821 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001822 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001823 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 ID.Kind = ValID::t_Constant;
1825 return false;
1826 }
1827 case lltok::kw_insertvalue: {
1828 Lex.Lex();
1829 Constant *Val0, *Val1;
1830 SmallVector<unsigned, 4> Indices;
1831 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1832 ParseGlobalTypeAndValue(Val0) ||
1833 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1834 ParseGlobalTypeAndValue(Val1) ||
1835 ParseIndexList(Indices) ||
1836 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1837 return true;
1838 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1839 return Error(ID.Loc, "extractvalue operand must be array or struct");
1840 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1841 Indices.end()))
1842 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001843 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1844 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001845 ID.Kind = ValID::t_Constant;
1846 return false;
1847 }
1848 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001849 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 unsigned PredVal, Opc = Lex.getUIntVal();
1851 Constant *Val0, *Val1;
1852 Lex.Lex();
1853 if (ParseCmpPredicate(PredVal, Opc) ||
1854 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1855 ParseGlobalTypeAndValue(Val0) ||
1856 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1857 ParseGlobalTypeAndValue(Val1) ||
1858 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1859 return true;
1860
1861 if (Val0->getType() != Val1->getType())
1862 return Error(ID.Loc, "compare operands must have the same type");
1863
1864 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1865
1866 if (Opc == Instruction::FCmp) {
1867 if (!Val0->getType()->isFPOrFPVector())
1868 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001869 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001870 } else {
1871 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 if (!Val0->getType()->isIntOrIntVector() &&
1873 !isa<PointerType>(Val0->getType()))
1874 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001875 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 }
1877 ID.Kind = ValID::t_Constant;
1878 return false;
1879 }
1880
1881 // Binary Operators.
1882 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001883 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001885 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001887 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001888 case lltok::kw_udiv:
1889 case lltok::kw_sdiv:
1890 case lltok::kw_fdiv:
1891 case lltok::kw_urem:
1892 case lltok::kw_srem:
1893 case lltok::kw_frem: {
1894 unsigned Opc = Lex.getUIntVal();
1895 Constant *Val0, *Val1;
1896 Lex.Lex();
1897 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1898 ParseGlobalTypeAndValue(Val0) ||
1899 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1900 ParseGlobalTypeAndValue(Val1) ||
1901 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1902 return true;
1903 if (Val0->getType() != Val1->getType())
1904 return Error(ID.Loc, "operands of constexpr must have same type");
1905 if (!Val0->getType()->isIntOrIntVector() &&
1906 !Val0->getType()->isFPOrFPVector())
1907 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001908 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 ID.Kind = ValID::t_Constant;
1910 return false;
1911 }
1912
1913 // Logical Operations
1914 case lltok::kw_shl:
1915 case lltok::kw_lshr:
1916 case lltok::kw_ashr:
1917 case lltok::kw_and:
1918 case lltok::kw_or:
1919 case lltok::kw_xor: {
1920 unsigned Opc = Lex.getUIntVal();
1921 Constant *Val0, *Val1;
1922 Lex.Lex();
1923 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1924 ParseGlobalTypeAndValue(Val0) ||
1925 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1926 ParseGlobalTypeAndValue(Val1) ||
1927 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1928 return true;
1929 if (Val0->getType() != Val1->getType())
1930 return Error(ID.Loc, "operands of constexpr must have same type");
1931 if (!Val0->getType()->isIntOrIntVector())
1932 return Error(ID.Loc,
1933 "constexpr requires integer or integer vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001934 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001935 ID.Kind = ValID::t_Constant;
1936 return false;
1937 }
1938
1939 case lltok::kw_getelementptr:
1940 case lltok::kw_shufflevector:
1941 case lltok::kw_insertelement:
1942 case lltok::kw_extractelement:
1943 case lltok::kw_select: {
1944 unsigned Opc = Lex.getUIntVal();
1945 SmallVector<Constant*, 16> Elts;
1946 Lex.Lex();
1947 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1948 ParseGlobalValueVector(Elts) ||
1949 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1950 return true;
1951
1952 if (Opc == Instruction::GetElementPtr) {
1953 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1954 return Error(ID.Loc, "getelementptr requires pointer operand");
1955
1956 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1957 (Value**)&Elts[1], Elts.size()-1))
1958 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00001959 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 &Elts[1], Elts.size()-1);
1961 } else if (Opc == Instruction::Select) {
1962 if (Elts.size() != 3)
1963 return Error(ID.Loc, "expected three operands to select");
1964 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1965 Elts[2]))
1966 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00001967 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001968 } else if (Opc == Instruction::ShuffleVector) {
1969 if (Elts.size() != 3)
1970 return Error(ID.Loc, "expected three operands to shufflevector");
1971 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1972 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00001973 ID.ConstantVal =
1974 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 } else if (Opc == Instruction::ExtractElement) {
1976 if (Elts.size() != 2)
1977 return Error(ID.Loc, "expected two operands to extractelement");
1978 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1979 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001980 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001981 } else {
1982 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1983 if (Elts.size() != 3)
1984 return Error(ID.Loc, "expected three operands to insertelement");
1985 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1986 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001987 ID.ConstantVal =
1988 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 }
1990
1991 ID.Kind = ValID::t_Constant;
1992 return false;
1993 }
1994 }
1995
1996 Lex.Lex();
1997 return false;
1998}
1999
2000/// ParseGlobalValue - Parse a global value with the specified type.
2001bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2002 V = 0;
2003 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002004 return ParseValID(ID) ||
2005 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002006}
2007
2008/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2009/// constant.
2010bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2011 Constant *&V) {
2012 if (isa<FunctionType>(Ty))
2013 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2014
2015 switch (ID.Kind) {
2016 default: assert(0 && "Unknown ValID!");
2017 case ValID::t_LocalID:
2018 case ValID::t_LocalName:
2019 return Error(ID.Loc, "invalid use of function-local name");
2020 case ValID::t_InlineAsm:
2021 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2022 case ValID::t_GlobalName:
2023 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2024 return V == 0;
2025 case ValID::t_GlobalID:
2026 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2027 return V == 0;
2028 case ValID::t_APSInt:
2029 if (!isa<IntegerType>(Ty))
2030 return Error(ID.Loc, "integer constant must have integer type");
2031 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002032 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 return false;
2034 case ValID::t_APFloat:
2035 if (!Ty->isFloatingPoint() ||
2036 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2037 return Error(ID.Loc, "floating point constant invalid for type");
2038
2039 // The lexer has no type info, so builds all float and double FP constants
2040 // as double. Fix this here. Long double does not need this.
2041 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2042 Ty == Type::FloatTy) {
2043 bool Ignored;
2044 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2045 &Ignored);
2046 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002047 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002048
2049 if (V->getType() != Ty)
2050 return Error(ID.Loc, "floating point constant does not have type '" +
2051 Ty->getDescription() + "'");
2052
Chris Lattnerdf986172009-01-02 07:01:27 +00002053 return false;
2054 case ValID::t_Null:
2055 if (!isa<PointerType>(Ty))
2056 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002057 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 return false;
2059 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002060 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002061 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2062 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002063 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002064 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002066 case ValID::t_EmptyArray:
2067 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2068 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002069 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002070 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002071 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002072 // FIXME: LabelTy should not be a first-class type.
2073 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002075 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002076 return false;
2077 case ValID::t_Constant:
2078 if (ID.ConstantVal->getType() != Ty)
2079 return Error(ID.Loc, "constant expression type mismatch");
2080 V = ID.ConstantVal;
2081 return false;
2082 }
2083}
2084
2085bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2086 PATypeHolder Type(Type::VoidTy);
2087 return ParseType(Type) ||
2088 ParseGlobalValue(Type, V);
2089}
2090
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002091/// ParseGlobalValueVector
2092/// ::= /*empty*/
2093/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002094bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2095 // Empty list.
2096 if (Lex.getKind() == lltok::rbrace ||
2097 Lex.getKind() == lltok::rsquare ||
2098 Lex.getKind() == lltok::greater ||
2099 Lex.getKind() == lltok::rparen)
2100 return false;
2101
2102 Constant *C;
2103 if (ParseGlobalTypeAndValue(C)) return true;
2104 Elts.push_back(C);
2105
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002106 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002107 if (ParseGlobalTypeAndValue(C)) return true;
2108 Elts.push_back(C);
2109 }
2110
2111 return false;
2112}
2113
2114
2115//===----------------------------------------------------------------------===//
2116// Function Parsing.
2117//===----------------------------------------------------------------------===//
2118
2119bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2120 PerFunctionState &PFS) {
2121 if (ID.Kind == ValID::t_LocalID)
2122 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2123 else if (ID.Kind == ValID::t_LocalName)
2124 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002125 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002126 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2127 const FunctionType *FTy =
2128 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2129 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2130 return Error(ID.Loc, "invalid type for inline asm constraint string");
2131 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2132 return false;
2133 } else {
2134 Constant *C;
2135 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2136 V = C;
2137 return false;
2138 }
2139
2140 return V == 0;
2141}
2142
2143bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2144 V = 0;
2145 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002146 return ParseValID(ID) ||
2147 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002148}
2149
2150bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2151 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002152 return ParseType(T) ||
2153 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002154}
2155
2156/// FunctionHeader
2157/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2158/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2159/// OptionalAlign OptGC
2160bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2161 // Parse the linkage.
2162 LocTy LinkageLoc = Lex.getLoc();
2163 unsigned Linkage;
2164
2165 unsigned Visibility, CC, RetAttrs;
2166 PATypeHolder RetType(Type::VoidTy);
2167 LocTy RetTypeLoc = Lex.getLoc();
2168 if (ParseOptionalLinkage(Linkage) ||
2169 ParseOptionalVisibility(Visibility) ||
2170 ParseOptionalCallingConv(CC) ||
2171 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002172 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 return true;
2174
2175 // Verify that the linkage is ok.
2176 switch ((GlobalValue::LinkageTypes)Linkage) {
2177 case GlobalValue::ExternalLinkage:
2178 break; // always ok.
2179 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002180 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 if (isDefine)
2182 return Error(LinkageLoc, "invalid linkage for function definition");
2183 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002184 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002186 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002187 case GlobalValue::LinkOnceAnyLinkage:
2188 case GlobalValue::LinkOnceODRLinkage:
2189 case GlobalValue::WeakAnyLinkage:
2190 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002191 case GlobalValue::DLLExportLinkage:
2192 if (!isDefine)
2193 return Error(LinkageLoc, "invalid linkage for function declaration");
2194 break;
2195 case GlobalValue::AppendingLinkage:
2196 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002197 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002198 return Error(LinkageLoc, "invalid function linkage type");
2199 }
2200
Chris Lattner99bb3152009-01-05 08:00:30 +00002201 if (!FunctionType::isValidReturnType(RetType) ||
2202 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 return Error(RetTypeLoc, "invalid function return type");
2204
Chris Lattnerdf986172009-01-02 07:01:27 +00002205 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002206
2207 std::string FunctionName;
2208 if (Lex.getKind() == lltok::GlobalVar) {
2209 FunctionName = Lex.getStrVal();
2210 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2211 unsigned NameID = Lex.getUIntVal();
2212
2213 if (NameID != NumberedVals.size())
2214 return TokError("function expected to be numbered '%" +
2215 utostr(NumberedVals.size()) + "'");
2216 } else {
2217 return TokError("expected function name");
2218 }
2219
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002220 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002221
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002222 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002223 return TokError("expected '(' in function argument list");
2224
2225 std::vector<ArgInfo> ArgList;
2226 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002230 std::string GC;
2231
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002232 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002233 ParseOptionalAttrs(FuncAttrs, 2) ||
2234 (EatIfPresent(lltok::kw_section) &&
2235 ParseStringConstant(Section)) ||
2236 ParseOptionalAlignment(Alignment) ||
2237 (EatIfPresent(lltok::kw_gc) &&
2238 ParseStringConstant(GC)))
2239 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002240
2241 // If the alignment was parsed as an attribute, move to the alignment field.
2242 if (FuncAttrs & Attribute::Alignment) {
2243 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2244 FuncAttrs &= ~Attribute::Alignment;
2245 }
2246
Chris Lattnerdf986172009-01-02 07:01:27 +00002247 // Okay, if we got here, the function is syntactically valid. Convert types
2248 // and do semantic checks.
2249 std::vector<const Type*> ParamTypeList;
2250 SmallVector<AttributeWithIndex, 8> Attrs;
2251 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2252 // attributes.
2253 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2254 if (FuncAttrs & ObsoleteFuncAttrs) {
2255 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2256 FuncAttrs &= ~ObsoleteFuncAttrs;
2257 }
2258
2259 if (RetAttrs != Attribute::None)
2260 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2261
2262 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2263 ParamTypeList.push_back(ArgList[i].Type);
2264 if (ArgList[i].Attrs != Attribute::None)
2265 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2266 }
2267
2268 if (FuncAttrs != Attribute::None)
2269 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2270
2271 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2272
Chris Lattnera9a9e072009-03-09 04:49:14 +00002273 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2274 RetType != Type::VoidTy)
2275 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2276
Owen Andersonfba933c2009-07-01 23:57:11 +00002277 const FunctionType *FT =
2278 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2279 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002280
2281 Fn = 0;
2282 if (!FunctionName.empty()) {
2283 // If this was a definition of a forward reference, remove the definition
2284 // from the forward reference table and fill in the forward ref.
2285 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2286 ForwardRefVals.find(FunctionName);
2287 if (FRVI != ForwardRefVals.end()) {
2288 Fn = M->getFunction(FunctionName);
2289 ForwardRefVals.erase(FRVI);
2290 } else if ((Fn = M->getFunction(FunctionName))) {
2291 // If this function already exists in the symbol table, then it is
2292 // multiply defined. We accept a few cases for old backwards compat.
2293 // FIXME: Remove this stuff for LLVM 3.0.
2294 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2295 (!Fn->isDeclaration() && isDefine)) {
2296 // If the redefinition has different type or different attributes,
2297 // reject it. If both have bodies, reject it.
2298 return Error(NameLoc, "invalid redefinition of function '" +
2299 FunctionName + "'");
2300 } else if (Fn->isDeclaration()) {
2301 // Make sure to strip off any argument names so we can't get conflicts.
2302 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2303 AI != AE; ++AI)
2304 AI->setName("");
2305 }
2306 }
2307
2308 } else if (FunctionName.empty()) {
2309 // If this is a definition of a forward referenced function, make sure the
2310 // types agree.
2311 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2312 = ForwardRefValIDs.find(NumberedVals.size());
2313 if (I != ForwardRefValIDs.end()) {
2314 Fn = cast<Function>(I->second.first);
2315 if (Fn->getType() != PFT)
2316 return Error(NameLoc, "type of definition and forward reference of '@" +
2317 utostr(NumberedVals.size()) +"' disagree");
2318 ForwardRefValIDs.erase(I);
2319 }
2320 }
2321
2322 if (Fn == 0)
2323 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2324 else // Move the forward-reference to the correct spot in the module.
2325 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2326
2327 if (FunctionName.empty())
2328 NumberedVals.push_back(Fn);
2329
2330 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2331 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2332 Fn->setCallingConv(CC);
2333 Fn->setAttributes(PAL);
2334 Fn->setAlignment(Alignment);
2335 Fn->setSection(Section);
2336 if (!GC.empty()) Fn->setGC(GC.c_str());
2337
2338 // Add all of the arguments we parsed to the function.
2339 Function::arg_iterator ArgIt = Fn->arg_begin();
2340 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2341 // If the argument has a name, insert it into the argument symbol table.
2342 if (ArgList[i].Name.empty()) continue;
2343
2344 // Set the name, if it conflicted, it will be auto-renamed.
2345 ArgIt->setName(ArgList[i].Name);
2346
2347 if (ArgIt->getNameStr() != ArgList[i].Name)
2348 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2349 ArgList[i].Name + "'");
2350 }
2351
2352 return false;
2353}
2354
2355
2356/// ParseFunctionBody
2357/// ::= '{' BasicBlock+ '}'
2358/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2359///
2360bool LLParser::ParseFunctionBody(Function &Fn) {
2361 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2362 return TokError("expected '{' in function body");
2363 Lex.Lex(); // eat the {.
2364
2365 PerFunctionState PFS(*this, Fn);
2366
2367 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2368 if (ParseBasicBlock(PFS)) return true;
2369
2370 // Eat the }.
2371 Lex.Lex();
2372
2373 // Verify function is ok.
2374 return PFS.VerifyFunctionComplete();
2375}
2376
2377/// ParseBasicBlock
2378/// ::= LabelStr? Instruction*
2379bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2380 // If this basic block starts out with a name, remember it.
2381 std::string Name;
2382 LocTy NameLoc = Lex.getLoc();
2383 if (Lex.getKind() == lltok::LabelStr) {
2384 Name = Lex.getStrVal();
2385 Lex.Lex();
2386 }
2387
2388 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2389 if (BB == 0) return true;
2390
2391 std::string NameStr;
2392
2393 // Parse the instructions in this block until we get a terminator.
2394 Instruction *Inst;
2395 do {
2396 // This instruction may have three possibilities for a name: a) none
2397 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2398 LocTy NameLoc = Lex.getLoc();
2399 int NameID = -1;
2400 NameStr = "";
2401
2402 if (Lex.getKind() == lltok::LocalVarID) {
2403 NameID = Lex.getUIntVal();
2404 Lex.Lex();
2405 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2406 return true;
2407 } else if (Lex.getKind() == lltok::LocalVar ||
2408 // FIXME: REMOVE IN LLVM 3.0
2409 Lex.getKind() == lltok::StringConstant) {
2410 NameStr = Lex.getStrVal();
2411 Lex.Lex();
2412 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2413 return true;
2414 }
2415
2416 if (ParseInstruction(Inst, BB, PFS)) return true;
2417
2418 BB->getInstList().push_back(Inst);
2419
2420 // Set the name on the instruction.
2421 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2422 } while (!isa<TerminatorInst>(Inst));
2423
2424 return false;
2425}
2426
2427//===----------------------------------------------------------------------===//
2428// Instruction Parsing.
2429//===----------------------------------------------------------------------===//
2430
2431/// ParseInstruction - Parse one of the many different instructions.
2432///
2433bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2434 PerFunctionState &PFS) {
2435 lltok::Kind Token = Lex.getKind();
2436 if (Token == lltok::Eof)
2437 return TokError("found end of file when expecting more instructions");
2438 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002439 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 Lex.Lex(); // Eat the keyword.
2441
2442 switch (Token) {
2443 default: return Error(Loc, "expected instruction opcode");
2444 // Terminator Instructions.
2445 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2446 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2447 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2448 case lltok::kw_br: return ParseBr(Inst, PFS);
2449 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2450 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2451 // Binary Operators.
2452 case lltok::kw_add:
2453 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002454 case lltok::kw_mul:
2455 // API compatibility: Accept either integer or floating-point types.
2456 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2457 case lltok::kw_fadd:
2458 case lltok::kw_fsub:
2459 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2460
Chris Lattnerdf986172009-01-02 07:01:27 +00002461 case lltok::kw_udiv:
2462 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002463 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002464 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002465 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002466 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002467 case lltok::kw_shl:
2468 case lltok::kw_lshr:
2469 case lltok::kw_ashr:
2470 case lltok::kw_and:
2471 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002472 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002473 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002474 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002475 // Casts.
2476 case lltok::kw_trunc:
2477 case lltok::kw_zext:
2478 case lltok::kw_sext:
2479 case lltok::kw_fptrunc:
2480 case lltok::kw_fpext:
2481 case lltok::kw_bitcast:
2482 case lltok::kw_uitofp:
2483 case lltok::kw_sitofp:
2484 case lltok::kw_fptoui:
2485 case lltok::kw_fptosi:
2486 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002487 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002488 // Other.
2489 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002490 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002491 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2492 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2493 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2494 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2495 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2496 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2497 // Memory.
2498 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002499 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002500 case lltok::kw_free: return ParseFree(Inst, PFS);
2501 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2502 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2503 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002504 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002505 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002506 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002507 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002508 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002509 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2511 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2512 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2513 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2514 }
2515}
2516
2517/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2518bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002519 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002520 switch (Lex.getKind()) {
2521 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2522 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2523 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2524 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2525 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2526 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2527 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2528 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2529 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2530 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2531 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2532 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2533 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2534 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2535 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2536 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2537 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2538 }
2539 } else {
2540 switch (Lex.getKind()) {
2541 default: TokError("expected icmp predicate (e.g. 'eq')");
2542 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2543 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2544 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2545 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2546 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2547 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2548 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2549 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2550 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2551 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2552 }
2553 }
2554 Lex.Lex();
2555 return false;
2556}
2557
2558//===----------------------------------------------------------------------===//
2559// Terminator Instructions.
2560//===----------------------------------------------------------------------===//
2561
2562/// ParseRet - Parse a return instruction.
2563/// ::= 'ret' void
2564/// ::= 'ret' TypeAndValue
2565/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2566bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2567 PerFunctionState &PFS) {
2568 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002569 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002570
2571 if (Ty == Type::VoidTy) {
2572 Inst = ReturnInst::Create();
2573 return false;
2574 }
2575
2576 Value *RV;
2577 if (ParseValue(Ty, RV, PFS)) return true;
2578
2579 // The normal case is one return value.
2580 if (Lex.getKind() == lltok::comma) {
2581 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2582 // of 'ret {i32,i32} {i32 1, i32 2}'
2583 SmallVector<Value*, 8> RVs;
2584 RVs.push_back(RV);
2585
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002586 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 if (ParseTypeAndValue(RV, PFS)) return true;
2588 RVs.push_back(RV);
2589 }
2590
Owen Andersonb43eae72009-07-02 17:04:01 +00002591 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2593 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2594 BB->getInstList().push_back(I);
2595 RV = I;
2596 }
2597 }
2598 Inst = ReturnInst::Create(RV);
2599 return false;
2600}
2601
2602
2603/// ParseBr
2604/// ::= 'br' TypeAndValue
2605/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2606bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2607 LocTy Loc, Loc2;
2608 Value *Op0, *Op1, *Op2;
2609 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2610
2611 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2612 Inst = BranchInst::Create(BB);
2613 return false;
2614 }
2615
2616 if (Op0->getType() != Type::Int1Ty)
2617 return Error(Loc, "branch condition must have 'i1' type");
2618
2619 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2620 ParseTypeAndValue(Op1, Loc, PFS) ||
2621 ParseToken(lltok::comma, "expected ',' after true destination") ||
2622 ParseTypeAndValue(Op2, Loc2, PFS))
2623 return true;
2624
2625 if (!isa<BasicBlock>(Op1))
2626 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 if (!isa<BasicBlock>(Op2))
2628 return Error(Loc2, "true destination of branch must be a basic block");
2629
2630 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2631 return false;
2632}
2633
2634/// ParseSwitch
2635/// Instruction
2636/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2637/// JumpTable
2638/// ::= (TypeAndValue ',' TypeAndValue)*
2639bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2640 LocTy CondLoc, BBLoc;
2641 Value *Cond, *DefaultBB;
2642 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2643 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2644 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2645 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2646 return true;
2647
2648 if (!isa<IntegerType>(Cond->getType()))
2649 return Error(CondLoc, "switch condition must have integer type");
2650 if (!isa<BasicBlock>(DefaultBB))
2651 return Error(BBLoc, "default destination must be a basic block");
2652
2653 // Parse the jump table pairs.
2654 SmallPtrSet<Value*, 32> SeenCases;
2655 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2656 while (Lex.getKind() != lltok::rsquare) {
2657 Value *Constant, *DestBB;
2658
2659 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2660 ParseToken(lltok::comma, "expected ',' after case value") ||
2661 ParseTypeAndValue(DestBB, BBLoc, PFS))
2662 return true;
2663
2664 if (!SeenCases.insert(Constant))
2665 return Error(CondLoc, "duplicate case value in switch");
2666 if (!isa<ConstantInt>(Constant))
2667 return Error(CondLoc, "case value is not a constant integer");
2668 if (!isa<BasicBlock>(DestBB))
2669 return Error(BBLoc, "case destination is not a basic block");
2670
2671 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2672 cast<BasicBlock>(DestBB)));
2673 }
2674
2675 Lex.Lex(); // Eat the ']'.
2676
2677 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2678 Table.size());
2679 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2680 SI->addCase(Table[i].first, Table[i].second);
2681 Inst = SI;
2682 return false;
2683}
2684
2685/// ParseInvoke
2686/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2687/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2688bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2689 LocTy CallLoc = Lex.getLoc();
2690 unsigned CC, RetAttrs, FnAttrs;
2691 PATypeHolder RetType(Type::VoidTy);
2692 LocTy RetTypeLoc;
2693 ValID CalleeID;
2694 SmallVector<ParamInfo, 16> ArgList;
2695
2696 Value *NormalBB, *UnwindBB;
2697 if (ParseOptionalCallingConv(CC) ||
2698 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002699 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 ParseValID(CalleeID) ||
2701 ParseParameterList(ArgList, PFS) ||
2702 ParseOptionalAttrs(FnAttrs, 2) ||
2703 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2704 ParseTypeAndValue(NormalBB, PFS) ||
2705 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2706 ParseTypeAndValue(UnwindBB, PFS))
2707 return true;
2708
2709 if (!isa<BasicBlock>(NormalBB))
2710 return Error(CallLoc, "normal destination is not a basic block");
2711 if (!isa<BasicBlock>(UnwindBB))
2712 return Error(CallLoc, "unwind destination is not a basic block");
2713
2714 // If RetType is a non-function pointer type, then this is the short syntax
2715 // for the call, which means that RetType is just the return type. Infer the
2716 // rest of the function argument types from the arguments that are present.
2717 const PointerType *PFTy = 0;
2718 const FunctionType *Ty = 0;
2719 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2720 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2721 // Pull out the types of all of the arguments...
2722 std::vector<const Type*> ParamTypes;
2723 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2724 ParamTypes.push_back(ArgList[i].V->getType());
2725
2726 if (!FunctionType::isValidReturnType(RetType))
2727 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2728
Owen Andersonfba933c2009-07-01 23:57:11 +00002729 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2730 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 }
2732
2733 // Look up the callee.
2734 Value *Callee;
2735 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2736
2737 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2738 // function attributes.
2739 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2740 if (FnAttrs & ObsoleteFuncAttrs) {
2741 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2742 FnAttrs &= ~ObsoleteFuncAttrs;
2743 }
2744
2745 // Set up the Attributes for the function.
2746 SmallVector<AttributeWithIndex, 8> Attrs;
2747 if (RetAttrs != Attribute::None)
2748 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2749
2750 SmallVector<Value*, 8> Args;
2751
2752 // Loop through FunctionType's arguments and ensure they are specified
2753 // correctly. Also, gather any parameter attributes.
2754 FunctionType::param_iterator I = Ty->param_begin();
2755 FunctionType::param_iterator E = Ty->param_end();
2756 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2757 const Type *ExpectedTy = 0;
2758 if (I != E) {
2759 ExpectedTy = *I++;
2760 } else if (!Ty->isVarArg()) {
2761 return Error(ArgList[i].Loc, "too many arguments specified");
2762 }
2763
2764 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2765 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2766 ExpectedTy->getDescription() + "'");
2767 Args.push_back(ArgList[i].V);
2768 if (ArgList[i].Attrs != Attribute::None)
2769 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2770 }
2771
2772 if (I != E)
2773 return Error(CallLoc, "not enough parameters specified for call");
2774
2775 if (FnAttrs != Attribute::None)
2776 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2777
2778 // Finish off the Attributes and check them
2779 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2780
2781 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2782 cast<BasicBlock>(UnwindBB),
2783 Args.begin(), Args.end());
2784 II->setCallingConv(CC);
2785 II->setAttributes(PAL);
2786 Inst = II;
2787 return false;
2788}
2789
2790
2791
2792//===----------------------------------------------------------------------===//
2793// Binary Operators.
2794//===----------------------------------------------------------------------===//
2795
2796/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002797/// ::= ArithmeticOps TypeAndValue ',' Value
2798///
2799/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2800/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002801bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002802 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002803 LocTy Loc; Value *LHS, *RHS;
2804 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2805 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2806 ParseValue(LHS->getType(), RHS, PFS))
2807 return true;
2808
Chris Lattnere914b592009-01-05 08:24:46 +00002809 bool Valid;
2810 switch (OperandType) {
2811 default: assert(0 && "Unknown operand type!");
2812 case 0: // int or FP.
2813 Valid = LHS->getType()->isIntOrIntVector() ||
2814 LHS->getType()->isFPOrFPVector();
2815 break;
2816 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2817 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2818 }
2819
2820 if (!Valid)
2821 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002822
2823 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2824 return false;
2825}
2826
2827/// ParseLogical
2828/// ::= ArithmeticOps TypeAndValue ',' Value {
2829bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2830 unsigned Opc) {
2831 LocTy Loc; Value *LHS, *RHS;
2832 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2833 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2834 ParseValue(LHS->getType(), RHS, PFS))
2835 return true;
2836
2837 if (!LHS->getType()->isIntOrIntVector())
2838 return Error(Loc,"instruction requires integer or integer vector operands");
2839
2840 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2841 return false;
2842}
2843
2844
2845/// ParseCompare
2846/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2847/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00002848bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2849 unsigned Opc) {
2850 // Parse the integer/fp comparison predicate.
2851 LocTy Loc;
2852 unsigned Pred;
2853 Value *LHS, *RHS;
2854 if (ParseCmpPredicate(Pred, Opc) ||
2855 ParseTypeAndValue(LHS, Loc, PFS) ||
2856 ParseToken(lltok::comma, "expected ',' after compare value") ||
2857 ParseValue(LHS->getType(), RHS, PFS))
2858 return true;
2859
2860 if (Opc == Instruction::FCmp) {
2861 if (!LHS->getType()->isFPOrFPVector())
2862 return Error(Loc, "fcmp requires floating point operands");
2863 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002864 } else {
2865 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002866 if (!LHS->getType()->isIntOrIntVector() &&
2867 !isa<PointerType>(LHS->getType()))
2868 return Error(Loc, "icmp requires integer operands");
2869 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002870 }
2871 return false;
2872}
2873
2874//===----------------------------------------------------------------------===//
2875// Other Instructions.
2876//===----------------------------------------------------------------------===//
2877
2878
2879/// ParseCast
2880/// ::= CastOpc TypeAndValue 'to' Type
2881bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2882 unsigned Opc) {
2883 LocTy Loc; Value *Op;
2884 PATypeHolder DestTy(Type::VoidTy);
2885 if (ParseTypeAndValue(Op, Loc, PFS) ||
2886 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2887 ParseType(DestTy))
2888 return true;
2889
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002890 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2891 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002892 return Error(Loc, "invalid cast opcode for cast from '" +
2893 Op->getType()->getDescription() + "' to '" +
2894 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002895 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2897 return false;
2898}
2899
2900/// ParseSelect
2901/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2902bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2903 LocTy Loc;
2904 Value *Op0, *Op1, *Op2;
2905 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2906 ParseToken(lltok::comma, "expected ',' after select condition") ||
2907 ParseTypeAndValue(Op1, PFS) ||
2908 ParseToken(lltok::comma, "expected ',' after select value") ||
2909 ParseTypeAndValue(Op2, PFS))
2910 return true;
2911
2912 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2913 return Error(Loc, Reason);
2914
2915 Inst = SelectInst::Create(Op0, Op1, Op2);
2916 return false;
2917}
2918
Chris Lattner0088a5c2009-01-05 08:18:44 +00002919/// ParseVA_Arg
2920/// ::= 'va_arg' TypeAndValue ',' Type
2921bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002922 Value *Op;
2923 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002924 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 if (ParseTypeAndValue(Op, PFS) ||
2926 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002927 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002929
2930 if (!EltTy->isFirstClassType())
2931 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002932
2933 Inst = new VAArgInst(Op, EltTy);
2934 return false;
2935}
2936
2937/// ParseExtractElement
2938/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2939bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2940 LocTy Loc;
2941 Value *Op0, *Op1;
2942 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2943 ParseToken(lltok::comma, "expected ',' after extract value") ||
2944 ParseTypeAndValue(Op1, PFS))
2945 return true;
2946
2947 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2948 return Error(Loc, "invalid extractelement operands");
2949
2950 Inst = new ExtractElementInst(Op0, Op1);
2951 return false;
2952}
2953
2954/// ParseInsertElement
2955/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2956bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2957 LocTy Loc;
2958 Value *Op0, *Op1, *Op2;
2959 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2960 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2961 ParseTypeAndValue(Op1, PFS) ||
2962 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2963 ParseTypeAndValue(Op2, PFS))
2964 return true;
2965
2966 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2967 return Error(Loc, "invalid extractelement operands");
2968
2969 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2970 return false;
2971}
2972
2973/// ParseShuffleVector
2974/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2975bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2976 LocTy Loc;
2977 Value *Op0, *Op1, *Op2;
2978 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2979 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2980 ParseTypeAndValue(Op1, PFS) ||
2981 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2982 ParseTypeAndValue(Op2, PFS))
2983 return true;
2984
2985 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2986 return Error(Loc, "invalid extractelement operands");
2987
2988 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2989 return false;
2990}
2991
2992/// ParsePHI
2993/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2994bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2995 PATypeHolder Ty(Type::VoidTy);
2996 Value *Op0, *Op1;
2997 LocTy TypeLoc = Lex.getLoc();
2998
2999 if (ParseType(Ty) ||
3000 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3001 ParseValue(Ty, Op0, PFS) ||
3002 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3003 ParseValue(Type::LabelTy, Op1, PFS) ||
3004 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3005 return true;
3006
3007 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3008 while (1) {
3009 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3010
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003011 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003012 break;
3013
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003014 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003015 ParseValue(Ty, Op0, PFS) ||
3016 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3017 ParseValue(Type::LabelTy, Op1, PFS) ||
3018 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3019 return true;
3020 }
3021
3022 if (!Ty->isFirstClassType())
3023 return Error(TypeLoc, "phi node must have first class type");
3024
3025 PHINode *PN = PHINode::Create(Ty);
3026 PN->reserveOperandSpace(PHIVals.size());
3027 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3028 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3029 Inst = PN;
3030 return false;
3031}
3032
3033/// ParseCall
3034/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3035/// ParameterList OptionalAttrs
3036bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3037 bool isTail) {
3038 unsigned CC, RetAttrs, FnAttrs;
3039 PATypeHolder RetType(Type::VoidTy);
3040 LocTy RetTypeLoc;
3041 ValID CalleeID;
3042 SmallVector<ParamInfo, 16> ArgList;
3043 LocTy CallLoc = Lex.getLoc();
3044
3045 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3046 ParseOptionalCallingConv(CC) ||
3047 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003048 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 ParseValID(CalleeID) ||
3050 ParseParameterList(ArgList, PFS) ||
3051 ParseOptionalAttrs(FnAttrs, 2))
3052 return true;
3053
3054 // If RetType is a non-function pointer type, then this is the short syntax
3055 // for the call, which means that RetType is just the return type. Infer the
3056 // rest of the function argument types from the arguments that are present.
3057 const PointerType *PFTy = 0;
3058 const FunctionType *Ty = 0;
3059 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3060 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3061 // Pull out the types of all of the arguments...
3062 std::vector<const Type*> ParamTypes;
3063 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3064 ParamTypes.push_back(ArgList[i].V->getType());
3065
3066 if (!FunctionType::isValidReturnType(RetType))
3067 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3068
Owen Andersonfba933c2009-07-01 23:57:11 +00003069 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3070 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 }
3072
3073 // Look up the callee.
3074 Value *Callee;
3075 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3076
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3078 // function attributes.
3079 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3080 if (FnAttrs & ObsoleteFuncAttrs) {
3081 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3082 FnAttrs &= ~ObsoleteFuncAttrs;
3083 }
3084
3085 // Set up the Attributes for the function.
3086 SmallVector<AttributeWithIndex, 8> Attrs;
3087 if (RetAttrs != Attribute::None)
3088 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3089
3090 SmallVector<Value*, 8> Args;
3091
3092 // Loop through FunctionType's arguments and ensure they are specified
3093 // correctly. Also, gather any parameter attributes.
3094 FunctionType::param_iterator I = Ty->param_begin();
3095 FunctionType::param_iterator E = Ty->param_end();
3096 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3097 const Type *ExpectedTy = 0;
3098 if (I != E) {
3099 ExpectedTy = *I++;
3100 } else if (!Ty->isVarArg()) {
3101 return Error(ArgList[i].Loc, "too many arguments specified");
3102 }
3103
3104 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3105 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3106 ExpectedTy->getDescription() + "'");
3107 Args.push_back(ArgList[i].V);
3108 if (ArgList[i].Attrs != Attribute::None)
3109 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3110 }
3111
3112 if (I != E)
3113 return Error(CallLoc, "not enough parameters specified for call");
3114
3115 if (FnAttrs != Attribute::None)
3116 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3117
3118 // Finish off the Attributes and check them
3119 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3120
3121 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3122 CI->setTailCall(isTail);
3123 CI->setCallingConv(CC);
3124 CI->setAttributes(PAL);
3125 Inst = CI;
3126 return false;
3127}
3128
3129//===----------------------------------------------------------------------===//
3130// Memory Instructions.
3131//===----------------------------------------------------------------------===//
3132
3133/// ParseAlloc
3134/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3135/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3136bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3137 unsigned Opc) {
3138 PATypeHolder Ty(Type::VoidTy);
3139 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003140 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003141 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003142 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003143
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003144 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003145 if (Lex.getKind() == lltok::kw_align) {
3146 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003147 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3148 ParseOptionalCommaAlignment(Alignment)) {
3149 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003150 }
3151 }
3152
3153 if (Size && Size->getType() != Type::Int32Ty)
3154 return Error(SizeLoc, "element count must be i32");
3155
3156 if (Opc == Instruction::Malloc)
3157 Inst = new MallocInst(Ty, Size, Alignment);
3158 else
3159 Inst = new AllocaInst(Ty, Size, Alignment);
3160 return false;
3161}
3162
3163/// ParseFree
3164/// ::= 'free' TypeAndValue
3165bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3166 Value *Val; LocTy Loc;
3167 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3168 if (!isa<PointerType>(Val->getType()))
3169 return Error(Loc, "operand to free must be a pointer");
3170 Inst = new FreeInst(Val);
3171 return false;
3172}
3173
3174/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003175/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003176bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3177 bool isVolatile) {
3178 Value *Val; LocTy Loc;
3179 unsigned Alignment;
3180 if (ParseTypeAndValue(Val, Loc, PFS) ||
3181 ParseOptionalCommaAlignment(Alignment))
3182 return true;
3183
3184 if (!isa<PointerType>(Val->getType()) ||
3185 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3186 return Error(Loc, "load operand must be a pointer to a first class type");
3187
3188 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3189 return false;
3190}
3191
3192/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003193/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003194bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3195 bool isVolatile) {
3196 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3197 unsigned Alignment;
3198 if (ParseTypeAndValue(Val, Loc, PFS) ||
3199 ParseToken(lltok::comma, "expected ',' after store operand") ||
3200 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3201 ParseOptionalCommaAlignment(Alignment))
3202 return true;
3203
3204 if (!isa<PointerType>(Ptr->getType()))
3205 return Error(PtrLoc, "store operand must be a pointer");
3206 if (!Val->getType()->isFirstClassType())
3207 return Error(Loc, "store operand must be a first class value");
3208 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3209 return Error(Loc, "stored value and pointer type do not match");
3210
3211 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3212 return false;
3213}
3214
3215/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003216/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003217/// FIXME: Remove support for getresult in LLVM 3.0
3218bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3219 Value *Val; LocTy ValLoc, EltLoc;
3220 unsigned Element;
3221 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3222 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003223 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 return true;
3225
3226 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3227 return Error(ValLoc, "getresult inst requires an aggregate operand");
3228 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3229 return Error(EltLoc, "invalid getresult index for value");
3230 Inst = ExtractValueInst::Create(Val, Element);
3231 return false;
3232}
3233
3234/// ParseGetElementPtr
3235/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3236bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3237 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003238 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003239
3240 if (!isa<PointerType>(Ptr->getType()))
3241 return Error(Loc, "base of getelementptr must be a pointer");
3242
3243 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003244 while (EatIfPresent(lltok::comma)) {
3245 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003246 if (!isa<IntegerType>(Val->getType()))
3247 return Error(EltLoc, "getelementptr index must be an integer");
3248 Indices.push_back(Val);
3249 }
3250
3251 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3252 Indices.begin(), Indices.end()))
3253 return Error(Loc, "invalid getelementptr indices");
3254 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3255 return false;
3256}
3257
3258/// ParseExtractValue
3259/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3260bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3261 Value *Val; LocTy Loc;
3262 SmallVector<unsigned, 4> Indices;
3263 if (ParseTypeAndValue(Val, Loc, PFS) ||
3264 ParseIndexList(Indices))
3265 return true;
3266
3267 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3268 return Error(Loc, "extractvalue operand must be array or struct");
3269
3270 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3271 Indices.end()))
3272 return Error(Loc, "invalid indices for extractvalue");
3273 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3274 return false;
3275}
3276
3277/// ParseInsertValue
3278/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3279bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3280 Value *Val0, *Val1; LocTy Loc0, Loc1;
3281 SmallVector<unsigned, 4> Indices;
3282 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3283 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3284 ParseTypeAndValue(Val1, Loc1, PFS) ||
3285 ParseIndexList(Indices))
3286 return true;
3287
3288 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3289 return Error(Loc0, "extractvalue operand must be array or struct");
3290
3291 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3292 Indices.end()))
3293 return Error(Loc0, "invalid indices for insertvalue");
3294 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3295 return false;
3296}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003297
3298//===----------------------------------------------------------------------===//
3299// Embedded metadata.
3300//===----------------------------------------------------------------------===//
3301
3302/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003303/// ::= Element (',' Element)*
3304/// Element
3305/// ::= 'null' | TypeAndValue
3306bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003307 assert(Lex.getKind() == lltok::lbrace);
3308 Lex.Lex();
3309 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003310 Value *V;
3311 if (Lex.getKind() == lltok::kw_null) {
3312 Lex.Lex();
3313 V = 0;
3314 } else {
3315 Constant *C;
3316 if (ParseGlobalTypeAndValue(C)) return true;
3317 V = C;
3318 }
3319 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003320 } while (EatIfPresent(lltok::comma));
3321
3322 return false;
3323}