blob: 909370cb669dca3916da9d861aeef08c35b28562 [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'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000811/// ::= 'arm_apcscc'
812/// ::= 'arm_aapcscc'
813/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000814/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000815///
Chris Lattnerdf986172009-01-02 07:01:27 +0000816bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
817 switch (Lex.getKind()) {
818 default: CC = CallingConv::C; return false;
819 case lltok::kw_ccc: CC = CallingConv::C; break;
820 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
821 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
822 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
823 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000824 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
825 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
826 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000827 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000828 }
829 Lex.Lex();
830 return false;
831}
832
833/// ParseOptionalAlignment
834/// ::= /* empty */
835/// ::= 'align' 4
836bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
837 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000838 if (!EatIfPresent(lltok::kw_align))
839 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000840 LocTy AlignLoc = Lex.getLoc();
841 if (ParseUInt32(Alignment)) return true;
842 if (!isPowerOf2_32(Alignment))
843 return Error(AlignLoc, "alignment is not a power of two");
844 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000845}
846
847/// ParseOptionalCommaAlignment
848/// ::= /* empty */
849/// ::= ',' 'align' 4
850bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
851 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000852 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000854 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000855 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000856}
857
858/// ParseIndexList
859/// ::= (',' uint32)+
860bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
861 if (Lex.getKind() != lltok::comma)
862 return TokError("expected ',' as start of index list");
863
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000864 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000865 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000866 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000867 Indices.push_back(Idx);
868 }
869
870 return false;
871}
872
873//===----------------------------------------------------------------------===//
874// Type Parsing.
875//===----------------------------------------------------------------------===//
876
877/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000878bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
879 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000880 if (ParseTypeRec(Result)) return true;
881
882 // Verify no unresolved uprefs.
883 if (!UpRefs.empty())
884 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000885
Chris Lattnera9a9e072009-03-09 04:49:14 +0000886 if (!AllowVoid && Result.get() == Type::VoidTy)
887 return Error(TypeLoc, "void type only allowed for function results");
888
Chris Lattnerdf986172009-01-02 07:01:27 +0000889 return false;
890}
891
892/// HandleUpRefs - Every time we finish a new layer of types, this function is
893/// called. It loops through the UpRefs vector, which is a list of the
894/// currently active types. For each type, if the up-reference is contained in
895/// the newly completed type, we decrement the level count. When the level
896/// count reaches zero, the up-referenced type is the type that is passed in:
897/// thus we can complete the cycle.
898///
899PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
900 // If Ty isn't abstract, or if there are no up-references in it, then there is
901 // nothing to resolve here.
902 if (!ty->isAbstract() || UpRefs.empty()) return ty;
903
904 PATypeHolder Ty(ty);
905#if 0
906 errs() << "Type '" << Ty->getDescription()
907 << "' newly formed. Resolving upreferences.\n"
908 << UpRefs.size() << " upreferences active!\n";
909#endif
910
911 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
912 // to zero), we resolve them all together before we resolve them to Ty. At
913 // the end of the loop, if there is anything to resolve to Ty, it will be in
914 // this variable.
915 OpaqueType *TypeToResolve = 0;
916
917 for (unsigned i = 0; i != UpRefs.size(); ++i) {
918 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
919 bool ContainsType =
920 std::find(Ty->subtype_begin(), Ty->subtype_end(),
921 UpRefs[i].LastContainedTy) != Ty->subtype_end();
922
923#if 0
924 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
925 << UpRefs[i].LastContainedTy->getDescription() << ") = "
926 << (ContainsType ? "true" : "false")
927 << " level=" << UpRefs[i].NestingLevel << "\n";
928#endif
929 if (!ContainsType)
930 continue;
931
932 // Decrement level of upreference
933 unsigned Level = --UpRefs[i].NestingLevel;
934 UpRefs[i].LastContainedTy = Ty;
935
936 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
937 if (Level != 0)
938 continue;
939
940#if 0
941 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
942#endif
943 if (!TypeToResolve)
944 TypeToResolve = UpRefs[i].UpRefTy;
945 else
946 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
947 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
948 --i; // Do not skip the next element.
949 }
950
951 if (TypeToResolve)
952 TypeToResolve->refineAbstractTypeTo(Ty);
953
954 return Ty;
955}
956
957
958/// ParseTypeRec - The recursive function used to process the internal
959/// implementation details of types.
960bool LLParser::ParseTypeRec(PATypeHolder &Result) {
961 switch (Lex.getKind()) {
962 default:
963 return TokError("expected type");
964 case lltok::Type:
965 // TypeRec ::= 'float' | 'void' (etc)
966 Result = Lex.getTyVal();
967 Lex.Lex();
968 break;
969 case lltok::kw_opaque:
970 // TypeRec ::= 'opaque'
971 Result = OpaqueType::get();
972 Lex.Lex();
973 break;
974 case lltok::lbrace:
975 // TypeRec ::= '{' ... '}'
976 if (ParseStructType(Result, false))
977 return true;
978 break;
979 case lltok::lsquare:
980 // TypeRec ::= '[' ... ']'
981 Lex.Lex(); // eat the lsquare.
982 if (ParseArrayVectorType(Result, false))
983 return true;
984 break;
985 case lltok::less: // Either vector or packed struct.
986 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000987 Lex.Lex();
988 if (Lex.getKind() == lltok::lbrace) {
989 if (ParseStructType(Result, true) ||
990 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000991 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000992 } else if (ParseArrayVectorType(Result, true))
993 return true;
994 break;
995 case lltok::LocalVar:
996 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
997 // TypeRec ::= %foo
998 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
999 Result = T;
1000 } else {
1001 Result = OpaqueType::get();
1002 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1003 std::make_pair(Result,
1004 Lex.getLoc())));
1005 M->addTypeName(Lex.getStrVal(), Result.get());
1006 }
1007 Lex.Lex();
1008 break;
1009
1010 case lltok::LocalVarID:
1011 // TypeRec ::= %4
1012 if (Lex.getUIntVal() < NumberedTypes.size())
1013 Result = NumberedTypes[Lex.getUIntVal()];
1014 else {
1015 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1016 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1017 if (I != ForwardRefTypeIDs.end())
1018 Result = I->second.first;
1019 else {
1020 Result = OpaqueType::get();
1021 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1022 std::make_pair(Result,
1023 Lex.getLoc())));
1024 }
1025 }
1026 Lex.Lex();
1027 break;
1028 case lltok::backslash: {
1029 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001030 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001031 unsigned Val;
1032 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001033 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1034 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1035 Result = OT;
1036 break;
1037 }
1038 }
1039
1040 // Parse the type suffixes.
1041 while (1) {
1042 switch (Lex.getKind()) {
1043 // End of type.
1044 default: return false;
1045
1046 // TypeRec ::= TypeRec '*'
1047 case lltok::star:
1048 if (Result.get() == Type::LabelTy)
1049 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001050 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001051 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001052 if (!PointerType::isValidElementType(Result.get()))
1053 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001054 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1055 Lex.Lex();
1056 break;
1057
1058 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1059 case lltok::kw_addrspace: {
1060 if (Result.get() == Type::LabelTy)
1061 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001062 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001063 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001064 if (!PointerType::isValidElementType(Result.get()))
1065 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001066 unsigned AddrSpace;
1067 if (ParseOptionalAddrSpace(AddrSpace) ||
1068 ParseToken(lltok::star, "expected '*' in address space"))
1069 return true;
1070
1071 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1072 break;
1073 }
1074
1075 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1076 case lltok::lparen:
1077 if (ParseFunctionType(Result))
1078 return true;
1079 break;
1080 }
1081 }
1082}
1083
1084/// ParseParameterList
1085/// ::= '(' ')'
1086/// ::= '(' Arg (',' Arg)* ')'
1087/// Arg
1088/// ::= Type OptionalAttributes Value OptionalAttributes
1089bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1090 PerFunctionState &PFS) {
1091 if (ParseToken(lltok::lparen, "expected '(' in call"))
1092 return true;
1093
1094 while (Lex.getKind() != lltok::rparen) {
1095 // If this isn't the first argument, we need a comma.
1096 if (!ArgList.empty() &&
1097 ParseToken(lltok::comma, "expected ',' in argument list"))
1098 return true;
1099
1100 // Parse the argument.
1101 LocTy ArgLoc;
1102 PATypeHolder ArgTy(Type::VoidTy);
1103 unsigned ArgAttrs1, ArgAttrs2;
1104 Value *V;
1105 if (ParseType(ArgTy, ArgLoc) ||
1106 ParseOptionalAttrs(ArgAttrs1, 0) ||
1107 ParseValue(ArgTy, V, PFS) ||
1108 // FIXME: Should not allow attributes after the argument, remove this in
1109 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001110 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001111 return true;
1112 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1113 }
1114
1115 Lex.Lex(); // Lex the ')'.
1116 return false;
1117}
1118
1119
1120
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001121/// ParseArgumentList - Parse the argument list for a function type or function
1122/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001123/// ::= '(' ArgTypeListI ')'
1124/// ArgTypeListI
1125/// ::= /*empty*/
1126/// ::= '...'
1127/// ::= ArgTypeList ',' '...'
1128/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001129///
Chris Lattnerdf986172009-01-02 07:01:27 +00001130bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001131 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001132 isVarArg = false;
1133 assert(Lex.getKind() == lltok::lparen);
1134 Lex.Lex(); // eat the (.
1135
1136 if (Lex.getKind() == lltok::rparen) {
1137 // empty
1138 } else if (Lex.getKind() == lltok::dotdotdot) {
1139 isVarArg = true;
1140 Lex.Lex();
1141 } else {
1142 LocTy TypeLoc = Lex.getLoc();
1143 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001144 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001145 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001146
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001147 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1148 // types (such as a function returning a pointer to itself). If parsing a
1149 // function prototype, we require fully resolved types.
1150 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001151 ParseOptionalAttrs(Attrs, 0)) return true;
1152
Chris Lattnera9a9e072009-03-09 04:49:14 +00001153 if (ArgTy == Type::VoidTy)
1154 return Error(TypeLoc, "argument can not have void type");
1155
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 if (Lex.getKind() == lltok::LocalVar ||
1157 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1158 Name = Lex.getStrVal();
1159 Lex.Lex();
1160 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001161
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001162 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001163 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001164
1165 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1166
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001167 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001168 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001169 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001170 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001171 break;
1172 }
1173
1174 // Otherwise must be an argument type.
1175 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001176 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001177 ParseOptionalAttrs(Attrs, 0)) return true;
1178
Chris Lattnera9a9e072009-03-09 04:49:14 +00001179 if (ArgTy == Type::VoidTy)
1180 return Error(TypeLoc, "argument can not have void type");
1181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182 if (Lex.getKind() == lltok::LocalVar ||
1183 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1184 Name = Lex.getStrVal();
1185 Lex.Lex();
1186 } else {
1187 Name = "";
1188 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001189
1190 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1191 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001192
1193 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1194 }
1195 }
1196
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001197 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001198}
1199
1200/// ParseFunctionType
1201/// ::= Type ArgumentList OptionalAttrs
1202bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1203 assert(Lex.getKind() == lltok::lparen);
1204
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001205 if (!FunctionType::isValidReturnType(Result))
1206 return TokError("invalid function return type");
1207
Chris Lattnerdf986172009-01-02 07:01:27 +00001208 std::vector<ArgInfo> ArgList;
1209 bool isVarArg;
1210 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001211 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 // FIXME: Allow, but ignore attributes on function types!
1213 // FIXME: Remove in LLVM 3.0
1214 ParseOptionalAttrs(Attrs, 2))
1215 return true;
1216
1217 // Reject names on the arguments lists.
1218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1219 if (!ArgList[i].Name.empty())
1220 return Error(ArgList[i].Loc, "argument name invalid in function type");
1221 if (!ArgList[i].Attrs != 0) {
1222 // Allow but ignore attributes on function types; this permits
1223 // auto-upgrade.
1224 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1225 }
1226 }
1227
1228 std::vector<const Type*> ArgListTy;
1229 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1230 ArgListTy.push_back(ArgList[i].Type);
1231
1232 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1233 return false;
1234}
1235
1236/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1237/// TypeRec
1238/// ::= '{' '}'
1239/// ::= '{' TypeRec (',' TypeRec)* '}'
1240/// ::= '<' '{' '}' '>'
1241/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1242bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1243 assert(Lex.getKind() == lltok::lbrace);
1244 Lex.Lex(); // Consume the '{'
1245
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001246 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 return false;
1249 }
1250
1251 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001252 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001253 if (ParseTypeRec(Result)) return true;
1254 ParamsList.push_back(Result);
1255
Chris Lattnera9a9e072009-03-09 04:49:14 +00001256 if (Result == Type::VoidTy)
1257 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001258 if (!StructType::isValidElementType(Result))
1259 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001260
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001261 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001262 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001263 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001264
1265 if (Result == Type::VoidTy)
1266 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001267 if (!StructType::isValidElementType(Result))
1268 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001269
Chris Lattnerdf986172009-01-02 07:01:27 +00001270 ParamsList.push_back(Result);
1271 }
1272
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001273 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1274 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001275
1276 std::vector<const Type*> ParamsListTy;
1277 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1278 ParamsListTy.push_back(ParamsList[i].get());
1279 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1280 return false;
1281}
1282
1283/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1284/// token has already been consumed.
1285/// TypeRec
1286/// ::= '[' APSINTVAL 'x' Types ']'
1287/// ::= '<' APSINTVAL 'x' Types '>'
1288bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1289 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1290 Lex.getAPSIntVal().getBitWidth() > 64)
1291 return TokError("expected number in address space");
1292
1293 LocTy SizeLoc = Lex.getLoc();
1294 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001295 Lex.Lex();
1296
1297 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1298 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001299
1300 LocTy TypeLoc = Lex.getLoc();
1301 PATypeHolder EltTy(Type::VoidTy);
1302 if (ParseTypeRec(EltTy)) return true;
1303
Chris Lattnera9a9e072009-03-09 04:49:14 +00001304 if (EltTy == Type::VoidTy)
1305 return Error(TypeLoc, "array and vector element type cannot be void");
1306
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001307 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1308 "expected end of sequential type"))
1309 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001310
1311 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001312 if (Size == 0)
1313 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 if ((unsigned)Size != Size)
1315 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001316 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001317 return Error(TypeLoc, "vector element type must be fp or integer");
1318 Result = VectorType::get(EltTy, unsigned(Size));
1319 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001320 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 return Error(TypeLoc, "invalid array element type");
1322 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1323 }
1324 return false;
1325}
1326
1327//===----------------------------------------------------------------------===//
1328// Function Semantic Analysis.
1329//===----------------------------------------------------------------------===//
1330
1331LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1332 : P(p), F(f) {
1333
1334 // Insert unnamed arguments into the NumberedVals list.
1335 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1336 AI != E; ++AI)
1337 if (!AI->hasName())
1338 NumberedVals.push_back(AI);
1339}
1340
1341LLParser::PerFunctionState::~PerFunctionState() {
1342 // If there were any forward referenced non-basicblock values, delete them.
1343 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1344 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1345 if (!isa<BasicBlock>(I->second.first)) {
1346 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1347 ->getType()));
1348 delete I->second.first;
1349 I->second.first = 0;
1350 }
1351
1352 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1353 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1354 if (!isa<BasicBlock>(I->second.first)) {
1355 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1356 ->getType()));
1357 delete I->second.first;
1358 I->second.first = 0;
1359 }
1360}
1361
1362bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1363 if (!ForwardRefVals.empty())
1364 return P.Error(ForwardRefVals.begin()->second.second,
1365 "use of undefined value '%" + ForwardRefVals.begin()->first +
1366 "'");
1367 if (!ForwardRefValIDs.empty())
1368 return P.Error(ForwardRefValIDs.begin()->second.second,
1369 "use of undefined value '%" +
1370 utostr(ForwardRefValIDs.begin()->first) + "'");
1371 return false;
1372}
1373
1374
1375/// GetVal - Get a value with the specified name or ID, creating a
1376/// forward reference record if needed. This can return null if the value
1377/// exists but does not have the right type.
1378Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1379 const Type *Ty, LocTy Loc) {
1380 // Look this name up in the normal function symbol table.
1381 Value *Val = F.getValueSymbolTable().lookup(Name);
1382
1383 // If this is a forward reference for the value, see if we already created a
1384 // forward ref record.
1385 if (Val == 0) {
1386 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1387 I = ForwardRefVals.find(Name);
1388 if (I != ForwardRefVals.end())
1389 Val = I->second.first;
1390 }
1391
1392 // If we have the value in the symbol table or fwd-ref table, return it.
1393 if (Val) {
1394 if (Val->getType() == Ty) return Val;
1395 if (Ty == Type::LabelTy)
1396 P.Error(Loc, "'%" + Name + "' is not a basic block");
1397 else
1398 P.Error(Loc, "'%" + Name + "' defined with type '" +
1399 Val->getType()->getDescription() + "'");
1400 return 0;
1401 }
1402
1403 // Don't make placeholders with invalid type.
1404 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1405 P.Error(Loc, "invalid use of a non-first-class type");
1406 return 0;
1407 }
1408
1409 // Otherwise, create a new forward reference for this value and remember it.
1410 Value *FwdVal;
1411 if (Ty == Type::LabelTy)
1412 FwdVal = BasicBlock::Create(Name, &F);
1413 else
1414 FwdVal = new Argument(Ty, Name);
1415
1416 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1417 return FwdVal;
1418}
1419
1420Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1421 LocTy Loc) {
1422 // Look this name up in the normal function symbol table.
1423 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1424
1425 // If this is a forward reference for the value, see if we already created a
1426 // forward ref record.
1427 if (Val == 0) {
1428 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1429 I = ForwardRefValIDs.find(ID);
1430 if (I != ForwardRefValIDs.end())
1431 Val = I->second.first;
1432 }
1433
1434 // If we have the value in the symbol table or fwd-ref table, return it.
1435 if (Val) {
1436 if (Val->getType() == Ty) return Val;
1437 if (Ty == Type::LabelTy)
1438 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1439 else
1440 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1441 Val->getType()->getDescription() + "'");
1442 return 0;
1443 }
1444
1445 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1446 P.Error(Loc, "invalid use of a non-first-class type");
1447 return 0;
1448 }
1449
1450 // Otherwise, create a new forward reference for this value and remember it.
1451 Value *FwdVal;
1452 if (Ty == Type::LabelTy)
1453 FwdVal = BasicBlock::Create("", &F);
1454 else
1455 FwdVal = new Argument(Ty);
1456
1457 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1458 return FwdVal;
1459}
1460
1461/// SetInstName - After an instruction is parsed and inserted into its
1462/// basic block, this installs its name.
1463bool LLParser::PerFunctionState::SetInstName(int NameID,
1464 const std::string &NameStr,
1465 LocTy NameLoc, Instruction *Inst) {
1466 // If this instruction has void type, it cannot have a name or ID specified.
1467 if (Inst->getType() == Type::VoidTy) {
1468 if (NameID != -1 || !NameStr.empty())
1469 return P.Error(NameLoc, "instructions returning void cannot have a name");
1470 return false;
1471 }
1472
1473 // If this was a numbered instruction, verify that the instruction is the
1474 // expected value and resolve any forward references.
1475 if (NameStr.empty()) {
1476 // If neither a name nor an ID was specified, just use the next ID.
1477 if (NameID == -1)
1478 NameID = NumberedVals.size();
1479
1480 if (unsigned(NameID) != NumberedVals.size())
1481 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1482 utostr(NumberedVals.size()) + "'");
1483
1484 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1485 ForwardRefValIDs.find(NameID);
1486 if (FI != ForwardRefValIDs.end()) {
1487 if (FI->second.first->getType() != Inst->getType())
1488 return P.Error(NameLoc, "instruction forward referenced with type '" +
1489 FI->second.first->getType()->getDescription() + "'");
1490 FI->second.first->replaceAllUsesWith(Inst);
1491 ForwardRefValIDs.erase(FI);
1492 }
1493
1494 NumberedVals.push_back(Inst);
1495 return false;
1496 }
1497
1498 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1499 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1500 FI = ForwardRefVals.find(NameStr);
1501 if (FI != ForwardRefVals.end()) {
1502 if (FI->second.first->getType() != Inst->getType())
1503 return P.Error(NameLoc, "instruction forward referenced with type '" +
1504 FI->second.first->getType()->getDescription() + "'");
1505 FI->second.first->replaceAllUsesWith(Inst);
1506 ForwardRefVals.erase(FI);
1507 }
1508
1509 // Set the name on the instruction.
1510 Inst->setName(NameStr);
1511
1512 if (Inst->getNameStr() != NameStr)
1513 return P.Error(NameLoc, "multiple definition of local value named '" +
1514 NameStr + "'");
1515 return false;
1516}
1517
1518/// GetBB - Get a basic block with the specified name or ID, creating a
1519/// forward reference record if needed.
1520BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1521 LocTy Loc) {
1522 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1523}
1524
1525BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1526 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1527}
1528
1529/// DefineBB - Define the specified basic block, which is either named or
1530/// unnamed. If there is an error, this returns null otherwise it returns
1531/// the block being defined.
1532BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1533 LocTy Loc) {
1534 BasicBlock *BB;
1535 if (Name.empty())
1536 BB = GetBB(NumberedVals.size(), Loc);
1537 else
1538 BB = GetBB(Name, Loc);
1539 if (BB == 0) return 0; // Already diagnosed error.
1540
1541 // Move the block to the end of the function. Forward ref'd blocks are
1542 // inserted wherever they happen to be referenced.
1543 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1544
1545 // Remove the block from forward ref sets.
1546 if (Name.empty()) {
1547 ForwardRefValIDs.erase(NumberedVals.size());
1548 NumberedVals.push_back(BB);
1549 } else {
1550 // BB forward references are already in the function symbol table.
1551 ForwardRefVals.erase(Name);
1552 }
1553
1554 return BB;
1555}
1556
1557//===----------------------------------------------------------------------===//
1558// Constants.
1559//===----------------------------------------------------------------------===//
1560
1561/// ParseValID - Parse an abstract value that doesn't necessarily have a
1562/// type implied. For example, if we parse "4" we don't know what integer type
1563/// it has. The value will later be combined with its type and checked for
1564/// sanity.
1565bool LLParser::ParseValID(ValID &ID) {
1566 ID.Loc = Lex.getLoc();
1567 switch (Lex.getKind()) {
1568 default: return TokError("expected value token");
1569 case lltok::GlobalID: // @42
1570 ID.UIntVal = Lex.getUIntVal();
1571 ID.Kind = ValID::t_GlobalID;
1572 break;
1573 case lltok::GlobalVar: // @foo
1574 ID.StrVal = Lex.getStrVal();
1575 ID.Kind = ValID::t_GlobalName;
1576 break;
1577 case lltok::LocalVarID: // %42
1578 ID.UIntVal = Lex.getUIntVal();
1579 ID.Kind = ValID::t_LocalID;
1580 break;
1581 case lltok::LocalVar: // %foo
1582 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1583 ID.StrVal = Lex.getStrVal();
1584 ID.Kind = ValID::t_LocalName;
1585 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001586 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1587 ID.Kind = ValID::t_Constant;
1588 Lex.Lex();
1589 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001590 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001591 if (ParseMDNodeVector(Elts) ||
1592 ParseToken(lltok::rbrace, "expected end of metadata node"))
1593 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001594
Jay Foade3e51c02009-05-21 09:52:38 +00001595 ID.ConstantVal = MDNode::get(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001596 return false;
1597 }
1598
1599 // MDString:
1600 // ::= '!' STRINGCONSTANT
1601 std::string Str;
1602 if (ParseStringConstant(Str)) return true;
1603
1604 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1605 return false;
1606 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001607 case lltok::APSInt:
1608 ID.APSIntVal = Lex.getAPSIntVal();
1609 ID.Kind = ValID::t_APSInt;
1610 break;
1611 case lltok::APFloat:
1612 ID.APFloatVal = Lex.getAPFloatVal();
1613 ID.Kind = ValID::t_APFloat;
1614 break;
1615 case lltok::kw_true:
1616 ID.ConstantVal = ConstantInt::getTrue();
1617 ID.Kind = ValID::t_Constant;
1618 break;
1619 case lltok::kw_false:
1620 ID.ConstantVal = ConstantInt::getFalse();
1621 ID.Kind = ValID::t_Constant;
1622 break;
1623 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1624 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1625 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1626
1627 case lltok::lbrace: {
1628 // ValID ::= '{' ConstVector '}'
1629 Lex.Lex();
1630 SmallVector<Constant*, 16> Elts;
1631 if (ParseGlobalValueVector(Elts) ||
1632 ParseToken(lltok::rbrace, "expected end of struct constant"))
1633 return true;
1634
Jay Foade3e51c02009-05-21 09:52:38 +00001635 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001636 ID.Kind = ValID::t_Constant;
1637 return false;
1638 }
1639 case lltok::less: {
1640 // ValID ::= '<' ConstVector '>' --> Vector.
1641 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1642 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001643 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001644
1645 SmallVector<Constant*, 16> Elts;
1646 LocTy FirstEltLoc = Lex.getLoc();
1647 if (ParseGlobalValueVector(Elts) ||
1648 (isPackedStruct &&
1649 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1650 ParseToken(lltok::greater, "expected end of constant"))
1651 return true;
1652
1653 if (isPackedStruct) {
Jay Foade3e51c02009-05-21 09:52:38 +00001654 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001655 ID.Kind = ValID::t_Constant;
1656 return false;
1657 }
1658
1659 if (Elts.empty())
1660 return Error(ID.Loc, "constant vector must not be empty");
1661
1662 if (!Elts[0]->getType()->isInteger() &&
1663 !Elts[0]->getType()->isFloatingPoint())
1664 return Error(FirstEltLoc,
1665 "vector elements must have integer or floating point type");
1666
1667 // Verify that all the vector elements have the same type.
1668 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1669 if (Elts[i]->getType() != Elts[0]->getType())
1670 return Error(FirstEltLoc,
1671 "vector element #" + utostr(i) +
1672 " is not of type '" + Elts[0]->getType()->getDescription());
1673
Jay Foade3e51c02009-05-21 09:52:38 +00001674 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001675 ID.Kind = ValID::t_Constant;
1676 return false;
1677 }
1678 case lltok::lsquare: { // Array Constant
1679 Lex.Lex();
1680 SmallVector<Constant*, 16> Elts;
1681 LocTy FirstEltLoc = Lex.getLoc();
1682 if (ParseGlobalValueVector(Elts) ||
1683 ParseToken(lltok::rsquare, "expected end of array constant"))
1684 return true;
1685
1686 // Handle empty element.
1687 if (Elts.empty()) {
1688 // Use undef instead of an array because it's inconvenient to determine
1689 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001690 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001691 return false;
1692 }
1693
1694 if (!Elts[0]->getType()->isFirstClassType())
1695 return Error(FirstEltLoc, "invalid array element type: " +
1696 Elts[0]->getType()->getDescription());
1697
1698 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1699
1700 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001701 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 if (Elts[i]->getType() != Elts[0]->getType())
1703 return Error(FirstEltLoc,
1704 "array element #" + utostr(i) +
1705 " is not of type '" +Elts[0]->getType()->getDescription());
1706 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001707
Jay Foade3e51c02009-05-21 09:52:38 +00001708 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 ID.Kind = ValID::t_Constant;
1710 return false;
1711 }
1712 case lltok::kw_c: // c "foo"
1713 Lex.Lex();
1714 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1715 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1716 ID.Kind = ValID::t_Constant;
1717 return false;
1718
1719 case lltok::kw_asm: {
1720 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1721 bool HasSideEffect;
1722 Lex.Lex();
1723 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001724 ParseStringConstant(ID.StrVal) ||
1725 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001726 ParseToken(lltok::StringConstant, "expected constraint string"))
1727 return true;
1728 ID.StrVal2 = Lex.getStrVal();
1729 ID.UIntVal = HasSideEffect;
1730 ID.Kind = ValID::t_InlineAsm;
1731 return false;
1732 }
1733
1734 case lltok::kw_trunc:
1735 case lltok::kw_zext:
1736 case lltok::kw_sext:
1737 case lltok::kw_fptrunc:
1738 case lltok::kw_fpext:
1739 case lltok::kw_bitcast:
1740 case lltok::kw_uitofp:
1741 case lltok::kw_sitofp:
1742 case lltok::kw_fptoui:
1743 case lltok::kw_fptosi:
1744 case lltok::kw_inttoptr:
1745 case lltok::kw_ptrtoint: {
1746 unsigned Opc = Lex.getUIntVal();
1747 PATypeHolder DestTy(Type::VoidTy);
1748 Constant *SrcVal;
1749 Lex.Lex();
1750 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1751 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001752 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 ParseType(DestTy) ||
1754 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1755 return true;
1756 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1757 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1758 SrcVal->getType()->getDescription() + "' to '" +
1759 DestTy->getDescription() + "'");
1760 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1761 DestTy);
1762 ID.Kind = ValID::t_Constant;
1763 return false;
1764 }
1765 case lltok::kw_extractvalue: {
1766 Lex.Lex();
1767 Constant *Val;
1768 SmallVector<unsigned, 4> Indices;
1769 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1770 ParseGlobalTypeAndValue(Val) ||
1771 ParseIndexList(Indices) ||
1772 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1773 return true;
1774 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1775 return Error(ID.Loc, "extractvalue operand must be array or struct");
1776 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1777 Indices.end()))
1778 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001779 ID.ConstantVal =
1780 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 ID.Kind = ValID::t_Constant;
1782 return false;
1783 }
1784 case lltok::kw_insertvalue: {
1785 Lex.Lex();
1786 Constant *Val0, *Val1;
1787 SmallVector<unsigned, 4> Indices;
1788 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1789 ParseGlobalTypeAndValue(Val0) ||
1790 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1791 ParseGlobalTypeAndValue(Val1) ||
1792 ParseIndexList(Indices) ||
1793 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1794 return true;
1795 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1796 return Error(ID.Loc, "extractvalue operand must be array or struct");
1797 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1798 Indices.end()))
1799 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001800 ID.ConstantVal =
1801 ConstantExpr::getInsertValue(Val0, Val1, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 ID.Kind = ValID::t_Constant;
1803 return false;
1804 }
1805 case lltok::kw_icmp:
1806 case lltok::kw_fcmp:
1807 case lltok::kw_vicmp:
1808 case lltok::kw_vfcmp: {
1809 unsigned PredVal, Opc = Lex.getUIntVal();
1810 Constant *Val0, *Val1;
1811 Lex.Lex();
1812 if (ParseCmpPredicate(PredVal, Opc) ||
1813 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1814 ParseGlobalTypeAndValue(Val0) ||
1815 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1816 ParseGlobalTypeAndValue(Val1) ||
1817 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1818 return true;
1819
1820 if (Val0->getType() != Val1->getType())
1821 return Error(ID.Loc, "compare operands must have the same type");
1822
1823 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1824
1825 if (Opc == Instruction::FCmp) {
1826 if (!Val0->getType()->isFPOrFPVector())
1827 return Error(ID.Loc, "fcmp requires floating point operands");
1828 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1829 } else if (Opc == Instruction::ICmp) {
1830 if (!Val0->getType()->isIntOrIntVector() &&
1831 !isa<PointerType>(Val0->getType()))
1832 return Error(ID.Loc, "icmp requires pointer or integer operands");
1833 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1834 } else if (Opc == Instruction::VFCmp) {
1835 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001836 if (!Val0->getType()->isFPOrFPVector() ||
1837 !isa<VectorType>(Val0->getType()))
1838 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1840 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001841 // FIXME: REMOVE VICMP Support
1842 if (!Val0->getType()->isIntOrIntVector() ||
1843 !isa<VectorType>(Val0->getType()))
1844 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001845 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1846 }
1847 ID.Kind = ValID::t_Constant;
1848 return false;
1849 }
1850
1851 // Binary Operators.
1852 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001853 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001854 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001855 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001856 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001857 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001858 case lltok::kw_udiv:
1859 case lltok::kw_sdiv:
1860 case lltok::kw_fdiv:
1861 case lltok::kw_urem:
1862 case lltok::kw_srem:
1863 case lltok::kw_frem: {
1864 unsigned Opc = Lex.getUIntVal();
1865 Constant *Val0, *Val1;
1866 Lex.Lex();
1867 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1868 ParseGlobalTypeAndValue(Val0) ||
1869 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1870 ParseGlobalTypeAndValue(Val1) ||
1871 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1872 return true;
1873 if (Val0->getType() != Val1->getType())
1874 return Error(ID.Loc, "operands of constexpr must have same type");
1875 if (!Val0->getType()->isIntOrIntVector() &&
1876 !Val0->getType()->isFPOrFPVector())
1877 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1878 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1879 ID.Kind = ValID::t_Constant;
1880 return false;
1881 }
1882
1883 // Logical Operations
1884 case lltok::kw_shl:
1885 case lltok::kw_lshr:
1886 case lltok::kw_ashr:
1887 case lltok::kw_and:
1888 case lltok::kw_or:
1889 case lltok::kw_xor: {
1890 unsigned Opc = Lex.getUIntVal();
1891 Constant *Val0, *Val1;
1892 Lex.Lex();
1893 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1894 ParseGlobalTypeAndValue(Val0) ||
1895 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1896 ParseGlobalTypeAndValue(Val1) ||
1897 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1898 return true;
1899 if (Val0->getType() != Val1->getType())
1900 return Error(ID.Loc, "operands of constexpr must have same type");
1901 if (!Val0->getType()->isIntOrIntVector())
1902 return Error(ID.Loc,
1903 "constexpr requires integer or integer vector operands");
1904 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1905 ID.Kind = ValID::t_Constant;
1906 return false;
1907 }
1908
1909 case lltok::kw_getelementptr:
1910 case lltok::kw_shufflevector:
1911 case lltok::kw_insertelement:
1912 case lltok::kw_extractelement:
1913 case lltok::kw_select: {
1914 unsigned Opc = Lex.getUIntVal();
1915 SmallVector<Constant*, 16> Elts;
1916 Lex.Lex();
1917 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1918 ParseGlobalValueVector(Elts) ||
1919 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1920 return true;
1921
1922 if (Opc == Instruction::GetElementPtr) {
1923 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1924 return Error(ID.Loc, "getelementptr requires pointer operand");
1925
1926 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1927 (Value**)&Elts[1], Elts.size()-1))
1928 return Error(ID.Loc, "invalid indices for getelementptr");
1929 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1930 &Elts[1], Elts.size()-1);
1931 } else if (Opc == Instruction::Select) {
1932 if (Elts.size() != 3)
1933 return Error(ID.Loc, "expected three operands to select");
1934 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1935 Elts[2]))
1936 return Error(ID.Loc, Reason);
1937 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1938 } else if (Opc == Instruction::ShuffleVector) {
1939 if (Elts.size() != 3)
1940 return Error(ID.Loc, "expected three operands to shufflevector");
1941 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1942 return Error(ID.Loc, "invalid operands to shufflevector");
1943 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1944 } else if (Opc == Instruction::ExtractElement) {
1945 if (Elts.size() != 2)
1946 return Error(ID.Loc, "expected two operands to extractelement");
1947 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1948 return Error(ID.Loc, "invalid extractelement operands");
1949 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1950 } else {
1951 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1952 if (Elts.size() != 3)
1953 return Error(ID.Loc, "expected three operands to insertelement");
1954 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1955 return Error(ID.Loc, "invalid insertelement operands");
1956 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1957 }
1958
1959 ID.Kind = ValID::t_Constant;
1960 return false;
1961 }
1962 }
1963
1964 Lex.Lex();
1965 return false;
1966}
1967
1968/// ParseGlobalValue - Parse a global value with the specified type.
1969bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1970 V = 0;
1971 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001972 return ParseValID(ID) ||
1973 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001974}
1975
1976/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1977/// constant.
1978bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1979 Constant *&V) {
1980 if (isa<FunctionType>(Ty))
1981 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1982
1983 switch (ID.Kind) {
1984 default: assert(0 && "Unknown ValID!");
1985 case ValID::t_LocalID:
1986 case ValID::t_LocalName:
1987 return Error(ID.Loc, "invalid use of function-local name");
1988 case ValID::t_InlineAsm:
1989 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1990 case ValID::t_GlobalName:
1991 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1992 return V == 0;
1993 case ValID::t_GlobalID:
1994 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1995 return V == 0;
1996 case ValID::t_APSInt:
1997 if (!isa<IntegerType>(Ty))
1998 return Error(ID.Loc, "integer constant must have integer type");
1999 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2000 V = ConstantInt::get(ID.APSIntVal);
2001 return false;
2002 case ValID::t_APFloat:
2003 if (!Ty->isFloatingPoint() ||
2004 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2005 return Error(ID.Loc, "floating point constant invalid for type");
2006
2007 // The lexer has no type info, so builds all float and double FP constants
2008 // as double. Fix this here. Long double does not need this.
2009 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2010 Ty == Type::FloatTy) {
2011 bool Ignored;
2012 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2013 &Ignored);
2014 }
2015 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002016
2017 if (V->getType() != Ty)
2018 return Error(ID.Loc, "floating point constant does not have type '" +
2019 Ty->getDescription() + "'");
2020
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 return false;
2022 case ValID::t_Null:
2023 if (!isa<PointerType>(Ty))
2024 return Error(ID.Loc, "null must be a pointer type");
2025 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2026 return false;
2027 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002028 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002029 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2030 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002031 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 V = UndefValue::get(Ty);
2033 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002034 case ValID::t_EmptyArray:
2035 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2036 return Error(ID.Loc, "invalid empty array initializer");
2037 V = UndefValue::get(Ty);
2038 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002040 // FIXME: LabelTy should not be a first-class type.
2041 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002042 return Error(ID.Loc, "invalid type for null constant");
2043 V = Constant::getNullValue(Ty);
2044 return false;
2045 case ValID::t_Constant:
2046 if (ID.ConstantVal->getType() != Ty)
2047 return Error(ID.Loc, "constant expression type mismatch");
2048 V = ID.ConstantVal;
2049 return false;
2050 }
2051}
2052
2053bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2054 PATypeHolder Type(Type::VoidTy);
2055 return ParseType(Type) ||
2056 ParseGlobalValue(Type, V);
2057}
2058
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002059/// ParseGlobalValueVector
2060/// ::= /*empty*/
2061/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002062bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2063 // Empty list.
2064 if (Lex.getKind() == lltok::rbrace ||
2065 Lex.getKind() == lltok::rsquare ||
2066 Lex.getKind() == lltok::greater ||
2067 Lex.getKind() == lltok::rparen)
2068 return false;
2069
2070 Constant *C;
2071 if (ParseGlobalTypeAndValue(C)) return true;
2072 Elts.push_back(C);
2073
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002074 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 if (ParseGlobalTypeAndValue(C)) return true;
2076 Elts.push_back(C);
2077 }
2078
2079 return false;
2080}
2081
2082
2083//===----------------------------------------------------------------------===//
2084// Function Parsing.
2085//===----------------------------------------------------------------------===//
2086
2087bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2088 PerFunctionState &PFS) {
2089 if (ID.Kind == ValID::t_LocalID)
2090 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2091 else if (ID.Kind == ValID::t_LocalName)
2092 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002093 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2095 const FunctionType *FTy =
2096 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2097 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2098 return Error(ID.Loc, "invalid type for inline asm constraint string");
2099 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2100 return false;
2101 } else {
2102 Constant *C;
2103 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2104 V = C;
2105 return false;
2106 }
2107
2108 return V == 0;
2109}
2110
2111bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2112 V = 0;
2113 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002114 return ParseValID(ID) ||
2115 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002116}
2117
2118bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2119 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002120 return ParseType(T) ||
2121 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002122}
2123
2124/// FunctionHeader
2125/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2126/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2127/// OptionalAlign OptGC
2128bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2129 // Parse the linkage.
2130 LocTy LinkageLoc = Lex.getLoc();
2131 unsigned Linkage;
2132
2133 unsigned Visibility, CC, RetAttrs;
2134 PATypeHolder RetType(Type::VoidTy);
2135 LocTy RetTypeLoc = Lex.getLoc();
2136 if (ParseOptionalLinkage(Linkage) ||
2137 ParseOptionalVisibility(Visibility) ||
2138 ParseOptionalCallingConv(CC) ||
2139 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002140 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 return true;
2142
2143 // Verify that the linkage is ok.
2144 switch ((GlobalValue::LinkageTypes)Linkage) {
2145 case GlobalValue::ExternalLinkage:
2146 break; // always ok.
2147 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002148 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002149 if (isDefine)
2150 return Error(LinkageLoc, "invalid linkage for function definition");
2151 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002152 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002154 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002155 case GlobalValue::LinkOnceAnyLinkage:
2156 case GlobalValue::LinkOnceODRLinkage:
2157 case GlobalValue::WeakAnyLinkage:
2158 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 case GlobalValue::DLLExportLinkage:
2160 if (!isDefine)
2161 return Error(LinkageLoc, "invalid linkage for function declaration");
2162 break;
2163 case GlobalValue::AppendingLinkage:
2164 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002165 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 return Error(LinkageLoc, "invalid function linkage type");
2167 }
2168
Chris Lattner99bb3152009-01-05 08:00:30 +00002169 if (!FunctionType::isValidReturnType(RetType) ||
2170 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 return Error(RetTypeLoc, "invalid function return type");
2172
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002174
2175 std::string FunctionName;
2176 if (Lex.getKind() == lltok::GlobalVar) {
2177 FunctionName = Lex.getStrVal();
2178 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2179 unsigned NameID = Lex.getUIntVal();
2180
2181 if (NameID != NumberedVals.size())
2182 return TokError("function expected to be numbered '%" +
2183 utostr(NumberedVals.size()) + "'");
2184 } else {
2185 return TokError("expected function name");
2186 }
2187
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002188 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002189
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002190 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002191 return TokError("expected '(' in function argument list");
2192
2193 std::vector<ArgInfo> ArgList;
2194 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002195 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002196 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002198 std::string GC;
2199
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002200 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002201 ParseOptionalAttrs(FuncAttrs, 2) ||
2202 (EatIfPresent(lltok::kw_section) &&
2203 ParseStringConstant(Section)) ||
2204 ParseOptionalAlignment(Alignment) ||
2205 (EatIfPresent(lltok::kw_gc) &&
2206 ParseStringConstant(GC)))
2207 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002208
2209 // If the alignment was parsed as an attribute, move to the alignment field.
2210 if (FuncAttrs & Attribute::Alignment) {
2211 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2212 FuncAttrs &= ~Attribute::Alignment;
2213 }
2214
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 // Okay, if we got here, the function is syntactically valid. Convert types
2216 // and do semantic checks.
2217 std::vector<const Type*> ParamTypeList;
2218 SmallVector<AttributeWithIndex, 8> Attrs;
2219 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2220 // attributes.
2221 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2222 if (FuncAttrs & ObsoleteFuncAttrs) {
2223 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2224 FuncAttrs &= ~ObsoleteFuncAttrs;
2225 }
2226
2227 if (RetAttrs != Attribute::None)
2228 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2229
2230 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2231 ParamTypeList.push_back(ArgList[i].Type);
2232 if (ArgList[i].Attrs != Attribute::None)
2233 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2234 }
2235
2236 if (FuncAttrs != Attribute::None)
2237 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2238
2239 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2240
Chris Lattnera9a9e072009-03-09 04:49:14 +00002241 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2242 RetType != Type::VoidTy)
2243 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2244
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2246 const PointerType *PFT = PointerType::getUnqual(FT);
2247
2248 Fn = 0;
2249 if (!FunctionName.empty()) {
2250 // If this was a definition of a forward reference, remove the definition
2251 // from the forward reference table and fill in the forward ref.
2252 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2253 ForwardRefVals.find(FunctionName);
2254 if (FRVI != ForwardRefVals.end()) {
2255 Fn = M->getFunction(FunctionName);
2256 ForwardRefVals.erase(FRVI);
2257 } else if ((Fn = M->getFunction(FunctionName))) {
2258 // If this function already exists in the symbol table, then it is
2259 // multiply defined. We accept a few cases for old backwards compat.
2260 // FIXME: Remove this stuff for LLVM 3.0.
2261 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2262 (!Fn->isDeclaration() && isDefine)) {
2263 // If the redefinition has different type or different attributes,
2264 // reject it. If both have bodies, reject it.
2265 return Error(NameLoc, "invalid redefinition of function '" +
2266 FunctionName + "'");
2267 } else if (Fn->isDeclaration()) {
2268 // Make sure to strip off any argument names so we can't get conflicts.
2269 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2270 AI != AE; ++AI)
2271 AI->setName("");
2272 }
2273 }
2274
2275 } else if (FunctionName.empty()) {
2276 // If this is a definition of a forward referenced function, make sure the
2277 // types agree.
2278 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2279 = ForwardRefValIDs.find(NumberedVals.size());
2280 if (I != ForwardRefValIDs.end()) {
2281 Fn = cast<Function>(I->second.first);
2282 if (Fn->getType() != PFT)
2283 return Error(NameLoc, "type of definition and forward reference of '@" +
2284 utostr(NumberedVals.size()) +"' disagree");
2285 ForwardRefValIDs.erase(I);
2286 }
2287 }
2288
2289 if (Fn == 0)
2290 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2291 else // Move the forward-reference to the correct spot in the module.
2292 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2293
2294 if (FunctionName.empty())
2295 NumberedVals.push_back(Fn);
2296
2297 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2298 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2299 Fn->setCallingConv(CC);
2300 Fn->setAttributes(PAL);
2301 Fn->setAlignment(Alignment);
2302 Fn->setSection(Section);
2303 if (!GC.empty()) Fn->setGC(GC.c_str());
2304
2305 // Add all of the arguments we parsed to the function.
2306 Function::arg_iterator ArgIt = Fn->arg_begin();
2307 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2308 // If the argument has a name, insert it into the argument symbol table.
2309 if (ArgList[i].Name.empty()) continue;
2310
2311 // Set the name, if it conflicted, it will be auto-renamed.
2312 ArgIt->setName(ArgList[i].Name);
2313
2314 if (ArgIt->getNameStr() != ArgList[i].Name)
2315 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2316 ArgList[i].Name + "'");
2317 }
2318
2319 return false;
2320}
2321
2322
2323/// ParseFunctionBody
2324/// ::= '{' BasicBlock+ '}'
2325/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2326///
2327bool LLParser::ParseFunctionBody(Function &Fn) {
2328 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2329 return TokError("expected '{' in function body");
2330 Lex.Lex(); // eat the {.
2331
2332 PerFunctionState PFS(*this, Fn);
2333
2334 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2335 if (ParseBasicBlock(PFS)) return true;
2336
2337 // Eat the }.
2338 Lex.Lex();
2339
2340 // Verify function is ok.
2341 return PFS.VerifyFunctionComplete();
2342}
2343
2344/// ParseBasicBlock
2345/// ::= LabelStr? Instruction*
2346bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2347 // If this basic block starts out with a name, remember it.
2348 std::string Name;
2349 LocTy NameLoc = Lex.getLoc();
2350 if (Lex.getKind() == lltok::LabelStr) {
2351 Name = Lex.getStrVal();
2352 Lex.Lex();
2353 }
2354
2355 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2356 if (BB == 0) return true;
2357
2358 std::string NameStr;
2359
2360 // Parse the instructions in this block until we get a terminator.
2361 Instruction *Inst;
2362 do {
2363 // This instruction may have three possibilities for a name: a) none
2364 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2365 LocTy NameLoc = Lex.getLoc();
2366 int NameID = -1;
2367 NameStr = "";
2368
2369 if (Lex.getKind() == lltok::LocalVarID) {
2370 NameID = Lex.getUIntVal();
2371 Lex.Lex();
2372 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2373 return true;
2374 } else if (Lex.getKind() == lltok::LocalVar ||
2375 // FIXME: REMOVE IN LLVM 3.0
2376 Lex.getKind() == lltok::StringConstant) {
2377 NameStr = Lex.getStrVal();
2378 Lex.Lex();
2379 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2380 return true;
2381 }
2382
2383 if (ParseInstruction(Inst, BB, PFS)) return true;
2384
2385 BB->getInstList().push_back(Inst);
2386
2387 // Set the name on the instruction.
2388 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2389 } while (!isa<TerminatorInst>(Inst));
2390
2391 return false;
2392}
2393
2394//===----------------------------------------------------------------------===//
2395// Instruction Parsing.
2396//===----------------------------------------------------------------------===//
2397
2398/// ParseInstruction - Parse one of the many different instructions.
2399///
2400bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2401 PerFunctionState &PFS) {
2402 lltok::Kind Token = Lex.getKind();
2403 if (Token == lltok::Eof)
2404 return TokError("found end of file when expecting more instructions");
2405 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002406 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 Lex.Lex(); // Eat the keyword.
2408
2409 switch (Token) {
2410 default: return Error(Loc, "expected instruction opcode");
2411 // Terminator Instructions.
2412 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2413 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2414 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2415 case lltok::kw_br: return ParseBr(Inst, PFS);
2416 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2417 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2418 // Binary Operators.
2419 case lltok::kw_add:
2420 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002421 case lltok::kw_mul:
2422 // API compatibility: Accept either integer or floating-point types.
2423 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2424 case lltok::kw_fadd:
2425 case lltok::kw_fsub:
2426 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2427
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 case lltok::kw_udiv:
2429 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002431 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002432 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002433 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002434 case lltok::kw_shl:
2435 case lltok::kw_lshr:
2436 case lltok::kw_ashr:
2437 case lltok::kw_and:
2438 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002439 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 case lltok::kw_icmp:
2441 case lltok::kw_fcmp:
2442 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002443 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002444 // Casts.
2445 case lltok::kw_trunc:
2446 case lltok::kw_zext:
2447 case lltok::kw_sext:
2448 case lltok::kw_fptrunc:
2449 case lltok::kw_fpext:
2450 case lltok::kw_bitcast:
2451 case lltok::kw_uitofp:
2452 case lltok::kw_sitofp:
2453 case lltok::kw_fptoui:
2454 case lltok::kw_fptosi:
2455 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002456 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002457 // Other.
2458 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002459 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002460 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2461 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2462 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2463 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2464 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2465 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2466 // Memory.
2467 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002468 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002469 case lltok::kw_free: return ParseFree(Inst, PFS);
2470 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2471 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2472 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002473 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002474 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002475 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002476 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002477 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002478 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002479 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2480 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2481 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2482 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2483 }
2484}
2485
2486/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2487bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2488 // FIXME: REMOVE vicmp/vfcmp!
2489 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2490 switch (Lex.getKind()) {
2491 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2492 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2493 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2494 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2495 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2496 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2497 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2498 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2499 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2500 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2501 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2502 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2503 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2504 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2505 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2506 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2507 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2508 }
2509 } else {
2510 switch (Lex.getKind()) {
2511 default: TokError("expected icmp predicate (e.g. 'eq')");
2512 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2513 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2514 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2515 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2516 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2517 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2518 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2519 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2520 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2521 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2522 }
2523 }
2524 Lex.Lex();
2525 return false;
2526}
2527
2528//===----------------------------------------------------------------------===//
2529// Terminator Instructions.
2530//===----------------------------------------------------------------------===//
2531
2532/// ParseRet - Parse a return instruction.
2533/// ::= 'ret' void
2534/// ::= 'ret' TypeAndValue
2535/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2536bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2537 PerFunctionState &PFS) {
2538 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002539 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002540
2541 if (Ty == Type::VoidTy) {
2542 Inst = ReturnInst::Create();
2543 return false;
2544 }
2545
2546 Value *RV;
2547 if (ParseValue(Ty, RV, PFS)) return true;
2548
2549 // The normal case is one return value.
2550 if (Lex.getKind() == lltok::comma) {
2551 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2552 // of 'ret {i32,i32} {i32 1, i32 2}'
2553 SmallVector<Value*, 8> RVs;
2554 RVs.push_back(RV);
2555
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002556 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002557 if (ParseTypeAndValue(RV, PFS)) return true;
2558 RVs.push_back(RV);
2559 }
2560
2561 RV = UndefValue::get(PFS.getFunction().getReturnType());
2562 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2563 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2564 BB->getInstList().push_back(I);
2565 RV = I;
2566 }
2567 }
2568 Inst = ReturnInst::Create(RV);
2569 return false;
2570}
2571
2572
2573/// ParseBr
2574/// ::= 'br' TypeAndValue
2575/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2576bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2577 LocTy Loc, Loc2;
2578 Value *Op0, *Op1, *Op2;
2579 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2580
2581 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2582 Inst = BranchInst::Create(BB);
2583 return false;
2584 }
2585
2586 if (Op0->getType() != Type::Int1Ty)
2587 return Error(Loc, "branch condition must have 'i1' type");
2588
2589 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2590 ParseTypeAndValue(Op1, Loc, PFS) ||
2591 ParseToken(lltok::comma, "expected ',' after true destination") ||
2592 ParseTypeAndValue(Op2, Loc2, PFS))
2593 return true;
2594
2595 if (!isa<BasicBlock>(Op1))
2596 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 if (!isa<BasicBlock>(Op2))
2598 return Error(Loc2, "true destination of branch must be a basic block");
2599
2600 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2601 return false;
2602}
2603
2604/// ParseSwitch
2605/// Instruction
2606/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2607/// JumpTable
2608/// ::= (TypeAndValue ',' TypeAndValue)*
2609bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2610 LocTy CondLoc, BBLoc;
2611 Value *Cond, *DefaultBB;
2612 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2613 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2614 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2615 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2616 return true;
2617
2618 if (!isa<IntegerType>(Cond->getType()))
2619 return Error(CondLoc, "switch condition must have integer type");
2620 if (!isa<BasicBlock>(DefaultBB))
2621 return Error(BBLoc, "default destination must be a basic block");
2622
2623 // Parse the jump table pairs.
2624 SmallPtrSet<Value*, 32> SeenCases;
2625 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2626 while (Lex.getKind() != lltok::rsquare) {
2627 Value *Constant, *DestBB;
2628
2629 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2630 ParseToken(lltok::comma, "expected ',' after case value") ||
2631 ParseTypeAndValue(DestBB, BBLoc, PFS))
2632 return true;
2633
2634 if (!SeenCases.insert(Constant))
2635 return Error(CondLoc, "duplicate case value in switch");
2636 if (!isa<ConstantInt>(Constant))
2637 return Error(CondLoc, "case value is not a constant integer");
2638 if (!isa<BasicBlock>(DestBB))
2639 return Error(BBLoc, "case destination is not a basic block");
2640
2641 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2642 cast<BasicBlock>(DestBB)));
2643 }
2644
2645 Lex.Lex(); // Eat the ']'.
2646
2647 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2648 Table.size());
2649 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2650 SI->addCase(Table[i].first, Table[i].second);
2651 Inst = SI;
2652 return false;
2653}
2654
2655/// ParseInvoke
2656/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2657/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2658bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2659 LocTy CallLoc = Lex.getLoc();
2660 unsigned CC, RetAttrs, FnAttrs;
2661 PATypeHolder RetType(Type::VoidTy);
2662 LocTy RetTypeLoc;
2663 ValID CalleeID;
2664 SmallVector<ParamInfo, 16> ArgList;
2665
2666 Value *NormalBB, *UnwindBB;
2667 if (ParseOptionalCallingConv(CC) ||
2668 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002669 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002670 ParseValID(CalleeID) ||
2671 ParseParameterList(ArgList, PFS) ||
2672 ParseOptionalAttrs(FnAttrs, 2) ||
2673 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2674 ParseTypeAndValue(NormalBB, PFS) ||
2675 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2676 ParseTypeAndValue(UnwindBB, PFS))
2677 return true;
2678
2679 if (!isa<BasicBlock>(NormalBB))
2680 return Error(CallLoc, "normal destination is not a basic block");
2681 if (!isa<BasicBlock>(UnwindBB))
2682 return Error(CallLoc, "unwind destination is not a basic block");
2683
2684 // If RetType is a non-function pointer type, then this is the short syntax
2685 // for the call, which means that RetType is just the return type. Infer the
2686 // rest of the function argument types from the arguments that are present.
2687 const PointerType *PFTy = 0;
2688 const FunctionType *Ty = 0;
2689 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2690 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2691 // Pull out the types of all of the arguments...
2692 std::vector<const Type*> ParamTypes;
2693 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2694 ParamTypes.push_back(ArgList[i].V->getType());
2695
2696 if (!FunctionType::isValidReturnType(RetType))
2697 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2698
2699 Ty = FunctionType::get(RetType, ParamTypes, false);
2700 PFTy = PointerType::getUnqual(Ty);
2701 }
2702
2703 // Look up the callee.
2704 Value *Callee;
2705 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2706
2707 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2708 // function attributes.
2709 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2710 if (FnAttrs & ObsoleteFuncAttrs) {
2711 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2712 FnAttrs &= ~ObsoleteFuncAttrs;
2713 }
2714
2715 // Set up the Attributes for the function.
2716 SmallVector<AttributeWithIndex, 8> Attrs;
2717 if (RetAttrs != Attribute::None)
2718 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2719
2720 SmallVector<Value*, 8> Args;
2721
2722 // Loop through FunctionType's arguments and ensure they are specified
2723 // correctly. Also, gather any parameter attributes.
2724 FunctionType::param_iterator I = Ty->param_begin();
2725 FunctionType::param_iterator E = Ty->param_end();
2726 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2727 const Type *ExpectedTy = 0;
2728 if (I != E) {
2729 ExpectedTy = *I++;
2730 } else if (!Ty->isVarArg()) {
2731 return Error(ArgList[i].Loc, "too many arguments specified");
2732 }
2733
2734 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2735 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2736 ExpectedTy->getDescription() + "'");
2737 Args.push_back(ArgList[i].V);
2738 if (ArgList[i].Attrs != Attribute::None)
2739 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2740 }
2741
2742 if (I != E)
2743 return Error(CallLoc, "not enough parameters specified for call");
2744
2745 if (FnAttrs != Attribute::None)
2746 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2747
2748 // Finish off the Attributes and check them
2749 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2750
2751 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2752 cast<BasicBlock>(UnwindBB),
2753 Args.begin(), Args.end());
2754 II->setCallingConv(CC);
2755 II->setAttributes(PAL);
2756 Inst = II;
2757 return false;
2758}
2759
2760
2761
2762//===----------------------------------------------------------------------===//
2763// Binary Operators.
2764//===----------------------------------------------------------------------===//
2765
2766/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002767/// ::= ArithmeticOps TypeAndValue ',' Value
2768///
2769/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2770/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002771bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002772 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002773 LocTy Loc; Value *LHS, *RHS;
2774 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2775 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2776 ParseValue(LHS->getType(), RHS, PFS))
2777 return true;
2778
Chris Lattnere914b592009-01-05 08:24:46 +00002779 bool Valid;
2780 switch (OperandType) {
2781 default: assert(0 && "Unknown operand type!");
2782 case 0: // int or FP.
2783 Valid = LHS->getType()->isIntOrIntVector() ||
2784 LHS->getType()->isFPOrFPVector();
2785 break;
2786 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2787 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2788 }
2789
2790 if (!Valid)
2791 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002792
2793 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2794 return false;
2795}
2796
2797/// ParseLogical
2798/// ::= ArithmeticOps TypeAndValue ',' Value {
2799bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2800 unsigned Opc) {
2801 LocTy Loc; Value *LHS, *RHS;
2802 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2803 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2804 ParseValue(LHS->getType(), RHS, PFS))
2805 return true;
2806
2807 if (!LHS->getType()->isIntOrIntVector())
2808 return Error(Loc,"instruction requires integer or integer vector operands");
2809
2810 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2811 return false;
2812}
2813
2814
2815/// ParseCompare
2816/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2817/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2818/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2819/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2820bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2821 unsigned Opc) {
2822 // Parse the integer/fp comparison predicate.
2823 LocTy Loc;
2824 unsigned Pred;
2825 Value *LHS, *RHS;
2826 if (ParseCmpPredicate(Pred, Opc) ||
2827 ParseTypeAndValue(LHS, Loc, PFS) ||
2828 ParseToken(lltok::comma, "expected ',' after compare value") ||
2829 ParseValue(LHS->getType(), RHS, PFS))
2830 return true;
2831
2832 if (Opc == Instruction::FCmp) {
2833 if (!LHS->getType()->isFPOrFPVector())
2834 return Error(Loc, "fcmp requires floating point operands");
2835 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2836 } else if (Opc == Instruction::ICmp) {
2837 if (!LHS->getType()->isIntOrIntVector() &&
2838 !isa<PointerType>(LHS->getType()))
2839 return Error(Loc, "icmp requires integer operands");
2840 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2841 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002842 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2843 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002844 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2845 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002846 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2847 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002848 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2849 }
2850 return false;
2851}
2852
2853//===----------------------------------------------------------------------===//
2854// Other Instructions.
2855//===----------------------------------------------------------------------===//
2856
2857
2858/// ParseCast
2859/// ::= CastOpc TypeAndValue 'to' Type
2860bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2861 unsigned Opc) {
2862 LocTy Loc; Value *Op;
2863 PATypeHolder DestTy(Type::VoidTy);
2864 if (ParseTypeAndValue(Op, Loc, PFS) ||
2865 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2866 ParseType(DestTy))
2867 return true;
2868
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002869 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2870 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 return Error(Loc, "invalid cast opcode for cast from '" +
2872 Op->getType()->getDescription() + "' to '" +
2873 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002874 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2876 return false;
2877}
2878
2879/// ParseSelect
2880/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2881bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2882 LocTy Loc;
2883 Value *Op0, *Op1, *Op2;
2884 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2885 ParseToken(lltok::comma, "expected ',' after select condition") ||
2886 ParseTypeAndValue(Op1, PFS) ||
2887 ParseToken(lltok::comma, "expected ',' after select value") ||
2888 ParseTypeAndValue(Op2, PFS))
2889 return true;
2890
2891 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2892 return Error(Loc, Reason);
2893
2894 Inst = SelectInst::Create(Op0, Op1, Op2);
2895 return false;
2896}
2897
Chris Lattner0088a5c2009-01-05 08:18:44 +00002898/// ParseVA_Arg
2899/// ::= 'va_arg' TypeAndValue ',' Type
2900bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002901 Value *Op;
2902 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002903 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002904 if (ParseTypeAndValue(Op, PFS) ||
2905 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002906 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002908
2909 if (!EltTy->isFirstClassType())
2910 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002911
2912 Inst = new VAArgInst(Op, EltTy);
2913 return false;
2914}
2915
2916/// ParseExtractElement
2917/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2918bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2919 LocTy Loc;
2920 Value *Op0, *Op1;
2921 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2922 ParseToken(lltok::comma, "expected ',' after extract value") ||
2923 ParseTypeAndValue(Op1, PFS))
2924 return true;
2925
2926 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2927 return Error(Loc, "invalid extractelement operands");
2928
2929 Inst = new ExtractElementInst(Op0, Op1);
2930 return false;
2931}
2932
2933/// ParseInsertElement
2934/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2935bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2936 LocTy Loc;
2937 Value *Op0, *Op1, *Op2;
2938 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2939 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2940 ParseTypeAndValue(Op1, PFS) ||
2941 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2942 ParseTypeAndValue(Op2, PFS))
2943 return true;
2944
2945 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2946 return Error(Loc, "invalid extractelement operands");
2947
2948 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2949 return false;
2950}
2951
2952/// ParseShuffleVector
2953/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2954bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2955 LocTy Loc;
2956 Value *Op0, *Op1, *Op2;
2957 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2958 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2959 ParseTypeAndValue(Op1, PFS) ||
2960 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2961 ParseTypeAndValue(Op2, PFS))
2962 return true;
2963
2964 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2965 return Error(Loc, "invalid extractelement operands");
2966
2967 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2968 return false;
2969}
2970
2971/// ParsePHI
2972/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2973bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2974 PATypeHolder Ty(Type::VoidTy);
2975 Value *Op0, *Op1;
2976 LocTy TypeLoc = Lex.getLoc();
2977
2978 if (ParseType(Ty) ||
2979 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2980 ParseValue(Ty, Op0, PFS) ||
2981 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2982 ParseValue(Type::LabelTy, Op1, PFS) ||
2983 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2984 return true;
2985
2986 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2987 while (1) {
2988 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2989
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002990 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 break;
2992
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002993 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 ParseValue(Ty, Op0, PFS) ||
2995 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2996 ParseValue(Type::LabelTy, Op1, PFS) ||
2997 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2998 return true;
2999 }
3000
3001 if (!Ty->isFirstClassType())
3002 return Error(TypeLoc, "phi node must have first class type");
3003
3004 PHINode *PN = PHINode::Create(Ty);
3005 PN->reserveOperandSpace(PHIVals.size());
3006 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3007 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3008 Inst = PN;
3009 return false;
3010}
3011
3012/// ParseCall
3013/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3014/// ParameterList OptionalAttrs
3015bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3016 bool isTail) {
3017 unsigned CC, RetAttrs, FnAttrs;
3018 PATypeHolder RetType(Type::VoidTy);
3019 LocTy RetTypeLoc;
3020 ValID CalleeID;
3021 SmallVector<ParamInfo, 16> ArgList;
3022 LocTy CallLoc = Lex.getLoc();
3023
3024 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3025 ParseOptionalCallingConv(CC) ||
3026 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003027 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003028 ParseValID(CalleeID) ||
3029 ParseParameterList(ArgList, PFS) ||
3030 ParseOptionalAttrs(FnAttrs, 2))
3031 return true;
3032
3033 // If RetType is a non-function pointer type, then this is the short syntax
3034 // for the call, which means that RetType is just the return type. Infer the
3035 // rest of the function argument types from the arguments that are present.
3036 const PointerType *PFTy = 0;
3037 const FunctionType *Ty = 0;
3038 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3039 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3040 // Pull out the types of all of the arguments...
3041 std::vector<const Type*> ParamTypes;
3042 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3043 ParamTypes.push_back(ArgList[i].V->getType());
3044
3045 if (!FunctionType::isValidReturnType(RetType))
3046 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3047
3048 Ty = FunctionType::get(RetType, ParamTypes, false);
3049 PFTy = PointerType::getUnqual(Ty);
3050 }
3051
3052 // Look up the callee.
3053 Value *Callee;
3054 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3055
Chris Lattnerdf986172009-01-02 07:01:27 +00003056 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3057 // function attributes.
3058 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3059 if (FnAttrs & ObsoleteFuncAttrs) {
3060 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3061 FnAttrs &= ~ObsoleteFuncAttrs;
3062 }
3063
3064 // Set up the Attributes for the function.
3065 SmallVector<AttributeWithIndex, 8> Attrs;
3066 if (RetAttrs != Attribute::None)
3067 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3068
3069 SmallVector<Value*, 8> Args;
3070
3071 // Loop through FunctionType's arguments and ensure they are specified
3072 // correctly. Also, gather any parameter attributes.
3073 FunctionType::param_iterator I = Ty->param_begin();
3074 FunctionType::param_iterator E = Ty->param_end();
3075 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3076 const Type *ExpectedTy = 0;
3077 if (I != E) {
3078 ExpectedTy = *I++;
3079 } else if (!Ty->isVarArg()) {
3080 return Error(ArgList[i].Loc, "too many arguments specified");
3081 }
3082
3083 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3084 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3085 ExpectedTy->getDescription() + "'");
3086 Args.push_back(ArgList[i].V);
3087 if (ArgList[i].Attrs != Attribute::None)
3088 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3089 }
3090
3091 if (I != E)
3092 return Error(CallLoc, "not enough parameters specified for call");
3093
3094 if (FnAttrs != Attribute::None)
3095 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3096
3097 // Finish off the Attributes and check them
3098 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3099
3100 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3101 CI->setTailCall(isTail);
3102 CI->setCallingConv(CC);
3103 CI->setAttributes(PAL);
3104 Inst = CI;
3105 return false;
3106}
3107
3108//===----------------------------------------------------------------------===//
3109// Memory Instructions.
3110//===----------------------------------------------------------------------===//
3111
3112/// ParseAlloc
3113/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3114/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3115bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3116 unsigned Opc) {
3117 PATypeHolder Ty(Type::VoidTy);
3118 Value *Size = 0;
3119 LocTy SizeLoc = 0;
3120 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003121 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003122
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003123 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003124 if (Lex.getKind() == lltok::kw_align) {
3125 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003126 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3127 ParseOptionalCommaAlignment(Alignment)) {
3128 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003129 }
3130 }
3131
3132 if (Size && Size->getType() != Type::Int32Ty)
3133 return Error(SizeLoc, "element count must be i32");
3134
3135 if (Opc == Instruction::Malloc)
3136 Inst = new MallocInst(Ty, Size, Alignment);
3137 else
3138 Inst = new AllocaInst(Ty, Size, Alignment);
3139 return false;
3140}
3141
3142/// ParseFree
3143/// ::= 'free' TypeAndValue
3144bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3145 Value *Val; LocTy Loc;
3146 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3147 if (!isa<PointerType>(Val->getType()))
3148 return Error(Loc, "operand to free must be a pointer");
3149 Inst = new FreeInst(Val);
3150 return false;
3151}
3152
3153/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003154/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003155bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3156 bool isVolatile) {
3157 Value *Val; LocTy Loc;
3158 unsigned Alignment;
3159 if (ParseTypeAndValue(Val, Loc, PFS) ||
3160 ParseOptionalCommaAlignment(Alignment))
3161 return true;
3162
3163 if (!isa<PointerType>(Val->getType()) ||
3164 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3165 return Error(Loc, "load operand must be a pointer to a first class type");
3166
3167 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3168 return false;
3169}
3170
3171/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003172/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003173bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3174 bool isVolatile) {
3175 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3176 unsigned Alignment;
3177 if (ParseTypeAndValue(Val, Loc, PFS) ||
3178 ParseToken(lltok::comma, "expected ',' after store operand") ||
3179 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3180 ParseOptionalCommaAlignment(Alignment))
3181 return true;
3182
3183 if (!isa<PointerType>(Ptr->getType()))
3184 return Error(PtrLoc, "store operand must be a pointer");
3185 if (!Val->getType()->isFirstClassType())
3186 return Error(Loc, "store operand must be a first class value");
3187 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3188 return Error(Loc, "stored value and pointer type do not match");
3189
3190 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3191 return false;
3192}
3193
3194/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003195/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003196/// FIXME: Remove support for getresult in LLVM 3.0
3197bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3198 Value *Val; LocTy ValLoc, EltLoc;
3199 unsigned Element;
3200 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3201 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003202 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 return true;
3204
3205 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3206 return Error(ValLoc, "getresult inst requires an aggregate operand");
3207 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3208 return Error(EltLoc, "invalid getresult index for value");
3209 Inst = ExtractValueInst::Create(Val, Element);
3210 return false;
3211}
3212
3213/// ParseGetElementPtr
3214/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3215bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3216 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003217 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003218
3219 if (!isa<PointerType>(Ptr->getType()))
3220 return Error(Loc, "base of getelementptr must be a pointer");
3221
3222 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003223 while (EatIfPresent(lltok::comma)) {
3224 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 if (!isa<IntegerType>(Val->getType()))
3226 return Error(EltLoc, "getelementptr index must be an integer");
3227 Indices.push_back(Val);
3228 }
3229
3230 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3231 Indices.begin(), Indices.end()))
3232 return Error(Loc, "invalid getelementptr indices");
3233 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3234 return false;
3235}
3236
3237/// ParseExtractValue
3238/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3239bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3240 Value *Val; LocTy Loc;
3241 SmallVector<unsigned, 4> Indices;
3242 if (ParseTypeAndValue(Val, Loc, PFS) ||
3243 ParseIndexList(Indices))
3244 return true;
3245
3246 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3247 return Error(Loc, "extractvalue operand must be array or struct");
3248
3249 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3250 Indices.end()))
3251 return Error(Loc, "invalid indices for extractvalue");
3252 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3253 return false;
3254}
3255
3256/// ParseInsertValue
3257/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3258bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3259 Value *Val0, *Val1; LocTy Loc0, Loc1;
3260 SmallVector<unsigned, 4> Indices;
3261 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3262 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3263 ParseTypeAndValue(Val1, Loc1, PFS) ||
3264 ParseIndexList(Indices))
3265 return true;
3266
3267 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3268 return Error(Loc0, "extractvalue operand must be array or struct");
3269
3270 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3271 Indices.end()))
3272 return Error(Loc0, "invalid indices for insertvalue");
3273 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3274 return false;
3275}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003276
3277//===----------------------------------------------------------------------===//
3278// Embedded metadata.
3279//===----------------------------------------------------------------------===//
3280
3281/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003282/// ::= Element (',' Element)*
3283/// Element
3284/// ::= 'null' | TypeAndValue
3285bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003286 assert(Lex.getKind() == lltok::lbrace);
3287 Lex.Lex();
3288 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003289 Value *V;
3290 if (Lex.getKind() == lltok::kw_null) {
3291 Lex.Lex();
3292 V = 0;
3293 } else {
3294 Constant *C;
3295 if (ParseGlobalTypeAndValue(C)) return true;
3296 V = C;
3297 }
3298 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003299 } while (EatIfPresent(lltok::comma));
3300
3301 return false;
3302}