blob: 4759d6f19de6b0f7e9de963892f7344b7e576e8b [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"
Nick Lewyckycb337992009-05-10 20:57:05 +000021#include "llvm/MDNode.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000022#include "llvm/Module.h"
23#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattnerdf986172009-01-02 07:01:27 +000029namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030 /// ValID - Represents a reference of a definition of some sort with no type.
31 /// There are several cases where we have to parse the value but where the
32 /// type can depend on later context. This may either be a numeric reference
33 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000034 struct ValID {
35 enum {
36 t_LocalID, t_GlobalID, // ID in UIntVal.
37 t_LocalName, t_GlobalName, // Name in StrVal.
38 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
39 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000040 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000041 t_Constant, // Value in ConstantVal.
42 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
43 } Kind;
44
45 LLParser::LocTy Loc;
46 unsigned UIntVal;
47 std::string StrVal, StrVal2;
48 APSInt APSIntVal;
49 APFloat APFloatVal;
50 Constant *ConstantVal;
51 ValID() : APFloatVal(0.0) {}
52 };
53}
54
Chris Lattner3ed88ef2009-01-02 08:05:26 +000055/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000056bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000057 // Prime the lexer.
58 Lex.Lex();
59
Chris Lattnerad7d1e22009-01-04 20:44:11 +000060 return ParseTopLevelEntities() ||
61 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000062}
63
64/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65/// module.
66bool LLParser::ValidateEndOfModule() {
67 if (!ForwardRefTypes.empty())
68 return Error(ForwardRefTypes.begin()->second.second,
69 "use of undefined type named '" +
70 ForwardRefTypes.begin()->first + "'");
71 if (!ForwardRefTypeIDs.empty())
72 return Error(ForwardRefTypeIDs.begin()->second.second,
73 "use of undefined type '%" +
74 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75
76 if (!ForwardRefVals.empty())
77 return Error(ForwardRefVals.begin()->second.second,
78 "use of undefined value '@" + ForwardRefVals.begin()->first +
79 "'");
80
81 if (!ForwardRefValIDs.empty())
82 return Error(ForwardRefValIDs.begin()->second.second,
83 "use of undefined value '@" +
84 utostr(ForwardRefValIDs.begin()->first) + "'");
85
86 // Look for intrinsic functions and CallInst that need to be upgraded
87 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
88 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
89
90 return false;
91}
92
93//===----------------------------------------------------------------------===//
94// Top-Level Entities
95//===----------------------------------------------------------------------===//
96
97bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000098 while (1) {
99 switch (Lex.getKind()) {
100 default: return TokError("expected top-level entity");
101 case lltok::Eof: return false;
102 //case lltok::kw_define:
103 case lltok::kw_declare: if (ParseDeclare()) return true; break;
104 case lltok::kw_define: if (ParseDefine()) return true; break;
105 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
106 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
107 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
108 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
109 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
110 case lltok::LocalVar: if (ParseNamedType()) return true; break;
111 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112
113 // The Global variable production with no name can have many different
114 // optional leading prefixes, the production is:
115 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
116 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000117 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 case lltok::kw_internal: // OptionalLinkage
119 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000120 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000121 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000122 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::kw_appending: // OptionalLinkage
124 case lltok::kw_dllexport: // OptionalLinkage
125 case lltok::kw_common: // OptionalLinkage
126 case lltok::kw_dllimport: // OptionalLinkage
127 case lltok::kw_extern_weak: // OptionalLinkage
128 case lltok::kw_external: { // OptionalLinkage
129 unsigned Linkage, Visibility;
130 if (ParseOptionalLinkage(Linkage) ||
131 ParseOptionalVisibility(Visibility) ||
132 ParseGlobal("", 0, Linkage, true, Visibility))
133 return true;
134 break;
135 }
136 case lltok::kw_default: // OptionalVisibility
137 case lltok::kw_hidden: // OptionalVisibility
138 case lltok::kw_protected: { // OptionalVisibility
139 unsigned Visibility;
140 if (ParseOptionalVisibility(Visibility) ||
141 ParseGlobal("", 0, 0, false, Visibility))
142 return true;
143 break;
144 }
145
146 case lltok::kw_thread_local: // OptionalThreadLocal
147 case lltok::kw_addrspace: // OptionalAddrSpace
148 case lltok::kw_constant: // GlobalType
149 case lltok::kw_global: // GlobalType
150 if (ParseGlobal("", 0, 0, false, 0)) return true;
151 break;
152 }
153 }
154}
155
156
157/// toplevelentity
158/// ::= 'module' 'asm' STRINGCONSTANT
159bool LLParser::ParseModuleAsm() {
160 assert(Lex.getKind() == lltok::kw_module);
161 Lex.Lex();
162
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000163 std::string AsmStr;
164 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
165 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000166
167 const std::string &AsmSoFar = M->getModuleInlineAsm();
168 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000169 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000170 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000171 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000172 return false;
173}
174
175/// toplevelentity
176/// ::= 'target' 'triple' '=' STRINGCONSTANT
177/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
178bool LLParser::ParseTargetDefinition() {
179 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000180 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 switch (Lex.Lex()) {
182 default: return TokError("unknown target property");
183 case lltok::kw_triple:
184 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000185 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
186 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000187 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000188 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000189 return false;
190 case lltok::kw_datalayout:
191 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000192 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
193 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000194 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000195 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000196 return false;
197 }
198}
199
200/// toplevelentity
201/// ::= 'deplibs' '=' '[' ']'
202/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
203bool LLParser::ParseDepLibs() {
204 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
207 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
208 return true;
209
210 if (EatIfPresent(lltok::rsquare))
211 return false;
212
213 std::string Str;
214 if (ParseStringConstant(Str)) return true;
215 M->addLibrary(Str);
216
217 while (EatIfPresent(lltok::comma)) {
218 if (ParseStringConstant(Str)) return true;
219 M->addLibrary(Str);
220 }
221
222 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000223}
224
225/// toplevelentity
226/// ::= 'type' type
227bool LLParser::ParseUnnamedType() {
228 assert(Lex.getKind() == lltok::kw_type);
229 LocTy TypeLoc = Lex.getLoc();
230 Lex.Lex(); // eat kw_type
231
232 PATypeHolder Ty(Type::VoidTy);
233 if (ParseType(Ty)) return true;
234
235 unsigned TypeID = NumberedTypes.size();
236
Chris Lattnerdf986172009-01-02 07:01:27 +0000237 // See if this type was previously referenced.
238 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239 FI = ForwardRefTypeIDs.find(TypeID);
240 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000241 if (FI->second.first.get() == Ty)
242 return Error(TypeLoc, "self referential type is invalid");
243
Chris Lattnerdf986172009-01-02 07:01:27 +0000244 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
245 Ty = FI->second.first.get();
246 ForwardRefTypeIDs.erase(FI);
247 }
248
249 NumberedTypes.push_back(Ty);
250
251 return false;
252}
253
254/// toplevelentity
255/// ::= LocalVar '=' 'type' type
256bool LLParser::ParseNamedType() {
257 std::string Name = Lex.getStrVal();
258 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000260
261 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262
263 if (ParseToken(lltok::equal, "expected '=' after name") ||
264 ParseToken(lltok::kw_type, "expected 'type' after name") ||
265 ParseType(Ty))
266 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000267
Chris Lattnerdf986172009-01-02 07:01:27 +0000268 // Set the type name, checking for conflicts as we do so.
269 bool AlreadyExists = M->addTypeName(Name, Ty);
270 if (!AlreadyExists) return false;
271
272 // See if this type is a forward reference. We need to eagerly resolve
273 // types to allow recursive type redefinitions below.
274 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
275 FI = ForwardRefTypes.find(Name);
276 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000277 if (FI->second.first.get() == Ty)
278 return Error(NameLoc, "self referential type is invalid");
279
Chris Lattnerdf986172009-01-02 07:01:27 +0000280 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
281 Ty = FI->second.first.get();
282 ForwardRefTypes.erase(FI);
283 }
284
285 // Inserting a name that is already defined, get the existing name.
286 const Type *Existing = M->getTypeByName(Name);
287 assert(Existing && "Conflict but no matching type?!");
288
289 // Otherwise, this is an attempt to redefine a type. That's okay if
290 // the redefinition is identical to the original.
291 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
292 if (Existing == Ty) return false;
293
294 // Any other kind of (non-equivalent) redefinition is an error.
295 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
296 Ty->getDescription() + "'");
297}
298
299
300/// toplevelentity
301/// ::= 'declare' FunctionHeader
302bool LLParser::ParseDeclare() {
303 assert(Lex.getKind() == lltok::kw_declare);
304 Lex.Lex();
305
306 Function *F;
307 return ParseFunctionHeader(F, false);
308}
309
310/// toplevelentity
311/// ::= 'define' FunctionHeader '{' ...
312bool LLParser::ParseDefine() {
313 assert(Lex.getKind() == lltok::kw_define);
314 Lex.Lex();
315
316 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000317 return ParseFunctionHeader(F, true) ||
318 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000319}
320
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000321/// ParseGlobalType
322/// ::= 'constant'
323/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000324bool LLParser::ParseGlobalType(bool &IsConstant) {
325 if (Lex.getKind() == lltok::kw_constant)
326 IsConstant = true;
327 else if (Lex.getKind() == lltok::kw_global)
328 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000329 else {
330 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000332 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 Lex.Lex();
334 return false;
335}
336
337/// ParseNamedGlobal:
338/// GlobalVar '=' OptionalVisibility ALIAS ...
339/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
340bool LLParser::ParseNamedGlobal() {
341 assert(Lex.getKind() == lltok::GlobalVar);
342 LocTy NameLoc = Lex.getLoc();
343 std::string Name = Lex.getStrVal();
344 Lex.Lex();
345
346 bool HasLinkage;
347 unsigned Linkage, Visibility;
348 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
349 ParseOptionalLinkage(Linkage, HasLinkage) ||
350 ParseOptionalVisibility(Visibility))
351 return true;
352
353 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
354 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
355 return ParseAlias(Name, NameLoc, Visibility);
356}
357
358/// ParseAlias:
359/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
360/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000361/// ::= TypeAndValue
362/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
363/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000364///
365/// Everything through visibility has already been parsed.
366///
367bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368 unsigned Visibility) {
369 assert(Lex.getKind() == lltok::kw_alias);
370 Lex.Lex();
371 unsigned Linkage;
372 LocTy LinkageLoc = Lex.getLoc();
373 if (ParseOptionalLinkage(Linkage))
374 return true;
375
376 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000377 Linkage != GlobalValue::WeakAnyLinkage &&
378 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000379 Linkage != GlobalValue::InternalLinkage &&
380 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 return Error(LinkageLoc, "invalid linkage type for alias");
382
383 Constant *Aliasee;
384 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000385 if (Lex.getKind() != lltok::kw_bitcast &&
386 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000387 if (ParseGlobalTypeAndValue(Aliasee)) return true;
388 } else {
389 // The bitcast dest type is not present, it is implied by the dest type.
390 ValID ID;
391 if (ParseValID(ID)) return true;
392 if (ID.Kind != ValID::t_Constant)
393 return Error(AliaseeLoc, "invalid aliasee");
394 Aliasee = ID.ConstantVal;
395 }
396
397 if (!isa<PointerType>(Aliasee->getType()))
398 return Error(AliaseeLoc, "alias must have pointer type");
399
400 // Okay, create the alias but do not insert it into the module yet.
401 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
402 (GlobalValue::LinkageTypes)Linkage, Name,
403 Aliasee);
404 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
405
406 // See if this value already exists in the symbol table. If so, it is either
407 // a redefinition or a definition of a forward reference.
408 if (GlobalValue *Val =
409 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
410 // See if this was a redefinition. If so, there is no entry in
411 // ForwardRefVals.
412 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
413 I = ForwardRefVals.find(Name);
414 if (I == ForwardRefVals.end())
415 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
416
417 // Otherwise, this was a definition of forward ref. Verify that types
418 // agree.
419 if (Val->getType() != GA->getType())
420 return Error(NameLoc,
421 "forward reference and definition of alias have different types");
422
423 // If they agree, just RAUW the old value with the alias and remove the
424 // forward ref info.
425 Val->replaceAllUsesWith(GA);
426 Val->eraseFromParent();
427 ForwardRefVals.erase(I);
428 }
429
430 // Insert into the module, we know its name won't collide now.
431 M->getAliasList().push_back(GA);
432 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
433
434 return false;
435}
436
437/// ParseGlobal
438/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
439/// OptionalAddrSpace GlobalType Type Const
440/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
441/// OptionalAddrSpace GlobalType Type Const
442///
443/// Everything through visibility has been parsed already.
444///
445bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
446 unsigned Linkage, bool HasLinkage,
447 unsigned Visibility) {
448 unsigned AddrSpace;
449 bool ThreadLocal, IsConstant;
450 LocTy TyLoc;
451
452 PATypeHolder Ty(Type::VoidTy);
453 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
454 ParseOptionalAddrSpace(AddrSpace) ||
455 ParseGlobalType(IsConstant) ||
456 ParseType(Ty, TyLoc))
457 return true;
458
459 // If the linkage is specified and is external, then no initializer is
460 // present.
461 Constant *Init = 0;
462 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000463 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000464 Linkage != GlobalValue::ExternalLinkage)) {
465 if (ParseGlobalValue(Ty, Init))
466 return true;
467 }
468
Chris Lattnera9a9e072009-03-09 04:49:14 +0000469 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000470 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000471
472 GlobalVariable *GV = 0;
473
474 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000475 if (!Name.empty()) {
476 if ((GV = M->getGlobalVariable(Name, true)) &&
477 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000478 return Error(NameLoc, "redefinition of global '@" + Name + "'");
479 } else {
480 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
481 I = ForwardRefValIDs.find(NumberedVals.size());
482 if (I != ForwardRefValIDs.end()) {
483 GV = cast<GlobalVariable>(I->second.first);
484 ForwardRefValIDs.erase(I);
485 }
486 }
487
488 if (GV == 0) {
489 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
490 M, false, AddrSpace);
491 } else {
492 if (GV->getType()->getElementType() != Ty)
493 return Error(TyLoc,
494 "forward reference and definition of global have different types");
495
496 // Move the forward-reference to the correct spot in the module.
497 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
498 }
499
500 if (Name.empty())
501 NumberedVals.push_back(GV);
502
503 // Set the parsed properties on the global.
504 if (Init)
505 GV->setInitializer(Init);
506 GV->setConstant(IsConstant);
507 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
508 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
509 GV->setThreadLocal(ThreadLocal);
510
511 // Parse attributes on the global.
512 while (Lex.getKind() == lltok::comma) {
513 Lex.Lex();
514
515 if (Lex.getKind() == lltok::kw_section) {
516 Lex.Lex();
517 GV->setSection(Lex.getStrVal());
518 if (ParseToken(lltok::StringConstant, "expected global section string"))
519 return true;
520 } else if (Lex.getKind() == lltok::kw_align) {
521 unsigned Alignment;
522 if (ParseOptionalAlignment(Alignment)) return true;
523 GV->setAlignment(Alignment);
524 } else {
525 TokError("unknown global variable property!");
526 }
527 }
528
529 return false;
530}
531
532
533//===----------------------------------------------------------------------===//
534// GlobalValue Reference/Resolution Routines.
535//===----------------------------------------------------------------------===//
536
537/// GetGlobalVal - Get a value with the specified name or ID, creating a
538/// forward reference record if needed. This can return null if the value
539/// exists but does not have the right type.
540GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
541 LocTy Loc) {
542 const PointerType *PTy = dyn_cast<PointerType>(Ty);
543 if (PTy == 0) {
544 Error(Loc, "global variable reference must have pointer type");
545 return 0;
546 }
547
548 // Look this name up in the normal function symbol table.
549 GlobalValue *Val =
550 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
551
552 // If this is a forward reference for the value, see if we already created a
553 // forward ref record.
554 if (Val == 0) {
555 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
556 I = ForwardRefVals.find(Name);
557 if (I != ForwardRefVals.end())
558 Val = I->second.first;
559 }
560
561 // If we have the value in the symbol table or fwd-ref table, return it.
562 if (Val) {
563 if (Val->getType() == Ty) return Val;
564 Error(Loc, "'@" + Name + "' defined with type '" +
565 Val->getType()->getDescription() + "'");
566 return 0;
567 }
568
569 // Otherwise, create a new forward reference for this value and remember it.
570 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000571 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
572 // Function types can return opaque but functions can't.
573 if (isa<OpaqueType>(FT->getReturnType())) {
574 Error(Loc, "function may not return opaque type");
575 return 0;
576 }
577
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000578 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000579 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000580 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000581 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000582 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000583
584 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
585 return FwdVal;
586}
587
588GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
589 const PointerType *PTy = dyn_cast<PointerType>(Ty);
590 if (PTy == 0) {
591 Error(Loc, "global variable reference must have pointer type");
592 return 0;
593 }
594
595 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
596
597 // If this is a forward reference for the value, see if we already created a
598 // forward ref record.
599 if (Val == 0) {
600 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
601 I = ForwardRefValIDs.find(ID);
602 if (I != ForwardRefValIDs.end())
603 Val = I->second.first;
604 }
605
606 // If we have the value in the symbol table or fwd-ref table, return it.
607 if (Val) {
608 if (Val->getType() == Ty) return Val;
609 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
610 Val->getType()->getDescription() + "'");
611 return 0;
612 }
613
614 // Otherwise, create a new forward reference for this value and remember it.
615 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000616 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
617 // Function types can return opaque but functions can't.
618 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000619 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000620 return 0;
621 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000622 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000623 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000624 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000625 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000626 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000627
628 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
629 return FwdVal;
630}
631
632
633//===----------------------------------------------------------------------===//
634// Helper Routines.
635//===----------------------------------------------------------------------===//
636
637/// ParseToken - If the current token has the specified kind, eat it and return
638/// success. Otherwise, emit the specified error and return failure.
639bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
640 if (Lex.getKind() != T)
641 return TokError(ErrMsg);
642 Lex.Lex();
643 return false;
644}
645
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000646/// ParseStringConstant
647/// ::= StringConstant
648bool LLParser::ParseStringConstant(std::string &Result) {
649 if (Lex.getKind() != lltok::StringConstant)
650 return TokError("expected string constant");
651 Result = Lex.getStrVal();
652 Lex.Lex();
653 return false;
654}
655
656/// ParseUInt32
657/// ::= uint32
658bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
660 return TokError("expected integer");
661 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
662 if (Val64 != unsigned(Val64))
663 return TokError("expected 32-bit integer (too large)");
664 Val = Val64;
665 Lex.Lex();
666 return false;
667}
668
669
670/// ParseOptionalAddrSpace
671/// := /*empty*/
672/// := 'addrspace' '(' uint32 ')'
673bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
674 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000675 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000678 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000679 ParseToken(lltok::rparen, "expected ')' in address space");
680}
681
682/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
683/// indicates what kind of attribute list this is: 0: function arg, 1: result,
684/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000685/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000686bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
687 Attrs = Attribute::None;
688 LocTy AttrLoc = Lex.getLoc();
689
690 while (1) {
691 switch (Lex.getKind()) {
692 case lltok::kw_sext:
693 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000694 // Treat these as signext/zeroext if they occur in the argument list after
695 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
696 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
697 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000698 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000699 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 if (Lex.getKind() == lltok::kw_sext)
701 Attrs |= Attribute::SExt;
702 else
703 Attrs |= Attribute::ZExt;
704 break;
705 }
706 // FALL THROUGH.
707 default: // End of attributes.
708 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
709 return Error(AttrLoc, "invalid use of function-only attribute");
710
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000711 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000712 return Error(AttrLoc, "invalid use of parameter-only attribute");
713
714 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000715 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
716 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
717 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
718 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
719 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
720 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
721 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
722 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000723
Devang Patel578efa92009-06-05 21:57:13 +0000724 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
725 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
726 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
727 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
728 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
729 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
730 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
731 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
732 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
733 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
734 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000735
736 case lltok::kw_align: {
737 unsigned Alignment;
738 if (ParseOptionalAlignment(Alignment))
739 return true;
740 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
741 continue;
742 }
743 }
744 Lex.Lex();
745 }
746}
747
748/// ParseOptionalLinkage
749/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000750/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000751/// ::= 'internal'
752/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000753/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000754/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000755/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000756/// ::= 'appending'
757/// ::= 'dllexport'
758/// ::= 'common'
759/// ::= 'dllimport'
760/// ::= 'extern_weak'
761/// ::= 'external'
762bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
763 HasLinkage = false;
764 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000765 default: Res = GlobalValue::ExternalLinkage; return false;
766 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
767 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
768 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
769 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
770 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
771 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000772 case lltok::kw_available_externally:
773 Res = GlobalValue::AvailableExternallyLinkage;
774 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000775 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
776 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000777 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000778 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000779 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000780 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000781 }
782 Lex.Lex();
783 HasLinkage = true;
784 return false;
785}
786
787/// ParseOptionalVisibility
788/// ::= /*empty*/
789/// ::= 'default'
790/// ::= 'hidden'
791/// ::= 'protected'
792///
793bool LLParser::ParseOptionalVisibility(unsigned &Res) {
794 switch (Lex.getKind()) {
795 default: Res = GlobalValue::DefaultVisibility; return false;
796 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
797 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
798 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
799 }
800 Lex.Lex();
801 return false;
802}
803
804/// ParseOptionalCallingConv
805/// ::= /*empty*/
806/// ::= 'ccc'
807/// ::= 'fastcc'
808/// ::= 'coldcc'
809/// ::= 'x86_stdcallcc'
810/// ::= 'x86_fastcallcc'
811/// ::= 'cc' UINT
812///
813bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
814 switch (Lex.getKind()) {
815 default: CC = CallingConv::C; return false;
816 case lltok::kw_ccc: CC = CallingConv::C; break;
817 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
818 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
819 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
820 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000821 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 }
823 Lex.Lex();
824 return false;
825}
826
827/// ParseOptionalAlignment
828/// ::= /* empty */
829/// ::= 'align' 4
830bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
831 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000832 if (!EatIfPresent(lltok::kw_align))
833 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000834 LocTy AlignLoc = Lex.getLoc();
835 if (ParseUInt32(Alignment)) return true;
836 if (!isPowerOf2_32(Alignment))
837 return Error(AlignLoc, "alignment is not a power of two");
838 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000839}
840
841/// ParseOptionalCommaAlignment
842/// ::= /* empty */
843/// ::= ',' 'align' 4
844bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
845 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000846 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000847 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000848 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000849 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000850}
851
852/// ParseIndexList
853/// ::= (',' uint32)+
854bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
855 if (Lex.getKind() != lltok::comma)
856 return TokError("expected ',' as start of index list");
857
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000858 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000860 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000861 Indices.push_back(Idx);
862 }
863
864 return false;
865}
866
867//===----------------------------------------------------------------------===//
868// Type Parsing.
869//===----------------------------------------------------------------------===//
870
871/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000872bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
873 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000874 if (ParseTypeRec(Result)) return true;
875
876 // Verify no unresolved uprefs.
877 if (!UpRefs.empty())
878 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000879
Chris Lattnera9a9e072009-03-09 04:49:14 +0000880 if (!AllowVoid && Result.get() == Type::VoidTy)
881 return Error(TypeLoc, "void type only allowed for function results");
882
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 return false;
884}
885
886/// HandleUpRefs - Every time we finish a new layer of types, this function is
887/// called. It loops through the UpRefs vector, which is a list of the
888/// currently active types. For each type, if the up-reference is contained in
889/// the newly completed type, we decrement the level count. When the level
890/// count reaches zero, the up-referenced type is the type that is passed in:
891/// thus we can complete the cycle.
892///
893PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
894 // If Ty isn't abstract, or if there are no up-references in it, then there is
895 // nothing to resolve here.
896 if (!ty->isAbstract() || UpRefs.empty()) return ty;
897
898 PATypeHolder Ty(ty);
899#if 0
900 errs() << "Type '" << Ty->getDescription()
901 << "' newly formed. Resolving upreferences.\n"
902 << UpRefs.size() << " upreferences active!\n";
903#endif
904
905 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
906 // to zero), we resolve them all together before we resolve them to Ty. At
907 // the end of the loop, if there is anything to resolve to Ty, it will be in
908 // this variable.
909 OpaqueType *TypeToResolve = 0;
910
911 for (unsigned i = 0; i != UpRefs.size(); ++i) {
912 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
913 bool ContainsType =
914 std::find(Ty->subtype_begin(), Ty->subtype_end(),
915 UpRefs[i].LastContainedTy) != Ty->subtype_end();
916
917#if 0
918 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
919 << UpRefs[i].LastContainedTy->getDescription() << ") = "
920 << (ContainsType ? "true" : "false")
921 << " level=" << UpRefs[i].NestingLevel << "\n";
922#endif
923 if (!ContainsType)
924 continue;
925
926 // Decrement level of upreference
927 unsigned Level = --UpRefs[i].NestingLevel;
928 UpRefs[i].LastContainedTy = Ty;
929
930 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
931 if (Level != 0)
932 continue;
933
934#if 0
935 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
936#endif
937 if (!TypeToResolve)
938 TypeToResolve = UpRefs[i].UpRefTy;
939 else
940 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
941 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
942 --i; // Do not skip the next element.
943 }
944
945 if (TypeToResolve)
946 TypeToResolve->refineAbstractTypeTo(Ty);
947
948 return Ty;
949}
950
951
952/// ParseTypeRec - The recursive function used to process the internal
953/// implementation details of types.
954bool LLParser::ParseTypeRec(PATypeHolder &Result) {
955 switch (Lex.getKind()) {
956 default:
957 return TokError("expected type");
958 case lltok::Type:
959 // TypeRec ::= 'float' | 'void' (etc)
960 Result = Lex.getTyVal();
961 Lex.Lex();
962 break;
963 case lltok::kw_opaque:
964 // TypeRec ::= 'opaque'
965 Result = OpaqueType::get();
966 Lex.Lex();
967 break;
968 case lltok::lbrace:
969 // TypeRec ::= '{' ... '}'
970 if (ParseStructType(Result, false))
971 return true;
972 break;
973 case lltok::lsquare:
974 // TypeRec ::= '[' ... ']'
975 Lex.Lex(); // eat the lsquare.
976 if (ParseArrayVectorType(Result, false))
977 return true;
978 break;
979 case lltok::less: // Either vector or packed struct.
980 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000981 Lex.Lex();
982 if (Lex.getKind() == lltok::lbrace) {
983 if (ParseStructType(Result, true) ||
984 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000985 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000986 } else if (ParseArrayVectorType(Result, true))
987 return true;
988 break;
989 case lltok::LocalVar:
990 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
991 // TypeRec ::= %foo
992 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
993 Result = T;
994 } else {
995 Result = OpaqueType::get();
996 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
997 std::make_pair(Result,
998 Lex.getLoc())));
999 M->addTypeName(Lex.getStrVal(), Result.get());
1000 }
1001 Lex.Lex();
1002 break;
1003
1004 case lltok::LocalVarID:
1005 // TypeRec ::= %4
1006 if (Lex.getUIntVal() < NumberedTypes.size())
1007 Result = NumberedTypes[Lex.getUIntVal()];
1008 else {
1009 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1010 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1011 if (I != ForwardRefTypeIDs.end())
1012 Result = I->second.first;
1013 else {
1014 Result = OpaqueType::get();
1015 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1016 std::make_pair(Result,
1017 Lex.getLoc())));
1018 }
1019 }
1020 Lex.Lex();
1021 break;
1022 case lltok::backslash: {
1023 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001024 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001025 unsigned Val;
1026 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001027 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1028 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1029 Result = OT;
1030 break;
1031 }
1032 }
1033
1034 // Parse the type suffixes.
1035 while (1) {
1036 switch (Lex.getKind()) {
1037 // End of type.
1038 default: return false;
1039
1040 // TypeRec ::= TypeRec '*'
1041 case lltok::star:
1042 if (Result.get() == Type::LabelTy)
1043 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001044 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001045 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001046 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1047 Lex.Lex();
1048 break;
1049
1050 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1051 case lltok::kw_addrspace: {
1052 if (Result.get() == Type::LabelTy)
1053 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001054 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001055 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001056 unsigned AddrSpace;
1057 if (ParseOptionalAddrSpace(AddrSpace) ||
1058 ParseToken(lltok::star, "expected '*' in address space"))
1059 return true;
1060
1061 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1062 break;
1063 }
1064
1065 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1066 case lltok::lparen:
1067 if (ParseFunctionType(Result))
1068 return true;
1069 break;
1070 }
1071 }
1072}
1073
1074/// ParseParameterList
1075/// ::= '(' ')'
1076/// ::= '(' Arg (',' Arg)* ')'
1077/// Arg
1078/// ::= Type OptionalAttributes Value OptionalAttributes
1079bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1080 PerFunctionState &PFS) {
1081 if (ParseToken(lltok::lparen, "expected '(' in call"))
1082 return true;
1083
1084 while (Lex.getKind() != lltok::rparen) {
1085 // If this isn't the first argument, we need a comma.
1086 if (!ArgList.empty() &&
1087 ParseToken(lltok::comma, "expected ',' in argument list"))
1088 return true;
1089
1090 // Parse the argument.
1091 LocTy ArgLoc;
1092 PATypeHolder ArgTy(Type::VoidTy);
1093 unsigned ArgAttrs1, ArgAttrs2;
1094 Value *V;
1095 if (ParseType(ArgTy, ArgLoc) ||
1096 ParseOptionalAttrs(ArgAttrs1, 0) ||
1097 ParseValue(ArgTy, V, PFS) ||
1098 // FIXME: Should not allow attributes after the argument, remove this in
1099 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001100 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001101 return true;
1102 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1103 }
1104
1105 Lex.Lex(); // Lex the ')'.
1106 return false;
1107}
1108
1109
1110
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001111/// ParseArgumentList - Parse the argument list for a function type or function
1112/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001113/// ::= '(' ArgTypeListI ')'
1114/// ArgTypeListI
1115/// ::= /*empty*/
1116/// ::= '...'
1117/// ::= ArgTypeList ',' '...'
1118/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001119///
Chris Lattnerdf986172009-01-02 07:01:27 +00001120bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001121 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001122 isVarArg = false;
1123 assert(Lex.getKind() == lltok::lparen);
1124 Lex.Lex(); // eat the (.
1125
1126 if (Lex.getKind() == lltok::rparen) {
1127 // empty
1128 } else if (Lex.getKind() == lltok::dotdotdot) {
1129 isVarArg = true;
1130 Lex.Lex();
1131 } else {
1132 LocTy TypeLoc = Lex.getLoc();
1133 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001134 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001135 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001136
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001137 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1138 // types (such as a function returning a pointer to itself). If parsing a
1139 // function prototype, we require fully resolved types.
1140 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001141 ParseOptionalAttrs(Attrs, 0)) return true;
1142
Chris Lattnera9a9e072009-03-09 04:49:14 +00001143 if (ArgTy == Type::VoidTy)
1144 return Error(TypeLoc, "argument can not have void type");
1145
Chris Lattnerdf986172009-01-02 07:01:27 +00001146 if (Lex.getKind() == lltok::LocalVar ||
1147 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1148 Name = Lex.getStrVal();
1149 Lex.Lex();
1150 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001151
Nick Lewycky00907c72009-06-07 01:45:11 +00001152 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
1153 (isa<PointerType>(ArgTy) &&
1154 cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001155 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001156
1157 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1158
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001159 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001160 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001161 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001163 break;
1164 }
1165
1166 // Otherwise must be an argument type.
1167 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001168 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001169 ParseOptionalAttrs(Attrs, 0)) return true;
1170
Chris Lattnera9a9e072009-03-09 04:49:14 +00001171 if (ArgTy == Type::VoidTy)
1172 return Error(TypeLoc, "argument can not have void type");
1173
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 if (Lex.getKind() == lltok::LocalVar ||
1175 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1176 Name = Lex.getStrVal();
1177 Lex.Lex();
1178 } else {
1179 Name = "";
1180 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001181
1182 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1183 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001184
1185 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1186 }
1187 }
1188
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001189 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001190}
1191
1192/// ParseFunctionType
1193/// ::= Type ArgumentList OptionalAttrs
1194bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1195 assert(Lex.getKind() == lltok::lparen);
1196
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001197 if (!FunctionType::isValidReturnType(Result))
1198 return TokError("invalid function return type");
1199
Chris Lattnerdf986172009-01-02 07:01:27 +00001200 std::vector<ArgInfo> ArgList;
1201 bool isVarArg;
1202 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001203 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001204 // FIXME: Allow, but ignore attributes on function types!
1205 // FIXME: Remove in LLVM 3.0
1206 ParseOptionalAttrs(Attrs, 2))
1207 return true;
1208
1209 // Reject names on the arguments lists.
1210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1211 if (!ArgList[i].Name.empty())
1212 return Error(ArgList[i].Loc, "argument name invalid in function type");
1213 if (!ArgList[i].Attrs != 0) {
1214 // Allow but ignore attributes on function types; this permits
1215 // auto-upgrade.
1216 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1217 }
1218 }
1219
1220 std::vector<const Type*> ArgListTy;
1221 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1222 ArgListTy.push_back(ArgList[i].Type);
1223
1224 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1225 return false;
1226}
1227
1228/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1229/// TypeRec
1230/// ::= '{' '}'
1231/// ::= '{' TypeRec (',' TypeRec)* '}'
1232/// ::= '<' '{' '}' '>'
1233/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1234bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1235 assert(Lex.getKind() == lltok::lbrace);
1236 Lex.Lex(); // Consume the '{'
1237
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001238 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001240 return false;
1241 }
1242
1243 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001244 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001245 if (ParseTypeRec(Result)) return true;
1246 ParamsList.push_back(Result);
1247
Chris Lattnera9a9e072009-03-09 04:49:14 +00001248 if (Result == Type::VoidTy)
1249 return Error(EltTyLoc, "struct element can not have void type");
1250
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001251 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001252 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001253 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001254
1255 if (Result == Type::VoidTy)
1256 return Error(EltTyLoc, "struct element can not have void type");
1257
Chris Lattnerdf986172009-01-02 07:01:27 +00001258 ParamsList.push_back(Result);
1259 }
1260
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001261 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1262 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001263
1264 std::vector<const Type*> ParamsListTy;
1265 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1266 ParamsListTy.push_back(ParamsList[i].get());
1267 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1268 return false;
1269}
1270
1271/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1272/// token has already been consumed.
1273/// TypeRec
1274/// ::= '[' APSINTVAL 'x' Types ']'
1275/// ::= '<' APSINTVAL 'x' Types '>'
1276bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1277 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1278 Lex.getAPSIntVal().getBitWidth() > 64)
1279 return TokError("expected number in address space");
1280
1281 LocTy SizeLoc = Lex.getLoc();
1282 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001283 Lex.Lex();
1284
1285 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1286 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001287
1288 LocTy TypeLoc = Lex.getLoc();
1289 PATypeHolder EltTy(Type::VoidTy);
1290 if (ParseTypeRec(EltTy)) return true;
1291
Chris Lattnera9a9e072009-03-09 04:49:14 +00001292 if (EltTy == Type::VoidTy)
1293 return Error(TypeLoc, "array and vector element type cannot be void");
1294
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001295 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1296 "expected end of sequential type"))
1297 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001298
1299 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001300 if (Size == 0)
1301 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 if ((unsigned)Size != Size)
1303 return Error(SizeLoc, "size too large for vector");
1304 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1305 return Error(TypeLoc, "vector element type must be fp or integer");
1306 Result = VectorType::get(EltTy, unsigned(Size));
1307 } else {
1308 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1309 return Error(TypeLoc, "invalid array element type");
1310 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1311 }
1312 return false;
1313}
1314
1315//===----------------------------------------------------------------------===//
1316// Function Semantic Analysis.
1317//===----------------------------------------------------------------------===//
1318
1319LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1320 : P(p), F(f) {
1321
1322 // Insert unnamed arguments into the NumberedVals list.
1323 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1324 AI != E; ++AI)
1325 if (!AI->hasName())
1326 NumberedVals.push_back(AI);
1327}
1328
1329LLParser::PerFunctionState::~PerFunctionState() {
1330 // If there were any forward referenced non-basicblock values, delete them.
1331 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1332 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1333 if (!isa<BasicBlock>(I->second.first)) {
1334 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1335 ->getType()));
1336 delete I->second.first;
1337 I->second.first = 0;
1338 }
1339
1340 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1341 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1342 if (!isa<BasicBlock>(I->second.first)) {
1343 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1344 ->getType()));
1345 delete I->second.first;
1346 I->second.first = 0;
1347 }
1348}
1349
1350bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1351 if (!ForwardRefVals.empty())
1352 return P.Error(ForwardRefVals.begin()->second.second,
1353 "use of undefined value '%" + ForwardRefVals.begin()->first +
1354 "'");
1355 if (!ForwardRefValIDs.empty())
1356 return P.Error(ForwardRefValIDs.begin()->second.second,
1357 "use of undefined value '%" +
1358 utostr(ForwardRefValIDs.begin()->first) + "'");
1359 return false;
1360}
1361
1362
1363/// GetVal - Get a value with the specified name or ID, creating a
1364/// forward reference record if needed. This can return null if the value
1365/// exists but does not have the right type.
1366Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1367 const Type *Ty, LocTy Loc) {
1368 // Look this name up in the normal function symbol table.
1369 Value *Val = F.getValueSymbolTable().lookup(Name);
1370
1371 // If this is a forward reference for the value, see if we already created a
1372 // forward ref record.
1373 if (Val == 0) {
1374 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1375 I = ForwardRefVals.find(Name);
1376 if (I != ForwardRefVals.end())
1377 Val = I->second.first;
1378 }
1379
1380 // If we have the value in the symbol table or fwd-ref table, return it.
1381 if (Val) {
1382 if (Val->getType() == Ty) return Val;
1383 if (Ty == Type::LabelTy)
1384 P.Error(Loc, "'%" + Name + "' is not a basic block");
1385 else
1386 P.Error(Loc, "'%" + Name + "' defined with type '" +
1387 Val->getType()->getDescription() + "'");
1388 return 0;
1389 }
1390
1391 // Don't make placeholders with invalid type.
1392 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1393 P.Error(Loc, "invalid use of a non-first-class type");
1394 return 0;
1395 }
1396
1397 // Otherwise, create a new forward reference for this value and remember it.
1398 Value *FwdVal;
1399 if (Ty == Type::LabelTy)
1400 FwdVal = BasicBlock::Create(Name, &F);
1401 else
1402 FwdVal = new Argument(Ty, Name);
1403
1404 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1405 return FwdVal;
1406}
1407
1408Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1409 LocTy Loc) {
1410 // Look this name up in the normal function symbol table.
1411 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1412
1413 // If this is a forward reference for the value, see if we already created a
1414 // forward ref record.
1415 if (Val == 0) {
1416 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1417 I = ForwardRefValIDs.find(ID);
1418 if (I != ForwardRefValIDs.end())
1419 Val = I->second.first;
1420 }
1421
1422 // If we have the value in the symbol table or fwd-ref table, return it.
1423 if (Val) {
1424 if (Val->getType() == Ty) return Val;
1425 if (Ty == Type::LabelTy)
1426 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1427 else
1428 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1429 Val->getType()->getDescription() + "'");
1430 return 0;
1431 }
1432
1433 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1434 P.Error(Loc, "invalid use of a non-first-class type");
1435 return 0;
1436 }
1437
1438 // Otherwise, create a new forward reference for this value and remember it.
1439 Value *FwdVal;
1440 if (Ty == Type::LabelTy)
1441 FwdVal = BasicBlock::Create("", &F);
1442 else
1443 FwdVal = new Argument(Ty);
1444
1445 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1446 return FwdVal;
1447}
1448
1449/// SetInstName - After an instruction is parsed and inserted into its
1450/// basic block, this installs its name.
1451bool LLParser::PerFunctionState::SetInstName(int NameID,
1452 const std::string &NameStr,
1453 LocTy NameLoc, Instruction *Inst) {
1454 // If this instruction has void type, it cannot have a name or ID specified.
1455 if (Inst->getType() == Type::VoidTy) {
1456 if (NameID != -1 || !NameStr.empty())
1457 return P.Error(NameLoc, "instructions returning void cannot have a name");
1458 return false;
1459 }
1460
1461 // If this was a numbered instruction, verify that the instruction is the
1462 // expected value and resolve any forward references.
1463 if (NameStr.empty()) {
1464 // If neither a name nor an ID was specified, just use the next ID.
1465 if (NameID == -1)
1466 NameID = NumberedVals.size();
1467
1468 if (unsigned(NameID) != NumberedVals.size())
1469 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1470 utostr(NumberedVals.size()) + "'");
1471
1472 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1473 ForwardRefValIDs.find(NameID);
1474 if (FI != ForwardRefValIDs.end()) {
1475 if (FI->second.first->getType() != Inst->getType())
1476 return P.Error(NameLoc, "instruction forward referenced with type '" +
1477 FI->second.first->getType()->getDescription() + "'");
1478 FI->second.first->replaceAllUsesWith(Inst);
1479 ForwardRefValIDs.erase(FI);
1480 }
1481
1482 NumberedVals.push_back(Inst);
1483 return false;
1484 }
1485
1486 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1487 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1488 FI = ForwardRefVals.find(NameStr);
1489 if (FI != ForwardRefVals.end()) {
1490 if (FI->second.first->getType() != Inst->getType())
1491 return P.Error(NameLoc, "instruction forward referenced with type '" +
1492 FI->second.first->getType()->getDescription() + "'");
1493 FI->second.first->replaceAllUsesWith(Inst);
1494 ForwardRefVals.erase(FI);
1495 }
1496
1497 // Set the name on the instruction.
1498 Inst->setName(NameStr);
1499
1500 if (Inst->getNameStr() != NameStr)
1501 return P.Error(NameLoc, "multiple definition of local value named '" +
1502 NameStr + "'");
1503 return false;
1504}
1505
1506/// GetBB - Get a basic block with the specified name or ID, creating a
1507/// forward reference record if needed.
1508BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1509 LocTy Loc) {
1510 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1511}
1512
1513BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1514 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1515}
1516
1517/// DefineBB - Define the specified basic block, which is either named or
1518/// unnamed. If there is an error, this returns null otherwise it returns
1519/// the block being defined.
1520BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1521 LocTy Loc) {
1522 BasicBlock *BB;
1523 if (Name.empty())
1524 BB = GetBB(NumberedVals.size(), Loc);
1525 else
1526 BB = GetBB(Name, Loc);
1527 if (BB == 0) return 0; // Already diagnosed error.
1528
1529 // Move the block to the end of the function. Forward ref'd blocks are
1530 // inserted wherever they happen to be referenced.
1531 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1532
1533 // Remove the block from forward ref sets.
1534 if (Name.empty()) {
1535 ForwardRefValIDs.erase(NumberedVals.size());
1536 NumberedVals.push_back(BB);
1537 } else {
1538 // BB forward references are already in the function symbol table.
1539 ForwardRefVals.erase(Name);
1540 }
1541
1542 return BB;
1543}
1544
1545//===----------------------------------------------------------------------===//
1546// Constants.
1547//===----------------------------------------------------------------------===//
1548
1549/// ParseValID - Parse an abstract value that doesn't necessarily have a
1550/// type implied. For example, if we parse "4" we don't know what integer type
1551/// it has. The value will later be combined with its type and checked for
1552/// sanity.
1553bool LLParser::ParseValID(ValID &ID) {
1554 ID.Loc = Lex.getLoc();
1555 switch (Lex.getKind()) {
1556 default: return TokError("expected value token");
1557 case lltok::GlobalID: // @42
1558 ID.UIntVal = Lex.getUIntVal();
1559 ID.Kind = ValID::t_GlobalID;
1560 break;
1561 case lltok::GlobalVar: // @foo
1562 ID.StrVal = Lex.getStrVal();
1563 ID.Kind = ValID::t_GlobalName;
1564 break;
1565 case lltok::LocalVarID: // %42
1566 ID.UIntVal = Lex.getUIntVal();
1567 ID.Kind = ValID::t_LocalID;
1568 break;
1569 case lltok::LocalVar: // %foo
1570 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1571 ID.StrVal = Lex.getStrVal();
1572 ID.Kind = ValID::t_LocalName;
1573 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001574 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1575 ID.Kind = ValID::t_Constant;
1576 Lex.Lex();
1577 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001578 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001579 if (ParseMDNodeVector(Elts) ||
1580 ParseToken(lltok::rbrace, "expected end of metadata node"))
1581 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001582
Jay Foade3e51c02009-05-21 09:52:38 +00001583 ID.ConstantVal = MDNode::get(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001584 return false;
1585 }
1586
1587 // MDString:
1588 // ::= '!' STRINGCONSTANT
1589 std::string Str;
1590 if (ParseStringConstant(Str)) return true;
1591
1592 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1593 return false;
1594 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 case lltok::APSInt:
1596 ID.APSIntVal = Lex.getAPSIntVal();
1597 ID.Kind = ValID::t_APSInt;
1598 break;
1599 case lltok::APFloat:
1600 ID.APFloatVal = Lex.getAPFloatVal();
1601 ID.Kind = ValID::t_APFloat;
1602 break;
1603 case lltok::kw_true:
1604 ID.ConstantVal = ConstantInt::getTrue();
1605 ID.Kind = ValID::t_Constant;
1606 break;
1607 case lltok::kw_false:
1608 ID.ConstantVal = ConstantInt::getFalse();
1609 ID.Kind = ValID::t_Constant;
1610 break;
1611 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1612 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1613 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1614
1615 case lltok::lbrace: {
1616 // ValID ::= '{' ConstVector '}'
1617 Lex.Lex();
1618 SmallVector<Constant*, 16> Elts;
1619 if (ParseGlobalValueVector(Elts) ||
1620 ParseToken(lltok::rbrace, "expected end of struct constant"))
1621 return true;
1622
Jay Foade3e51c02009-05-21 09:52:38 +00001623 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001624 ID.Kind = ValID::t_Constant;
1625 return false;
1626 }
1627 case lltok::less: {
1628 // ValID ::= '<' ConstVector '>' --> Vector.
1629 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1630 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001631 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001632
1633 SmallVector<Constant*, 16> Elts;
1634 LocTy FirstEltLoc = Lex.getLoc();
1635 if (ParseGlobalValueVector(Elts) ||
1636 (isPackedStruct &&
1637 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1638 ParseToken(lltok::greater, "expected end of constant"))
1639 return true;
1640
1641 if (isPackedStruct) {
Jay Foade3e51c02009-05-21 09:52:38 +00001642 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001643 ID.Kind = ValID::t_Constant;
1644 return false;
1645 }
1646
1647 if (Elts.empty())
1648 return Error(ID.Loc, "constant vector must not be empty");
1649
1650 if (!Elts[0]->getType()->isInteger() &&
1651 !Elts[0]->getType()->isFloatingPoint())
1652 return Error(FirstEltLoc,
1653 "vector elements must have integer or floating point type");
1654
1655 // Verify that all the vector elements have the same type.
1656 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1657 if (Elts[i]->getType() != Elts[0]->getType())
1658 return Error(FirstEltLoc,
1659 "vector element #" + utostr(i) +
1660 " is not of type '" + Elts[0]->getType()->getDescription());
1661
Jay Foade3e51c02009-05-21 09:52:38 +00001662 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 ID.Kind = ValID::t_Constant;
1664 return false;
1665 }
1666 case lltok::lsquare: { // Array Constant
1667 Lex.Lex();
1668 SmallVector<Constant*, 16> Elts;
1669 LocTy FirstEltLoc = Lex.getLoc();
1670 if (ParseGlobalValueVector(Elts) ||
1671 ParseToken(lltok::rsquare, "expected end of array constant"))
1672 return true;
1673
1674 // Handle empty element.
1675 if (Elts.empty()) {
1676 // Use undef instead of an array because it's inconvenient to determine
1677 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001678 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 return false;
1680 }
1681
1682 if (!Elts[0]->getType()->isFirstClassType())
1683 return Error(FirstEltLoc, "invalid array element type: " +
1684 Elts[0]->getType()->getDescription());
1685
1686 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1687
1688 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001689 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 if (Elts[i]->getType() != Elts[0]->getType())
1691 return Error(FirstEltLoc,
1692 "array element #" + utostr(i) +
1693 " is not of type '" +Elts[0]->getType()->getDescription());
1694 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001695
Jay Foade3e51c02009-05-21 09:52:38 +00001696 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001697 ID.Kind = ValID::t_Constant;
1698 return false;
1699 }
1700 case lltok::kw_c: // c "foo"
1701 Lex.Lex();
1702 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1703 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1704 ID.Kind = ValID::t_Constant;
1705 return false;
1706
1707 case lltok::kw_asm: {
1708 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1709 bool HasSideEffect;
1710 Lex.Lex();
1711 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001712 ParseStringConstant(ID.StrVal) ||
1713 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 ParseToken(lltok::StringConstant, "expected constraint string"))
1715 return true;
1716 ID.StrVal2 = Lex.getStrVal();
1717 ID.UIntVal = HasSideEffect;
1718 ID.Kind = ValID::t_InlineAsm;
1719 return false;
1720 }
1721
1722 case lltok::kw_trunc:
1723 case lltok::kw_zext:
1724 case lltok::kw_sext:
1725 case lltok::kw_fptrunc:
1726 case lltok::kw_fpext:
1727 case lltok::kw_bitcast:
1728 case lltok::kw_uitofp:
1729 case lltok::kw_sitofp:
1730 case lltok::kw_fptoui:
1731 case lltok::kw_fptosi:
1732 case lltok::kw_inttoptr:
1733 case lltok::kw_ptrtoint: {
1734 unsigned Opc = Lex.getUIntVal();
1735 PATypeHolder DestTy(Type::VoidTy);
1736 Constant *SrcVal;
1737 Lex.Lex();
1738 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1739 ParseGlobalTypeAndValue(SrcVal) ||
1740 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1741 ParseType(DestTy) ||
1742 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1743 return true;
1744 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1745 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1746 SrcVal->getType()->getDescription() + "' to '" +
1747 DestTy->getDescription() + "'");
1748 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1749 DestTy);
1750 ID.Kind = ValID::t_Constant;
1751 return false;
1752 }
1753 case lltok::kw_extractvalue: {
1754 Lex.Lex();
1755 Constant *Val;
1756 SmallVector<unsigned, 4> Indices;
1757 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1758 ParseGlobalTypeAndValue(Val) ||
1759 ParseIndexList(Indices) ||
1760 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1761 return true;
1762 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1763 return Error(ID.Loc, "extractvalue operand must be array or struct");
1764 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1765 Indices.end()))
1766 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001767 ID.ConstantVal =
1768 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 ID.Kind = ValID::t_Constant;
1770 return false;
1771 }
1772 case lltok::kw_insertvalue: {
1773 Lex.Lex();
1774 Constant *Val0, *Val1;
1775 SmallVector<unsigned, 4> Indices;
1776 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1777 ParseGlobalTypeAndValue(Val0) ||
1778 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1779 ParseGlobalTypeAndValue(Val1) ||
1780 ParseIndexList(Indices) ||
1781 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1782 return true;
1783 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1784 return Error(ID.Loc, "extractvalue operand must be array or struct");
1785 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1786 Indices.end()))
1787 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001788 ID.ConstantVal =
1789 ConstantExpr::getInsertValue(Val0, Val1, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001790 ID.Kind = ValID::t_Constant;
1791 return false;
1792 }
1793 case lltok::kw_icmp:
1794 case lltok::kw_fcmp:
1795 case lltok::kw_vicmp:
1796 case lltok::kw_vfcmp: {
1797 unsigned PredVal, Opc = Lex.getUIntVal();
1798 Constant *Val0, *Val1;
1799 Lex.Lex();
1800 if (ParseCmpPredicate(PredVal, Opc) ||
1801 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1802 ParseGlobalTypeAndValue(Val0) ||
1803 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1804 ParseGlobalTypeAndValue(Val1) ||
1805 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1806 return true;
1807
1808 if (Val0->getType() != Val1->getType())
1809 return Error(ID.Loc, "compare operands must have the same type");
1810
1811 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1812
1813 if (Opc == Instruction::FCmp) {
1814 if (!Val0->getType()->isFPOrFPVector())
1815 return Error(ID.Loc, "fcmp requires floating point operands");
1816 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1817 } else if (Opc == Instruction::ICmp) {
1818 if (!Val0->getType()->isIntOrIntVector() &&
1819 !isa<PointerType>(Val0->getType()))
1820 return Error(ID.Loc, "icmp requires pointer or integer operands");
1821 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1822 } else if (Opc == Instruction::VFCmp) {
1823 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001824 if (!Val0->getType()->isFPOrFPVector() ||
1825 !isa<VectorType>(Val0->getType()))
1826 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1828 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001829 // FIXME: REMOVE VICMP Support
1830 if (!Val0->getType()->isIntOrIntVector() ||
1831 !isa<VectorType>(Val0->getType()))
1832 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1834 }
1835 ID.Kind = ValID::t_Constant;
1836 return false;
1837 }
1838
1839 // Binary Operators.
1840 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001841 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001843 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001844 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001845 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001846 case lltok::kw_udiv:
1847 case lltok::kw_sdiv:
1848 case lltok::kw_fdiv:
1849 case lltok::kw_urem:
1850 case lltok::kw_srem:
1851 case lltok::kw_frem: {
1852 unsigned Opc = Lex.getUIntVal();
1853 Constant *Val0, *Val1;
1854 Lex.Lex();
1855 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1856 ParseGlobalTypeAndValue(Val0) ||
1857 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1858 ParseGlobalTypeAndValue(Val1) ||
1859 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1860 return true;
1861 if (Val0->getType() != Val1->getType())
1862 return Error(ID.Loc, "operands of constexpr must have same type");
1863 if (!Val0->getType()->isIntOrIntVector() &&
1864 !Val0->getType()->isFPOrFPVector())
1865 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1866 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1867 ID.Kind = ValID::t_Constant;
1868 return false;
1869 }
1870
1871 // Logical Operations
1872 case lltok::kw_shl:
1873 case lltok::kw_lshr:
1874 case lltok::kw_ashr:
1875 case lltok::kw_and:
1876 case lltok::kw_or:
1877 case lltok::kw_xor: {
1878 unsigned Opc = Lex.getUIntVal();
1879 Constant *Val0, *Val1;
1880 Lex.Lex();
1881 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1882 ParseGlobalTypeAndValue(Val0) ||
1883 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1884 ParseGlobalTypeAndValue(Val1) ||
1885 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1886 return true;
1887 if (Val0->getType() != Val1->getType())
1888 return Error(ID.Loc, "operands of constexpr must have same type");
1889 if (!Val0->getType()->isIntOrIntVector())
1890 return Error(ID.Loc,
1891 "constexpr requires integer or integer vector operands");
1892 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1893 ID.Kind = ValID::t_Constant;
1894 return false;
1895 }
1896
1897 case lltok::kw_getelementptr:
1898 case lltok::kw_shufflevector:
1899 case lltok::kw_insertelement:
1900 case lltok::kw_extractelement:
1901 case lltok::kw_select: {
1902 unsigned Opc = Lex.getUIntVal();
1903 SmallVector<Constant*, 16> Elts;
1904 Lex.Lex();
1905 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1906 ParseGlobalValueVector(Elts) ||
1907 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1908 return true;
1909
1910 if (Opc == Instruction::GetElementPtr) {
1911 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1912 return Error(ID.Loc, "getelementptr requires pointer operand");
1913
1914 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1915 (Value**)&Elts[1], Elts.size()-1))
1916 return Error(ID.Loc, "invalid indices for getelementptr");
1917 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1918 &Elts[1], Elts.size()-1);
1919 } else if (Opc == Instruction::Select) {
1920 if (Elts.size() != 3)
1921 return Error(ID.Loc, "expected three operands to select");
1922 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1923 Elts[2]))
1924 return Error(ID.Loc, Reason);
1925 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1926 } else if (Opc == Instruction::ShuffleVector) {
1927 if (Elts.size() != 3)
1928 return Error(ID.Loc, "expected three operands to shufflevector");
1929 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1930 return Error(ID.Loc, "invalid operands to shufflevector");
1931 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1932 } else if (Opc == Instruction::ExtractElement) {
1933 if (Elts.size() != 2)
1934 return Error(ID.Loc, "expected two operands to extractelement");
1935 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1936 return Error(ID.Loc, "invalid extractelement operands");
1937 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1938 } else {
1939 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1940 if (Elts.size() != 3)
1941 return Error(ID.Loc, "expected three operands to insertelement");
1942 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1943 return Error(ID.Loc, "invalid insertelement operands");
1944 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1945 }
1946
1947 ID.Kind = ValID::t_Constant;
1948 return false;
1949 }
1950 }
1951
1952 Lex.Lex();
1953 return false;
1954}
1955
1956/// ParseGlobalValue - Parse a global value with the specified type.
1957bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1958 V = 0;
1959 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001960 return ParseValID(ID) ||
1961 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001962}
1963
1964/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1965/// constant.
1966bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1967 Constant *&V) {
1968 if (isa<FunctionType>(Ty))
1969 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1970
1971 switch (ID.Kind) {
1972 default: assert(0 && "Unknown ValID!");
1973 case ValID::t_LocalID:
1974 case ValID::t_LocalName:
1975 return Error(ID.Loc, "invalid use of function-local name");
1976 case ValID::t_InlineAsm:
1977 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1978 case ValID::t_GlobalName:
1979 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1980 return V == 0;
1981 case ValID::t_GlobalID:
1982 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1983 return V == 0;
1984 case ValID::t_APSInt:
1985 if (!isa<IntegerType>(Ty))
1986 return Error(ID.Loc, "integer constant must have integer type");
1987 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1988 V = ConstantInt::get(ID.APSIntVal);
1989 return false;
1990 case ValID::t_APFloat:
1991 if (!Ty->isFloatingPoint() ||
1992 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1993 return Error(ID.Loc, "floating point constant invalid for type");
1994
1995 // The lexer has no type info, so builds all float and double FP constants
1996 // as double. Fix this here. Long double does not need this.
1997 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1998 Ty == Type::FloatTy) {
1999 bool Ignored;
2000 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2001 &Ignored);
2002 }
2003 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002004
2005 if (V->getType() != Ty)
2006 return Error(ID.Loc, "floating point constant does not have type '" +
2007 Ty->getDescription() + "'");
2008
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 return false;
2010 case ValID::t_Null:
2011 if (!isa<PointerType>(Ty))
2012 return Error(ID.Loc, "null must be a pointer type");
2013 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2014 return false;
2015 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002016 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002017 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2018 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002019 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00002020 V = UndefValue::get(Ty);
2021 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002022 case ValID::t_EmptyArray:
2023 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2024 return Error(ID.Loc, "invalid empty array initializer");
2025 V = UndefValue::get(Ty);
2026 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002028 // FIXME: LabelTy should not be a first-class type.
2029 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002030 return Error(ID.Loc, "invalid type for null constant");
2031 V = Constant::getNullValue(Ty);
2032 return false;
2033 case ValID::t_Constant:
2034 if (ID.ConstantVal->getType() != Ty)
2035 return Error(ID.Loc, "constant expression type mismatch");
2036 V = ID.ConstantVal;
2037 return false;
2038 }
2039}
2040
2041bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2042 PATypeHolder Type(Type::VoidTy);
2043 return ParseType(Type) ||
2044 ParseGlobalValue(Type, V);
2045}
2046
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002047/// ParseGlobalValueVector
2048/// ::= /*empty*/
2049/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002050bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2051 // Empty list.
2052 if (Lex.getKind() == lltok::rbrace ||
2053 Lex.getKind() == lltok::rsquare ||
2054 Lex.getKind() == lltok::greater ||
2055 Lex.getKind() == lltok::rparen)
2056 return false;
2057
2058 Constant *C;
2059 if (ParseGlobalTypeAndValue(C)) return true;
2060 Elts.push_back(C);
2061
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002062 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 if (ParseGlobalTypeAndValue(C)) return true;
2064 Elts.push_back(C);
2065 }
2066
2067 return false;
2068}
2069
2070
2071//===----------------------------------------------------------------------===//
2072// Function Parsing.
2073//===----------------------------------------------------------------------===//
2074
2075bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2076 PerFunctionState &PFS) {
2077 if (ID.Kind == ValID::t_LocalID)
2078 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2079 else if (ID.Kind == ValID::t_LocalName)
2080 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002081 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2083 const FunctionType *FTy =
2084 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2085 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2086 return Error(ID.Loc, "invalid type for inline asm constraint string");
2087 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2088 return false;
2089 } else {
2090 Constant *C;
2091 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2092 V = C;
2093 return false;
2094 }
2095
2096 return V == 0;
2097}
2098
2099bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2100 V = 0;
2101 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002102 return ParseValID(ID) ||
2103 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002104}
2105
2106bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2107 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002108 return ParseType(T) ||
2109 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002110}
2111
2112/// FunctionHeader
2113/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2114/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2115/// OptionalAlign OptGC
2116bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2117 // Parse the linkage.
2118 LocTy LinkageLoc = Lex.getLoc();
2119 unsigned Linkage;
2120
2121 unsigned Visibility, CC, RetAttrs;
2122 PATypeHolder RetType(Type::VoidTy);
2123 LocTy RetTypeLoc = Lex.getLoc();
2124 if (ParseOptionalLinkage(Linkage) ||
2125 ParseOptionalVisibility(Visibility) ||
2126 ParseOptionalCallingConv(CC) ||
2127 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002128 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 return true;
2130
2131 // Verify that the linkage is ok.
2132 switch ((GlobalValue::LinkageTypes)Linkage) {
2133 case GlobalValue::ExternalLinkage:
2134 break; // always ok.
2135 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002136 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 if (isDefine)
2138 return Error(LinkageLoc, "invalid linkage for function definition");
2139 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002140 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002142 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002143 case GlobalValue::LinkOnceAnyLinkage:
2144 case GlobalValue::LinkOnceODRLinkage:
2145 case GlobalValue::WeakAnyLinkage:
2146 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 case GlobalValue::DLLExportLinkage:
2148 if (!isDefine)
2149 return Error(LinkageLoc, "invalid linkage for function declaration");
2150 break;
2151 case GlobalValue::AppendingLinkage:
2152 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002153 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002154 return Error(LinkageLoc, "invalid function linkage type");
2155 }
2156
Chris Lattner99bb3152009-01-05 08:00:30 +00002157 if (!FunctionType::isValidReturnType(RetType) ||
2158 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 return Error(RetTypeLoc, "invalid function return type");
2160
Chris Lattnerdf986172009-01-02 07:01:27 +00002161 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002162
2163 std::string FunctionName;
2164 if (Lex.getKind() == lltok::GlobalVar) {
2165 FunctionName = Lex.getStrVal();
2166 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2167 unsigned NameID = Lex.getUIntVal();
2168
2169 if (NameID != NumberedVals.size())
2170 return TokError("function expected to be numbered '%" +
2171 utostr(NumberedVals.size()) + "'");
2172 } else {
2173 return TokError("expected function name");
2174 }
2175
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002176 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002177
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002178 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 return TokError("expected '(' in function argument list");
2180
2181 std::vector<ArgInfo> ArgList;
2182 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002183 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002186 std::string GC;
2187
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002188 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002189 ParseOptionalAttrs(FuncAttrs, 2) ||
2190 (EatIfPresent(lltok::kw_section) &&
2191 ParseStringConstant(Section)) ||
2192 ParseOptionalAlignment(Alignment) ||
2193 (EatIfPresent(lltok::kw_gc) &&
2194 ParseStringConstant(GC)))
2195 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002196
2197 // If the alignment was parsed as an attribute, move to the alignment field.
2198 if (FuncAttrs & Attribute::Alignment) {
2199 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2200 FuncAttrs &= ~Attribute::Alignment;
2201 }
2202
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 // Okay, if we got here, the function is syntactically valid. Convert types
2204 // and do semantic checks.
2205 std::vector<const Type*> ParamTypeList;
2206 SmallVector<AttributeWithIndex, 8> Attrs;
2207 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2208 // attributes.
2209 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2210 if (FuncAttrs & ObsoleteFuncAttrs) {
2211 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2212 FuncAttrs &= ~ObsoleteFuncAttrs;
2213 }
2214
2215 if (RetAttrs != Attribute::None)
2216 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2217
2218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2219 ParamTypeList.push_back(ArgList[i].Type);
2220 if (ArgList[i].Attrs != Attribute::None)
2221 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2222 }
2223
2224 if (FuncAttrs != Attribute::None)
2225 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2226
2227 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2228
Chris Lattnera9a9e072009-03-09 04:49:14 +00002229 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2230 RetType != Type::VoidTy)
2231 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2232
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2234 const PointerType *PFT = PointerType::getUnqual(FT);
2235
2236 Fn = 0;
2237 if (!FunctionName.empty()) {
2238 // If this was a definition of a forward reference, remove the definition
2239 // from the forward reference table and fill in the forward ref.
2240 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2241 ForwardRefVals.find(FunctionName);
2242 if (FRVI != ForwardRefVals.end()) {
2243 Fn = M->getFunction(FunctionName);
2244 ForwardRefVals.erase(FRVI);
2245 } else if ((Fn = M->getFunction(FunctionName))) {
2246 // If this function already exists in the symbol table, then it is
2247 // multiply defined. We accept a few cases for old backwards compat.
2248 // FIXME: Remove this stuff for LLVM 3.0.
2249 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2250 (!Fn->isDeclaration() && isDefine)) {
2251 // If the redefinition has different type or different attributes,
2252 // reject it. If both have bodies, reject it.
2253 return Error(NameLoc, "invalid redefinition of function '" +
2254 FunctionName + "'");
2255 } else if (Fn->isDeclaration()) {
2256 // Make sure to strip off any argument names so we can't get conflicts.
2257 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2258 AI != AE; ++AI)
2259 AI->setName("");
2260 }
2261 }
2262
2263 } else if (FunctionName.empty()) {
2264 // If this is a definition of a forward referenced function, make sure the
2265 // types agree.
2266 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2267 = ForwardRefValIDs.find(NumberedVals.size());
2268 if (I != ForwardRefValIDs.end()) {
2269 Fn = cast<Function>(I->second.first);
2270 if (Fn->getType() != PFT)
2271 return Error(NameLoc, "type of definition and forward reference of '@" +
2272 utostr(NumberedVals.size()) +"' disagree");
2273 ForwardRefValIDs.erase(I);
2274 }
2275 }
2276
2277 if (Fn == 0)
2278 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2279 else // Move the forward-reference to the correct spot in the module.
2280 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2281
2282 if (FunctionName.empty())
2283 NumberedVals.push_back(Fn);
2284
2285 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2286 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2287 Fn->setCallingConv(CC);
2288 Fn->setAttributes(PAL);
2289 Fn->setAlignment(Alignment);
2290 Fn->setSection(Section);
2291 if (!GC.empty()) Fn->setGC(GC.c_str());
2292
2293 // Add all of the arguments we parsed to the function.
2294 Function::arg_iterator ArgIt = Fn->arg_begin();
2295 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2296 // If the argument has a name, insert it into the argument symbol table.
2297 if (ArgList[i].Name.empty()) continue;
2298
2299 // Set the name, if it conflicted, it will be auto-renamed.
2300 ArgIt->setName(ArgList[i].Name);
2301
2302 if (ArgIt->getNameStr() != ArgList[i].Name)
2303 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2304 ArgList[i].Name + "'");
2305 }
2306
2307 return false;
2308}
2309
2310
2311/// ParseFunctionBody
2312/// ::= '{' BasicBlock+ '}'
2313/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2314///
2315bool LLParser::ParseFunctionBody(Function &Fn) {
2316 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2317 return TokError("expected '{' in function body");
2318 Lex.Lex(); // eat the {.
2319
2320 PerFunctionState PFS(*this, Fn);
2321
2322 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2323 if (ParseBasicBlock(PFS)) return true;
2324
2325 // Eat the }.
2326 Lex.Lex();
2327
2328 // Verify function is ok.
2329 return PFS.VerifyFunctionComplete();
2330}
2331
2332/// ParseBasicBlock
2333/// ::= LabelStr? Instruction*
2334bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2335 // If this basic block starts out with a name, remember it.
2336 std::string Name;
2337 LocTy NameLoc = Lex.getLoc();
2338 if (Lex.getKind() == lltok::LabelStr) {
2339 Name = Lex.getStrVal();
2340 Lex.Lex();
2341 }
2342
2343 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2344 if (BB == 0) return true;
2345
2346 std::string NameStr;
2347
2348 // Parse the instructions in this block until we get a terminator.
2349 Instruction *Inst;
2350 do {
2351 // This instruction may have three possibilities for a name: a) none
2352 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2353 LocTy NameLoc = Lex.getLoc();
2354 int NameID = -1;
2355 NameStr = "";
2356
2357 if (Lex.getKind() == lltok::LocalVarID) {
2358 NameID = Lex.getUIntVal();
2359 Lex.Lex();
2360 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2361 return true;
2362 } else if (Lex.getKind() == lltok::LocalVar ||
2363 // FIXME: REMOVE IN LLVM 3.0
2364 Lex.getKind() == lltok::StringConstant) {
2365 NameStr = Lex.getStrVal();
2366 Lex.Lex();
2367 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2368 return true;
2369 }
2370
2371 if (ParseInstruction(Inst, BB, PFS)) return true;
2372
2373 BB->getInstList().push_back(Inst);
2374
2375 // Set the name on the instruction.
2376 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2377 } while (!isa<TerminatorInst>(Inst));
2378
2379 return false;
2380}
2381
2382//===----------------------------------------------------------------------===//
2383// Instruction Parsing.
2384//===----------------------------------------------------------------------===//
2385
2386/// ParseInstruction - Parse one of the many different instructions.
2387///
2388bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2389 PerFunctionState &PFS) {
2390 lltok::Kind Token = Lex.getKind();
2391 if (Token == lltok::Eof)
2392 return TokError("found end of file when expecting more instructions");
2393 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002394 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 Lex.Lex(); // Eat the keyword.
2396
2397 switch (Token) {
2398 default: return Error(Loc, "expected instruction opcode");
2399 // Terminator Instructions.
2400 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2401 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2402 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2403 case lltok::kw_br: return ParseBr(Inst, PFS);
2404 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2405 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2406 // Binary Operators.
2407 case lltok::kw_add:
2408 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002409 case lltok::kw_mul:
2410 // API compatibility: Accept either integer or floating-point types.
2411 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2412 case lltok::kw_fadd:
2413 case lltok::kw_fsub:
2414 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2415
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 case lltok::kw_udiv:
2417 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002419 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002420 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002421 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 case lltok::kw_shl:
2423 case lltok::kw_lshr:
2424 case lltok::kw_ashr:
2425 case lltok::kw_and:
2426 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002427 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 case lltok::kw_icmp:
2429 case lltok::kw_fcmp:
2430 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002431 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 // Casts.
2433 case lltok::kw_trunc:
2434 case lltok::kw_zext:
2435 case lltok::kw_sext:
2436 case lltok::kw_fptrunc:
2437 case lltok::kw_fpext:
2438 case lltok::kw_bitcast:
2439 case lltok::kw_uitofp:
2440 case lltok::kw_sitofp:
2441 case lltok::kw_fptoui:
2442 case lltok::kw_fptosi:
2443 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002444 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 // Other.
2446 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002447 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002448 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2449 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2450 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2451 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2452 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2453 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2454 // Memory.
2455 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002456 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002457 case lltok::kw_free: return ParseFree(Inst, PFS);
2458 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2459 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2460 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002461 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002462 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002463 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002464 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002465 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002466 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002467 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2468 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2469 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2470 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2471 }
2472}
2473
2474/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2475bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2476 // FIXME: REMOVE vicmp/vfcmp!
2477 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2478 switch (Lex.getKind()) {
2479 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2480 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2481 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2482 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2483 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2484 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2485 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2486 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2487 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2488 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2489 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2490 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2491 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2492 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2493 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2494 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2495 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2496 }
2497 } else {
2498 switch (Lex.getKind()) {
2499 default: TokError("expected icmp predicate (e.g. 'eq')");
2500 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2501 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2502 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2503 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2504 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2505 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2506 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2507 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2508 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2509 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2510 }
2511 }
2512 Lex.Lex();
2513 return false;
2514}
2515
2516//===----------------------------------------------------------------------===//
2517// Terminator Instructions.
2518//===----------------------------------------------------------------------===//
2519
2520/// ParseRet - Parse a return instruction.
2521/// ::= 'ret' void
2522/// ::= 'ret' TypeAndValue
2523/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2524bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2525 PerFunctionState &PFS) {
2526 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002527 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002528
2529 if (Ty == Type::VoidTy) {
2530 Inst = ReturnInst::Create();
2531 return false;
2532 }
2533
2534 Value *RV;
2535 if (ParseValue(Ty, RV, PFS)) return true;
2536
2537 // The normal case is one return value.
2538 if (Lex.getKind() == lltok::comma) {
2539 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2540 // of 'ret {i32,i32} {i32 1, i32 2}'
2541 SmallVector<Value*, 8> RVs;
2542 RVs.push_back(RV);
2543
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002544 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 if (ParseTypeAndValue(RV, PFS)) return true;
2546 RVs.push_back(RV);
2547 }
2548
2549 RV = UndefValue::get(PFS.getFunction().getReturnType());
2550 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2551 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2552 BB->getInstList().push_back(I);
2553 RV = I;
2554 }
2555 }
2556 Inst = ReturnInst::Create(RV);
2557 return false;
2558}
2559
2560
2561/// ParseBr
2562/// ::= 'br' TypeAndValue
2563/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2564bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2565 LocTy Loc, Loc2;
2566 Value *Op0, *Op1, *Op2;
2567 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2568
2569 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2570 Inst = BranchInst::Create(BB);
2571 return false;
2572 }
2573
2574 if (Op0->getType() != Type::Int1Ty)
2575 return Error(Loc, "branch condition must have 'i1' type");
2576
2577 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2578 ParseTypeAndValue(Op1, Loc, PFS) ||
2579 ParseToken(lltok::comma, "expected ',' after true destination") ||
2580 ParseTypeAndValue(Op2, Loc2, PFS))
2581 return true;
2582
2583 if (!isa<BasicBlock>(Op1))
2584 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 if (!isa<BasicBlock>(Op2))
2586 return Error(Loc2, "true destination of branch must be a basic block");
2587
2588 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2589 return false;
2590}
2591
2592/// ParseSwitch
2593/// Instruction
2594/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2595/// JumpTable
2596/// ::= (TypeAndValue ',' TypeAndValue)*
2597bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2598 LocTy CondLoc, BBLoc;
2599 Value *Cond, *DefaultBB;
2600 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2601 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2602 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2603 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2604 return true;
2605
2606 if (!isa<IntegerType>(Cond->getType()))
2607 return Error(CondLoc, "switch condition must have integer type");
2608 if (!isa<BasicBlock>(DefaultBB))
2609 return Error(BBLoc, "default destination must be a basic block");
2610
2611 // Parse the jump table pairs.
2612 SmallPtrSet<Value*, 32> SeenCases;
2613 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2614 while (Lex.getKind() != lltok::rsquare) {
2615 Value *Constant, *DestBB;
2616
2617 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2618 ParseToken(lltok::comma, "expected ',' after case value") ||
2619 ParseTypeAndValue(DestBB, BBLoc, PFS))
2620 return true;
2621
2622 if (!SeenCases.insert(Constant))
2623 return Error(CondLoc, "duplicate case value in switch");
2624 if (!isa<ConstantInt>(Constant))
2625 return Error(CondLoc, "case value is not a constant integer");
2626 if (!isa<BasicBlock>(DestBB))
2627 return Error(BBLoc, "case destination is not a basic block");
2628
2629 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2630 cast<BasicBlock>(DestBB)));
2631 }
2632
2633 Lex.Lex(); // Eat the ']'.
2634
2635 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2636 Table.size());
2637 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2638 SI->addCase(Table[i].first, Table[i].second);
2639 Inst = SI;
2640 return false;
2641}
2642
2643/// ParseInvoke
2644/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2645/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2646bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2647 LocTy CallLoc = Lex.getLoc();
2648 unsigned CC, RetAttrs, FnAttrs;
2649 PATypeHolder RetType(Type::VoidTy);
2650 LocTy RetTypeLoc;
2651 ValID CalleeID;
2652 SmallVector<ParamInfo, 16> ArgList;
2653
2654 Value *NormalBB, *UnwindBB;
2655 if (ParseOptionalCallingConv(CC) ||
2656 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002657 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002658 ParseValID(CalleeID) ||
2659 ParseParameterList(ArgList, PFS) ||
2660 ParseOptionalAttrs(FnAttrs, 2) ||
2661 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2662 ParseTypeAndValue(NormalBB, PFS) ||
2663 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2664 ParseTypeAndValue(UnwindBB, PFS))
2665 return true;
2666
2667 if (!isa<BasicBlock>(NormalBB))
2668 return Error(CallLoc, "normal destination is not a basic block");
2669 if (!isa<BasicBlock>(UnwindBB))
2670 return Error(CallLoc, "unwind destination is not a basic block");
2671
2672 // If RetType is a non-function pointer type, then this is the short syntax
2673 // for the call, which means that RetType is just the return type. Infer the
2674 // rest of the function argument types from the arguments that are present.
2675 const PointerType *PFTy = 0;
2676 const FunctionType *Ty = 0;
2677 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2678 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2679 // Pull out the types of all of the arguments...
2680 std::vector<const Type*> ParamTypes;
2681 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2682 ParamTypes.push_back(ArgList[i].V->getType());
2683
2684 if (!FunctionType::isValidReturnType(RetType))
2685 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2686
2687 Ty = FunctionType::get(RetType, ParamTypes, false);
2688 PFTy = PointerType::getUnqual(Ty);
2689 }
2690
2691 // Look up the callee.
2692 Value *Callee;
2693 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2694
2695 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2696 // function attributes.
2697 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2698 if (FnAttrs & ObsoleteFuncAttrs) {
2699 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2700 FnAttrs &= ~ObsoleteFuncAttrs;
2701 }
2702
2703 // Set up the Attributes for the function.
2704 SmallVector<AttributeWithIndex, 8> Attrs;
2705 if (RetAttrs != Attribute::None)
2706 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2707
2708 SmallVector<Value*, 8> Args;
2709
2710 // Loop through FunctionType's arguments and ensure they are specified
2711 // correctly. Also, gather any parameter attributes.
2712 FunctionType::param_iterator I = Ty->param_begin();
2713 FunctionType::param_iterator E = Ty->param_end();
2714 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2715 const Type *ExpectedTy = 0;
2716 if (I != E) {
2717 ExpectedTy = *I++;
2718 } else if (!Ty->isVarArg()) {
2719 return Error(ArgList[i].Loc, "too many arguments specified");
2720 }
2721
2722 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2723 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2724 ExpectedTy->getDescription() + "'");
2725 Args.push_back(ArgList[i].V);
2726 if (ArgList[i].Attrs != Attribute::None)
2727 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2728 }
2729
2730 if (I != E)
2731 return Error(CallLoc, "not enough parameters specified for call");
2732
2733 if (FnAttrs != Attribute::None)
2734 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2735
2736 // Finish off the Attributes and check them
2737 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2738
2739 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2740 cast<BasicBlock>(UnwindBB),
2741 Args.begin(), Args.end());
2742 II->setCallingConv(CC);
2743 II->setAttributes(PAL);
2744 Inst = II;
2745 return false;
2746}
2747
2748
2749
2750//===----------------------------------------------------------------------===//
2751// Binary Operators.
2752//===----------------------------------------------------------------------===//
2753
2754/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002755/// ::= ArithmeticOps TypeAndValue ',' Value
2756///
2757/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2758/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002759bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002760 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 LocTy Loc; Value *LHS, *RHS;
2762 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2763 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2764 ParseValue(LHS->getType(), RHS, PFS))
2765 return true;
2766
Chris Lattnere914b592009-01-05 08:24:46 +00002767 bool Valid;
2768 switch (OperandType) {
2769 default: assert(0 && "Unknown operand type!");
2770 case 0: // int or FP.
2771 Valid = LHS->getType()->isIntOrIntVector() ||
2772 LHS->getType()->isFPOrFPVector();
2773 break;
2774 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2775 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2776 }
2777
2778 if (!Valid)
2779 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002780
2781 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2782 return false;
2783}
2784
2785/// ParseLogical
2786/// ::= ArithmeticOps TypeAndValue ',' Value {
2787bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2788 unsigned Opc) {
2789 LocTy Loc; Value *LHS, *RHS;
2790 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2791 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2792 ParseValue(LHS->getType(), RHS, PFS))
2793 return true;
2794
2795 if (!LHS->getType()->isIntOrIntVector())
2796 return Error(Loc,"instruction requires integer or integer vector operands");
2797
2798 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2799 return false;
2800}
2801
2802
2803/// ParseCompare
2804/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2805/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2806/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2807/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2808bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2809 unsigned Opc) {
2810 // Parse the integer/fp comparison predicate.
2811 LocTy Loc;
2812 unsigned Pred;
2813 Value *LHS, *RHS;
2814 if (ParseCmpPredicate(Pred, Opc) ||
2815 ParseTypeAndValue(LHS, Loc, PFS) ||
2816 ParseToken(lltok::comma, "expected ',' after compare value") ||
2817 ParseValue(LHS->getType(), RHS, PFS))
2818 return true;
2819
2820 if (Opc == Instruction::FCmp) {
2821 if (!LHS->getType()->isFPOrFPVector())
2822 return Error(Loc, "fcmp requires floating point operands");
2823 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2824 } else if (Opc == Instruction::ICmp) {
2825 if (!LHS->getType()->isIntOrIntVector() &&
2826 !isa<PointerType>(LHS->getType()))
2827 return Error(Loc, "icmp requires integer operands");
2828 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2829 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002830 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2831 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002832 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2833 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002834 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2835 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002836 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2837 }
2838 return false;
2839}
2840
2841//===----------------------------------------------------------------------===//
2842// Other Instructions.
2843//===----------------------------------------------------------------------===//
2844
2845
2846/// ParseCast
2847/// ::= CastOpc TypeAndValue 'to' Type
2848bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2849 unsigned Opc) {
2850 LocTy Loc; Value *Op;
2851 PATypeHolder DestTy(Type::VoidTy);
2852 if (ParseTypeAndValue(Op, Loc, PFS) ||
2853 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2854 ParseType(DestTy))
2855 return true;
2856
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002857 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2858 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 return Error(Loc, "invalid cast opcode for cast from '" +
2860 Op->getType()->getDescription() + "' to '" +
2861 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002862 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002863 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2864 return false;
2865}
2866
2867/// ParseSelect
2868/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2869bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2870 LocTy Loc;
2871 Value *Op0, *Op1, *Op2;
2872 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2873 ParseToken(lltok::comma, "expected ',' after select condition") ||
2874 ParseTypeAndValue(Op1, PFS) ||
2875 ParseToken(lltok::comma, "expected ',' after select value") ||
2876 ParseTypeAndValue(Op2, PFS))
2877 return true;
2878
2879 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2880 return Error(Loc, Reason);
2881
2882 Inst = SelectInst::Create(Op0, Op1, Op2);
2883 return false;
2884}
2885
Chris Lattner0088a5c2009-01-05 08:18:44 +00002886/// ParseVA_Arg
2887/// ::= 'va_arg' TypeAndValue ',' Type
2888bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 Value *Op;
2890 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002891 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002892 if (ParseTypeAndValue(Op, PFS) ||
2893 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002894 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002896
2897 if (!EltTy->isFirstClassType())
2898 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002899
2900 Inst = new VAArgInst(Op, EltTy);
2901 return false;
2902}
2903
2904/// ParseExtractElement
2905/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2906bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2907 LocTy Loc;
2908 Value *Op0, *Op1;
2909 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2910 ParseToken(lltok::comma, "expected ',' after extract value") ||
2911 ParseTypeAndValue(Op1, PFS))
2912 return true;
2913
2914 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2915 return Error(Loc, "invalid extractelement operands");
2916
2917 Inst = new ExtractElementInst(Op0, Op1);
2918 return false;
2919}
2920
2921/// ParseInsertElement
2922/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2923bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2924 LocTy Loc;
2925 Value *Op0, *Op1, *Op2;
2926 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2927 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2928 ParseTypeAndValue(Op1, PFS) ||
2929 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2930 ParseTypeAndValue(Op2, PFS))
2931 return true;
2932
2933 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2934 return Error(Loc, "invalid extractelement operands");
2935
2936 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2937 return false;
2938}
2939
2940/// ParseShuffleVector
2941/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2942bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2943 LocTy Loc;
2944 Value *Op0, *Op1, *Op2;
2945 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2946 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2947 ParseTypeAndValue(Op1, PFS) ||
2948 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2949 ParseTypeAndValue(Op2, PFS))
2950 return true;
2951
2952 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2953 return Error(Loc, "invalid extractelement operands");
2954
2955 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2956 return false;
2957}
2958
2959/// ParsePHI
2960/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2961bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2962 PATypeHolder Ty(Type::VoidTy);
2963 Value *Op0, *Op1;
2964 LocTy TypeLoc = Lex.getLoc();
2965
2966 if (ParseType(Ty) ||
2967 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2968 ParseValue(Ty, Op0, PFS) ||
2969 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2970 ParseValue(Type::LabelTy, Op1, PFS) ||
2971 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2972 return true;
2973
2974 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2975 while (1) {
2976 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2977
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002978 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 break;
2980
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002981 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002982 ParseValue(Ty, Op0, PFS) ||
2983 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2984 ParseValue(Type::LabelTy, Op1, PFS) ||
2985 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2986 return true;
2987 }
2988
2989 if (!Ty->isFirstClassType())
2990 return Error(TypeLoc, "phi node must have first class type");
2991
2992 PHINode *PN = PHINode::Create(Ty);
2993 PN->reserveOperandSpace(PHIVals.size());
2994 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2995 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2996 Inst = PN;
2997 return false;
2998}
2999
3000/// ParseCall
3001/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3002/// ParameterList OptionalAttrs
3003bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3004 bool isTail) {
3005 unsigned CC, RetAttrs, FnAttrs;
3006 PATypeHolder RetType(Type::VoidTy);
3007 LocTy RetTypeLoc;
3008 ValID CalleeID;
3009 SmallVector<ParamInfo, 16> ArgList;
3010 LocTy CallLoc = Lex.getLoc();
3011
3012 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3013 ParseOptionalCallingConv(CC) ||
3014 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003015 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 ParseValID(CalleeID) ||
3017 ParseParameterList(ArgList, PFS) ||
3018 ParseOptionalAttrs(FnAttrs, 2))
3019 return true;
3020
3021 // If RetType is a non-function pointer type, then this is the short syntax
3022 // for the call, which means that RetType is just the return type. Infer the
3023 // rest of the function argument types from the arguments that are present.
3024 const PointerType *PFTy = 0;
3025 const FunctionType *Ty = 0;
3026 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3027 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3028 // Pull out the types of all of the arguments...
3029 std::vector<const Type*> ParamTypes;
3030 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3031 ParamTypes.push_back(ArgList[i].V->getType());
3032
3033 if (!FunctionType::isValidReturnType(RetType))
3034 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3035
3036 Ty = FunctionType::get(RetType, ParamTypes, false);
3037 PFTy = PointerType::getUnqual(Ty);
3038 }
3039
3040 // Look up the callee.
3041 Value *Callee;
3042 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3043
Chris Lattnerdf986172009-01-02 07:01:27 +00003044 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3045 // function attributes.
3046 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3047 if (FnAttrs & ObsoleteFuncAttrs) {
3048 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3049 FnAttrs &= ~ObsoleteFuncAttrs;
3050 }
3051
3052 // Set up the Attributes for the function.
3053 SmallVector<AttributeWithIndex, 8> Attrs;
3054 if (RetAttrs != Attribute::None)
3055 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3056
3057 SmallVector<Value*, 8> Args;
3058
3059 // Loop through FunctionType's arguments and ensure they are specified
3060 // correctly. Also, gather any parameter attributes.
3061 FunctionType::param_iterator I = Ty->param_begin();
3062 FunctionType::param_iterator E = Ty->param_end();
3063 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3064 const Type *ExpectedTy = 0;
3065 if (I != E) {
3066 ExpectedTy = *I++;
3067 } else if (!Ty->isVarArg()) {
3068 return Error(ArgList[i].Loc, "too many arguments specified");
3069 }
3070
3071 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3072 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3073 ExpectedTy->getDescription() + "'");
3074 Args.push_back(ArgList[i].V);
3075 if (ArgList[i].Attrs != Attribute::None)
3076 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3077 }
3078
3079 if (I != E)
3080 return Error(CallLoc, "not enough parameters specified for call");
3081
3082 if (FnAttrs != Attribute::None)
3083 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3084
3085 // Finish off the Attributes and check them
3086 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3087
3088 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3089 CI->setTailCall(isTail);
3090 CI->setCallingConv(CC);
3091 CI->setAttributes(PAL);
3092 Inst = CI;
3093 return false;
3094}
3095
3096//===----------------------------------------------------------------------===//
3097// Memory Instructions.
3098//===----------------------------------------------------------------------===//
3099
3100/// ParseAlloc
3101/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3102/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3103bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3104 unsigned Opc) {
3105 PATypeHolder Ty(Type::VoidTy);
3106 Value *Size = 0;
3107 LocTy SizeLoc = 0;
3108 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003109 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003110
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003111 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 if (Lex.getKind() == lltok::kw_align) {
3113 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003114 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3115 ParseOptionalCommaAlignment(Alignment)) {
3116 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003117 }
3118 }
3119
3120 if (Size && Size->getType() != Type::Int32Ty)
3121 return Error(SizeLoc, "element count must be i32");
3122
3123 if (Opc == Instruction::Malloc)
3124 Inst = new MallocInst(Ty, Size, Alignment);
3125 else
3126 Inst = new AllocaInst(Ty, Size, Alignment);
3127 return false;
3128}
3129
3130/// ParseFree
3131/// ::= 'free' TypeAndValue
3132bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3133 Value *Val; LocTy Loc;
3134 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3135 if (!isa<PointerType>(Val->getType()))
3136 return Error(Loc, "operand to free must be a pointer");
3137 Inst = new FreeInst(Val);
3138 return false;
3139}
3140
3141/// ParseLoad
3142/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3143bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3144 bool isVolatile) {
3145 Value *Val; LocTy Loc;
3146 unsigned Alignment;
3147 if (ParseTypeAndValue(Val, Loc, PFS) ||
3148 ParseOptionalCommaAlignment(Alignment))
3149 return true;
3150
3151 if (!isa<PointerType>(Val->getType()) ||
3152 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3153 return Error(Loc, "load operand must be a pointer to a first class type");
3154
3155 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3156 return false;
3157}
3158
3159/// ParseStore
3160/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3161bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3162 bool isVolatile) {
3163 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3164 unsigned Alignment;
3165 if (ParseTypeAndValue(Val, Loc, PFS) ||
3166 ParseToken(lltok::comma, "expected ',' after store operand") ||
3167 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3168 ParseOptionalCommaAlignment(Alignment))
3169 return true;
3170
3171 if (!isa<PointerType>(Ptr->getType()))
3172 return Error(PtrLoc, "store operand must be a pointer");
3173 if (!Val->getType()->isFirstClassType())
3174 return Error(Loc, "store operand must be a first class value");
3175 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3176 return Error(Loc, "stored value and pointer type do not match");
3177
3178 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3179 return false;
3180}
3181
3182/// ParseGetResult
3183/// ::= 'getresult' TypeAndValue ',' uint
3184/// FIXME: Remove support for getresult in LLVM 3.0
3185bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3186 Value *Val; LocTy ValLoc, EltLoc;
3187 unsigned Element;
3188 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3189 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003190 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003191 return true;
3192
3193 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3194 return Error(ValLoc, "getresult inst requires an aggregate operand");
3195 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3196 return Error(EltLoc, "invalid getresult index for value");
3197 Inst = ExtractValueInst::Create(Val, Element);
3198 return false;
3199}
3200
3201/// ParseGetElementPtr
3202/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3203bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3204 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003205 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003206
3207 if (!isa<PointerType>(Ptr->getType()))
3208 return Error(Loc, "base of getelementptr must be a pointer");
3209
3210 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003211 while (EatIfPresent(lltok::comma)) {
3212 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003213 if (!isa<IntegerType>(Val->getType()))
3214 return Error(EltLoc, "getelementptr index must be an integer");
3215 Indices.push_back(Val);
3216 }
3217
3218 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3219 Indices.begin(), Indices.end()))
3220 return Error(Loc, "invalid getelementptr indices");
3221 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3222 return false;
3223}
3224
3225/// ParseExtractValue
3226/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3227bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3228 Value *Val; LocTy Loc;
3229 SmallVector<unsigned, 4> Indices;
3230 if (ParseTypeAndValue(Val, Loc, PFS) ||
3231 ParseIndexList(Indices))
3232 return true;
3233
3234 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3235 return Error(Loc, "extractvalue operand must be array or struct");
3236
3237 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3238 Indices.end()))
3239 return Error(Loc, "invalid indices for extractvalue");
3240 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3241 return false;
3242}
3243
3244/// ParseInsertValue
3245/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3246bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3247 Value *Val0, *Val1; LocTy Loc0, Loc1;
3248 SmallVector<unsigned, 4> Indices;
3249 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3250 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3251 ParseTypeAndValue(Val1, Loc1, PFS) ||
3252 ParseIndexList(Indices))
3253 return true;
3254
3255 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3256 return Error(Loc0, "extractvalue operand must be array or struct");
3257
3258 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3259 Indices.end()))
3260 return Error(Loc0, "invalid indices for insertvalue");
3261 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3262 return false;
3263}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003264
3265//===----------------------------------------------------------------------===//
3266// Embedded metadata.
3267//===----------------------------------------------------------------------===//
3268
3269/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003270/// ::= Element (',' Element)*
3271/// Element
3272/// ::= 'null' | TypeAndValue
3273bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003274 assert(Lex.getKind() == lltok::lbrace);
3275 Lex.Lex();
3276 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003277 Value *V;
3278 if (Lex.getKind() == lltok::kw_null) {
3279 Lex.Lex();
3280 V = 0;
3281 } else {
3282 Constant *C;
3283 if (ParseGlobalTypeAndValue(C)) return true;
3284 V = C;
3285 }
3286 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003287 } while (EatIfPresent(lltok::comma));
3288
3289 return false;
3290}