blob: af309926afd615f7b82cc30f2366df21864ccd86 [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"
21#include "llvm/Module.h"
22#include "llvm/ValueSymbolTable.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
Chris Lattnerdf986172009-01-02 07:01:27 +000028namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000029 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000033 struct ValID {
34 enum {
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000039 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000040 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
42 } Kind;
43
44 LLParser::LocTy Loc;
45 unsigned UIntVal;
46 std::string StrVal, StrVal2;
47 APSInt APSIntVal;
48 APFloat APFloatVal;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
51 };
52}
53
Chris Lattner3ed88ef2009-01-02 08:05:26 +000054/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000055bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000056 // Prime the lexer.
57 Lex.Lex();
58
Chris Lattnerad7d1e22009-01-04 20:44:11 +000059 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000061}
62
63/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64/// module.
65bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
74
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
78 "'");
79
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
84
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
88
89 return false;
90}
91
92//===----------------------------------------------------------------------===//
93// Top-Level Entities
94//===----------------------------------------------------------------------===//
95
96bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000097 while (1) {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
111
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000116 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000119 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000121 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000122 case lltok::kw_appending: // OptionalLinkage
123 case lltok::kw_dllexport: // OptionalLinkage
124 case lltok::kw_common: // OptionalLinkage
125 case lltok::kw_dllimport: // OptionalLinkage
126 case lltok::kw_extern_weak: // OptionalLinkage
127 case lltok::kw_external: { // OptionalLinkage
128 unsigned Linkage, Visibility;
129 if (ParseOptionalLinkage(Linkage) ||
130 ParseOptionalVisibility(Visibility) ||
131 ParseGlobal("", 0, Linkage, true, Visibility))
132 return true;
133 break;
134 }
135 case lltok::kw_default: // OptionalVisibility
136 case lltok::kw_hidden: // OptionalVisibility
137 case lltok::kw_protected: { // OptionalVisibility
138 unsigned Visibility;
139 if (ParseOptionalVisibility(Visibility) ||
140 ParseGlobal("", 0, 0, false, Visibility))
141 return true;
142 break;
143 }
144
145 case lltok::kw_thread_local: // OptionalThreadLocal
146 case lltok::kw_addrspace: // OptionalAddrSpace
147 case lltok::kw_constant: // GlobalType
148 case lltok::kw_global: // GlobalType
149 if (ParseGlobal("", 0, 0, false, 0)) return true;
150 break;
151 }
152 }
153}
154
155
156/// toplevelentity
157/// ::= 'module' 'asm' STRINGCONSTANT
158bool LLParser::ParseModuleAsm() {
159 assert(Lex.getKind() == lltok::kw_module);
160 Lex.Lex();
161
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000162 std::string AsmStr;
163 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
164 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000165
166 const std::string &AsmSoFar = M->getModuleInlineAsm();
167 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000168 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000170 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000171 return false;
172}
173
174/// toplevelentity
175/// ::= 'target' 'triple' '=' STRINGCONSTANT
176/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
177bool LLParser::ParseTargetDefinition() {
178 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000179 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000180 switch (Lex.Lex()) {
181 default: return TokError("unknown target property");
182 case lltok::kw_triple:
183 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000184 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
185 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 return false;
189 case lltok::kw_datalayout:
190 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000191 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
192 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000193 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000194 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000195 return false;
196 }
197}
198
199/// toplevelentity
200/// ::= 'deplibs' '=' '[' ']'
201/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
202bool LLParser::ParseDepLibs() {
203 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000205 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
206 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
207 return true;
208
209 if (EatIfPresent(lltok::rsquare))
210 return false;
211
212 std::string Str;
213 if (ParseStringConstant(Str)) return true;
214 M->addLibrary(Str);
215
216 while (EatIfPresent(lltok::comma)) {
217 if (ParseStringConstant(Str)) return true;
218 M->addLibrary(Str);
219 }
220
221 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000222}
223
224/// toplevelentity
225/// ::= 'type' type
226bool LLParser::ParseUnnamedType() {
227 assert(Lex.getKind() == lltok::kw_type);
228 LocTy TypeLoc = Lex.getLoc();
229 Lex.Lex(); // eat kw_type
230
231 PATypeHolder Ty(Type::VoidTy);
232 if (ParseType(Ty)) return true;
233
234 unsigned TypeID = NumberedTypes.size();
235
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 // See if this type was previously referenced.
237 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
238 FI = ForwardRefTypeIDs.find(TypeID);
239 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000240 if (FI->second.first.get() == Ty)
241 return Error(TypeLoc, "self referential type is invalid");
242
Chris Lattnerdf986172009-01-02 07:01:27 +0000243 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
244 Ty = FI->second.first.get();
245 ForwardRefTypeIDs.erase(FI);
246 }
247
248 NumberedTypes.push_back(Ty);
249
250 return false;
251}
252
253/// toplevelentity
254/// ::= LocalVar '=' 'type' type
255bool LLParser::ParseNamedType() {
256 std::string Name = Lex.getStrVal();
257 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000258 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000259
260 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261
262 if (ParseToken(lltok::equal, "expected '=' after name") ||
263 ParseToken(lltok::kw_type, "expected 'type' after name") ||
264 ParseType(Ty))
265 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000266
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 // Set the type name, checking for conflicts as we do so.
268 bool AlreadyExists = M->addTypeName(Name, Ty);
269 if (!AlreadyExists) return false;
270
271 // See if this type is a forward reference. We need to eagerly resolve
272 // types to allow recursive type redefinitions below.
273 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
274 FI = ForwardRefTypes.find(Name);
275 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000276 if (FI->second.first.get() == Ty)
277 return Error(NameLoc, "self referential type is invalid");
278
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
280 Ty = FI->second.first.get();
281 ForwardRefTypes.erase(FI);
282 }
283
284 // Inserting a name that is already defined, get the existing name.
285 const Type *Existing = M->getTypeByName(Name);
286 assert(Existing && "Conflict but no matching type?!");
287
288 // Otherwise, this is an attempt to redefine a type. That's okay if
289 // the redefinition is identical to the original.
290 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
291 if (Existing == Ty) return false;
292
293 // Any other kind of (non-equivalent) redefinition is an error.
294 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
295 Ty->getDescription() + "'");
296}
297
298
299/// toplevelentity
300/// ::= 'declare' FunctionHeader
301bool LLParser::ParseDeclare() {
302 assert(Lex.getKind() == lltok::kw_declare);
303 Lex.Lex();
304
305 Function *F;
306 return ParseFunctionHeader(F, false);
307}
308
309/// toplevelentity
310/// ::= 'define' FunctionHeader '{' ...
311bool LLParser::ParseDefine() {
312 assert(Lex.getKind() == lltok::kw_define);
313 Lex.Lex();
314
315 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000316 return ParseFunctionHeader(F, true) ||
317 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000318}
319
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000320/// ParseGlobalType
321/// ::= 'constant'
322/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000323bool LLParser::ParseGlobalType(bool &IsConstant) {
324 if (Lex.getKind() == lltok::kw_constant)
325 IsConstant = true;
326 else if (Lex.getKind() == lltok::kw_global)
327 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000328 else {
329 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000331 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 Lex.Lex();
333 return false;
334}
335
336/// ParseNamedGlobal:
337/// GlobalVar '=' OptionalVisibility ALIAS ...
338/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
339bool LLParser::ParseNamedGlobal() {
340 assert(Lex.getKind() == lltok::GlobalVar);
341 LocTy NameLoc = Lex.getLoc();
342 std::string Name = Lex.getStrVal();
343 Lex.Lex();
344
345 bool HasLinkage;
346 unsigned Linkage, Visibility;
347 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
348 ParseOptionalLinkage(Linkage, HasLinkage) ||
349 ParseOptionalVisibility(Visibility))
350 return true;
351
352 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
353 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
354 return ParseAlias(Name, NameLoc, Visibility);
355}
356
357/// ParseAlias:
358/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
359/// Aliasee
360/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
361///
362/// Everything through visibility has already been parsed.
363///
364bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
365 unsigned Visibility) {
366 assert(Lex.getKind() == lltok::kw_alias);
367 Lex.Lex();
368 unsigned Linkage;
369 LocTy LinkageLoc = Lex.getLoc();
370 if (ParseOptionalLinkage(Linkage))
371 return true;
372
373 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000374 Linkage != GlobalValue::WeakAnyLinkage &&
375 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000376 Linkage != GlobalValue::InternalLinkage &&
377 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000378 return Error(LinkageLoc, "invalid linkage type for alias");
379
380 Constant *Aliasee;
381 LocTy AliaseeLoc = Lex.getLoc();
382 if (Lex.getKind() != lltok::kw_bitcast) {
383 if (ParseGlobalTypeAndValue(Aliasee)) return true;
384 } else {
385 // The bitcast dest type is not present, it is implied by the dest type.
386 ValID ID;
387 if (ParseValID(ID)) return true;
388 if (ID.Kind != ValID::t_Constant)
389 return Error(AliaseeLoc, "invalid aliasee");
390 Aliasee = ID.ConstantVal;
391 }
392
393 if (!isa<PointerType>(Aliasee->getType()))
394 return Error(AliaseeLoc, "alias must have pointer type");
395
396 // Okay, create the alias but do not insert it into the module yet.
397 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
398 (GlobalValue::LinkageTypes)Linkage, Name,
399 Aliasee);
400 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
401
402 // See if this value already exists in the symbol table. If so, it is either
403 // a redefinition or a definition of a forward reference.
404 if (GlobalValue *Val =
405 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
406 // See if this was a redefinition. If so, there is no entry in
407 // ForwardRefVals.
408 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
409 I = ForwardRefVals.find(Name);
410 if (I == ForwardRefVals.end())
411 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
412
413 // Otherwise, this was a definition of forward ref. Verify that types
414 // agree.
415 if (Val->getType() != GA->getType())
416 return Error(NameLoc,
417 "forward reference and definition of alias have different types");
418
419 // If they agree, just RAUW the old value with the alias and remove the
420 // forward ref info.
421 Val->replaceAllUsesWith(GA);
422 Val->eraseFromParent();
423 ForwardRefVals.erase(I);
424 }
425
426 // Insert into the module, we know its name won't collide now.
427 M->getAliasList().push_back(GA);
428 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
429
430 return false;
431}
432
433/// ParseGlobal
434/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
435/// OptionalAddrSpace GlobalType Type Const
436/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
437/// OptionalAddrSpace GlobalType Type Const
438///
439/// Everything through visibility has been parsed already.
440///
441bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
442 unsigned Linkage, bool HasLinkage,
443 unsigned Visibility) {
444 unsigned AddrSpace;
445 bool ThreadLocal, IsConstant;
446 LocTy TyLoc;
447
448 PATypeHolder Ty(Type::VoidTy);
449 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
450 ParseOptionalAddrSpace(AddrSpace) ||
451 ParseGlobalType(IsConstant) ||
452 ParseType(Ty, TyLoc))
453 return true;
454
455 // If the linkage is specified and is external, then no initializer is
456 // present.
457 Constant *Init = 0;
458 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000459 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000460 Linkage != GlobalValue::ExternalLinkage)) {
461 if (ParseGlobalValue(Ty, Init))
462 return true;
463 }
464
Chris Lattnera9a9e072009-03-09 04:49:14 +0000465 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000466 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000467
468 GlobalVariable *GV = 0;
469
470 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000471 if (!Name.empty()) {
472 if ((GV = M->getGlobalVariable(Name, true)) &&
473 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000474 return Error(NameLoc, "redefinition of global '@" + Name + "'");
475 } else {
476 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
477 I = ForwardRefValIDs.find(NumberedVals.size());
478 if (I != ForwardRefValIDs.end()) {
479 GV = cast<GlobalVariable>(I->second.first);
480 ForwardRefValIDs.erase(I);
481 }
482 }
483
484 if (GV == 0) {
485 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
486 M, false, AddrSpace);
487 } else {
488 if (GV->getType()->getElementType() != Ty)
489 return Error(TyLoc,
490 "forward reference and definition of global have different types");
491
492 // Move the forward-reference to the correct spot in the module.
493 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
494 }
495
496 if (Name.empty())
497 NumberedVals.push_back(GV);
498
499 // Set the parsed properties on the global.
500 if (Init)
501 GV->setInitializer(Init);
502 GV->setConstant(IsConstant);
503 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
504 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
505 GV->setThreadLocal(ThreadLocal);
506
507 // Parse attributes on the global.
508 while (Lex.getKind() == lltok::comma) {
509 Lex.Lex();
510
511 if (Lex.getKind() == lltok::kw_section) {
512 Lex.Lex();
513 GV->setSection(Lex.getStrVal());
514 if (ParseToken(lltok::StringConstant, "expected global section string"))
515 return true;
516 } else if (Lex.getKind() == lltok::kw_align) {
517 unsigned Alignment;
518 if (ParseOptionalAlignment(Alignment)) return true;
519 GV->setAlignment(Alignment);
520 } else {
521 TokError("unknown global variable property!");
522 }
523 }
524
525 return false;
526}
527
528
529//===----------------------------------------------------------------------===//
530// GlobalValue Reference/Resolution Routines.
531//===----------------------------------------------------------------------===//
532
533/// GetGlobalVal - Get a value with the specified name or ID, creating a
534/// forward reference record if needed. This can return null if the value
535/// exists but does not have the right type.
536GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
537 LocTy Loc) {
538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
539 if (PTy == 0) {
540 Error(Loc, "global variable reference must have pointer type");
541 return 0;
542 }
543
544 // Look this name up in the normal function symbol table.
545 GlobalValue *Val =
546 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
547
548 // If this is a forward reference for the value, see if we already created a
549 // forward ref record.
550 if (Val == 0) {
551 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
552 I = ForwardRefVals.find(Name);
553 if (I != ForwardRefVals.end())
554 Val = I->second.first;
555 }
556
557 // If we have the value in the symbol table or fwd-ref table, return it.
558 if (Val) {
559 if (Val->getType() == Ty) return Val;
560 Error(Loc, "'@" + Name + "' defined with type '" +
561 Val->getType()->getDescription() + "'");
562 return 0;
563 }
564
565 // Otherwise, create a new forward reference for this value and remember it.
566 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
568 // Function types can return opaque but functions can't.
569 if (isa<OpaqueType>(FT->getReturnType())) {
570 Error(Loc, "function may not return opaque type");
571 return 0;
572 }
573
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000574 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000575 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000576 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000577 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000578 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000579
580 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
581 return FwdVal;
582}
583
584GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
586 if (PTy == 0) {
587 Error(Loc, "global variable reference must have pointer type");
588 return 0;
589 }
590
591 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
592
593 // If this is a forward reference for the value, see if we already created a
594 // forward ref record.
595 if (Val == 0) {
596 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
597 I = ForwardRefValIDs.find(ID);
598 if (I != ForwardRefValIDs.end())
599 Val = I->second.first;
600 }
601
602 // If we have the value in the symbol table or fwd-ref table, return it.
603 if (Val) {
604 if (Val->getType() == Ty) return Val;
605 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
606 Val->getType()->getDescription() + "'");
607 return 0;
608 }
609
610 // Otherwise, create a new forward reference for this value and remember it.
611 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000612 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
613 // Function types can return opaque but functions can't.
614 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000615 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000616 return 0;
617 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000618 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000619 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000621 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000622 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000623
624 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
625 return FwdVal;
626}
627
628
629//===----------------------------------------------------------------------===//
630// Helper Routines.
631//===----------------------------------------------------------------------===//
632
633/// ParseToken - If the current token has the specified kind, eat it and return
634/// success. Otherwise, emit the specified error and return failure.
635bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
636 if (Lex.getKind() != T)
637 return TokError(ErrMsg);
638 Lex.Lex();
639 return false;
640}
641
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000642/// ParseStringConstant
643/// ::= StringConstant
644bool LLParser::ParseStringConstant(std::string &Result) {
645 if (Lex.getKind() != lltok::StringConstant)
646 return TokError("expected string constant");
647 Result = Lex.getStrVal();
648 Lex.Lex();
649 return false;
650}
651
652/// ParseUInt32
653/// ::= uint32
654bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
656 return TokError("expected integer");
657 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
658 if (Val64 != unsigned(Val64))
659 return TokError("expected 32-bit integer (too large)");
660 Val = Val64;
661 Lex.Lex();
662 return false;
663}
664
665
666/// ParseOptionalAddrSpace
667/// := /*empty*/
668/// := 'addrspace' '(' uint32 ')'
669bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
670 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000671 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000673 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000674 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 ParseToken(lltok::rparen, "expected ')' in address space");
676}
677
678/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
679/// indicates what kind of attribute list this is: 0: function arg, 1: result,
680/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000681/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000682bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
683 Attrs = Attribute::None;
684 LocTy AttrLoc = Lex.getLoc();
685
686 while (1) {
687 switch (Lex.getKind()) {
688 case lltok::kw_sext:
689 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000690 // Treat these as signext/zeroext if they occur in the argument list after
691 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
692 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
693 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000695 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000696 if (Lex.getKind() == lltok::kw_sext)
697 Attrs |= Attribute::SExt;
698 else
699 Attrs |= Attribute::ZExt;
700 break;
701 }
702 // FALL THROUGH.
703 default: // End of attributes.
704 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
705 return Error(AttrLoc, "invalid use of function-only attribute");
706
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000707 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000708 return Error(AttrLoc, "invalid use of parameter-only attribute");
709
710 return false;
711 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
712 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
713 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
714 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
715 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
716 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
717 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
718 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
719
720 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
721 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
722 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
723 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
724 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
725 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
726 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
727 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
728 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
729
730
731 case lltok::kw_align: {
732 unsigned Alignment;
733 if (ParseOptionalAlignment(Alignment))
734 return true;
735 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
736 continue;
737 }
738 }
739 Lex.Lex();
740 }
741}
742
743/// ParseOptionalLinkage
744/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000745/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000746/// ::= 'internal'
747/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000748/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000749/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000750/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000751/// ::= 'appending'
752/// ::= 'dllexport'
753/// ::= 'common'
754/// ::= 'dllimport'
755/// ::= 'extern_weak'
756/// ::= 'external'
757bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
758 HasLinkage = false;
759 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000760 default: Res = GlobalValue::ExternalLinkage; return false;
761 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
762 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
763 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
764 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
765 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
766 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000767 case lltok::kw_available_externally:
768 Res = GlobalValue::AvailableExternallyLinkage;
769 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000770 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
771 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000772 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000773 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000774 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000775 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 }
777 Lex.Lex();
778 HasLinkage = true;
779 return false;
780}
781
782/// ParseOptionalVisibility
783/// ::= /*empty*/
784/// ::= 'default'
785/// ::= 'hidden'
786/// ::= 'protected'
787///
788bool LLParser::ParseOptionalVisibility(unsigned &Res) {
789 switch (Lex.getKind()) {
790 default: Res = GlobalValue::DefaultVisibility; return false;
791 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
792 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
793 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
794 }
795 Lex.Lex();
796 return false;
797}
798
799/// ParseOptionalCallingConv
800/// ::= /*empty*/
801/// ::= 'ccc'
802/// ::= 'fastcc'
803/// ::= 'coldcc'
804/// ::= 'x86_stdcallcc'
805/// ::= 'x86_fastcallcc'
806/// ::= 'cc' UINT
807///
808bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
809 switch (Lex.getKind()) {
810 default: CC = CallingConv::C; return false;
811 case lltok::kw_ccc: CC = CallingConv::C; break;
812 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
813 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
814 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
815 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000816 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 }
818 Lex.Lex();
819 return false;
820}
821
822/// ParseOptionalAlignment
823/// ::= /* empty */
824/// ::= 'align' 4
825bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
826 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000827 if (!EatIfPresent(lltok::kw_align))
828 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000829 LocTy AlignLoc = Lex.getLoc();
830 if (ParseUInt32(Alignment)) return true;
831 if (!isPowerOf2_32(Alignment))
832 return Error(AlignLoc, "alignment is not a power of two");
833 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000834}
835
836/// ParseOptionalCommaAlignment
837/// ::= /* empty */
838/// ::= ',' 'align' 4
839bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
840 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000841 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000842 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000844 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000845}
846
847/// ParseIndexList
848/// ::= (',' uint32)+
849bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
850 if (Lex.getKind() != lltok::comma)
851 return TokError("expected ',' as start of index list");
852
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000853 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000854 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000855 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000856 Indices.push_back(Idx);
857 }
858
859 return false;
860}
861
862//===----------------------------------------------------------------------===//
863// Type Parsing.
864//===----------------------------------------------------------------------===//
865
866/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000867bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
868 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000869 if (ParseTypeRec(Result)) return true;
870
871 // Verify no unresolved uprefs.
872 if (!UpRefs.empty())
873 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000874
Chris Lattnera9a9e072009-03-09 04:49:14 +0000875 if (!AllowVoid && Result.get() == Type::VoidTy)
876 return Error(TypeLoc, "void type only allowed for function results");
877
Chris Lattnerdf986172009-01-02 07:01:27 +0000878 return false;
879}
880
881/// HandleUpRefs - Every time we finish a new layer of types, this function is
882/// called. It loops through the UpRefs vector, which is a list of the
883/// currently active types. For each type, if the up-reference is contained in
884/// the newly completed type, we decrement the level count. When the level
885/// count reaches zero, the up-referenced type is the type that is passed in:
886/// thus we can complete the cycle.
887///
888PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
889 // If Ty isn't abstract, or if there are no up-references in it, then there is
890 // nothing to resolve here.
891 if (!ty->isAbstract() || UpRefs.empty()) return ty;
892
893 PATypeHolder Ty(ty);
894#if 0
895 errs() << "Type '" << Ty->getDescription()
896 << "' newly formed. Resolving upreferences.\n"
897 << UpRefs.size() << " upreferences active!\n";
898#endif
899
900 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
901 // to zero), we resolve them all together before we resolve them to Ty. At
902 // the end of the loop, if there is anything to resolve to Ty, it will be in
903 // this variable.
904 OpaqueType *TypeToResolve = 0;
905
906 for (unsigned i = 0; i != UpRefs.size(); ++i) {
907 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
908 bool ContainsType =
909 std::find(Ty->subtype_begin(), Ty->subtype_end(),
910 UpRefs[i].LastContainedTy) != Ty->subtype_end();
911
912#if 0
913 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
914 << UpRefs[i].LastContainedTy->getDescription() << ") = "
915 << (ContainsType ? "true" : "false")
916 << " level=" << UpRefs[i].NestingLevel << "\n";
917#endif
918 if (!ContainsType)
919 continue;
920
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
924
925 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
926 if (Level != 0)
927 continue;
928
929#if 0
930 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
931#endif
932 if (!TypeToResolve)
933 TypeToResolve = UpRefs[i].UpRefTy;
934 else
935 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
937 --i; // Do not skip the next element.
938 }
939
940 if (TypeToResolve)
941 TypeToResolve->refineAbstractTypeTo(Ty);
942
943 return Ty;
944}
945
946
947/// ParseTypeRec - The recursive function used to process the internal
948/// implementation details of types.
949bool LLParser::ParseTypeRec(PATypeHolder &Result) {
950 switch (Lex.getKind()) {
951 default:
952 return TokError("expected type");
953 case lltok::Type:
954 // TypeRec ::= 'float' | 'void' (etc)
955 Result = Lex.getTyVal();
956 Lex.Lex();
957 break;
958 case lltok::kw_opaque:
959 // TypeRec ::= 'opaque'
960 Result = OpaqueType::get();
961 Lex.Lex();
962 break;
963 case lltok::lbrace:
964 // TypeRec ::= '{' ... '}'
965 if (ParseStructType(Result, false))
966 return true;
967 break;
968 case lltok::lsquare:
969 // TypeRec ::= '[' ... ']'
970 Lex.Lex(); // eat the lsquare.
971 if (ParseArrayVectorType(Result, false))
972 return true;
973 break;
974 case lltok::less: // Either vector or packed struct.
975 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000976 Lex.Lex();
977 if (Lex.getKind() == lltok::lbrace) {
978 if (ParseStructType(Result, true) ||
979 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000980 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000981 } else if (ParseArrayVectorType(Result, true))
982 return true;
983 break;
984 case lltok::LocalVar:
985 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
986 // TypeRec ::= %foo
987 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
988 Result = T;
989 } else {
990 Result = OpaqueType::get();
991 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
992 std::make_pair(Result,
993 Lex.getLoc())));
994 M->addTypeName(Lex.getStrVal(), Result.get());
995 }
996 Lex.Lex();
997 break;
998
999 case lltok::LocalVarID:
1000 // TypeRec ::= %4
1001 if (Lex.getUIntVal() < NumberedTypes.size())
1002 Result = NumberedTypes[Lex.getUIntVal()];
1003 else {
1004 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1005 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1006 if (I != ForwardRefTypeIDs.end())
1007 Result = I->second.first;
1008 else {
1009 Result = OpaqueType::get();
1010 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1011 std::make_pair(Result,
1012 Lex.getLoc())));
1013 }
1014 }
1015 Lex.Lex();
1016 break;
1017 case lltok::backslash: {
1018 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001019 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001020 unsigned Val;
1021 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001022 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1023 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1024 Result = OT;
1025 break;
1026 }
1027 }
1028
1029 // Parse the type suffixes.
1030 while (1) {
1031 switch (Lex.getKind()) {
1032 // End of type.
1033 default: return false;
1034
1035 // TypeRec ::= TypeRec '*'
1036 case lltok::star:
1037 if (Result.get() == Type::LabelTy)
1038 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001039 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001040 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001041 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1042 Lex.Lex();
1043 break;
1044
1045 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1046 case lltok::kw_addrspace: {
1047 if (Result.get() == Type::LabelTy)
1048 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001049 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001050 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001051 unsigned AddrSpace;
1052 if (ParseOptionalAddrSpace(AddrSpace) ||
1053 ParseToken(lltok::star, "expected '*' in address space"))
1054 return true;
1055
1056 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1057 break;
1058 }
1059
1060 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1061 case lltok::lparen:
1062 if (ParseFunctionType(Result))
1063 return true;
1064 break;
1065 }
1066 }
1067}
1068
1069/// ParseParameterList
1070/// ::= '(' ')'
1071/// ::= '(' Arg (',' Arg)* ')'
1072/// Arg
1073/// ::= Type OptionalAttributes Value OptionalAttributes
1074bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1075 PerFunctionState &PFS) {
1076 if (ParseToken(lltok::lparen, "expected '(' in call"))
1077 return true;
1078
1079 while (Lex.getKind() != lltok::rparen) {
1080 // If this isn't the first argument, we need a comma.
1081 if (!ArgList.empty() &&
1082 ParseToken(lltok::comma, "expected ',' in argument list"))
1083 return true;
1084
1085 // Parse the argument.
1086 LocTy ArgLoc;
1087 PATypeHolder ArgTy(Type::VoidTy);
1088 unsigned ArgAttrs1, ArgAttrs2;
1089 Value *V;
1090 if (ParseType(ArgTy, ArgLoc) ||
1091 ParseOptionalAttrs(ArgAttrs1, 0) ||
1092 ParseValue(ArgTy, V, PFS) ||
1093 // FIXME: Should not allow attributes after the argument, remove this in
1094 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001095 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001096 return true;
1097 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1098 }
1099
1100 Lex.Lex(); // Lex the ')'.
1101 return false;
1102}
1103
1104
1105
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001106/// ParseArgumentList - Parse the argument list for a function type or function
1107/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001108/// ::= '(' ArgTypeListI ')'
1109/// ArgTypeListI
1110/// ::= /*empty*/
1111/// ::= '...'
1112/// ::= ArgTypeList ',' '...'
1113/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001114///
Chris Lattnerdf986172009-01-02 07:01:27 +00001115bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001116 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 isVarArg = false;
1118 assert(Lex.getKind() == lltok::lparen);
1119 Lex.Lex(); // eat the (.
1120
1121 if (Lex.getKind() == lltok::rparen) {
1122 // empty
1123 } else if (Lex.getKind() == lltok::dotdotdot) {
1124 isVarArg = true;
1125 Lex.Lex();
1126 } else {
1127 LocTy TypeLoc = Lex.getLoc();
1128 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001129 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001130 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001131
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001132 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1133 // types (such as a function returning a pointer to itself). If parsing a
1134 // function prototype, we require fully resolved types.
1135 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001136 ParseOptionalAttrs(Attrs, 0)) return true;
1137
Chris Lattnera9a9e072009-03-09 04:49:14 +00001138 if (ArgTy == Type::VoidTy)
1139 return Error(TypeLoc, "argument can not have void type");
1140
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 if (Lex.getKind() == lltok::LocalVar ||
1142 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1143 Name = Lex.getStrVal();
1144 Lex.Lex();
1145 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001146
1147 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1148 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001149
1150 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1151
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001152 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001153 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001154 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001155 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 break;
1157 }
1158
1159 // Otherwise must be an argument type.
1160 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001161 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001162 ParseOptionalAttrs(Attrs, 0)) return true;
1163
Chris Lattnera9a9e072009-03-09 04:49:14 +00001164 if (ArgTy == Type::VoidTy)
1165 return Error(TypeLoc, "argument can not have void type");
1166
Chris Lattnerdf986172009-01-02 07:01:27 +00001167 if (Lex.getKind() == lltok::LocalVar ||
1168 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1169 Name = Lex.getStrVal();
1170 Lex.Lex();
1171 } else {
1172 Name = "";
1173 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001174
1175 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1176 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001177
1178 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1179 }
1180 }
1181
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001182 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001183}
1184
1185/// ParseFunctionType
1186/// ::= Type ArgumentList OptionalAttrs
1187bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1188 assert(Lex.getKind() == lltok::lparen);
1189
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001190 if (!FunctionType::isValidReturnType(Result))
1191 return TokError("invalid function return type");
1192
Chris Lattnerdf986172009-01-02 07:01:27 +00001193 std::vector<ArgInfo> ArgList;
1194 bool isVarArg;
1195 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001196 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001197 // FIXME: Allow, but ignore attributes on function types!
1198 // FIXME: Remove in LLVM 3.0
1199 ParseOptionalAttrs(Attrs, 2))
1200 return true;
1201
1202 // Reject names on the arguments lists.
1203 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1204 if (!ArgList[i].Name.empty())
1205 return Error(ArgList[i].Loc, "argument name invalid in function type");
1206 if (!ArgList[i].Attrs != 0) {
1207 // Allow but ignore attributes on function types; this permits
1208 // auto-upgrade.
1209 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1210 }
1211 }
1212
1213 std::vector<const Type*> ArgListTy;
1214 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1215 ArgListTy.push_back(ArgList[i].Type);
1216
1217 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1218 return false;
1219}
1220
1221/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1222/// TypeRec
1223/// ::= '{' '}'
1224/// ::= '{' TypeRec (',' TypeRec)* '}'
1225/// ::= '<' '{' '}' '>'
1226/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1227bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1228 assert(Lex.getKind() == lltok::lbrace);
1229 Lex.Lex(); // Consume the '{'
1230
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001231 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001232 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001233 return false;
1234 }
1235
1236 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001237 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 if (ParseTypeRec(Result)) return true;
1239 ParamsList.push_back(Result);
1240
Chris Lattnera9a9e072009-03-09 04:49:14 +00001241 if (Result == Type::VoidTy)
1242 return Error(EltTyLoc, "struct element can not have void type");
1243
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001244 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001245 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001247
1248 if (Result == Type::VoidTy)
1249 return Error(EltTyLoc, "struct element can not have void type");
1250
Chris Lattnerdf986172009-01-02 07:01:27 +00001251 ParamsList.push_back(Result);
1252 }
1253
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001254 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1255 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001256
1257 std::vector<const Type*> ParamsListTy;
1258 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1259 ParamsListTy.push_back(ParamsList[i].get());
1260 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1261 return false;
1262}
1263
1264/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1265/// token has already been consumed.
1266/// TypeRec
1267/// ::= '[' APSINTVAL 'x' Types ']'
1268/// ::= '<' APSINTVAL 'x' Types '>'
1269bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1270 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1271 Lex.getAPSIntVal().getBitWidth() > 64)
1272 return TokError("expected number in address space");
1273
1274 LocTy SizeLoc = Lex.getLoc();
1275 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001276 Lex.Lex();
1277
1278 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1279 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001280
1281 LocTy TypeLoc = Lex.getLoc();
1282 PATypeHolder EltTy(Type::VoidTy);
1283 if (ParseTypeRec(EltTy)) return true;
1284
Chris Lattnera9a9e072009-03-09 04:49:14 +00001285 if (EltTy == Type::VoidTy)
1286 return Error(TypeLoc, "array and vector element type cannot be void");
1287
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001288 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1289 "expected end of sequential type"))
1290 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001291
1292 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001293 if (Size == 0)
1294 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 if ((unsigned)Size != Size)
1296 return Error(SizeLoc, "size too large for vector");
1297 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1298 return Error(TypeLoc, "vector element type must be fp or integer");
1299 Result = VectorType::get(EltTy, unsigned(Size));
1300 } else {
1301 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1302 return Error(TypeLoc, "invalid array element type");
1303 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1304 }
1305 return false;
1306}
1307
1308//===----------------------------------------------------------------------===//
1309// Function Semantic Analysis.
1310//===----------------------------------------------------------------------===//
1311
1312LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1313 : P(p), F(f) {
1314
1315 // Insert unnamed arguments into the NumberedVals list.
1316 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1317 AI != E; ++AI)
1318 if (!AI->hasName())
1319 NumberedVals.push_back(AI);
1320}
1321
1322LLParser::PerFunctionState::~PerFunctionState() {
1323 // If there were any forward referenced non-basicblock values, delete them.
1324 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1325 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1326 if (!isa<BasicBlock>(I->second.first)) {
1327 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1328 ->getType()));
1329 delete I->second.first;
1330 I->second.first = 0;
1331 }
1332
1333 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1334 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1335 if (!isa<BasicBlock>(I->second.first)) {
1336 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1337 ->getType()));
1338 delete I->second.first;
1339 I->second.first = 0;
1340 }
1341}
1342
1343bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1344 if (!ForwardRefVals.empty())
1345 return P.Error(ForwardRefVals.begin()->second.second,
1346 "use of undefined value '%" + ForwardRefVals.begin()->first +
1347 "'");
1348 if (!ForwardRefValIDs.empty())
1349 return P.Error(ForwardRefValIDs.begin()->second.second,
1350 "use of undefined value '%" +
1351 utostr(ForwardRefValIDs.begin()->first) + "'");
1352 return false;
1353}
1354
1355
1356/// GetVal - Get a value with the specified name or ID, creating a
1357/// forward reference record if needed. This can return null if the value
1358/// exists but does not have the right type.
1359Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1360 const Type *Ty, LocTy Loc) {
1361 // Look this name up in the normal function symbol table.
1362 Value *Val = F.getValueSymbolTable().lookup(Name);
1363
1364 // If this is a forward reference for the value, see if we already created a
1365 // forward ref record.
1366 if (Val == 0) {
1367 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1368 I = ForwardRefVals.find(Name);
1369 if (I != ForwardRefVals.end())
1370 Val = I->second.first;
1371 }
1372
1373 // If we have the value in the symbol table or fwd-ref table, return it.
1374 if (Val) {
1375 if (Val->getType() == Ty) return Val;
1376 if (Ty == Type::LabelTy)
1377 P.Error(Loc, "'%" + Name + "' is not a basic block");
1378 else
1379 P.Error(Loc, "'%" + Name + "' defined with type '" +
1380 Val->getType()->getDescription() + "'");
1381 return 0;
1382 }
1383
1384 // Don't make placeholders with invalid type.
1385 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1386 P.Error(Loc, "invalid use of a non-first-class type");
1387 return 0;
1388 }
1389
1390 // Otherwise, create a new forward reference for this value and remember it.
1391 Value *FwdVal;
1392 if (Ty == Type::LabelTy)
1393 FwdVal = BasicBlock::Create(Name, &F);
1394 else
1395 FwdVal = new Argument(Ty, Name);
1396
1397 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1398 return FwdVal;
1399}
1400
1401Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1402 LocTy Loc) {
1403 // Look this name up in the normal function symbol table.
1404 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1405
1406 // If this is a forward reference for the value, see if we already created a
1407 // forward ref record.
1408 if (Val == 0) {
1409 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1410 I = ForwardRefValIDs.find(ID);
1411 if (I != ForwardRefValIDs.end())
1412 Val = I->second.first;
1413 }
1414
1415 // If we have the value in the symbol table or fwd-ref table, return it.
1416 if (Val) {
1417 if (Val->getType() == Ty) return Val;
1418 if (Ty == Type::LabelTy)
1419 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1420 else
1421 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1422 Val->getType()->getDescription() + "'");
1423 return 0;
1424 }
1425
1426 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1427 P.Error(Loc, "invalid use of a non-first-class type");
1428 return 0;
1429 }
1430
1431 // Otherwise, create a new forward reference for this value and remember it.
1432 Value *FwdVal;
1433 if (Ty == Type::LabelTy)
1434 FwdVal = BasicBlock::Create("", &F);
1435 else
1436 FwdVal = new Argument(Ty);
1437
1438 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1439 return FwdVal;
1440}
1441
1442/// SetInstName - After an instruction is parsed and inserted into its
1443/// basic block, this installs its name.
1444bool LLParser::PerFunctionState::SetInstName(int NameID,
1445 const std::string &NameStr,
1446 LocTy NameLoc, Instruction *Inst) {
1447 // If this instruction has void type, it cannot have a name or ID specified.
1448 if (Inst->getType() == Type::VoidTy) {
1449 if (NameID != -1 || !NameStr.empty())
1450 return P.Error(NameLoc, "instructions returning void cannot have a name");
1451 return false;
1452 }
1453
1454 // If this was a numbered instruction, verify that the instruction is the
1455 // expected value and resolve any forward references.
1456 if (NameStr.empty()) {
1457 // If neither a name nor an ID was specified, just use the next ID.
1458 if (NameID == -1)
1459 NameID = NumberedVals.size();
1460
1461 if (unsigned(NameID) != NumberedVals.size())
1462 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1463 utostr(NumberedVals.size()) + "'");
1464
1465 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1466 ForwardRefValIDs.find(NameID);
1467 if (FI != ForwardRefValIDs.end()) {
1468 if (FI->second.first->getType() != Inst->getType())
1469 return P.Error(NameLoc, "instruction forward referenced with type '" +
1470 FI->second.first->getType()->getDescription() + "'");
1471 FI->second.first->replaceAllUsesWith(Inst);
1472 ForwardRefValIDs.erase(FI);
1473 }
1474
1475 NumberedVals.push_back(Inst);
1476 return false;
1477 }
1478
1479 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1480 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1481 FI = ForwardRefVals.find(NameStr);
1482 if (FI != ForwardRefVals.end()) {
1483 if (FI->second.first->getType() != Inst->getType())
1484 return P.Error(NameLoc, "instruction forward referenced with type '" +
1485 FI->second.first->getType()->getDescription() + "'");
1486 FI->second.first->replaceAllUsesWith(Inst);
1487 ForwardRefVals.erase(FI);
1488 }
1489
1490 // Set the name on the instruction.
1491 Inst->setName(NameStr);
1492
1493 if (Inst->getNameStr() != NameStr)
1494 return P.Error(NameLoc, "multiple definition of local value named '" +
1495 NameStr + "'");
1496 return false;
1497}
1498
1499/// GetBB - Get a basic block with the specified name or ID, creating a
1500/// forward reference record if needed.
1501BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1502 LocTy Loc) {
1503 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1504}
1505
1506BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1507 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1508}
1509
1510/// DefineBB - Define the specified basic block, which is either named or
1511/// unnamed. If there is an error, this returns null otherwise it returns
1512/// the block being defined.
1513BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1514 LocTy Loc) {
1515 BasicBlock *BB;
1516 if (Name.empty())
1517 BB = GetBB(NumberedVals.size(), Loc);
1518 else
1519 BB = GetBB(Name, Loc);
1520 if (BB == 0) return 0; // Already diagnosed error.
1521
1522 // Move the block to the end of the function. Forward ref'd blocks are
1523 // inserted wherever they happen to be referenced.
1524 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1525
1526 // Remove the block from forward ref sets.
1527 if (Name.empty()) {
1528 ForwardRefValIDs.erase(NumberedVals.size());
1529 NumberedVals.push_back(BB);
1530 } else {
1531 // BB forward references are already in the function symbol table.
1532 ForwardRefVals.erase(Name);
1533 }
1534
1535 return BB;
1536}
1537
1538//===----------------------------------------------------------------------===//
1539// Constants.
1540//===----------------------------------------------------------------------===//
1541
1542/// ParseValID - Parse an abstract value that doesn't necessarily have a
1543/// type implied. For example, if we parse "4" we don't know what integer type
1544/// it has. The value will later be combined with its type and checked for
1545/// sanity.
1546bool LLParser::ParseValID(ValID &ID) {
1547 ID.Loc = Lex.getLoc();
1548 switch (Lex.getKind()) {
1549 default: return TokError("expected value token");
1550 case lltok::GlobalID: // @42
1551 ID.UIntVal = Lex.getUIntVal();
1552 ID.Kind = ValID::t_GlobalID;
1553 break;
1554 case lltok::GlobalVar: // @foo
1555 ID.StrVal = Lex.getStrVal();
1556 ID.Kind = ValID::t_GlobalName;
1557 break;
1558 case lltok::LocalVarID: // %42
1559 ID.UIntVal = Lex.getUIntVal();
1560 ID.Kind = ValID::t_LocalID;
1561 break;
1562 case lltok::LocalVar: // %foo
1563 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1564 ID.StrVal = Lex.getStrVal();
1565 ID.Kind = ValID::t_LocalName;
1566 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001567 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1568 ID.Kind = ValID::t_Constant;
1569 Lex.Lex();
1570 if (Lex.getKind() == lltok::lbrace) {
1571 // MDNode:
1572 // ::= '!' '{' TypeAndValue (',' TypeAndValue)* '}'
1573 SmallVector<Constant*, 16> Elts;
1574 if (ParseMDNodeVector(Elts) ||
1575 ParseToken(lltok::rbrace, "expected end of metadata node"))
1576 return true;
1577
1578 ID.ConstantVal = MDNode::get(&Elts[0], Elts.size());
1579 return false;
1580 }
1581
1582 // MDString:
1583 // ::= '!' STRINGCONSTANT
1584 std::string Str;
1585 if (ParseStringConstant(Str)) return true;
1586
1587 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1588 return false;
1589 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 case lltok::APSInt:
1591 ID.APSIntVal = Lex.getAPSIntVal();
1592 ID.Kind = ValID::t_APSInt;
1593 break;
1594 case lltok::APFloat:
1595 ID.APFloatVal = Lex.getAPFloatVal();
1596 ID.Kind = ValID::t_APFloat;
1597 break;
1598 case lltok::kw_true:
1599 ID.ConstantVal = ConstantInt::getTrue();
1600 ID.Kind = ValID::t_Constant;
1601 break;
1602 case lltok::kw_false:
1603 ID.ConstantVal = ConstantInt::getFalse();
1604 ID.Kind = ValID::t_Constant;
1605 break;
1606 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1607 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1608 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1609
1610 case lltok::lbrace: {
1611 // ValID ::= '{' ConstVector '}'
1612 Lex.Lex();
1613 SmallVector<Constant*, 16> Elts;
1614 if (ParseGlobalValueVector(Elts) ||
1615 ParseToken(lltok::rbrace, "expected end of struct constant"))
1616 return true;
1617
1618 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1619 ID.Kind = ValID::t_Constant;
1620 return false;
1621 }
1622 case lltok::less: {
1623 // ValID ::= '<' ConstVector '>' --> Vector.
1624 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1625 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001626 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001627
1628 SmallVector<Constant*, 16> Elts;
1629 LocTy FirstEltLoc = Lex.getLoc();
1630 if (ParseGlobalValueVector(Elts) ||
1631 (isPackedStruct &&
1632 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1633 ParseToken(lltok::greater, "expected end of constant"))
1634 return true;
1635
1636 if (isPackedStruct) {
1637 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1638 ID.Kind = ValID::t_Constant;
1639 return false;
1640 }
1641
1642 if (Elts.empty())
1643 return Error(ID.Loc, "constant vector must not be empty");
1644
1645 if (!Elts[0]->getType()->isInteger() &&
1646 !Elts[0]->getType()->isFloatingPoint())
1647 return Error(FirstEltLoc,
1648 "vector elements must have integer or floating point type");
1649
1650 // Verify that all the vector elements have the same type.
1651 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1652 if (Elts[i]->getType() != Elts[0]->getType())
1653 return Error(FirstEltLoc,
1654 "vector element #" + utostr(i) +
1655 " is not of type '" + Elts[0]->getType()->getDescription());
1656
1657 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1658 ID.Kind = ValID::t_Constant;
1659 return false;
1660 }
1661 case lltok::lsquare: { // Array Constant
1662 Lex.Lex();
1663 SmallVector<Constant*, 16> Elts;
1664 LocTy FirstEltLoc = Lex.getLoc();
1665 if (ParseGlobalValueVector(Elts) ||
1666 ParseToken(lltok::rsquare, "expected end of array constant"))
1667 return true;
1668
1669 // Handle empty element.
1670 if (Elts.empty()) {
1671 // Use undef instead of an array because it's inconvenient to determine
1672 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001673 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001674 return false;
1675 }
1676
1677 if (!Elts[0]->getType()->isFirstClassType())
1678 return Error(FirstEltLoc, "invalid array element type: " +
1679 Elts[0]->getType()->getDescription());
1680
1681 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1682
1683 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001684 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001685 if (Elts[i]->getType() != Elts[0]->getType())
1686 return Error(FirstEltLoc,
1687 "array element #" + utostr(i) +
1688 " is not of type '" +Elts[0]->getType()->getDescription());
1689 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001690
Chris Lattnerdf986172009-01-02 07:01:27 +00001691 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1692 ID.Kind = ValID::t_Constant;
1693 return false;
1694 }
1695 case lltok::kw_c: // c "foo"
1696 Lex.Lex();
1697 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1698 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1699 ID.Kind = ValID::t_Constant;
1700 return false;
1701
1702 case lltok::kw_asm: {
1703 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1704 bool HasSideEffect;
1705 Lex.Lex();
1706 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001707 ParseStringConstant(ID.StrVal) ||
1708 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 ParseToken(lltok::StringConstant, "expected constraint string"))
1710 return true;
1711 ID.StrVal2 = Lex.getStrVal();
1712 ID.UIntVal = HasSideEffect;
1713 ID.Kind = ValID::t_InlineAsm;
1714 return false;
1715 }
1716
1717 case lltok::kw_trunc:
1718 case lltok::kw_zext:
1719 case lltok::kw_sext:
1720 case lltok::kw_fptrunc:
1721 case lltok::kw_fpext:
1722 case lltok::kw_bitcast:
1723 case lltok::kw_uitofp:
1724 case lltok::kw_sitofp:
1725 case lltok::kw_fptoui:
1726 case lltok::kw_fptosi:
1727 case lltok::kw_inttoptr:
1728 case lltok::kw_ptrtoint: {
1729 unsigned Opc = Lex.getUIntVal();
1730 PATypeHolder DestTy(Type::VoidTy);
1731 Constant *SrcVal;
1732 Lex.Lex();
1733 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1734 ParseGlobalTypeAndValue(SrcVal) ||
1735 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1736 ParseType(DestTy) ||
1737 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1738 return true;
1739 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1740 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1741 SrcVal->getType()->getDescription() + "' to '" +
1742 DestTy->getDescription() + "'");
1743 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1744 DestTy);
1745 ID.Kind = ValID::t_Constant;
1746 return false;
1747 }
1748 case lltok::kw_extractvalue: {
1749 Lex.Lex();
1750 Constant *Val;
1751 SmallVector<unsigned, 4> Indices;
1752 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1753 ParseGlobalTypeAndValue(Val) ||
1754 ParseIndexList(Indices) ||
1755 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1756 return true;
1757 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1758 return Error(ID.Loc, "extractvalue operand must be array or struct");
1759 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1760 Indices.end()))
1761 return Error(ID.Loc, "invalid indices for extractvalue");
1762 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1763 &Indices[0], Indices.size());
1764 ID.Kind = ValID::t_Constant;
1765 return false;
1766 }
1767 case lltok::kw_insertvalue: {
1768 Lex.Lex();
1769 Constant *Val0, *Val1;
1770 SmallVector<unsigned, 4> Indices;
1771 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1772 ParseGlobalTypeAndValue(Val0) ||
1773 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1774 ParseGlobalTypeAndValue(Val1) ||
1775 ParseIndexList(Indices) ||
1776 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1777 return true;
1778 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1779 return Error(ID.Loc, "extractvalue operand must be array or struct");
1780 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1781 Indices.end()))
1782 return Error(ID.Loc, "invalid indices for insertvalue");
1783 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1784 &Indices[0], Indices.size());
1785 ID.Kind = ValID::t_Constant;
1786 return false;
1787 }
1788 case lltok::kw_icmp:
1789 case lltok::kw_fcmp:
1790 case lltok::kw_vicmp:
1791 case lltok::kw_vfcmp: {
1792 unsigned PredVal, Opc = Lex.getUIntVal();
1793 Constant *Val0, *Val1;
1794 Lex.Lex();
1795 if (ParseCmpPredicate(PredVal, Opc) ||
1796 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1797 ParseGlobalTypeAndValue(Val0) ||
1798 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1799 ParseGlobalTypeAndValue(Val1) ||
1800 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1801 return true;
1802
1803 if (Val0->getType() != Val1->getType())
1804 return Error(ID.Loc, "compare operands must have the same type");
1805
1806 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1807
1808 if (Opc == Instruction::FCmp) {
1809 if (!Val0->getType()->isFPOrFPVector())
1810 return Error(ID.Loc, "fcmp requires floating point operands");
1811 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1812 } else if (Opc == Instruction::ICmp) {
1813 if (!Val0->getType()->isIntOrIntVector() &&
1814 !isa<PointerType>(Val0->getType()))
1815 return Error(ID.Loc, "icmp requires pointer or integer operands");
1816 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1817 } else if (Opc == Instruction::VFCmp) {
1818 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001819 if (!Val0->getType()->isFPOrFPVector() ||
1820 !isa<VectorType>(Val0->getType()))
1821 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1823 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001824 // FIXME: REMOVE VICMP Support
1825 if (!Val0->getType()->isIntOrIntVector() ||
1826 !isa<VectorType>(Val0->getType()))
1827 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1829 }
1830 ID.Kind = ValID::t_Constant;
1831 return false;
1832 }
1833
1834 // Binary Operators.
1835 case lltok::kw_add:
1836 case lltok::kw_sub:
1837 case lltok::kw_mul:
1838 case lltok::kw_udiv:
1839 case lltok::kw_sdiv:
1840 case lltok::kw_fdiv:
1841 case lltok::kw_urem:
1842 case lltok::kw_srem:
1843 case lltok::kw_frem: {
1844 unsigned Opc = Lex.getUIntVal();
1845 Constant *Val0, *Val1;
1846 Lex.Lex();
1847 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1848 ParseGlobalTypeAndValue(Val0) ||
1849 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1850 ParseGlobalTypeAndValue(Val1) ||
1851 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1852 return true;
1853 if (Val0->getType() != Val1->getType())
1854 return Error(ID.Loc, "operands of constexpr must have same type");
1855 if (!Val0->getType()->isIntOrIntVector() &&
1856 !Val0->getType()->isFPOrFPVector())
1857 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1858 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1859 ID.Kind = ValID::t_Constant;
1860 return false;
1861 }
1862
1863 // Logical Operations
1864 case lltok::kw_shl:
1865 case lltok::kw_lshr:
1866 case lltok::kw_ashr:
1867 case lltok::kw_and:
1868 case lltok::kw_or:
1869 case lltok::kw_xor: {
1870 unsigned Opc = Lex.getUIntVal();
1871 Constant *Val0, *Val1;
1872 Lex.Lex();
1873 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1874 ParseGlobalTypeAndValue(Val0) ||
1875 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1876 ParseGlobalTypeAndValue(Val1) ||
1877 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1878 return true;
1879 if (Val0->getType() != Val1->getType())
1880 return Error(ID.Loc, "operands of constexpr must have same type");
1881 if (!Val0->getType()->isIntOrIntVector())
1882 return Error(ID.Loc,
1883 "constexpr requires integer or integer vector operands");
1884 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1885 ID.Kind = ValID::t_Constant;
1886 return false;
1887 }
1888
1889 case lltok::kw_getelementptr:
1890 case lltok::kw_shufflevector:
1891 case lltok::kw_insertelement:
1892 case lltok::kw_extractelement:
1893 case lltok::kw_select: {
1894 unsigned Opc = Lex.getUIntVal();
1895 SmallVector<Constant*, 16> Elts;
1896 Lex.Lex();
1897 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1898 ParseGlobalValueVector(Elts) ||
1899 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1900 return true;
1901
1902 if (Opc == Instruction::GetElementPtr) {
1903 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1904 return Error(ID.Loc, "getelementptr requires pointer operand");
1905
1906 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1907 (Value**)&Elts[1], Elts.size()-1))
1908 return Error(ID.Loc, "invalid indices for getelementptr");
1909 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1910 &Elts[1], Elts.size()-1);
1911 } else if (Opc == Instruction::Select) {
1912 if (Elts.size() != 3)
1913 return Error(ID.Loc, "expected three operands to select");
1914 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1915 Elts[2]))
1916 return Error(ID.Loc, Reason);
1917 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1918 } else if (Opc == Instruction::ShuffleVector) {
1919 if (Elts.size() != 3)
1920 return Error(ID.Loc, "expected three operands to shufflevector");
1921 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1922 return Error(ID.Loc, "invalid operands to shufflevector");
1923 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1924 } else if (Opc == Instruction::ExtractElement) {
1925 if (Elts.size() != 2)
1926 return Error(ID.Loc, "expected two operands to extractelement");
1927 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1928 return Error(ID.Loc, "invalid extractelement operands");
1929 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1930 } else {
1931 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1932 if (Elts.size() != 3)
1933 return Error(ID.Loc, "expected three operands to insertelement");
1934 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1935 return Error(ID.Loc, "invalid insertelement operands");
1936 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1937 }
1938
1939 ID.Kind = ValID::t_Constant;
1940 return false;
1941 }
1942 }
1943
1944 Lex.Lex();
1945 return false;
1946}
1947
1948/// ParseGlobalValue - Parse a global value with the specified type.
1949bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1950 V = 0;
1951 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001952 return ParseValID(ID) ||
1953 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001954}
1955
1956/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1957/// constant.
1958bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1959 Constant *&V) {
1960 if (isa<FunctionType>(Ty))
1961 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1962
1963 switch (ID.Kind) {
1964 default: assert(0 && "Unknown ValID!");
1965 case ValID::t_LocalID:
1966 case ValID::t_LocalName:
1967 return Error(ID.Loc, "invalid use of function-local name");
1968 case ValID::t_InlineAsm:
1969 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1970 case ValID::t_GlobalName:
1971 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1972 return V == 0;
1973 case ValID::t_GlobalID:
1974 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1975 return V == 0;
1976 case ValID::t_APSInt:
1977 if (!isa<IntegerType>(Ty))
1978 return Error(ID.Loc, "integer constant must have integer type");
1979 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1980 V = ConstantInt::get(ID.APSIntVal);
1981 return false;
1982 case ValID::t_APFloat:
1983 if (!Ty->isFloatingPoint() ||
1984 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1985 return Error(ID.Loc, "floating point constant invalid for type");
1986
1987 // The lexer has no type info, so builds all float and double FP constants
1988 // as double. Fix this here. Long double does not need this.
1989 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1990 Ty == Type::FloatTy) {
1991 bool Ignored;
1992 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1993 &Ignored);
1994 }
1995 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001996
1997 if (V->getType() != Ty)
1998 return Error(ID.Loc, "floating point constant does not have type '" +
1999 Ty->getDescription() + "'");
2000
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 return false;
2002 case ValID::t_Null:
2003 if (!isa<PointerType>(Ty))
2004 return Error(ID.Loc, "null must be a pointer type");
2005 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2006 return false;
2007 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002008 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002009 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2010 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002011 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00002012 V = UndefValue::get(Ty);
2013 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002014 case ValID::t_EmptyArray:
2015 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2016 return Error(ID.Loc, "invalid empty array initializer");
2017 V = UndefValue::get(Ty);
2018 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002020 // FIXME: LabelTy should not be a first-class type.
2021 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 return Error(ID.Loc, "invalid type for null constant");
2023 V = Constant::getNullValue(Ty);
2024 return false;
2025 case ValID::t_Constant:
2026 if (ID.ConstantVal->getType() != Ty)
2027 return Error(ID.Loc, "constant expression type mismatch");
2028 V = ID.ConstantVal;
2029 return false;
2030 }
2031}
2032
2033bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2034 PATypeHolder Type(Type::VoidTy);
2035 return ParseType(Type) ||
2036 ParseGlobalValue(Type, V);
2037}
2038
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002039/// ParseGlobalValueVector
2040/// ::= /*empty*/
2041/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002042bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2043 // Empty list.
2044 if (Lex.getKind() == lltok::rbrace ||
2045 Lex.getKind() == lltok::rsquare ||
2046 Lex.getKind() == lltok::greater ||
2047 Lex.getKind() == lltok::rparen)
2048 return false;
2049
2050 Constant *C;
2051 if (ParseGlobalTypeAndValue(C)) return true;
2052 Elts.push_back(C);
2053
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002054 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 if (ParseGlobalTypeAndValue(C)) return true;
2056 Elts.push_back(C);
2057 }
2058
2059 return false;
2060}
2061
2062
2063//===----------------------------------------------------------------------===//
2064// Function Parsing.
2065//===----------------------------------------------------------------------===//
2066
2067bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2068 PerFunctionState &PFS) {
2069 if (ID.Kind == ValID::t_LocalID)
2070 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2071 else if (ID.Kind == ValID::t_LocalName)
2072 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002073 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2075 const FunctionType *FTy =
2076 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2077 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2078 return Error(ID.Loc, "invalid type for inline asm constraint string");
2079 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2080 return false;
2081 } else {
2082 Constant *C;
2083 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2084 V = C;
2085 return false;
2086 }
2087
2088 return V == 0;
2089}
2090
2091bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2092 V = 0;
2093 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002094 return ParseValID(ID) ||
2095 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002096}
2097
2098bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2099 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002100 return ParseType(T) ||
2101 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002102}
2103
2104/// FunctionHeader
2105/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2106/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2107/// OptionalAlign OptGC
2108bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2109 // Parse the linkage.
2110 LocTy LinkageLoc = Lex.getLoc();
2111 unsigned Linkage;
2112
2113 unsigned Visibility, CC, RetAttrs;
2114 PATypeHolder RetType(Type::VoidTy);
2115 LocTy RetTypeLoc = Lex.getLoc();
2116 if (ParseOptionalLinkage(Linkage) ||
2117 ParseOptionalVisibility(Visibility) ||
2118 ParseOptionalCallingConv(CC) ||
2119 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002120 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002121 return true;
2122
2123 // Verify that the linkage is ok.
2124 switch ((GlobalValue::LinkageTypes)Linkage) {
2125 case GlobalValue::ExternalLinkage:
2126 break; // always ok.
2127 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002128 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 if (isDefine)
2130 return Error(LinkageLoc, "invalid linkage for function definition");
2131 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002132 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002134 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002135 case GlobalValue::LinkOnceAnyLinkage:
2136 case GlobalValue::LinkOnceODRLinkage:
2137 case GlobalValue::WeakAnyLinkage:
2138 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002139 case GlobalValue::DLLExportLinkage:
2140 if (!isDefine)
2141 return Error(LinkageLoc, "invalid linkage for function declaration");
2142 break;
2143 case GlobalValue::AppendingLinkage:
2144 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002145 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 return Error(LinkageLoc, "invalid function linkage type");
2147 }
2148
Chris Lattner99bb3152009-01-05 08:00:30 +00002149 if (!FunctionType::isValidReturnType(RetType) ||
2150 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 return Error(RetTypeLoc, "invalid function return type");
2152
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002154
2155 std::string FunctionName;
2156 if (Lex.getKind() == lltok::GlobalVar) {
2157 FunctionName = Lex.getStrVal();
2158 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2159 unsigned NameID = Lex.getUIntVal();
2160
2161 if (NameID != NumberedVals.size())
2162 return TokError("function expected to be numbered '%" +
2163 utostr(NumberedVals.size()) + "'");
2164 } else {
2165 return TokError("expected function name");
2166 }
2167
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002168 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002169
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002170 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 return TokError("expected '(' in function argument list");
2172
2173 std::vector<ArgInfo> ArgList;
2174 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002178 std::string GC;
2179
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002180 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002181 ParseOptionalAttrs(FuncAttrs, 2) ||
2182 (EatIfPresent(lltok::kw_section) &&
2183 ParseStringConstant(Section)) ||
2184 ParseOptionalAlignment(Alignment) ||
2185 (EatIfPresent(lltok::kw_gc) &&
2186 ParseStringConstant(GC)))
2187 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002188
2189 // If the alignment was parsed as an attribute, move to the alignment field.
2190 if (FuncAttrs & Attribute::Alignment) {
2191 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2192 FuncAttrs &= ~Attribute::Alignment;
2193 }
2194
Chris Lattnerdf986172009-01-02 07:01:27 +00002195 // Okay, if we got here, the function is syntactically valid. Convert types
2196 // and do semantic checks.
2197 std::vector<const Type*> ParamTypeList;
2198 SmallVector<AttributeWithIndex, 8> Attrs;
2199 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2200 // attributes.
2201 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2202 if (FuncAttrs & ObsoleteFuncAttrs) {
2203 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2204 FuncAttrs &= ~ObsoleteFuncAttrs;
2205 }
2206
2207 if (RetAttrs != Attribute::None)
2208 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2209
2210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2211 ParamTypeList.push_back(ArgList[i].Type);
2212 if (ArgList[i].Attrs != Attribute::None)
2213 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2214 }
2215
2216 if (FuncAttrs != Attribute::None)
2217 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2218
2219 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2220
Chris Lattnera9a9e072009-03-09 04:49:14 +00002221 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2222 RetType != Type::VoidTy)
2223 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2224
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2226 const PointerType *PFT = PointerType::getUnqual(FT);
2227
2228 Fn = 0;
2229 if (!FunctionName.empty()) {
2230 // If this was a definition of a forward reference, remove the definition
2231 // from the forward reference table and fill in the forward ref.
2232 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2233 ForwardRefVals.find(FunctionName);
2234 if (FRVI != ForwardRefVals.end()) {
2235 Fn = M->getFunction(FunctionName);
2236 ForwardRefVals.erase(FRVI);
2237 } else if ((Fn = M->getFunction(FunctionName))) {
2238 // If this function already exists in the symbol table, then it is
2239 // multiply defined. We accept a few cases for old backwards compat.
2240 // FIXME: Remove this stuff for LLVM 3.0.
2241 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2242 (!Fn->isDeclaration() && isDefine)) {
2243 // If the redefinition has different type or different attributes,
2244 // reject it. If both have bodies, reject it.
2245 return Error(NameLoc, "invalid redefinition of function '" +
2246 FunctionName + "'");
2247 } else if (Fn->isDeclaration()) {
2248 // Make sure to strip off any argument names so we can't get conflicts.
2249 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2250 AI != AE; ++AI)
2251 AI->setName("");
2252 }
2253 }
2254
2255 } else if (FunctionName.empty()) {
2256 // If this is a definition of a forward referenced function, make sure the
2257 // types agree.
2258 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2259 = ForwardRefValIDs.find(NumberedVals.size());
2260 if (I != ForwardRefValIDs.end()) {
2261 Fn = cast<Function>(I->second.first);
2262 if (Fn->getType() != PFT)
2263 return Error(NameLoc, "type of definition and forward reference of '@" +
2264 utostr(NumberedVals.size()) +"' disagree");
2265 ForwardRefValIDs.erase(I);
2266 }
2267 }
2268
2269 if (Fn == 0)
2270 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2271 else // Move the forward-reference to the correct spot in the module.
2272 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2273
2274 if (FunctionName.empty())
2275 NumberedVals.push_back(Fn);
2276
2277 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2278 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2279 Fn->setCallingConv(CC);
2280 Fn->setAttributes(PAL);
2281 Fn->setAlignment(Alignment);
2282 Fn->setSection(Section);
2283 if (!GC.empty()) Fn->setGC(GC.c_str());
2284
2285 // Add all of the arguments we parsed to the function.
2286 Function::arg_iterator ArgIt = Fn->arg_begin();
2287 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2288 // If the argument has a name, insert it into the argument symbol table.
2289 if (ArgList[i].Name.empty()) continue;
2290
2291 // Set the name, if it conflicted, it will be auto-renamed.
2292 ArgIt->setName(ArgList[i].Name);
2293
2294 if (ArgIt->getNameStr() != ArgList[i].Name)
2295 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2296 ArgList[i].Name + "'");
2297 }
2298
2299 return false;
2300}
2301
2302
2303/// ParseFunctionBody
2304/// ::= '{' BasicBlock+ '}'
2305/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2306///
2307bool LLParser::ParseFunctionBody(Function &Fn) {
2308 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2309 return TokError("expected '{' in function body");
2310 Lex.Lex(); // eat the {.
2311
2312 PerFunctionState PFS(*this, Fn);
2313
2314 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2315 if (ParseBasicBlock(PFS)) return true;
2316
2317 // Eat the }.
2318 Lex.Lex();
2319
2320 // Verify function is ok.
2321 return PFS.VerifyFunctionComplete();
2322}
2323
2324/// ParseBasicBlock
2325/// ::= LabelStr? Instruction*
2326bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2327 // If this basic block starts out with a name, remember it.
2328 std::string Name;
2329 LocTy NameLoc = Lex.getLoc();
2330 if (Lex.getKind() == lltok::LabelStr) {
2331 Name = Lex.getStrVal();
2332 Lex.Lex();
2333 }
2334
2335 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2336 if (BB == 0) return true;
2337
2338 std::string NameStr;
2339
2340 // Parse the instructions in this block until we get a terminator.
2341 Instruction *Inst;
2342 do {
2343 // This instruction may have three possibilities for a name: a) none
2344 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2345 LocTy NameLoc = Lex.getLoc();
2346 int NameID = -1;
2347 NameStr = "";
2348
2349 if (Lex.getKind() == lltok::LocalVarID) {
2350 NameID = Lex.getUIntVal();
2351 Lex.Lex();
2352 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2353 return true;
2354 } else if (Lex.getKind() == lltok::LocalVar ||
2355 // FIXME: REMOVE IN LLVM 3.0
2356 Lex.getKind() == lltok::StringConstant) {
2357 NameStr = Lex.getStrVal();
2358 Lex.Lex();
2359 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2360 return true;
2361 }
2362
2363 if (ParseInstruction(Inst, BB, PFS)) return true;
2364
2365 BB->getInstList().push_back(Inst);
2366
2367 // Set the name on the instruction.
2368 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2369 } while (!isa<TerminatorInst>(Inst));
2370
2371 return false;
2372}
2373
2374//===----------------------------------------------------------------------===//
2375// Instruction Parsing.
2376//===----------------------------------------------------------------------===//
2377
2378/// ParseInstruction - Parse one of the many different instructions.
2379///
2380bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2381 PerFunctionState &PFS) {
2382 lltok::Kind Token = Lex.getKind();
2383 if (Token == lltok::Eof)
2384 return TokError("found end of file when expecting more instructions");
2385 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002386 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 Lex.Lex(); // Eat the keyword.
2388
2389 switch (Token) {
2390 default: return Error(Loc, "expected instruction opcode");
2391 // Terminator Instructions.
2392 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2393 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2394 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2395 case lltok::kw_br: return ParseBr(Inst, PFS);
2396 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2397 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2398 // Binary Operators.
2399 case lltok::kw_add:
2400 case lltok::kw_sub:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002401 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
Chris Lattnere914b592009-01-05 08:24:46 +00002402
Chris Lattnerdf986172009-01-02 07:01:27 +00002403 case lltok::kw_udiv:
2404 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002405 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002406 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002407 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002408 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 case lltok::kw_shl:
2410 case lltok::kw_lshr:
2411 case lltok::kw_ashr:
2412 case lltok::kw_and:
2413 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002414 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 case lltok::kw_icmp:
2416 case lltok::kw_fcmp:
2417 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002418 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002419 // Casts.
2420 case lltok::kw_trunc:
2421 case lltok::kw_zext:
2422 case lltok::kw_sext:
2423 case lltok::kw_fptrunc:
2424 case lltok::kw_fpext:
2425 case lltok::kw_bitcast:
2426 case lltok::kw_uitofp:
2427 case lltok::kw_sitofp:
2428 case lltok::kw_fptoui:
2429 case lltok::kw_fptosi:
2430 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002431 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 // Other.
2433 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002434 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2436 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2437 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2438 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2439 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2440 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2441 // Memory.
2442 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002443 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002444 case lltok::kw_free: return ParseFree(Inst, PFS);
2445 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2446 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2447 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002448 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002449 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002450 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002452 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002454 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2455 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2456 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2457 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2458 }
2459}
2460
2461/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2462bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2463 // FIXME: REMOVE vicmp/vfcmp!
2464 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2465 switch (Lex.getKind()) {
2466 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2467 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2468 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2469 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2470 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2471 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2472 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2473 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2474 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2475 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2476 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2477 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2478 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2479 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2480 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2481 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2482 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2483 }
2484 } else {
2485 switch (Lex.getKind()) {
2486 default: TokError("expected icmp predicate (e.g. 'eq')");
2487 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2488 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2489 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2490 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2491 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2492 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2493 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2494 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2495 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2496 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2497 }
2498 }
2499 Lex.Lex();
2500 return false;
2501}
2502
2503//===----------------------------------------------------------------------===//
2504// Terminator Instructions.
2505//===----------------------------------------------------------------------===//
2506
2507/// ParseRet - Parse a return instruction.
2508/// ::= 'ret' void
2509/// ::= 'ret' TypeAndValue
2510/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2511bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2512 PerFunctionState &PFS) {
2513 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002514 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002515
2516 if (Ty == Type::VoidTy) {
2517 Inst = ReturnInst::Create();
2518 return false;
2519 }
2520
2521 Value *RV;
2522 if (ParseValue(Ty, RV, PFS)) return true;
2523
2524 // The normal case is one return value.
2525 if (Lex.getKind() == lltok::comma) {
2526 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2527 // of 'ret {i32,i32} {i32 1, i32 2}'
2528 SmallVector<Value*, 8> RVs;
2529 RVs.push_back(RV);
2530
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002531 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 if (ParseTypeAndValue(RV, PFS)) return true;
2533 RVs.push_back(RV);
2534 }
2535
2536 RV = UndefValue::get(PFS.getFunction().getReturnType());
2537 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2538 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2539 BB->getInstList().push_back(I);
2540 RV = I;
2541 }
2542 }
2543 Inst = ReturnInst::Create(RV);
2544 return false;
2545}
2546
2547
2548/// ParseBr
2549/// ::= 'br' TypeAndValue
2550/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2551bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2552 LocTy Loc, Loc2;
2553 Value *Op0, *Op1, *Op2;
2554 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2555
2556 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2557 Inst = BranchInst::Create(BB);
2558 return false;
2559 }
2560
2561 if (Op0->getType() != Type::Int1Ty)
2562 return Error(Loc, "branch condition must have 'i1' type");
2563
2564 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2565 ParseTypeAndValue(Op1, Loc, PFS) ||
2566 ParseToken(lltok::comma, "expected ',' after true destination") ||
2567 ParseTypeAndValue(Op2, Loc2, PFS))
2568 return true;
2569
2570 if (!isa<BasicBlock>(Op1))
2571 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002572 if (!isa<BasicBlock>(Op2))
2573 return Error(Loc2, "true destination of branch must be a basic block");
2574
2575 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2576 return false;
2577}
2578
2579/// ParseSwitch
2580/// Instruction
2581/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2582/// JumpTable
2583/// ::= (TypeAndValue ',' TypeAndValue)*
2584bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2585 LocTy CondLoc, BBLoc;
2586 Value *Cond, *DefaultBB;
2587 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2588 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2589 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2590 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2591 return true;
2592
2593 if (!isa<IntegerType>(Cond->getType()))
2594 return Error(CondLoc, "switch condition must have integer type");
2595 if (!isa<BasicBlock>(DefaultBB))
2596 return Error(BBLoc, "default destination must be a basic block");
2597
2598 // Parse the jump table pairs.
2599 SmallPtrSet<Value*, 32> SeenCases;
2600 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2601 while (Lex.getKind() != lltok::rsquare) {
2602 Value *Constant, *DestBB;
2603
2604 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2605 ParseToken(lltok::comma, "expected ',' after case value") ||
2606 ParseTypeAndValue(DestBB, BBLoc, PFS))
2607 return true;
2608
2609 if (!SeenCases.insert(Constant))
2610 return Error(CondLoc, "duplicate case value in switch");
2611 if (!isa<ConstantInt>(Constant))
2612 return Error(CondLoc, "case value is not a constant integer");
2613 if (!isa<BasicBlock>(DestBB))
2614 return Error(BBLoc, "case destination is not a basic block");
2615
2616 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2617 cast<BasicBlock>(DestBB)));
2618 }
2619
2620 Lex.Lex(); // Eat the ']'.
2621
2622 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2623 Table.size());
2624 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2625 SI->addCase(Table[i].first, Table[i].second);
2626 Inst = SI;
2627 return false;
2628}
2629
2630/// ParseInvoke
2631/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2632/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2633bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2634 LocTy CallLoc = Lex.getLoc();
2635 unsigned CC, RetAttrs, FnAttrs;
2636 PATypeHolder RetType(Type::VoidTy);
2637 LocTy RetTypeLoc;
2638 ValID CalleeID;
2639 SmallVector<ParamInfo, 16> ArgList;
2640
2641 Value *NormalBB, *UnwindBB;
2642 if (ParseOptionalCallingConv(CC) ||
2643 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002644 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002645 ParseValID(CalleeID) ||
2646 ParseParameterList(ArgList, PFS) ||
2647 ParseOptionalAttrs(FnAttrs, 2) ||
2648 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2649 ParseTypeAndValue(NormalBB, PFS) ||
2650 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2651 ParseTypeAndValue(UnwindBB, PFS))
2652 return true;
2653
2654 if (!isa<BasicBlock>(NormalBB))
2655 return Error(CallLoc, "normal destination is not a basic block");
2656 if (!isa<BasicBlock>(UnwindBB))
2657 return Error(CallLoc, "unwind destination is not a basic block");
2658
2659 // If RetType is a non-function pointer type, then this is the short syntax
2660 // for the call, which means that RetType is just the return type. Infer the
2661 // rest of the function argument types from the arguments that are present.
2662 const PointerType *PFTy = 0;
2663 const FunctionType *Ty = 0;
2664 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2665 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2666 // Pull out the types of all of the arguments...
2667 std::vector<const Type*> ParamTypes;
2668 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2669 ParamTypes.push_back(ArgList[i].V->getType());
2670
2671 if (!FunctionType::isValidReturnType(RetType))
2672 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2673
2674 Ty = FunctionType::get(RetType, ParamTypes, false);
2675 PFTy = PointerType::getUnqual(Ty);
2676 }
2677
2678 // Look up the callee.
2679 Value *Callee;
2680 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2681
2682 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2683 // function attributes.
2684 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2685 if (FnAttrs & ObsoleteFuncAttrs) {
2686 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2687 FnAttrs &= ~ObsoleteFuncAttrs;
2688 }
2689
2690 // Set up the Attributes for the function.
2691 SmallVector<AttributeWithIndex, 8> Attrs;
2692 if (RetAttrs != Attribute::None)
2693 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2694
2695 SmallVector<Value*, 8> Args;
2696
2697 // Loop through FunctionType's arguments and ensure they are specified
2698 // correctly. Also, gather any parameter attributes.
2699 FunctionType::param_iterator I = Ty->param_begin();
2700 FunctionType::param_iterator E = Ty->param_end();
2701 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2702 const Type *ExpectedTy = 0;
2703 if (I != E) {
2704 ExpectedTy = *I++;
2705 } else if (!Ty->isVarArg()) {
2706 return Error(ArgList[i].Loc, "too many arguments specified");
2707 }
2708
2709 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2710 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2711 ExpectedTy->getDescription() + "'");
2712 Args.push_back(ArgList[i].V);
2713 if (ArgList[i].Attrs != Attribute::None)
2714 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2715 }
2716
2717 if (I != E)
2718 return Error(CallLoc, "not enough parameters specified for call");
2719
2720 if (FnAttrs != Attribute::None)
2721 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2722
2723 // Finish off the Attributes and check them
2724 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2725
2726 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2727 cast<BasicBlock>(UnwindBB),
2728 Args.begin(), Args.end());
2729 II->setCallingConv(CC);
2730 II->setAttributes(PAL);
2731 Inst = II;
2732 return false;
2733}
2734
2735
2736
2737//===----------------------------------------------------------------------===//
2738// Binary Operators.
2739//===----------------------------------------------------------------------===//
2740
2741/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002742/// ::= ArithmeticOps TypeAndValue ',' Value
2743///
2744/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2745/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002746bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002747 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 LocTy Loc; Value *LHS, *RHS;
2749 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2750 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2751 ParseValue(LHS->getType(), RHS, PFS))
2752 return true;
2753
Chris Lattnere914b592009-01-05 08:24:46 +00002754 bool Valid;
2755 switch (OperandType) {
2756 default: assert(0 && "Unknown operand type!");
2757 case 0: // int or FP.
2758 Valid = LHS->getType()->isIntOrIntVector() ||
2759 LHS->getType()->isFPOrFPVector();
2760 break;
2761 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2762 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2763 }
2764
2765 if (!Valid)
2766 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002767
2768 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2769 return false;
2770}
2771
2772/// ParseLogical
2773/// ::= ArithmeticOps TypeAndValue ',' Value {
2774bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2775 unsigned Opc) {
2776 LocTy Loc; Value *LHS, *RHS;
2777 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2778 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2779 ParseValue(LHS->getType(), RHS, PFS))
2780 return true;
2781
2782 if (!LHS->getType()->isIntOrIntVector())
2783 return Error(Loc,"instruction requires integer or integer vector operands");
2784
2785 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2786 return false;
2787}
2788
2789
2790/// ParseCompare
2791/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2792/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2793/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2794/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2795bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2796 unsigned Opc) {
2797 // Parse the integer/fp comparison predicate.
2798 LocTy Loc;
2799 unsigned Pred;
2800 Value *LHS, *RHS;
2801 if (ParseCmpPredicate(Pred, Opc) ||
2802 ParseTypeAndValue(LHS, Loc, PFS) ||
2803 ParseToken(lltok::comma, "expected ',' after compare value") ||
2804 ParseValue(LHS->getType(), RHS, PFS))
2805 return true;
2806
2807 if (Opc == Instruction::FCmp) {
2808 if (!LHS->getType()->isFPOrFPVector())
2809 return Error(Loc, "fcmp requires floating point operands");
2810 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2811 } else if (Opc == Instruction::ICmp) {
2812 if (!LHS->getType()->isIntOrIntVector() &&
2813 !isa<PointerType>(LHS->getType()))
2814 return Error(Loc, "icmp requires integer operands");
2815 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2816 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002817 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2818 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2820 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002821 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2822 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002823 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2824 }
2825 return false;
2826}
2827
2828//===----------------------------------------------------------------------===//
2829// Other Instructions.
2830//===----------------------------------------------------------------------===//
2831
2832
2833/// ParseCast
2834/// ::= CastOpc TypeAndValue 'to' Type
2835bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2836 unsigned Opc) {
2837 LocTy Loc; Value *Op;
2838 PATypeHolder DestTy(Type::VoidTy);
2839 if (ParseTypeAndValue(Op, Loc, PFS) ||
2840 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2841 ParseType(DestTy))
2842 return true;
2843
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002844 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2845 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002846 return Error(Loc, "invalid cast opcode for cast from '" +
2847 Op->getType()->getDescription() + "' to '" +
2848 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002849 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002850 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2851 return false;
2852}
2853
2854/// ParseSelect
2855/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2856bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2857 LocTy Loc;
2858 Value *Op0, *Op1, *Op2;
2859 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2860 ParseToken(lltok::comma, "expected ',' after select condition") ||
2861 ParseTypeAndValue(Op1, PFS) ||
2862 ParseToken(lltok::comma, "expected ',' after select value") ||
2863 ParseTypeAndValue(Op2, PFS))
2864 return true;
2865
2866 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2867 return Error(Loc, Reason);
2868
2869 Inst = SelectInst::Create(Op0, Op1, Op2);
2870 return false;
2871}
2872
Chris Lattner0088a5c2009-01-05 08:18:44 +00002873/// ParseVA_Arg
2874/// ::= 'va_arg' TypeAndValue ',' Type
2875bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002876 Value *Op;
2877 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002878 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002879 if (ParseTypeAndValue(Op, PFS) ||
2880 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002881 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002883
2884 if (!EltTy->isFirstClassType())
2885 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002886
2887 Inst = new VAArgInst(Op, EltTy);
2888 return false;
2889}
2890
2891/// ParseExtractElement
2892/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2893bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2894 LocTy Loc;
2895 Value *Op0, *Op1;
2896 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2897 ParseToken(lltok::comma, "expected ',' after extract value") ||
2898 ParseTypeAndValue(Op1, PFS))
2899 return true;
2900
2901 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2902 return Error(Loc, "invalid extractelement operands");
2903
2904 Inst = new ExtractElementInst(Op0, Op1);
2905 return false;
2906}
2907
2908/// ParseInsertElement
2909/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2910bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2911 LocTy Loc;
2912 Value *Op0, *Op1, *Op2;
2913 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2914 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2915 ParseTypeAndValue(Op1, PFS) ||
2916 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2917 ParseTypeAndValue(Op2, PFS))
2918 return true;
2919
2920 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2921 return Error(Loc, "invalid extractelement operands");
2922
2923 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2924 return false;
2925}
2926
2927/// ParseShuffleVector
2928/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2929bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2930 LocTy Loc;
2931 Value *Op0, *Op1, *Op2;
2932 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2933 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2934 ParseTypeAndValue(Op1, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2936 ParseTypeAndValue(Op2, PFS))
2937 return true;
2938
2939 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2940 return Error(Loc, "invalid extractelement operands");
2941
2942 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2943 return false;
2944}
2945
2946/// ParsePHI
2947/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2948bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2949 PATypeHolder Ty(Type::VoidTy);
2950 Value *Op0, *Op1;
2951 LocTy TypeLoc = Lex.getLoc();
2952
2953 if (ParseType(Ty) ||
2954 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2955 ParseValue(Ty, Op0, PFS) ||
2956 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2957 ParseValue(Type::LabelTy, Op1, PFS) ||
2958 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2959 return true;
2960
2961 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2962 while (1) {
2963 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2964
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002965 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002966 break;
2967
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002968 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002969 ParseValue(Ty, Op0, PFS) ||
2970 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2971 ParseValue(Type::LabelTy, Op1, PFS) ||
2972 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2973 return true;
2974 }
2975
2976 if (!Ty->isFirstClassType())
2977 return Error(TypeLoc, "phi node must have first class type");
2978
2979 PHINode *PN = PHINode::Create(Ty);
2980 PN->reserveOperandSpace(PHIVals.size());
2981 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2982 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2983 Inst = PN;
2984 return false;
2985}
2986
2987/// ParseCall
2988/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2989/// ParameterList OptionalAttrs
2990bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2991 bool isTail) {
2992 unsigned CC, RetAttrs, FnAttrs;
2993 PATypeHolder RetType(Type::VoidTy);
2994 LocTy RetTypeLoc;
2995 ValID CalleeID;
2996 SmallVector<ParamInfo, 16> ArgList;
2997 LocTy CallLoc = Lex.getLoc();
2998
2999 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3000 ParseOptionalCallingConv(CC) ||
3001 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003002 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003003 ParseValID(CalleeID) ||
3004 ParseParameterList(ArgList, PFS) ||
3005 ParseOptionalAttrs(FnAttrs, 2))
3006 return true;
3007
3008 // If RetType is a non-function pointer type, then this is the short syntax
3009 // for the call, which means that RetType is just the return type. Infer the
3010 // rest of the function argument types from the arguments that are present.
3011 const PointerType *PFTy = 0;
3012 const FunctionType *Ty = 0;
3013 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3014 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3015 // Pull out the types of all of the arguments...
3016 std::vector<const Type*> ParamTypes;
3017 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3018 ParamTypes.push_back(ArgList[i].V->getType());
3019
3020 if (!FunctionType::isValidReturnType(RetType))
3021 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3022
3023 Ty = FunctionType::get(RetType, ParamTypes, false);
3024 PFTy = PointerType::getUnqual(Ty);
3025 }
3026
3027 // Look up the callee.
3028 Value *Callee;
3029 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3030
Chris Lattnerdf986172009-01-02 07:01:27 +00003031 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3032 // function attributes.
3033 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3034 if (FnAttrs & ObsoleteFuncAttrs) {
3035 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3036 FnAttrs &= ~ObsoleteFuncAttrs;
3037 }
3038
3039 // Set up the Attributes for the function.
3040 SmallVector<AttributeWithIndex, 8> Attrs;
3041 if (RetAttrs != Attribute::None)
3042 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3043
3044 SmallVector<Value*, 8> Args;
3045
3046 // Loop through FunctionType's arguments and ensure they are specified
3047 // correctly. Also, gather any parameter attributes.
3048 FunctionType::param_iterator I = Ty->param_begin();
3049 FunctionType::param_iterator E = Ty->param_end();
3050 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3051 const Type *ExpectedTy = 0;
3052 if (I != E) {
3053 ExpectedTy = *I++;
3054 } else if (!Ty->isVarArg()) {
3055 return Error(ArgList[i].Loc, "too many arguments specified");
3056 }
3057
3058 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3059 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3060 ExpectedTy->getDescription() + "'");
3061 Args.push_back(ArgList[i].V);
3062 if (ArgList[i].Attrs != Attribute::None)
3063 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3064 }
3065
3066 if (I != E)
3067 return Error(CallLoc, "not enough parameters specified for call");
3068
3069 if (FnAttrs != Attribute::None)
3070 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3071
3072 // Finish off the Attributes and check them
3073 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3074
3075 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3076 CI->setTailCall(isTail);
3077 CI->setCallingConv(CC);
3078 CI->setAttributes(PAL);
3079 Inst = CI;
3080 return false;
3081}
3082
3083//===----------------------------------------------------------------------===//
3084// Memory Instructions.
3085//===----------------------------------------------------------------------===//
3086
3087/// ParseAlloc
3088/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3089/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3090bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3091 unsigned Opc) {
3092 PATypeHolder Ty(Type::VoidTy);
3093 Value *Size = 0;
3094 LocTy SizeLoc = 0;
3095 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003096 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003097
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003098 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 if (Lex.getKind() == lltok::kw_align) {
3100 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003101 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3102 ParseOptionalCommaAlignment(Alignment)) {
3103 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 }
3105 }
3106
3107 if (Size && Size->getType() != Type::Int32Ty)
3108 return Error(SizeLoc, "element count must be i32");
3109
3110 if (Opc == Instruction::Malloc)
3111 Inst = new MallocInst(Ty, Size, Alignment);
3112 else
3113 Inst = new AllocaInst(Ty, Size, Alignment);
3114 return false;
3115}
3116
3117/// ParseFree
3118/// ::= 'free' TypeAndValue
3119bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3120 Value *Val; LocTy Loc;
3121 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3122 if (!isa<PointerType>(Val->getType()))
3123 return Error(Loc, "operand to free must be a pointer");
3124 Inst = new FreeInst(Val);
3125 return false;
3126}
3127
3128/// ParseLoad
3129/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3130bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3131 bool isVolatile) {
3132 Value *Val; LocTy Loc;
3133 unsigned Alignment;
3134 if (ParseTypeAndValue(Val, Loc, PFS) ||
3135 ParseOptionalCommaAlignment(Alignment))
3136 return true;
3137
3138 if (!isa<PointerType>(Val->getType()) ||
3139 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3140 return Error(Loc, "load operand must be a pointer to a first class type");
3141
3142 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3143 return false;
3144}
3145
3146/// ParseStore
3147/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3148bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3149 bool isVolatile) {
3150 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3151 unsigned Alignment;
3152 if (ParseTypeAndValue(Val, Loc, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' after store operand") ||
3154 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3155 ParseOptionalCommaAlignment(Alignment))
3156 return true;
3157
3158 if (!isa<PointerType>(Ptr->getType()))
3159 return Error(PtrLoc, "store operand must be a pointer");
3160 if (!Val->getType()->isFirstClassType())
3161 return Error(Loc, "store operand must be a first class value");
3162 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3163 return Error(Loc, "stored value and pointer type do not match");
3164
3165 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3166 return false;
3167}
3168
3169/// ParseGetResult
3170/// ::= 'getresult' TypeAndValue ',' uint
3171/// FIXME: Remove support for getresult in LLVM 3.0
3172bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3173 Value *Val; LocTy ValLoc, EltLoc;
3174 unsigned Element;
3175 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3176 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003177 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 return true;
3179
3180 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3181 return Error(ValLoc, "getresult inst requires an aggregate operand");
3182 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3183 return Error(EltLoc, "invalid getresult index for value");
3184 Inst = ExtractValueInst::Create(Val, Element);
3185 return false;
3186}
3187
3188/// ParseGetElementPtr
3189/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3190bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3191 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003192 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003193
3194 if (!isa<PointerType>(Ptr->getType()))
3195 return Error(Loc, "base of getelementptr must be a pointer");
3196
3197 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003198 while (EatIfPresent(lltok::comma)) {
3199 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003200 if (!isa<IntegerType>(Val->getType()))
3201 return Error(EltLoc, "getelementptr index must be an integer");
3202 Indices.push_back(Val);
3203 }
3204
3205 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3206 Indices.begin(), Indices.end()))
3207 return Error(Loc, "invalid getelementptr indices");
3208 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3209 return false;
3210}
3211
3212/// ParseExtractValue
3213/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3214bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3215 Value *Val; LocTy Loc;
3216 SmallVector<unsigned, 4> Indices;
3217 if (ParseTypeAndValue(Val, Loc, PFS) ||
3218 ParseIndexList(Indices))
3219 return true;
3220
3221 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3222 return Error(Loc, "extractvalue operand must be array or struct");
3223
3224 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3225 Indices.end()))
3226 return Error(Loc, "invalid indices for extractvalue");
3227 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3228 return false;
3229}
3230
3231/// ParseInsertValue
3232/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3233bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3234 Value *Val0, *Val1; LocTy Loc0, Loc1;
3235 SmallVector<unsigned, 4> Indices;
3236 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3237 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3238 ParseTypeAndValue(Val1, Loc1, PFS) ||
3239 ParseIndexList(Indices))
3240 return true;
3241
3242 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3243 return Error(Loc0, "extractvalue operand must be array or struct");
3244
3245 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3246 Indices.end()))
3247 return Error(Loc0, "invalid indices for insertvalue");
3248 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3249 return false;
3250}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003251
3252//===----------------------------------------------------------------------===//
3253// Embedded metadata.
3254//===----------------------------------------------------------------------===//
3255
3256/// ParseMDNodeVector
3257/// ::= TypeAndValue (',' TypeAndValue)*
3258bool LLParser::ParseMDNodeVector(SmallVectorImpl<Constant*> &Elts) {
3259 assert(Lex.getKind() == lltok::lbrace);
3260 Lex.Lex();
3261 do {
3262 Constant *C;
3263 if (ParseGlobalTypeAndValue(C)) return true;
3264 Elts.push_back(C);
3265 } while (EatIfPresent(lltok::comma));
3266
3267 return false;
3268}