blob: ab686ced9b07952abafdb5acc49e128ddaea3445 [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
Owen Andersonfba933c2009-07-01 23:57:11 +000021#include "llvm/LLVMContext.h"
Devang Patel0a9f7b92009-07-28 21:49:47 +000022#include "llvm/Metadata.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000024#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000025#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000029#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
Chris Lattnerdf986172009-01-02 07:01:27 +000032namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000033 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000037 struct ValID {
38 enum {
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000043 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000044 t_Constant, // Value in ConstantVal.
Devang Patele54abc92009-07-22 17:43:22 +000045 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
Chris Lattnerdf986172009-01-02 07:01:27 +000047 } Kind;
48
49 LLParser::LocTy Loc;
50 unsigned UIntVal;
51 std::string StrVal, StrVal2;
52 APSInt APSIntVal;
53 APFloat APFloatVal;
54 Constant *ConstantVal;
Devang Patele54abc92009-07-22 17:43:22 +000055 MetadataBase *MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +000056 ValID() : APFloatVal(0.0) {}
57 };
58}
59
Chris Lattner3ed88ef2009-01-02 08:05:26 +000060/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000061bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000062 // Prime the lexer.
63 Lex.Lex();
64
Chris Lattnerad7d1e22009-01-04 20:44:11 +000065 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000067}
68
69/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70/// module.
71bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes.empty())
73 return Error(ForwardRefTypes.begin()->second.second,
74 "use of undefined type named '" +
75 ForwardRefTypes.begin()->first + "'");
76 if (!ForwardRefTypeIDs.empty())
77 return Error(ForwardRefTypeIDs.begin()->second.second,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs.begin()->first) + "'");
80
81 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
84 "'");
85
86 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
90
Devang Patel1c7eea62009-07-08 19:23:54 +000091 if (!ForwardRefMDNodes.empty())
92 return Error(ForwardRefMDNodes.begin()->second.second,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes.begin()->first) + "'");
95
96
Chris Lattnerdf986172009-01-02 07:01:27 +000097 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100
101 return false;
102}
103
104//===----------------------------------------------------------------------===//
105// Top-Level Entities
106//===----------------------------------------------------------------------===//
107
108bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000109 while (1) {
110 switch (Lex.getKind()) {
111 default: return TokError("expected top-level entity");
112 case lltok::Eof: return false;
113 //case lltok::kw_define:
114 case lltok::kw_declare: if (ParseDeclare()) return true; break;
115 case lltok::kw_define: if (ParseDefine()) return true; break;
116 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
117 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
118 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000120 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000121 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
122 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000123 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000124 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000125 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Pateleff2ab62009-07-29 00:34:02 +0000126 case lltok::NamedMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000127
128 // The Global variable production with no name can have many different
129 // optional leading prefixes, the production is:
130 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
131 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000132 case lltok::kw_private : // OptionalLinkage
133 case lltok::kw_linker_private: // OptionalLinkage
134 case lltok::kw_internal: // OptionalLinkage
135 case lltok::kw_weak: // OptionalLinkage
136 case lltok::kw_weak_odr: // OptionalLinkage
137 case lltok::kw_linkonce: // OptionalLinkage
138 case lltok::kw_linkonce_odr: // OptionalLinkage
139 case lltok::kw_appending: // OptionalLinkage
140 case lltok::kw_dllexport: // OptionalLinkage
141 case lltok::kw_common: // OptionalLinkage
142 case lltok::kw_dllimport: // OptionalLinkage
143 case lltok::kw_extern_weak: // OptionalLinkage
144 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000145 unsigned Linkage, Visibility;
146 if (ParseOptionalLinkage(Linkage) ||
147 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000148 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000149 return true;
150 break;
151 }
152 case lltok::kw_default: // OptionalVisibility
153 case lltok::kw_hidden: // OptionalVisibility
154 case lltok::kw_protected: { // OptionalVisibility
155 unsigned Visibility;
156 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000157 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000158 return true;
159 break;
160 }
161
162 case lltok::kw_thread_local: // OptionalThreadLocal
163 case lltok::kw_addrspace: // OptionalAddrSpace
164 case lltok::kw_constant: // GlobalType
165 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000166 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 break;
168 }
169 }
170}
171
172
173/// toplevelentity
174/// ::= 'module' 'asm' STRINGCONSTANT
175bool LLParser::ParseModuleAsm() {
176 assert(Lex.getKind() == lltok::kw_module);
177 Lex.Lex();
178
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000179 std::string AsmStr;
180 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
181 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000182
183 const std::string &AsmSoFar = M->getModuleInlineAsm();
184 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000185 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 return false;
189}
190
191/// toplevelentity
192/// ::= 'target' 'triple' '=' STRINGCONSTANT
193/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
194bool LLParser::ParseTargetDefinition() {
195 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000196 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000197 switch (Lex.Lex()) {
198 default: return TokError("unknown target property");
199 case lltok::kw_triple:
200 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000201 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
202 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000203 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000204 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return false;
206 case lltok::kw_datalayout:
207 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000208 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
209 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000210 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000211 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return false;
213 }
214}
215
216/// toplevelentity
217/// ::= 'deplibs' '=' '[' ']'
218/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
219bool LLParser::ParseDepLibs() {
220 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000221 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000222 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
223 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
224 return true;
225
226 if (EatIfPresent(lltok::rsquare))
227 return false;
228
229 std::string Str;
230 if (ParseStringConstant(Str)) return true;
231 M->addLibrary(Str);
232
233 while (EatIfPresent(lltok::comma)) {
234 if (ParseStringConstant(Str)) return true;
235 M->addLibrary(Str);
236 }
237
238 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000239}
240
Dan Gohman3845e502009-08-12 23:32:33 +0000241/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000242/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000243/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000244bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000245 unsigned TypeID = NumberedTypes.size();
246
247 // Handle the LocalVarID form.
248 if (Lex.getKind() == lltok::LocalVarID) {
249 if (Lex.getUIntVal() != TypeID)
250 return Error(Lex.getLoc(), "type expected to be numbered '%" +
251 utostr(TypeID) + "'");
252 Lex.Lex(); // eat LocalVarID;
253
254 if (ParseToken(lltok::equal, "expected '=' after name"))
255 return true;
256 }
257
Chris Lattnerdf986172009-01-02 07:01:27 +0000258 assert(Lex.getKind() == lltok::kw_type);
259 LocTy TypeLoc = Lex.getLoc();
260 Lex.Lex(); // eat kw_type
261
262 PATypeHolder Ty(Type::VoidTy);
263 if (ParseType(Ty)) return true;
264
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 // See if this type was previously referenced.
266 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
267 FI = ForwardRefTypeIDs.find(TypeID);
268 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000269 if (FI->second.first.get() == Ty)
270 return Error(TypeLoc, "self referential type is invalid");
271
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
273 Ty = FI->second.first.get();
274 ForwardRefTypeIDs.erase(FI);
275 }
276
277 NumberedTypes.push_back(Ty);
278
279 return false;
280}
281
282/// toplevelentity
283/// ::= LocalVar '=' 'type' type
284bool LLParser::ParseNamedType() {
285 std::string Name = Lex.getStrVal();
286 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000287 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000288
289 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000290
291 if (ParseToken(lltok::equal, "expected '=' after name") ||
292 ParseToken(lltok::kw_type, "expected 'type' after name") ||
293 ParseType(Ty))
294 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000295
Chris Lattnerdf986172009-01-02 07:01:27 +0000296 // Set the type name, checking for conflicts as we do so.
297 bool AlreadyExists = M->addTypeName(Name, Ty);
298 if (!AlreadyExists) return false;
299
300 // See if this type is a forward reference. We need to eagerly resolve
301 // types to allow recursive type redefinitions below.
302 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
303 FI = ForwardRefTypes.find(Name);
304 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000305 if (FI->second.first.get() == Ty)
306 return Error(NameLoc, "self referential type is invalid");
307
Chris Lattnerdf986172009-01-02 07:01:27 +0000308 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
309 Ty = FI->second.first.get();
310 ForwardRefTypes.erase(FI);
311 }
312
313 // Inserting a name that is already defined, get the existing name.
314 const Type *Existing = M->getTypeByName(Name);
315 assert(Existing && "Conflict but no matching type?!");
316
317 // Otherwise, this is an attempt to redefine a type. That's okay if
318 // the redefinition is identical to the original.
319 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
320 if (Existing == Ty) return false;
321
322 // Any other kind of (non-equivalent) redefinition is an error.
323 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
324 Ty->getDescription() + "'");
325}
326
327
328/// toplevelentity
329/// ::= 'declare' FunctionHeader
330bool LLParser::ParseDeclare() {
331 assert(Lex.getKind() == lltok::kw_declare);
332 Lex.Lex();
333
334 Function *F;
335 return ParseFunctionHeader(F, false);
336}
337
338/// toplevelentity
339/// ::= 'define' FunctionHeader '{' ...
340bool LLParser::ParseDefine() {
341 assert(Lex.getKind() == lltok::kw_define);
342 Lex.Lex();
343
344 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000345 return ParseFunctionHeader(F, true) ||
346 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000347}
348
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000349/// ParseGlobalType
350/// ::= 'constant'
351/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000352bool LLParser::ParseGlobalType(bool &IsConstant) {
353 if (Lex.getKind() == lltok::kw_constant)
354 IsConstant = true;
355 else if (Lex.getKind() == lltok::kw_global)
356 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000357 else {
358 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000359 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000360 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000361 Lex.Lex();
362 return false;
363}
364
Dan Gohman3845e502009-08-12 23:32:33 +0000365/// ParseUnnamedGlobal:
366/// OptionalVisibility ALIAS ...
367/// OptionalLinkage OptionalVisibility ... -> global variable
368/// GlobalID '=' OptionalVisibility ALIAS ...
369/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
370bool LLParser::ParseUnnamedGlobal() {
371 unsigned VarID = NumberedVals.size();
372 std::string Name;
373 LocTy NameLoc = Lex.getLoc();
374
375 // Handle the GlobalID form.
376 if (Lex.getKind() == lltok::GlobalID) {
377 if (Lex.getUIntVal() != VarID)
378 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
379 utostr(VarID) + "'");
380 Lex.Lex(); // eat GlobalID;
381
382 if (ParseToken(lltok::equal, "expected '=' after name"))
383 return true;
384 }
385
386 bool HasLinkage;
387 unsigned Linkage, Visibility;
388 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
389 ParseOptionalVisibility(Visibility))
390 return true;
391
392 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
393 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
394 return ParseAlias(Name, NameLoc, Visibility);
395}
396
Chris Lattnerdf986172009-01-02 07:01:27 +0000397/// ParseNamedGlobal:
398/// GlobalVar '=' OptionalVisibility ALIAS ...
399/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
400bool LLParser::ParseNamedGlobal() {
401 assert(Lex.getKind() == lltok::GlobalVar);
402 LocTy NameLoc = Lex.getLoc();
403 std::string Name = Lex.getStrVal();
404 Lex.Lex();
405
406 bool HasLinkage;
407 unsigned Linkage, Visibility;
408 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
409 ParseOptionalLinkage(Linkage, HasLinkage) ||
410 ParseOptionalVisibility(Visibility))
411 return true;
412
413 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
415 return ParseAlias(Name, NameLoc, Visibility);
416}
417
Devang Patel256be962009-07-20 19:00:08 +0000418// MDString:
419// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000420bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000421 std::string Str;
422 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000423 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000424 return false;
425}
426
427// MDNode:
428// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000429bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000430 // !{ ..., !42, ... }
431 unsigned MID = 0;
432 if (ParseUInt32(MID)) return true;
433
434 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000435 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000436 if (I != MetadataCache.end()) {
437 Node = I->second;
438 return false;
439 }
440
441 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000442 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000443 FI = ForwardRefMDNodes.find(MID);
444 if (FI != ForwardRefMDNodes.end()) {
445 Node = FI->second.first;
446 return false;
447 }
448
449 // Create MDNode forward reference
450 SmallVector<Value *, 1> Elts;
451 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000452 Elts.push_back(MDString::get(Context, FwdRefName));
453 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000454 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
455 Node = FwdNode;
456 return false;
457}
458
Devang Pateleff2ab62009-07-29 00:34:02 +0000459///ParseNamedMetadata:
460/// !foo = !{ !1, !2 }
461bool LLParser::ParseNamedMetadata() {
462 assert(Lex.getKind() == lltok::NamedMD);
463 Lex.Lex();
464 std::string Name = Lex.getStrVal();
465
466 if (ParseToken(lltok::equal, "expected '=' here"))
467 return true;
468
469 if (Lex.getKind() != lltok::Metadata)
470 return TokError("Expected '!' here");
471 Lex.Lex();
472
473 if (Lex.getKind() != lltok::lbrace)
474 return TokError("Expected '{' here");
475 Lex.Lex();
476 SmallVector<MetadataBase *, 8> Elts;
477 do {
478 if (Lex.getKind() != lltok::Metadata)
479 return TokError("Expected '!' here");
480 Lex.Lex();
481 MetadataBase *N = 0;
482 if (ParseMDNode(N)) return true;
483 Elts.push_back(N);
484 } while (EatIfPresent(lltok::comma));
485
486 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
487 return true;
488
Devang Patel5316bf02009-07-29 21:58:56 +0000489 NamedMDNode::Create(Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000490 return false;
491}
492
Devang Patel923078c2009-07-01 19:21:12 +0000493/// ParseStandaloneMetadata:
494/// !42 = !{...}
495bool LLParser::ParseStandaloneMetadata() {
496 assert(Lex.getKind() == lltok::Metadata);
497 Lex.Lex();
498 unsigned MetadataID = 0;
499 if (ParseUInt32(MetadataID))
500 return true;
501 if (MetadataCache.find(MetadataID) != MetadataCache.end())
502 return TokError("Metadata id is already used");
503 if (ParseToken(lltok::equal, "expected '=' here"))
504 return true;
505
506 LocTy TyLoc;
Devang Patel923078c2009-07-01 19:21:12 +0000507 PATypeHolder Ty(Type::VoidTy);
Devang Patel2214c942009-07-08 21:57:07 +0000508 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000509 return true;
510
Devang Patel104cf9e2009-07-23 01:07:34 +0000511 if (Lex.getKind() != lltok::Metadata)
512 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000513
Devang Patel104cf9e2009-07-23 01:07:34 +0000514 Lex.Lex();
515 if (Lex.getKind() != lltok::lbrace)
516 return TokError("Expected '{' here");
517
518 SmallVector<Value *, 16> Elts;
519 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000520 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000521 return true;
522
Owen Anderson647e3012009-07-31 21:35:40 +0000523 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000524 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000525 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000526 FI = ForwardRefMDNodes.find(MetadataID);
527 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000528 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000529 FwdNode->replaceAllUsesWith(Init);
530 ForwardRefMDNodes.erase(FI);
531 }
532
Devang Patel923078c2009-07-01 19:21:12 +0000533 return false;
534}
535
Chris Lattnerdf986172009-01-02 07:01:27 +0000536/// ParseAlias:
537/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
538/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000539/// ::= TypeAndValue
540/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000541/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000542///
543/// Everything through visibility has already been parsed.
544///
545bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
546 unsigned Visibility) {
547 assert(Lex.getKind() == lltok::kw_alias);
548 Lex.Lex();
549 unsigned Linkage;
550 LocTy LinkageLoc = Lex.getLoc();
551 if (ParseOptionalLinkage(Linkage))
552 return true;
553
554 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000555 Linkage != GlobalValue::WeakAnyLinkage &&
556 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000557 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000558 Linkage != GlobalValue::PrivateLinkage &&
559 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000560 return Error(LinkageLoc, "invalid linkage type for alias");
561
562 Constant *Aliasee;
563 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000564 if (Lex.getKind() != lltok::kw_bitcast &&
565 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000566 if (ParseGlobalTypeAndValue(Aliasee)) return true;
567 } else {
568 // The bitcast dest type is not present, it is implied by the dest type.
569 ValID ID;
570 if (ParseValID(ID)) return true;
571 if (ID.Kind != ValID::t_Constant)
572 return Error(AliaseeLoc, "invalid aliasee");
573 Aliasee = ID.ConstantVal;
574 }
575
576 if (!isa<PointerType>(Aliasee->getType()))
577 return Error(AliaseeLoc, "alias must have pointer type");
578
579 // Okay, create the alias but do not insert it into the module yet.
580 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
581 (GlobalValue::LinkageTypes)Linkage, Name,
582 Aliasee);
583 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
584
585 // See if this value already exists in the symbol table. If so, it is either
586 // a redefinition or a definition of a forward reference.
587 if (GlobalValue *Val =
588 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
589 // See if this was a redefinition. If so, there is no entry in
590 // ForwardRefVals.
591 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
592 I = ForwardRefVals.find(Name);
593 if (I == ForwardRefVals.end())
594 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
595
596 // Otherwise, this was a definition of forward ref. Verify that types
597 // agree.
598 if (Val->getType() != GA->getType())
599 return Error(NameLoc,
600 "forward reference and definition of alias have different types");
601
602 // If they agree, just RAUW the old value with the alias and remove the
603 // forward ref info.
604 Val->replaceAllUsesWith(GA);
605 Val->eraseFromParent();
606 ForwardRefVals.erase(I);
607 }
608
609 // Insert into the module, we know its name won't collide now.
610 M->getAliasList().push_back(GA);
611 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
612
613 return false;
614}
615
616/// ParseGlobal
617/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
618/// OptionalAddrSpace GlobalType Type Const
619/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
620/// OptionalAddrSpace GlobalType Type Const
621///
622/// Everything through visibility has been parsed already.
623///
624bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
625 unsigned Linkage, bool HasLinkage,
626 unsigned Visibility) {
627 unsigned AddrSpace;
628 bool ThreadLocal, IsConstant;
629 LocTy TyLoc;
630
631 PATypeHolder Ty(Type::VoidTy);
632 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
633 ParseOptionalAddrSpace(AddrSpace) ||
634 ParseGlobalType(IsConstant) ||
635 ParseType(Ty, TyLoc))
636 return true;
637
638 // If the linkage is specified and is external, then no initializer is
639 // present.
640 Constant *Init = 0;
641 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000642 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000643 Linkage != GlobalValue::ExternalLinkage)) {
644 if (ParseGlobalValue(Ty, Init))
645 return true;
646 }
647
Chris Lattnera9a9e072009-03-09 04:49:14 +0000648 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000649 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000650
651 GlobalVariable *GV = 0;
652
653 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000654 if (!Name.empty()) {
655 if ((GV = M->getGlobalVariable(Name, true)) &&
656 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 return Error(NameLoc, "redefinition of global '@" + Name + "'");
658 } else {
659 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefValIDs.find(NumberedVals.size());
661 if (I != ForwardRefValIDs.end()) {
662 GV = cast<GlobalVariable>(I->second.first);
663 ForwardRefValIDs.erase(I);
664 }
665 }
666
667 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000668 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
669 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 } else {
671 if (GV->getType()->getElementType() != Ty)
672 return Error(TyLoc,
673 "forward reference and definition of global have different types");
674
675 // Move the forward-reference to the correct spot in the module.
676 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
677 }
678
679 if (Name.empty())
680 NumberedVals.push_back(GV);
681
682 // Set the parsed properties on the global.
683 if (Init)
684 GV->setInitializer(Init);
685 GV->setConstant(IsConstant);
686 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
687 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
688 GV->setThreadLocal(ThreadLocal);
689
690 // Parse attributes on the global.
691 while (Lex.getKind() == lltok::comma) {
692 Lex.Lex();
693
694 if (Lex.getKind() == lltok::kw_section) {
695 Lex.Lex();
696 GV->setSection(Lex.getStrVal());
697 if (ParseToken(lltok::StringConstant, "expected global section string"))
698 return true;
699 } else if (Lex.getKind() == lltok::kw_align) {
700 unsigned Alignment;
701 if (ParseOptionalAlignment(Alignment)) return true;
702 GV->setAlignment(Alignment);
703 } else {
704 TokError("unknown global variable property!");
705 }
706 }
707
708 return false;
709}
710
711
712//===----------------------------------------------------------------------===//
713// GlobalValue Reference/Resolution Routines.
714//===----------------------------------------------------------------------===//
715
716/// GetGlobalVal - Get a value with the specified name or ID, creating a
717/// forward reference record if needed. This can return null if the value
718/// exists but does not have the right type.
719GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
720 LocTy Loc) {
721 const PointerType *PTy = dyn_cast<PointerType>(Ty);
722 if (PTy == 0) {
723 Error(Loc, "global variable reference must have pointer type");
724 return 0;
725 }
726
727 // Look this name up in the normal function symbol table.
728 GlobalValue *Val =
729 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
730
731 // If this is a forward reference for the value, see if we already created a
732 // forward ref record.
733 if (Val == 0) {
734 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
735 I = ForwardRefVals.find(Name);
736 if (I != ForwardRefVals.end())
737 Val = I->second.first;
738 }
739
740 // If we have the value in the symbol table or fwd-ref table, return it.
741 if (Val) {
742 if (Val->getType() == Ty) return Val;
743 Error(Loc, "'@" + Name + "' defined with type '" +
744 Val->getType()->getDescription() + "'");
745 return 0;
746 }
747
748 // Otherwise, create a new forward reference for this value and remember it.
749 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000750 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
751 // Function types can return opaque but functions can't.
752 if (isa<OpaqueType>(FT->getReturnType())) {
753 Error(Loc, "function may not return opaque type");
754 return 0;
755 }
756
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000757 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000758 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000759 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
760 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000761 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000762
763 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
764 return FwdVal;
765}
766
767GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
768 const PointerType *PTy = dyn_cast<PointerType>(Ty);
769 if (PTy == 0) {
770 Error(Loc, "global variable reference must have pointer type");
771 return 0;
772 }
773
774 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
775
776 // If this is a forward reference for the value, see if we already created a
777 // forward ref record.
778 if (Val == 0) {
779 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
780 I = ForwardRefValIDs.find(ID);
781 if (I != ForwardRefValIDs.end())
782 Val = I->second.first;
783 }
784
785 // If we have the value in the symbol table or fwd-ref table, return it.
786 if (Val) {
787 if (Val->getType() == Ty) return Val;
788 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
789 Val->getType()->getDescription() + "'");
790 return 0;
791 }
792
793 // Otherwise, create a new forward reference for this value and remember it.
794 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000795 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
796 // Function types can return opaque but functions can't.
797 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000798 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000799 return 0;
800 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000801 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000802 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000803 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
804 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000805 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000806
807 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
808 return FwdVal;
809}
810
811
812//===----------------------------------------------------------------------===//
813// Helper Routines.
814//===----------------------------------------------------------------------===//
815
816/// ParseToken - If the current token has the specified kind, eat it and return
817/// success. Otherwise, emit the specified error and return failure.
818bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
819 if (Lex.getKind() != T)
820 return TokError(ErrMsg);
821 Lex.Lex();
822 return false;
823}
824
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000825/// ParseStringConstant
826/// ::= StringConstant
827bool LLParser::ParseStringConstant(std::string &Result) {
828 if (Lex.getKind() != lltok::StringConstant)
829 return TokError("expected string constant");
830 Result = Lex.getStrVal();
831 Lex.Lex();
832 return false;
833}
834
835/// ParseUInt32
836/// ::= uint32
837bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000838 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
839 return TokError("expected integer");
840 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
841 if (Val64 != unsigned(Val64))
842 return TokError("expected 32-bit integer (too large)");
843 Val = Val64;
844 Lex.Lex();
845 return false;
846}
847
848
849/// ParseOptionalAddrSpace
850/// := /*empty*/
851/// := 'addrspace' '(' uint32 ')'
852bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
853 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000854 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000856 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000857 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 ParseToken(lltok::rparen, "expected ')' in address space");
859}
860
861/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
862/// indicates what kind of attribute list this is: 0: function arg, 1: result,
863/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000864/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000865bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
866 Attrs = Attribute::None;
867 LocTy AttrLoc = Lex.getLoc();
868
869 while (1) {
870 switch (Lex.getKind()) {
871 case lltok::kw_sext:
872 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000873 // Treat these as signext/zeroext if they occur in the argument list after
874 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
875 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
876 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000877 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000878 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 if (Lex.getKind() == lltok::kw_sext)
880 Attrs |= Attribute::SExt;
881 else
882 Attrs |= Attribute::ZExt;
883 break;
884 }
885 // FALL THROUGH.
886 default: // End of attributes.
887 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
888 return Error(AttrLoc, "invalid use of function-only attribute");
889
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000890 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000891 return Error(AttrLoc, "invalid use of parameter-only attribute");
892
893 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000894 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
895 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
896 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
897 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
898 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
899 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
900 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
901 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000902
Devang Patel578efa92009-06-05 21:57:13 +0000903 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
904 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
905 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
906 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
907 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
908 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
909 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
910 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
911 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
912 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
913 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000914 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000915
916 case lltok::kw_align: {
917 unsigned Alignment;
918 if (ParseOptionalAlignment(Alignment))
919 return true;
920 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
921 continue;
922 }
923 }
924 Lex.Lex();
925 }
926}
927
928/// ParseOptionalLinkage
929/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000930/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000931/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000932/// ::= 'internal'
933/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000934/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000935/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000936/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000937/// ::= 'appending'
938/// ::= 'dllexport'
939/// ::= 'common'
940/// ::= 'dllimport'
941/// ::= 'extern_weak'
942/// ::= 'external'
943bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
944 HasLinkage = false;
945 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000946 default: Res=GlobalValue::ExternalLinkage; return false;
947 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
948 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
949 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
950 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
951 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
952 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
953 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000954 case lltok::kw_available_externally:
955 Res = GlobalValue::AvailableExternallyLinkage;
956 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000957 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
958 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
959 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
960 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
961 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
962 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000963 }
964 Lex.Lex();
965 HasLinkage = true;
966 return false;
967}
968
969/// ParseOptionalVisibility
970/// ::= /*empty*/
971/// ::= 'default'
972/// ::= 'hidden'
973/// ::= 'protected'
974///
975bool LLParser::ParseOptionalVisibility(unsigned &Res) {
976 switch (Lex.getKind()) {
977 default: Res = GlobalValue::DefaultVisibility; return false;
978 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
979 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
980 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
981 }
982 Lex.Lex();
983 return false;
984}
985
986/// ParseOptionalCallingConv
987/// ::= /*empty*/
988/// ::= 'ccc'
989/// ::= 'fastcc'
990/// ::= 'coldcc'
991/// ::= 'x86_stdcallcc'
992/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000993/// ::= 'arm_apcscc'
994/// ::= 'arm_aapcscc'
995/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000996/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000997///
Chris Lattnerdf986172009-01-02 07:01:27 +0000998bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
999 switch (Lex.getKind()) {
1000 default: CC = CallingConv::C; return false;
1001 case lltok::kw_ccc: CC = CallingConv::C; break;
1002 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1003 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1004 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1005 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001006 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1007 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1008 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001009 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +00001010 }
1011 Lex.Lex();
1012 return false;
1013}
1014
1015/// ParseOptionalAlignment
1016/// ::= /* empty */
1017/// ::= 'align' 4
1018bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1019 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001020 if (!EatIfPresent(lltok::kw_align))
1021 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001022 LocTy AlignLoc = Lex.getLoc();
1023 if (ParseUInt32(Alignment)) return true;
1024 if (!isPowerOf2_32(Alignment))
1025 return Error(AlignLoc, "alignment is not a power of two");
1026 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001027}
1028
1029/// ParseOptionalCommaAlignment
1030/// ::= /* empty */
1031/// ::= ',' 'align' 4
1032bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1033 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001034 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00001035 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001036 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001037 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001038}
1039
1040/// ParseIndexList
1041/// ::= (',' uint32)+
1042bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1043 if (Lex.getKind() != lltok::comma)
1044 return TokError("expected ',' as start of index list");
1045
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001046 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001047 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001048 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001049 Indices.push_back(Idx);
1050 }
1051
1052 return false;
1053}
1054
1055//===----------------------------------------------------------------------===//
1056// Type Parsing.
1057//===----------------------------------------------------------------------===//
1058
1059/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001060bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1061 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001062 if (ParseTypeRec(Result)) return true;
1063
1064 // Verify no unresolved uprefs.
1065 if (!UpRefs.empty())
1066 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +00001067
Chris Lattnera9a9e072009-03-09 04:49:14 +00001068 if (!AllowVoid && Result.get() == Type::VoidTy)
1069 return Error(TypeLoc, "void type only allowed for function results");
1070
Chris Lattnerdf986172009-01-02 07:01:27 +00001071 return false;
1072}
1073
1074/// HandleUpRefs - Every time we finish a new layer of types, this function is
1075/// called. It loops through the UpRefs vector, which is a list of the
1076/// currently active types. For each type, if the up-reference is contained in
1077/// the newly completed type, we decrement the level count. When the level
1078/// count reaches zero, the up-referenced type is the type that is passed in:
1079/// thus we can complete the cycle.
1080///
1081PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1082 // If Ty isn't abstract, or if there are no up-references in it, then there is
1083 // nothing to resolve here.
1084 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1085
1086 PATypeHolder Ty(ty);
1087#if 0
1088 errs() << "Type '" << Ty->getDescription()
1089 << "' newly formed. Resolving upreferences.\n"
1090 << UpRefs.size() << " upreferences active!\n";
1091#endif
1092
1093 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1094 // to zero), we resolve them all together before we resolve them to Ty. At
1095 // the end of the loop, if there is anything to resolve to Ty, it will be in
1096 // this variable.
1097 OpaqueType *TypeToResolve = 0;
1098
1099 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1100 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1101 bool ContainsType =
1102 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1103 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1104
1105#if 0
1106 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1107 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1108 << (ContainsType ? "true" : "false")
1109 << " level=" << UpRefs[i].NestingLevel << "\n";
1110#endif
1111 if (!ContainsType)
1112 continue;
1113
1114 // Decrement level of upreference
1115 unsigned Level = --UpRefs[i].NestingLevel;
1116 UpRefs[i].LastContainedTy = Ty;
1117
1118 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1119 if (Level != 0)
1120 continue;
1121
1122#if 0
1123 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1124#endif
1125 if (!TypeToResolve)
1126 TypeToResolve = UpRefs[i].UpRefTy;
1127 else
1128 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1129 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1130 --i; // Do not skip the next element.
1131 }
1132
1133 if (TypeToResolve)
1134 TypeToResolve->refineAbstractTypeTo(Ty);
1135
1136 return Ty;
1137}
1138
1139
1140/// ParseTypeRec - The recursive function used to process the internal
1141/// implementation details of types.
1142bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1143 switch (Lex.getKind()) {
1144 default:
1145 return TokError("expected type");
1146 case lltok::Type:
1147 // TypeRec ::= 'float' | 'void' (etc)
1148 Result = Lex.getTyVal();
1149 Lex.Lex();
1150 break;
1151 case lltok::kw_opaque:
1152 // TypeRec ::= 'opaque'
Owen Andersondebcb012009-07-29 22:17:13 +00001153 Result = OpaqueType::get();
Chris Lattnerdf986172009-01-02 07:01:27 +00001154 Lex.Lex();
1155 break;
1156 case lltok::lbrace:
1157 // TypeRec ::= '{' ... '}'
1158 if (ParseStructType(Result, false))
1159 return true;
1160 break;
1161 case lltok::lsquare:
1162 // TypeRec ::= '[' ... ']'
1163 Lex.Lex(); // eat the lsquare.
1164 if (ParseArrayVectorType(Result, false))
1165 return true;
1166 break;
1167 case lltok::less: // Either vector or packed struct.
1168 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001169 Lex.Lex();
1170 if (Lex.getKind() == lltok::lbrace) {
1171 if (ParseStructType(Result, true) ||
1172 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001173 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 } else if (ParseArrayVectorType(Result, true))
1175 return true;
1176 break;
1177 case lltok::LocalVar:
1178 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1179 // TypeRec ::= %foo
1180 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1181 Result = T;
1182 } else {
Owen Andersondebcb012009-07-29 22:17:13 +00001183 Result = OpaqueType::get();
Chris Lattnerdf986172009-01-02 07:01:27 +00001184 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1185 std::make_pair(Result,
1186 Lex.getLoc())));
1187 M->addTypeName(Lex.getStrVal(), Result.get());
1188 }
1189 Lex.Lex();
1190 break;
1191
1192 case lltok::LocalVarID:
1193 // TypeRec ::= %4
1194 if (Lex.getUIntVal() < NumberedTypes.size())
1195 Result = NumberedTypes[Lex.getUIntVal()];
1196 else {
1197 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1198 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1199 if (I != ForwardRefTypeIDs.end())
1200 Result = I->second.first;
1201 else {
Owen Andersondebcb012009-07-29 22:17:13 +00001202 Result = OpaqueType::get();
Chris Lattnerdf986172009-01-02 07:01:27 +00001203 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1204 std::make_pair(Result,
1205 Lex.getLoc())));
1206 }
1207 }
1208 Lex.Lex();
1209 break;
1210 case lltok::backslash: {
1211 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001213 unsigned Val;
1214 if (ParseUInt32(Val)) return true;
Owen Andersondebcb012009-07-29 22:17:13 +00001215 OpaqueType *OT = OpaqueType::get(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1217 Result = OT;
1218 break;
1219 }
1220 }
1221
1222 // Parse the type suffixes.
1223 while (1) {
1224 switch (Lex.getKind()) {
1225 // End of type.
1226 default: return false;
1227
1228 // TypeRec ::= TypeRec '*'
1229 case lltok::star:
1230 if (Result.get() == Type::LabelTy)
1231 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001232 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001233 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001234 if (!PointerType::isValidElementType(Result.get()))
1235 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001236 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 Lex.Lex();
1238 break;
1239
1240 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1241 case lltok::kw_addrspace: {
1242 if (Result.get() == Type::LabelTy)
1243 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001244 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001245 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001246 if (!PointerType::isValidElementType(Result.get()))
1247 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 unsigned AddrSpace;
1249 if (ParseOptionalAddrSpace(AddrSpace) ||
1250 ParseToken(lltok::star, "expected '*' in address space"))
1251 return true;
1252
Owen Andersondebcb012009-07-29 22:17:13 +00001253 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 break;
1255 }
1256
1257 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1258 case lltok::lparen:
1259 if (ParseFunctionType(Result))
1260 return true;
1261 break;
1262 }
1263 }
1264}
1265
1266/// ParseParameterList
1267/// ::= '(' ')'
1268/// ::= '(' Arg (',' Arg)* ')'
1269/// Arg
1270/// ::= Type OptionalAttributes Value OptionalAttributes
1271bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1272 PerFunctionState &PFS) {
1273 if (ParseToken(lltok::lparen, "expected '(' in call"))
1274 return true;
1275
1276 while (Lex.getKind() != lltok::rparen) {
1277 // If this isn't the first argument, we need a comma.
1278 if (!ArgList.empty() &&
1279 ParseToken(lltok::comma, "expected ',' in argument list"))
1280 return true;
1281
1282 // Parse the argument.
1283 LocTy ArgLoc;
1284 PATypeHolder ArgTy(Type::VoidTy);
1285 unsigned ArgAttrs1, ArgAttrs2;
1286 Value *V;
1287 if (ParseType(ArgTy, ArgLoc) ||
1288 ParseOptionalAttrs(ArgAttrs1, 0) ||
1289 ParseValue(ArgTy, V, PFS) ||
1290 // FIXME: Should not allow attributes after the argument, remove this in
1291 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001292 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 return true;
1294 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1295 }
1296
1297 Lex.Lex(); // Lex the ')'.
1298 return false;
1299}
1300
1301
1302
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001303/// ParseArgumentList - Parse the argument list for a function type or function
1304/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001305/// ::= '(' ArgTypeListI ')'
1306/// ArgTypeListI
1307/// ::= /*empty*/
1308/// ::= '...'
1309/// ::= ArgTypeList ',' '...'
1310/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001311///
Chris Lattnerdf986172009-01-02 07:01:27 +00001312bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001313 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 isVarArg = false;
1315 assert(Lex.getKind() == lltok::lparen);
1316 Lex.Lex(); // eat the (.
1317
1318 if (Lex.getKind() == lltok::rparen) {
1319 // empty
1320 } else if (Lex.getKind() == lltok::dotdotdot) {
1321 isVarArg = true;
1322 Lex.Lex();
1323 } else {
1324 LocTy TypeLoc = Lex.getLoc();
1325 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001328
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001329 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1330 // types (such as a function returning a pointer to itself). If parsing a
1331 // function prototype, we require fully resolved types.
1332 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001333 ParseOptionalAttrs(Attrs, 0)) return true;
1334
Chris Lattnera9a9e072009-03-09 04:49:14 +00001335 if (ArgTy == Type::VoidTy)
1336 return Error(TypeLoc, "argument can not have void type");
1337
Chris Lattnerdf986172009-01-02 07:01:27 +00001338 if (Lex.getKind() == lltok::LocalVar ||
1339 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1340 Name = Lex.getStrVal();
1341 Lex.Lex();
1342 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001343
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001344 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001345 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001346
1347 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1348
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001349 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001351 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 break;
1354 }
1355
1356 // Otherwise must be an argument type.
1357 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001358 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001359 ParseOptionalAttrs(Attrs, 0)) return true;
1360
Chris Lattnera9a9e072009-03-09 04:49:14 +00001361 if (ArgTy == Type::VoidTy)
1362 return Error(TypeLoc, "argument can not have void type");
1363
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 if (Lex.getKind() == lltok::LocalVar ||
1365 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1366 Name = Lex.getStrVal();
1367 Lex.Lex();
1368 } else {
1369 Name = "";
1370 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001371
1372 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1373 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001374
1375 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1376 }
1377 }
1378
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001379 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001380}
1381
1382/// ParseFunctionType
1383/// ::= Type ArgumentList OptionalAttrs
1384bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1385 assert(Lex.getKind() == lltok::lparen);
1386
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001387 if (!FunctionType::isValidReturnType(Result))
1388 return TokError("invalid function return type");
1389
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 std::vector<ArgInfo> ArgList;
1391 bool isVarArg;
1392 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001393 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 // FIXME: Allow, but ignore attributes on function types!
1395 // FIXME: Remove in LLVM 3.0
1396 ParseOptionalAttrs(Attrs, 2))
1397 return true;
1398
1399 // Reject names on the arguments lists.
1400 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1401 if (!ArgList[i].Name.empty())
1402 return Error(ArgList[i].Loc, "argument name invalid in function type");
1403 if (!ArgList[i].Attrs != 0) {
1404 // Allow but ignore attributes on function types; this permits
1405 // auto-upgrade.
1406 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1407 }
1408 }
1409
1410 std::vector<const Type*> ArgListTy;
1411 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1412 ArgListTy.push_back(ArgList[i].Type);
1413
Owen Andersondebcb012009-07-29 22:17:13 +00001414 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001415 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 return false;
1417}
1418
1419/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1420/// TypeRec
1421/// ::= '{' '}'
1422/// ::= '{' TypeRec (',' TypeRec)* '}'
1423/// ::= '<' '{' '}' '>'
1424/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1425bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1426 assert(Lex.getKind() == lltok::lbrace);
1427 Lex.Lex(); // Consume the '{'
1428
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001429 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001430 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001431 return false;
1432 }
1433
1434 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001435 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001436 if (ParseTypeRec(Result)) return true;
1437 ParamsList.push_back(Result);
1438
Chris Lattnera9a9e072009-03-09 04:49:14 +00001439 if (Result == Type::VoidTy)
1440 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001441 if (!StructType::isValidElementType(Result))
1442 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001443
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001444 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001445 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001446 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001447
1448 if (Result == Type::VoidTy)
1449 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001450 if (!StructType::isValidElementType(Result))
1451 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001452
Chris Lattnerdf986172009-01-02 07:01:27 +00001453 ParamsList.push_back(Result);
1454 }
1455
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001456 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1457 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001458
1459 std::vector<const Type*> ParamsListTy;
1460 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1461 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001462 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001463 return false;
1464}
1465
1466/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1467/// token has already been consumed.
1468/// TypeRec
1469/// ::= '[' APSINTVAL 'x' Types ']'
1470/// ::= '<' APSINTVAL 'x' Types '>'
1471bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1472 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1473 Lex.getAPSIntVal().getBitWidth() > 64)
1474 return TokError("expected number in address space");
1475
1476 LocTy SizeLoc = Lex.getLoc();
1477 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001478 Lex.Lex();
1479
1480 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1481 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001482
1483 LocTy TypeLoc = Lex.getLoc();
1484 PATypeHolder EltTy(Type::VoidTy);
1485 if (ParseTypeRec(EltTy)) return true;
1486
Chris Lattnera9a9e072009-03-09 04:49:14 +00001487 if (EltTy == Type::VoidTy)
1488 return Error(TypeLoc, "array and vector element type cannot be void");
1489
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001490 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1491 "expected end of sequential type"))
1492 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001493
1494 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001495 if (Size == 0)
1496 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 if ((unsigned)Size != Size)
1498 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001499 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001501 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001502 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001503 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001505 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001506 }
1507 return false;
1508}
1509
1510//===----------------------------------------------------------------------===//
1511// Function Semantic Analysis.
1512//===----------------------------------------------------------------------===//
1513
1514LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1515 : P(p), F(f) {
1516
1517 // Insert unnamed arguments into the NumberedVals list.
1518 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1519 AI != E; ++AI)
1520 if (!AI->hasName())
1521 NumberedVals.push_back(AI);
1522}
1523
1524LLParser::PerFunctionState::~PerFunctionState() {
1525 // If there were any forward referenced non-basicblock values, delete them.
1526 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1527 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1528 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001529 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001530 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 delete I->second.first;
1532 I->second.first = 0;
1533 }
1534
1535 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1536 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1537 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001538 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001539 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 delete I->second.first;
1541 I->second.first = 0;
1542 }
1543}
1544
1545bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1546 if (!ForwardRefVals.empty())
1547 return P.Error(ForwardRefVals.begin()->second.second,
1548 "use of undefined value '%" + ForwardRefVals.begin()->first +
1549 "'");
1550 if (!ForwardRefValIDs.empty())
1551 return P.Error(ForwardRefValIDs.begin()->second.second,
1552 "use of undefined value '%" +
1553 utostr(ForwardRefValIDs.begin()->first) + "'");
1554 return false;
1555}
1556
1557
1558/// GetVal - Get a value with the specified name or ID, creating a
1559/// forward reference record if needed. This can return null if the value
1560/// exists but does not have the right type.
1561Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1562 const Type *Ty, LocTy Loc) {
1563 // Look this name up in the normal function symbol table.
1564 Value *Val = F.getValueSymbolTable().lookup(Name);
1565
1566 // If this is a forward reference for the value, see if we already created a
1567 // forward ref record.
1568 if (Val == 0) {
1569 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1570 I = ForwardRefVals.find(Name);
1571 if (I != ForwardRefVals.end())
1572 Val = I->second.first;
1573 }
1574
1575 // If we have the value in the symbol table or fwd-ref table, return it.
1576 if (Val) {
1577 if (Val->getType() == Ty) return Val;
1578 if (Ty == Type::LabelTy)
1579 P.Error(Loc, "'%" + Name + "' is not a basic block");
1580 else
1581 P.Error(Loc, "'%" + Name + "' defined with type '" +
1582 Val->getType()->getDescription() + "'");
1583 return 0;
1584 }
1585
1586 // Don't make placeholders with invalid type.
1587 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1588 P.Error(Loc, "invalid use of a non-first-class type");
1589 return 0;
1590 }
1591
1592 // Otherwise, create a new forward reference for this value and remember it.
1593 Value *FwdVal;
1594 if (Ty == Type::LabelTy)
1595 FwdVal = BasicBlock::Create(Name, &F);
1596 else
1597 FwdVal = new Argument(Ty, Name);
1598
1599 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1600 return FwdVal;
1601}
1602
1603Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1604 LocTy Loc) {
1605 // Look this name up in the normal function symbol table.
1606 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1607
1608 // If this is a forward reference for the value, see if we already created a
1609 // forward ref record.
1610 if (Val == 0) {
1611 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1612 I = ForwardRefValIDs.find(ID);
1613 if (I != ForwardRefValIDs.end())
1614 Val = I->second.first;
1615 }
1616
1617 // If we have the value in the symbol table or fwd-ref table, return it.
1618 if (Val) {
1619 if (Val->getType() == Ty) return Val;
1620 if (Ty == Type::LabelTy)
1621 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1622 else
1623 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1624 Val->getType()->getDescription() + "'");
1625 return 0;
1626 }
1627
1628 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1629 P.Error(Loc, "invalid use of a non-first-class type");
1630 return 0;
1631 }
1632
1633 // Otherwise, create a new forward reference for this value and remember it.
1634 Value *FwdVal;
1635 if (Ty == Type::LabelTy)
1636 FwdVal = BasicBlock::Create("", &F);
1637 else
1638 FwdVal = new Argument(Ty);
1639
1640 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1641 return FwdVal;
1642}
1643
1644/// SetInstName - After an instruction is parsed and inserted into its
1645/// basic block, this installs its name.
1646bool LLParser::PerFunctionState::SetInstName(int NameID,
1647 const std::string &NameStr,
1648 LocTy NameLoc, Instruction *Inst) {
1649 // If this instruction has void type, it cannot have a name or ID specified.
1650 if (Inst->getType() == Type::VoidTy) {
1651 if (NameID != -1 || !NameStr.empty())
1652 return P.Error(NameLoc, "instructions returning void cannot have a name");
1653 return false;
1654 }
1655
1656 // If this was a numbered instruction, verify that the instruction is the
1657 // expected value and resolve any forward references.
1658 if (NameStr.empty()) {
1659 // If neither a name nor an ID was specified, just use the next ID.
1660 if (NameID == -1)
1661 NameID = NumberedVals.size();
1662
1663 if (unsigned(NameID) != NumberedVals.size())
1664 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1665 utostr(NumberedVals.size()) + "'");
1666
1667 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1668 ForwardRefValIDs.find(NameID);
1669 if (FI != ForwardRefValIDs.end()) {
1670 if (FI->second.first->getType() != Inst->getType())
1671 return P.Error(NameLoc, "instruction forward referenced with type '" +
1672 FI->second.first->getType()->getDescription() + "'");
1673 FI->second.first->replaceAllUsesWith(Inst);
1674 ForwardRefValIDs.erase(FI);
1675 }
1676
1677 NumberedVals.push_back(Inst);
1678 return false;
1679 }
1680
1681 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1682 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1683 FI = ForwardRefVals.find(NameStr);
1684 if (FI != ForwardRefVals.end()) {
1685 if (FI->second.first->getType() != Inst->getType())
1686 return P.Error(NameLoc, "instruction forward referenced with type '" +
1687 FI->second.first->getType()->getDescription() + "'");
1688 FI->second.first->replaceAllUsesWith(Inst);
1689 ForwardRefVals.erase(FI);
1690 }
1691
1692 // Set the name on the instruction.
1693 Inst->setName(NameStr);
1694
1695 if (Inst->getNameStr() != NameStr)
1696 return P.Error(NameLoc, "multiple definition of local value named '" +
1697 NameStr + "'");
1698 return false;
1699}
1700
1701/// GetBB - Get a basic block with the specified name or ID, creating a
1702/// forward reference record if needed.
1703BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1704 LocTy Loc) {
1705 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1706}
1707
1708BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1709 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1710}
1711
1712/// DefineBB - Define the specified basic block, which is either named or
1713/// unnamed. If there is an error, this returns null otherwise it returns
1714/// the block being defined.
1715BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1716 LocTy Loc) {
1717 BasicBlock *BB;
1718 if (Name.empty())
1719 BB = GetBB(NumberedVals.size(), Loc);
1720 else
1721 BB = GetBB(Name, Loc);
1722 if (BB == 0) return 0; // Already diagnosed error.
1723
1724 // Move the block to the end of the function. Forward ref'd blocks are
1725 // inserted wherever they happen to be referenced.
1726 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1727
1728 // Remove the block from forward ref sets.
1729 if (Name.empty()) {
1730 ForwardRefValIDs.erase(NumberedVals.size());
1731 NumberedVals.push_back(BB);
1732 } else {
1733 // BB forward references are already in the function symbol table.
1734 ForwardRefVals.erase(Name);
1735 }
1736
1737 return BB;
1738}
1739
1740//===----------------------------------------------------------------------===//
1741// Constants.
1742//===----------------------------------------------------------------------===//
1743
1744/// ParseValID - Parse an abstract value that doesn't necessarily have a
1745/// type implied. For example, if we parse "4" we don't know what integer type
1746/// it has. The value will later be combined with its type and checked for
1747/// sanity.
1748bool LLParser::ParseValID(ValID &ID) {
1749 ID.Loc = Lex.getLoc();
1750 switch (Lex.getKind()) {
1751 default: return TokError("expected value token");
1752 case lltok::GlobalID: // @42
1753 ID.UIntVal = Lex.getUIntVal();
1754 ID.Kind = ValID::t_GlobalID;
1755 break;
1756 case lltok::GlobalVar: // @foo
1757 ID.StrVal = Lex.getStrVal();
1758 ID.Kind = ValID::t_GlobalName;
1759 break;
1760 case lltok::LocalVarID: // %42
1761 ID.UIntVal = Lex.getUIntVal();
1762 ID.Kind = ValID::t_LocalID;
1763 break;
1764 case lltok::LocalVar: // %foo
1765 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1766 ID.StrVal = Lex.getStrVal();
1767 ID.Kind = ValID::t_LocalName;
1768 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001769 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001770 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001771 Lex.Lex();
1772 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001773 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001774 if (ParseMDNodeVector(Elts) ||
1775 ParseToken(lltok::rbrace, "expected end of metadata node"))
1776 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001777
Owen Anderson647e3012009-07-31 21:35:40 +00001778 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001779 return false;
1780 }
1781
Devang Patel923078c2009-07-01 19:21:12 +00001782 // Standalone metadata reference
1783 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001784 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001785 return false;
Devang Patel256be962009-07-20 19:00:08 +00001786
Nick Lewycky21cc4462009-04-04 07:22:01 +00001787 // MDString:
1788 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001789 if (ParseMDString(ID.MetadataVal)) return true;
1790 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001791 return false;
1792 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 case lltok::APSInt:
1794 ID.APSIntVal = Lex.getAPSIntVal();
1795 ID.Kind = ValID::t_APSInt;
1796 break;
1797 case lltok::APFloat:
1798 ID.APFloatVal = Lex.getAPFloatVal();
1799 ID.Kind = ValID::t_APFloat;
1800 break;
1801 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001802 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001803 ID.Kind = ValID::t_Constant;
1804 break;
1805 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001806 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 ID.Kind = ValID::t_Constant;
1808 break;
1809 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1810 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1811 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1812
1813 case lltok::lbrace: {
1814 // ValID ::= '{' ConstVector '}'
1815 Lex.Lex();
1816 SmallVector<Constant*, 16> Elts;
1817 if (ParseGlobalValueVector(Elts) ||
1818 ParseToken(lltok::rbrace, "expected end of struct constant"))
1819 return true;
1820
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001821 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1822 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001823 ID.Kind = ValID::t_Constant;
1824 return false;
1825 }
1826 case lltok::less: {
1827 // ValID ::= '<' ConstVector '>' --> Vector.
1828 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1829 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001830 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001831
1832 SmallVector<Constant*, 16> Elts;
1833 LocTy FirstEltLoc = Lex.getLoc();
1834 if (ParseGlobalValueVector(Elts) ||
1835 (isPackedStruct &&
1836 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1837 ParseToken(lltok::greater, "expected end of constant"))
1838 return true;
1839
1840 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001841 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001842 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001843 ID.Kind = ValID::t_Constant;
1844 return false;
1845 }
1846
1847 if (Elts.empty())
1848 return Error(ID.Loc, "constant vector must not be empty");
1849
1850 if (!Elts[0]->getType()->isInteger() &&
1851 !Elts[0]->getType()->isFloatingPoint())
1852 return Error(FirstEltLoc,
1853 "vector elements must have integer or floating point type");
1854
1855 // Verify that all the vector elements have the same type.
1856 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1857 if (Elts[i]->getType() != Elts[0]->getType())
1858 return Error(FirstEltLoc,
1859 "vector element #" + utostr(i) +
1860 " is not of type '" + Elts[0]->getType()->getDescription());
1861
Owen Andersonaf7ec972009-07-28 21:19:26 +00001862 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 ID.Kind = ValID::t_Constant;
1864 return false;
1865 }
1866 case lltok::lsquare: { // Array Constant
1867 Lex.Lex();
1868 SmallVector<Constant*, 16> Elts;
1869 LocTy FirstEltLoc = Lex.getLoc();
1870 if (ParseGlobalValueVector(Elts) ||
1871 ParseToken(lltok::rsquare, "expected end of array constant"))
1872 return true;
1873
1874 // Handle empty element.
1875 if (Elts.empty()) {
1876 // Use undef instead of an array because it's inconvenient to determine
1877 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001878 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001879 return false;
1880 }
1881
1882 if (!Elts[0]->getType()->isFirstClassType())
1883 return Error(FirstEltLoc, "invalid array element type: " +
1884 Elts[0]->getType()->getDescription());
1885
Owen Andersondebcb012009-07-29 22:17:13 +00001886 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001887
1888 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001889 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 if (Elts[i]->getType() != Elts[0]->getType())
1891 return Error(FirstEltLoc,
1892 "array element #" + utostr(i) +
1893 " is not of type '" +Elts[0]->getType()->getDescription());
1894 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001895
Owen Anderson1fd70962009-07-28 18:32:17 +00001896 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001897 ID.Kind = ValID::t_Constant;
1898 return false;
1899 }
1900 case lltok::kw_c: // c "foo"
1901 Lex.Lex();
Owen Anderson1fd70962009-07-28 18:32:17 +00001902 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1904 ID.Kind = ValID::t_Constant;
1905 return false;
1906
1907 case lltok::kw_asm: {
1908 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1909 bool HasSideEffect;
1910 Lex.Lex();
1911 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001912 ParseStringConstant(ID.StrVal) ||
1913 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 ParseToken(lltok::StringConstant, "expected constraint string"))
1915 return true;
1916 ID.StrVal2 = Lex.getStrVal();
1917 ID.UIntVal = HasSideEffect;
1918 ID.Kind = ValID::t_InlineAsm;
1919 return false;
1920 }
1921
1922 case lltok::kw_trunc:
1923 case lltok::kw_zext:
1924 case lltok::kw_sext:
1925 case lltok::kw_fptrunc:
1926 case lltok::kw_fpext:
1927 case lltok::kw_bitcast:
1928 case lltok::kw_uitofp:
1929 case lltok::kw_sitofp:
1930 case lltok::kw_fptoui:
1931 case lltok::kw_fptosi:
1932 case lltok::kw_inttoptr:
1933 case lltok::kw_ptrtoint: {
1934 unsigned Opc = Lex.getUIntVal();
1935 PATypeHolder DestTy(Type::VoidTy);
1936 Constant *SrcVal;
1937 Lex.Lex();
1938 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1939 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001940 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001941 ParseType(DestTy) ||
1942 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1943 return true;
1944 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1945 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1946 SrcVal->getType()->getDescription() + "' to '" +
1947 DestTy->getDescription() + "'");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001948 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00001949 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001950 ID.Kind = ValID::t_Constant;
1951 return false;
1952 }
1953 case lltok::kw_extractvalue: {
1954 Lex.Lex();
1955 Constant *Val;
1956 SmallVector<unsigned, 4> Indices;
1957 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1958 ParseGlobalTypeAndValue(Val) ||
1959 ParseIndexList(Indices) ||
1960 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1961 return true;
1962 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1963 return Error(ID.Loc, "extractvalue operand must be array or struct");
1964 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1965 Indices.end()))
1966 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001967 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001968 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 ID.Kind = ValID::t_Constant;
1970 return false;
1971 }
1972 case lltok::kw_insertvalue: {
1973 Lex.Lex();
1974 Constant *Val0, *Val1;
1975 SmallVector<unsigned, 4> Indices;
1976 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1977 ParseGlobalTypeAndValue(Val0) ||
1978 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1979 ParseGlobalTypeAndValue(Val1) ||
1980 ParseIndexList(Indices) ||
1981 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1982 return true;
1983 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1984 return Error(ID.Loc, "extractvalue operand must be array or struct");
1985 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1986 Indices.end()))
1987 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001988 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00001989 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001990 ID.Kind = ValID::t_Constant;
1991 return false;
1992 }
1993 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001994 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 unsigned PredVal, Opc = Lex.getUIntVal();
1996 Constant *Val0, *Val1;
1997 Lex.Lex();
1998 if (ParseCmpPredicate(PredVal, Opc) ||
1999 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2000 ParseGlobalTypeAndValue(Val0) ||
2001 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2002 ParseGlobalTypeAndValue(Val1) ||
2003 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2004 return true;
2005
2006 if (Val0->getType() != Val1->getType())
2007 return Error(ID.Loc, "compare operands must have the same type");
2008
2009 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2010
2011 if (Opc == Instruction::FCmp) {
2012 if (!Val0->getType()->isFPOrFPVector())
2013 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002014 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002015 } else {
2016 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 if (!Val0->getType()->isIntOrIntVector() &&
2018 !isa<PointerType>(Val0->getType()))
2019 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002020 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 }
2022 ID.Kind = ValID::t_Constant;
2023 return false;
2024 }
2025
2026 // Binary Operators.
2027 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002028 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002029 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002030 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002032 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 case lltok::kw_udiv:
2034 case lltok::kw_sdiv:
2035 case lltok::kw_fdiv:
2036 case lltok::kw_urem:
2037 case lltok::kw_srem:
2038 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002039 bool NUW = false;
2040 bool NSW = false;
2041 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002042 unsigned Opc = Lex.getUIntVal();
2043 Constant *Val0, *Val1;
2044 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002045 LocTy ModifierLoc = Lex.getLoc();
2046 if (Opc == Instruction::Add ||
2047 Opc == Instruction::Sub ||
2048 Opc == Instruction::Mul) {
2049 if (EatIfPresent(lltok::kw_nuw))
2050 NUW = true;
2051 if (EatIfPresent(lltok::kw_nsw)) {
2052 NSW = true;
2053 if (EatIfPresent(lltok::kw_nuw))
2054 NUW = true;
2055 }
2056 } else if (Opc == Instruction::SDiv) {
2057 if (EatIfPresent(lltok::kw_exact))
2058 Exact = true;
2059 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2061 ParseGlobalTypeAndValue(Val0) ||
2062 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2063 ParseGlobalTypeAndValue(Val1) ||
2064 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2065 return true;
2066 if (Val0->getType() != Val1->getType())
2067 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002068 if (!Val0->getType()->isIntOrIntVector()) {
2069 if (NUW)
2070 return Error(ModifierLoc, "nuw only applies to integer operations");
2071 if (NSW)
2072 return Error(ModifierLoc, "nsw only applies to integer operations");
2073 }
2074 // API compatibility: Accept either integer or floating-point types with
2075 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002076 if (!Val0->getType()->isIntOrIntVector() &&
2077 !Val0->getType()->isFPOrFPVector())
2078 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002079 Constant *C = ConstantExpr::get(Opc, Val0, Val1);
Dan Gohman59858cf2009-07-27 16:11:46 +00002080 if (NUW)
2081 cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2082 if (NSW)
2083 cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2084 if (Exact)
2085 cast<SDivOperator>(C)->setIsExact(true);
2086 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002087 ID.Kind = ValID::t_Constant;
2088 return false;
2089 }
2090
2091 // Logical Operations
2092 case lltok::kw_shl:
2093 case lltok::kw_lshr:
2094 case lltok::kw_ashr:
2095 case lltok::kw_and:
2096 case lltok::kw_or:
2097 case lltok::kw_xor: {
2098 unsigned Opc = Lex.getUIntVal();
2099 Constant *Val0, *Val1;
2100 Lex.Lex();
2101 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2102 ParseGlobalTypeAndValue(Val0) ||
2103 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2104 ParseGlobalTypeAndValue(Val1) ||
2105 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2106 return true;
2107 if (Val0->getType() != Val1->getType())
2108 return Error(ID.Loc, "operands of constexpr must have same type");
2109 if (!Val0->getType()->isIntOrIntVector())
2110 return Error(ID.Loc,
2111 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002112 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 ID.Kind = ValID::t_Constant;
2114 return false;
2115 }
2116
2117 case lltok::kw_getelementptr:
2118 case lltok::kw_shufflevector:
2119 case lltok::kw_insertelement:
2120 case lltok::kw_extractelement:
2121 case lltok::kw_select: {
2122 unsigned Opc = Lex.getUIntVal();
2123 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002124 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002126 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002127 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2129 ParseGlobalValueVector(Elts) ||
2130 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2131 return true;
2132
2133 if (Opc == Instruction::GetElementPtr) {
2134 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2135 return Error(ID.Loc, "getelementptr requires pointer operand");
2136
2137 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002138 (Value**)(Elts.data() + 1),
2139 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002141 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
Eli Friedman4e9bac32009-07-24 21:56:17 +00002142 Elts.data() + 1, Elts.size() - 1);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002143 if (InBounds)
2144 cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002145 } else if (Opc == Instruction::Select) {
2146 if (Elts.size() != 3)
2147 return Error(ID.Loc, "expected three operands to select");
2148 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2149 Elts[2]))
2150 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002151 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 } else if (Opc == Instruction::ShuffleVector) {
2153 if (Elts.size() != 3)
2154 return Error(ID.Loc, "expected three operands to shufflevector");
2155 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2156 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002157 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002158 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 } else if (Opc == Instruction::ExtractElement) {
2160 if (Elts.size() != 2)
2161 return Error(ID.Loc, "expected two operands to extractelement");
2162 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2163 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002164 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 } else {
2166 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2167 if (Elts.size() != 3)
2168 return Error(ID.Loc, "expected three operands to insertelement");
2169 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2170 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002171 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002172 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 }
2174
2175 ID.Kind = ValID::t_Constant;
2176 return false;
2177 }
2178 }
2179
2180 Lex.Lex();
2181 return false;
2182}
2183
2184/// ParseGlobalValue - Parse a global value with the specified type.
2185bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2186 V = 0;
2187 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002188 return ParseValID(ID) ||
2189 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002190}
2191
2192/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2193/// constant.
2194bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2195 Constant *&V) {
2196 if (isa<FunctionType>(Ty))
2197 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2198
2199 switch (ID.Kind) {
Devang Patele54abc92009-07-22 17:43:22 +00002200 default: llvm_unreachable("Unknown ValID!");
2201 case ValID::t_Metadata:
2202 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 case ValID::t_LocalID:
2204 case ValID::t_LocalName:
2205 return Error(ID.Loc, "invalid use of function-local name");
2206 case ValID::t_InlineAsm:
2207 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2208 case ValID::t_GlobalName:
2209 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2210 return V == 0;
2211 case ValID::t_GlobalID:
2212 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2213 return V == 0;
2214 case ValID::t_APSInt:
2215 if (!isa<IntegerType>(Ty))
2216 return Error(ID.Loc, "integer constant must have integer type");
2217 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002218 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002219 return false;
2220 case ValID::t_APFloat:
2221 if (!Ty->isFloatingPoint() ||
2222 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2223 return Error(ID.Loc, "floating point constant invalid for type");
2224
2225 // The lexer has no type info, so builds all float and double FP constants
2226 // as double. Fix this here. Long double does not need this.
2227 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2228 Ty == Type::FloatTy) {
2229 bool Ignored;
2230 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2231 &Ignored);
2232 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002233 V = ConstantFP::get(Context, ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002234
2235 if (V->getType() != Ty)
2236 return Error(ID.Loc, "floating point constant does not have type '" +
2237 Ty->getDescription() + "'");
2238
Chris Lattnerdf986172009-01-02 07:01:27 +00002239 return false;
2240 case ValID::t_Null:
2241 if (!isa<PointerType>(Ty))
2242 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002243 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 return false;
2245 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002246 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002247 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2248 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002249 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002250 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002251 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002252 case ValID::t_EmptyArray:
2253 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2254 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002255 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002256 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002258 // FIXME: LabelTy should not be a first-class type.
2259 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002261 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002262 return false;
2263 case ValID::t_Constant:
2264 if (ID.ConstantVal->getType() != Ty)
2265 return Error(ID.Loc, "constant expression type mismatch");
2266 V = ID.ConstantVal;
2267 return false;
2268 }
2269}
2270
2271bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2272 PATypeHolder Type(Type::VoidTy);
2273 return ParseType(Type) ||
2274 ParseGlobalValue(Type, V);
2275}
2276
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002277/// ParseGlobalValueVector
2278/// ::= /*empty*/
2279/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002280bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2281 // Empty list.
2282 if (Lex.getKind() == lltok::rbrace ||
2283 Lex.getKind() == lltok::rsquare ||
2284 Lex.getKind() == lltok::greater ||
2285 Lex.getKind() == lltok::rparen)
2286 return false;
2287
2288 Constant *C;
2289 if (ParseGlobalTypeAndValue(C)) return true;
2290 Elts.push_back(C);
2291
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002292 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002293 if (ParseGlobalTypeAndValue(C)) return true;
2294 Elts.push_back(C);
2295 }
2296
2297 return false;
2298}
2299
2300
2301//===----------------------------------------------------------------------===//
2302// Function Parsing.
2303//===----------------------------------------------------------------------===//
2304
2305bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2306 PerFunctionState &PFS) {
2307 if (ID.Kind == ValID::t_LocalID)
2308 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2309 else if (ID.Kind == ValID::t_LocalName)
2310 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002311 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2313 const FunctionType *FTy =
2314 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2315 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2316 return Error(ID.Loc, "invalid type for inline asm constraint string");
2317 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2318 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002319 } else if (ID.Kind == ValID::t_Metadata) {
2320 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002321 } else {
2322 Constant *C;
2323 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2324 V = C;
2325 return false;
2326 }
2327
2328 return V == 0;
2329}
2330
2331bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2332 V = 0;
2333 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002334 return ParseValID(ID) ||
2335 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002336}
2337
2338bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2339 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002340 return ParseType(T) ||
2341 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002342}
2343
2344/// FunctionHeader
2345/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2346/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2347/// OptionalAlign OptGC
2348bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2349 // Parse the linkage.
2350 LocTy LinkageLoc = Lex.getLoc();
2351 unsigned Linkage;
2352
2353 unsigned Visibility, CC, RetAttrs;
2354 PATypeHolder RetType(Type::VoidTy);
2355 LocTy RetTypeLoc = Lex.getLoc();
2356 if (ParseOptionalLinkage(Linkage) ||
2357 ParseOptionalVisibility(Visibility) ||
2358 ParseOptionalCallingConv(CC) ||
2359 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002360 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002361 return true;
2362
2363 // Verify that the linkage is ok.
2364 switch ((GlobalValue::LinkageTypes)Linkage) {
2365 case GlobalValue::ExternalLinkage:
2366 break; // always ok.
2367 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002368 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002369 if (isDefine)
2370 return Error(LinkageLoc, "invalid linkage for function definition");
2371 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002372 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002373 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002375 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002376 case GlobalValue::LinkOnceAnyLinkage:
2377 case GlobalValue::LinkOnceODRLinkage:
2378 case GlobalValue::WeakAnyLinkage:
2379 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002380 case GlobalValue::DLLExportLinkage:
2381 if (!isDefine)
2382 return Error(LinkageLoc, "invalid linkage for function declaration");
2383 break;
2384 case GlobalValue::AppendingLinkage:
2385 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002386 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 return Error(LinkageLoc, "invalid function linkage type");
2388 }
2389
Chris Lattner99bb3152009-01-05 08:00:30 +00002390 if (!FunctionType::isValidReturnType(RetType) ||
2391 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 return Error(RetTypeLoc, "invalid function return type");
2393
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002395
2396 std::string FunctionName;
2397 if (Lex.getKind() == lltok::GlobalVar) {
2398 FunctionName = Lex.getStrVal();
2399 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2400 unsigned NameID = Lex.getUIntVal();
2401
2402 if (NameID != NumberedVals.size())
2403 return TokError("function expected to be numbered '%" +
2404 utostr(NumberedVals.size()) + "'");
2405 } else {
2406 return TokError("expected function name");
2407 }
2408
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002409 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002410
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002411 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002412 return TokError("expected '(' in function argument list");
2413
2414 std::vector<ArgInfo> ArgList;
2415 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002417 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002419 std::string GC;
2420
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002421 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002422 ParseOptionalAttrs(FuncAttrs, 2) ||
2423 (EatIfPresent(lltok::kw_section) &&
2424 ParseStringConstant(Section)) ||
2425 ParseOptionalAlignment(Alignment) ||
2426 (EatIfPresent(lltok::kw_gc) &&
2427 ParseStringConstant(GC)))
2428 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002429
2430 // If the alignment was parsed as an attribute, move to the alignment field.
2431 if (FuncAttrs & Attribute::Alignment) {
2432 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2433 FuncAttrs &= ~Attribute::Alignment;
2434 }
2435
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 // Okay, if we got here, the function is syntactically valid. Convert types
2437 // and do semantic checks.
2438 std::vector<const Type*> ParamTypeList;
2439 SmallVector<AttributeWithIndex, 8> Attrs;
2440 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2441 // attributes.
2442 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2443 if (FuncAttrs & ObsoleteFuncAttrs) {
2444 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2445 FuncAttrs &= ~ObsoleteFuncAttrs;
2446 }
2447
2448 if (RetAttrs != Attribute::None)
2449 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2450
2451 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2452 ParamTypeList.push_back(ArgList[i].Type);
2453 if (ArgList[i].Attrs != Attribute::None)
2454 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2455 }
2456
2457 if (FuncAttrs != Attribute::None)
2458 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2459
2460 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2461
Chris Lattnera9a9e072009-03-09 04:49:14 +00002462 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2463 RetType != Type::VoidTy)
2464 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2465
Owen Andersonfba933c2009-07-01 23:57:11 +00002466 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002467 FunctionType::get(RetType, ParamTypeList, isVarArg);
2468 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002469
2470 Fn = 0;
2471 if (!FunctionName.empty()) {
2472 // If this was a definition of a forward reference, remove the definition
2473 // from the forward reference table and fill in the forward ref.
2474 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2475 ForwardRefVals.find(FunctionName);
2476 if (FRVI != ForwardRefVals.end()) {
2477 Fn = M->getFunction(FunctionName);
2478 ForwardRefVals.erase(FRVI);
2479 } else if ((Fn = M->getFunction(FunctionName))) {
2480 // If this function already exists in the symbol table, then it is
2481 // multiply defined. We accept a few cases for old backwards compat.
2482 // FIXME: Remove this stuff for LLVM 3.0.
2483 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2484 (!Fn->isDeclaration() && isDefine)) {
2485 // If the redefinition has different type or different attributes,
2486 // reject it. If both have bodies, reject it.
2487 return Error(NameLoc, "invalid redefinition of function '" +
2488 FunctionName + "'");
2489 } else if (Fn->isDeclaration()) {
2490 // Make sure to strip off any argument names so we can't get conflicts.
2491 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2492 AI != AE; ++AI)
2493 AI->setName("");
2494 }
2495 }
2496
2497 } else if (FunctionName.empty()) {
2498 // If this is a definition of a forward referenced function, make sure the
2499 // types agree.
2500 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2501 = ForwardRefValIDs.find(NumberedVals.size());
2502 if (I != ForwardRefValIDs.end()) {
2503 Fn = cast<Function>(I->second.first);
2504 if (Fn->getType() != PFT)
2505 return Error(NameLoc, "type of definition and forward reference of '@" +
2506 utostr(NumberedVals.size()) +"' disagree");
2507 ForwardRefValIDs.erase(I);
2508 }
2509 }
2510
2511 if (Fn == 0)
2512 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2513 else // Move the forward-reference to the correct spot in the module.
2514 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2515
2516 if (FunctionName.empty())
2517 NumberedVals.push_back(Fn);
2518
2519 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2520 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2521 Fn->setCallingConv(CC);
2522 Fn->setAttributes(PAL);
2523 Fn->setAlignment(Alignment);
2524 Fn->setSection(Section);
2525 if (!GC.empty()) Fn->setGC(GC.c_str());
2526
2527 // Add all of the arguments we parsed to the function.
2528 Function::arg_iterator ArgIt = Fn->arg_begin();
2529 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2530 // If the argument has a name, insert it into the argument symbol table.
2531 if (ArgList[i].Name.empty()) continue;
2532
2533 // Set the name, if it conflicted, it will be auto-renamed.
2534 ArgIt->setName(ArgList[i].Name);
2535
2536 if (ArgIt->getNameStr() != ArgList[i].Name)
2537 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2538 ArgList[i].Name + "'");
2539 }
2540
2541 return false;
2542}
2543
2544
2545/// ParseFunctionBody
2546/// ::= '{' BasicBlock+ '}'
2547/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2548///
2549bool LLParser::ParseFunctionBody(Function &Fn) {
2550 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2551 return TokError("expected '{' in function body");
2552 Lex.Lex(); // eat the {.
2553
2554 PerFunctionState PFS(*this, Fn);
2555
2556 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2557 if (ParseBasicBlock(PFS)) return true;
2558
2559 // Eat the }.
2560 Lex.Lex();
2561
2562 // Verify function is ok.
2563 return PFS.VerifyFunctionComplete();
2564}
2565
2566/// ParseBasicBlock
2567/// ::= LabelStr? Instruction*
2568bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2569 // If this basic block starts out with a name, remember it.
2570 std::string Name;
2571 LocTy NameLoc = Lex.getLoc();
2572 if (Lex.getKind() == lltok::LabelStr) {
2573 Name = Lex.getStrVal();
2574 Lex.Lex();
2575 }
2576
2577 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2578 if (BB == 0) return true;
2579
2580 std::string NameStr;
2581
2582 // Parse the instructions in this block until we get a terminator.
2583 Instruction *Inst;
2584 do {
2585 // This instruction may have three possibilities for a name: a) none
2586 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2587 LocTy NameLoc = Lex.getLoc();
2588 int NameID = -1;
2589 NameStr = "";
2590
2591 if (Lex.getKind() == lltok::LocalVarID) {
2592 NameID = Lex.getUIntVal();
2593 Lex.Lex();
2594 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2595 return true;
2596 } else if (Lex.getKind() == lltok::LocalVar ||
2597 // FIXME: REMOVE IN LLVM 3.0
2598 Lex.getKind() == lltok::StringConstant) {
2599 NameStr = Lex.getStrVal();
2600 Lex.Lex();
2601 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2602 return true;
2603 }
2604
2605 if (ParseInstruction(Inst, BB, PFS)) return true;
2606
2607 BB->getInstList().push_back(Inst);
2608
2609 // Set the name on the instruction.
2610 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2611 } while (!isa<TerminatorInst>(Inst));
2612
2613 return false;
2614}
2615
2616//===----------------------------------------------------------------------===//
2617// Instruction Parsing.
2618//===----------------------------------------------------------------------===//
2619
2620/// ParseInstruction - Parse one of the many different instructions.
2621///
2622bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2623 PerFunctionState &PFS) {
2624 lltok::Kind Token = Lex.getKind();
2625 if (Token == lltok::Eof)
2626 return TokError("found end of file when expecting more instructions");
2627 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002628 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002629 Lex.Lex(); // Eat the keyword.
2630
2631 switch (Token) {
2632 default: return Error(Loc, "expected instruction opcode");
2633 // Terminator Instructions.
2634 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2635 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2636 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2637 case lltok::kw_br: return ParseBr(Inst, PFS);
2638 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2639 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2640 // Binary Operators.
2641 case lltok::kw_add:
2642 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002643 case lltok::kw_mul: {
2644 bool NUW = false;
2645 bool NSW = false;
2646 LocTy ModifierLoc = Lex.getLoc();
2647 if (EatIfPresent(lltok::kw_nuw))
2648 NUW = true;
2649 if (EatIfPresent(lltok::kw_nsw)) {
2650 NSW = true;
2651 if (EatIfPresent(lltok::kw_nuw))
2652 NUW = true;
2653 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002654 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002655 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2656 if (!Result) {
2657 if (!Inst->getType()->isIntOrIntVector()) {
2658 if (NUW)
2659 return Error(ModifierLoc, "nuw only applies to integer operations");
2660 if (NSW)
2661 return Error(ModifierLoc, "nsw only applies to integer operations");
2662 }
2663 if (NUW)
2664 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2665 if (NSW)
2666 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2667 }
2668 return Result;
2669 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002670 case lltok::kw_fadd:
2671 case lltok::kw_fsub:
2672 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2673
Dan Gohman59858cf2009-07-27 16:11:46 +00002674 case lltok::kw_sdiv: {
2675 bool Exact = false;
2676 if (EatIfPresent(lltok::kw_exact))
2677 Exact = true;
2678 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2679 if (!Result)
2680 if (Exact)
2681 cast<SDivOperator>(Inst)->setIsExact(true);
2682 return Result;
2683 }
2684
Chris Lattnerdf986172009-01-02 07:01:27 +00002685 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002686 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002687 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002688 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002689 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 case lltok::kw_shl:
2691 case lltok::kw_lshr:
2692 case lltok::kw_ashr:
2693 case lltok::kw_and:
2694 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002695 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002697 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 // Casts.
2699 case lltok::kw_trunc:
2700 case lltok::kw_zext:
2701 case lltok::kw_sext:
2702 case lltok::kw_fptrunc:
2703 case lltok::kw_fpext:
2704 case lltok::kw_bitcast:
2705 case lltok::kw_uitofp:
2706 case lltok::kw_sitofp:
2707 case lltok::kw_fptoui:
2708 case lltok::kw_fptosi:
2709 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002710 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002711 // Other.
2712 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002713 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002714 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2715 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2716 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2717 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2718 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2719 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2720 // Memory.
2721 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002722 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 case lltok::kw_free: return ParseFree(Inst, PFS);
2724 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2725 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2726 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002727 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002729 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002731 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2734 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2735 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2736 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2737 }
2738}
2739
2740/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2741bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002742 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002743 switch (Lex.getKind()) {
2744 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2745 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2746 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2747 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2748 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2749 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2750 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2751 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2752 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2753 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2754 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2755 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2756 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2757 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2758 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2759 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2760 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2761 }
2762 } else {
2763 switch (Lex.getKind()) {
2764 default: TokError("expected icmp predicate (e.g. 'eq')");
2765 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2766 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2767 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2768 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2769 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2770 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2771 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2772 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2773 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2774 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2775 }
2776 }
2777 Lex.Lex();
2778 return false;
2779}
2780
2781//===----------------------------------------------------------------------===//
2782// Terminator Instructions.
2783//===----------------------------------------------------------------------===//
2784
2785/// ParseRet - Parse a return instruction.
2786/// ::= 'ret' void
2787/// ::= 'ret' TypeAndValue
2788/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2789bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2790 PerFunctionState &PFS) {
2791 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002792 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002793
2794 if (Ty == Type::VoidTy) {
2795 Inst = ReturnInst::Create();
2796 return false;
2797 }
2798
2799 Value *RV;
2800 if (ParseValue(Ty, RV, PFS)) return true;
2801
2802 // The normal case is one return value.
2803 if (Lex.getKind() == lltok::comma) {
2804 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2805 // of 'ret {i32,i32} {i32 1, i32 2}'
2806 SmallVector<Value*, 8> RVs;
2807 RVs.push_back(RV);
2808
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002809 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 if (ParseTypeAndValue(RV, PFS)) return true;
2811 RVs.push_back(RV);
2812 }
2813
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002814 RV = UndefValue::get(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2816 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2817 BB->getInstList().push_back(I);
2818 RV = I;
2819 }
2820 }
2821 Inst = ReturnInst::Create(RV);
2822 return false;
2823}
2824
2825
2826/// ParseBr
2827/// ::= 'br' TypeAndValue
2828/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2829bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2830 LocTy Loc, Loc2;
2831 Value *Op0, *Op1, *Op2;
2832 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2833
2834 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2835 Inst = BranchInst::Create(BB);
2836 return false;
2837 }
2838
2839 if (Op0->getType() != Type::Int1Ty)
2840 return Error(Loc, "branch condition must have 'i1' type");
2841
2842 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2843 ParseTypeAndValue(Op1, Loc, PFS) ||
2844 ParseToken(lltok::comma, "expected ',' after true destination") ||
2845 ParseTypeAndValue(Op2, Loc2, PFS))
2846 return true;
2847
2848 if (!isa<BasicBlock>(Op1))
2849 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002850 if (!isa<BasicBlock>(Op2))
2851 return Error(Loc2, "true destination of branch must be a basic block");
2852
2853 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2854 return false;
2855}
2856
2857/// ParseSwitch
2858/// Instruction
2859/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2860/// JumpTable
2861/// ::= (TypeAndValue ',' TypeAndValue)*
2862bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2863 LocTy CondLoc, BBLoc;
2864 Value *Cond, *DefaultBB;
2865 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2866 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2867 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2868 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2869 return true;
2870
2871 if (!isa<IntegerType>(Cond->getType()))
2872 return Error(CondLoc, "switch condition must have integer type");
2873 if (!isa<BasicBlock>(DefaultBB))
2874 return Error(BBLoc, "default destination must be a basic block");
2875
2876 // Parse the jump table pairs.
2877 SmallPtrSet<Value*, 32> SeenCases;
2878 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2879 while (Lex.getKind() != lltok::rsquare) {
2880 Value *Constant, *DestBB;
2881
2882 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2883 ParseToken(lltok::comma, "expected ',' after case value") ||
2884 ParseTypeAndValue(DestBB, BBLoc, PFS))
2885 return true;
2886
2887 if (!SeenCases.insert(Constant))
2888 return Error(CondLoc, "duplicate case value in switch");
2889 if (!isa<ConstantInt>(Constant))
2890 return Error(CondLoc, "case value is not a constant integer");
2891 if (!isa<BasicBlock>(DestBB))
2892 return Error(BBLoc, "case destination is not a basic block");
2893
2894 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2895 cast<BasicBlock>(DestBB)));
2896 }
2897
2898 Lex.Lex(); // Eat the ']'.
2899
2900 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2901 Table.size());
2902 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2903 SI->addCase(Table[i].first, Table[i].second);
2904 Inst = SI;
2905 return false;
2906}
2907
2908/// ParseInvoke
2909/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2910/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2911bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2912 LocTy CallLoc = Lex.getLoc();
2913 unsigned CC, RetAttrs, FnAttrs;
2914 PATypeHolder RetType(Type::VoidTy);
2915 LocTy RetTypeLoc;
2916 ValID CalleeID;
2917 SmallVector<ParamInfo, 16> ArgList;
2918
2919 Value *NormalBB, *UnwindBB;
2920 if (ParseOptionalCallingConv(CC) ||
2921 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002922 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 ParseValID(CalleeID) ||
2924 ParseParameterList(ArgList, PFS) ||
2925 ParseOptionalAttrs(FnAttrs, 2) ||
2926 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2927 ParseTypeAndValue(NormalBB, PFS) ||
2928 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2929 ParseTypeAndValue(UnwindBB, PFS))
2930 return true;
2931
2932 if (!isa<BasicBlock>(NormalBB))
2933 return Error(CallLoc, "normal destination is not a basic block");
2934 if (!isa<BasicBlock>(UnwindBB))
2935 return Error(CallLoc, "unwind destination is not a basic block");
2936
2937 // If RetType is a non-function pointer type, then this is the short syntax
2938 // for the call, which means that RetType is just the return type. Infer the
2939 // rest of the function argument types from the arguments that are present.
2940 const PointerType *PFTy = 0;
2941 const FunctionType *Ty = 0;
2942 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2943 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2944 // Pull out the types of all of the arguments...
2945 std::vector<const Type*> ParamTypes;
2946 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2947 ParamTypes.push_back(ArgList[i].V->getType());
2948
2949 if (!FunctionType::isValidReturnType(RetType))
2950 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2951
Owen Andersondebcb012009-07-29 22:17:13 +00002952 Ty = FunctionType::get(RetType, ParamTypes, false);
2953 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002954 }
2955
2956 // Look up the callee.
2957 Value *Callee;
2958 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2959
2960 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2961 // function attributes.
2962 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2963 if (FnAttrs & ObsoleteFuncAttrs) {
2964 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2965 FnAttrs &= ~ObsoleteFuncAttrs;
2966 }
2967
2968 // Set up the Attributes for the function.
2969 SmallVector<AttributeWithIndex, 8> Attrs;
2970 if (RetAttrs != Attribute::None)
2971 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2972
2973 SmallVector<Value*, 8> Args;
2974
2975 // Loop through FunctionType's arguments and ensure they are specified
2976 // correctly. Also, gather any parameter attributes.
2977 FunctionType::param_iterator I = Ty->param_begin();
2978 FunctionType::param_iterator E = Ty->param_end();
2979 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2980 const Type *ExpectedTy = 0;
2981 if (I != E) {
2982 ExpectedTy = *I++;
2983 } else if (!Ty->isVarArg()) {
2984 return Error(ArgList[i].Loc, "too many arguments specified");
2985 }
2986
2987 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2988 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2989 ExpectedTy->getDescription() + "'");
2990 Args.push_back(ArgList[i].V);
2991 if (ArgList[i].Attrs != Attribute::None)
2992 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2993 }
2994
2995 if (I != E)
2996 return Error(CallLoc, "not enough parameters specified for call");
2997
2998 if (FnAttrs != Attribute::None)
2999 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3000
3001 // Finish off the Attributes and check them
3002 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3003
3004 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3005 cast<BasicBlock>(UnwindBB),
3006 Args.begin(), Args.end());
3007 II->setCallingConv(CC);
3008 II->setAttributes(PAL);
3009 Inst = II;
3010 return false;
3011}
3012
3013
3014
3015//===----------------------------------------------------------------------===//
3016// Binary Operators.
3017//===----------------------------------------------------------------------===//
3018
3019/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003020/// ::= ArithmeticOps TypeAndValue ',' Value
3021///
3022/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3023/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003024bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003025 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 LocTy Loc; Value *LHS, *RHS;
3027 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3028 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3029 ParseValue(LHS->getType(), RHS, PFS))
3030 return true;
3031
Chris Lattnere914b592009-01-05 08:24:46 +00003032 bool Valid;
3033 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003034 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003035 case 0: // int or FP.
3036 Valid = LHS->getType()->isIntOrIntVector() ||
3037 LHS->getType()->isFPOrFPVector();
3038 break;
3039 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3040 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3041 }
3042
3043 if (!Valid)
3044 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00003045
3046 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3047 return false;
3048}
3049
3050/// ParseLogical
3051/// ::= ArithmeticOps TypeAndValue ',' Value {
3052bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3053 unsigned Opc) {
3054 LocTy Loc; Value *LHS, *RHS;
3055 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3056 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3057 ParseValue(LHS->getType(), RHS, PFS))
3058 return true;
3059
3060 if (!LHS->getType()->isIntOrIntVector())
3061 return Error(Loc,"instruction requires integer or integer vector operands");
3062
3063 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3064 return false;
3065}
3066
3067
3068/// ParseCompare
3069/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3070/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003071bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3072 unsigned Opc) {
3073 // Parse the integer/fp comparison predicate.
3074 LocTy Loc;
3075 unsigned Pred;
3076 Value *LHS, *RHS;
3077 if (ParseCmpPredicate(Pred, Opc) ||
3078 ParseTypeAndValue(LHS, Loc, PFS) ||
3079 ParseToken(lltok::comma, "expected ',' after compare value") ||
3080 ParseValue(LHS->getType(), RHS, PFS))
3081 return true;
3082
3083 if (Opc == Instruction::FCmp) {
3084 if (!LHS->getType()->isFPOrFPVector())
3085 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003086 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003087 } else {
3088 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003089 if (!LHS->getType()->isIntOrIntVector() &&
3090 !isa<PointerType>(LHS->getType()))
3091 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003092 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003093 }
3094 return false;
3095}
3096
3097//===----------------------------------------------------------------------===//
3098// Other Instructions.
3099//===----------------------------------------------------------------------===//
3100
3101
3102/// ParseCast
3103/// ::= CastOpc TypeAndValue 'to' Type
3104bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3105 unsigned Opc) {
3106 LocTy Loc; Value *Op;
3107 PATypeHolder DestTy(Type::VoidTy);
3108 if (ParseTypeAndValue(Op, Loc, PFS) ||
3109 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3110 ParseType(DestTy))
3111 return true;
3112
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003113 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3114 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 return Error(Loc, "invalid cast opcode for cast from '" +
3116 Op->getType()->getDescription() + "' to '" +
3117 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003118 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003119 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3120 return false;
3121}
3122
3123/// ParseSelect
3124/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3125bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3126 LocTy Loc;
3127 Value *Op0, *Op1, *Op2;
3128 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3129 ParseToken(lltok::comma, "expected ',' after select condition") ||
3130 ParseTypeAndValue(Op1, PFS) ||
3131 ParseToken(lltok::comma, "expected ',' after select value") ||
3132 ParseTypeAndValue(Op2, PFS))
3133 return true;
3134
3135 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3136 return Error(Loc, Reason);
3137
3138 Inst = SelectInst::Create(Op0, Op1, Op2);
3139 return false;
3140}
3141
Chris Lattner0088a5c2009-01-05 08:18:44 +00003142/// ParseVA_Arg
3143/// ::= 'va_arg' TypeAndValue ',' Type
3144bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003145 Value *Op;
3146 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003147 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003148 if (ParseTypeAndValue(Op, PFS) ||
3149 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003150 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003152
3153 if (!EltTy->isFirstClassType())
3154 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003155
3156 Inst = new VAArgInst(Op, EltTy);
3157 return false;
3158}
3159
3160/// ParseExtractElement
3161/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3162bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3163 LocTy Loc;
3164 Value *Op0, *Op1;
3165 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3166 ParseToken(lltok::comma, "expected ',' after extract value") ||
3167 ParseTypeAndValue(Op1, PFS))
3168 return true;
3169
3170 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3171 return Error(Loc, "invalid extractelement operands");
3172
Eric Christophera3500da2009-07-25 02:28:41 +00003173 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003174 return false;
3175}
3176
3177/// ParseInsertElement
3178/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3179bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3180 LocTy Loc;
3181 Value *Op0, *Op1, *Op2;
3182 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3183 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3184 ParseTypeAndValue(Op1, PFS) ||
3185 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3186 ParseTypeAndValue(Op2, PFS))
3187 return true;
3188
3189 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003190 return Error(Loc, "invalid insertelement operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00003191
3192 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3193 return false;
3194}
3195
3196/// ParseShuffleVector
3197/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3198bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3199 LocTy Loc;
3200 Value *Op0, *Op1, *Op2;
3201 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3202 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3203 ParseTypeAndValue(Op1, PFS) ||
3204 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3205 ParseTypeAndValue(Op2, PFS))
3206 return true;
3207
3208 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3209 return Error(Loc, "invalid extractelement operands");
3210
3211 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3212 return false;
3213}
3214
3215/// ParsePHI
3216/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3217bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3218 PATypeHolder Ty(Type::VoidTy);
3219 Value *Op0, *Op1;
3220 LocTy TypeLoc = Lex.getLoc();
3221
3222 if (ParseType(Ty) ||
3223 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3224 ParseValue(Ty, Op0, PFS) ||
3225 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3226 ParseValue(Type::LabelTy, Op1, PFS) ||
3227 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3228 return true;
3229
3230 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3231 while (1) {
3232 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3233
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003234 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 break;
3236
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003237 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 ParseValue(Ty, Op0, PFS) ||
3239 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3240 ParseValue(Type::LabelTy, Op1, PFS) ||
3241 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3242 return true;
3243 }
3244
3245 if (!Ty->isFirstClassType())
3246 return Error(TypeLoc, "phi node must have first class type");
3247
3248 PHINode *PN = PHINode::Create(Ty);
3249 PN->reserveOperandSpace(PHIVals.size());
3250 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3251 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3252 Inst = PN;
3253 return false;
3254}
3255
3256/// ParseCall
3257/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3258/// ParameterList OptionalAttrs
3259bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3260 bool isTail) {
3261 unsigned CC, RetAttrs, FnAttrs;
3262 PATypeHolder RetType(Type::VoidTy);
3263 LocTy RetTypeLoc;
3264 ValID CalleeID;
3265 SmallVector<ParamInfo, 16> ArgList;
3266 LocTy CallLoc = Lex.getLoc();
3267
3268 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3269 ParseOptionalCallingConv(CC) ||
3270 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003271 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003272 ParseValID(CalleeID) ||
3273 ParseParameterList(ArgList, PFS) ||
3274 ParseOptionalAttrs(FnAttrs, 2))
3275 return true;
3276
3277 // If RetType is a non-function pointer type, then this is the short syntax
3278 // for the call, which means that RetType is just the return type. Infer the
3279 // rest of the function argument types from the arguments that are present.
3280 const PointerType *PFTy = 0;
3281 const FunctionType *Ty = 0;
3282 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3283 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3284 // Pull out the types of all of the arguments...
3285 std::vector<const Type*> ParamTypes;
3286 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3287 ParamTypes.push_back(ArgList[i].V->getType());
3288
3289 if (!FunctionType::isValidReturnType(RetType))
3290 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3291
Owen Andersondebcb012009-07-29 22:17:13 +00003292 Ty = FunctionType::get(RetType, ParamTypes, false);
3293 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003294 }
3295
3296 // Look up the callee.
3297 Value *Callee;
3298 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3299
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3301 // function attributes.
3302 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3303 if (FnAttrs & ObsoleteFuncAttrs) {
3304 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3305 FnAttrs &= ~ObsoleteFuncAttrs;
3306 }
3307
3308 // Set up the Attributes for the function.
3309 SmallVector<AttributeWithIndex, 8> Attrs;
3310 if (RetAttrs != Attribute::None)
3311 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3312
3313 SmallVector<Value*, 8> Args;
3314
3315 // Loop through FunctionType's arguments and ensure they are specified
3316 // correctly. Also, gather any parameter attributes.
3317 FunctionType::param_iterator I = Ty->param_begin();
3318 FunctionType::param_iterator E = Ty->param_end();
3319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3320 const Type *ExpectedTy = 0;
3321 if (I != E) {
3322 ExpectedTy = *I++;
3323 } else if (!Ty->isVarArg()) {
3324 return Error(ArgList[i].Loc, "too many arguments specified");
3325 }
3326
3327 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3328 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3329 ExpectedTy->getDescription() + "'");
3330 Args.push_back(ArgList[i].V);
3331 if (ArgList[i].Attrs != Attribute::None)
3332 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3333 }
3334
3335 if (I != E)
3336 return Error(CallLoc, "not enough parameters specified for call");
3337
3338 if (FnAttrs != Attribute::None)
3339 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3340
3341 // Finish off the Attributes and check them
3342 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3343
3344 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3345 CI->setTailCall(isTail);
3346 CI->setCallingConv(CC);
3347 CI->setAttributes(PAL);
3348 Inst = CI;
3349 return false;
3350}
3351
3352//===----------------------------------------------------------------------===//
3353// Memory Instructions.
3354//===----------------------------------------------------------------------===//
3355
3356/// ParseAlloc
3357/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3358/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3359bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3360 unsigned Opc) {
3361 PATypeHolder Ty(Type::VoidTy);
3362 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003363 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003365 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003366
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003367 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 if (Lex.getKind() == lltok::kw_align) {
3369 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003370 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3371 ParseOptionalCommaAlignment(Alignment)) {
3372 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 }
3374 }
3375
3376 if (Size && Size->getType() != Type::Int32Ty)
3377 return Error(SizeLoc, "element count must be i32");
3378
3379 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003380 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 else
Owen Anderson50dead02009-07-15 23:53:25 +00003382 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 return false;
3384}
3385
3386/// ParseFree
3387/// ::= 'free' TypeAndValue
3388bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3389 Value *Val; LocTy Loc;
3390 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3391 if (!isa<PointerType>(Val->getType()))
3392 return Error(Loc, "operand to free must be a pointer");
3393 Inst = new FreeInst(Val);
3394 return false;
3395}
3396
3397/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003398/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003399bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3400 bool isVolatile) {
3401 Value *Val; LocTy Loc;
3402 unsigned Alignment;
3403 if (ParseTypeAndValue(Val, Loc, PFS) ||
3404 ParseOptionalCommaAlignment(Alignment))
3405 return true;
3406
3407 if (!isa<PointerType>(Val->getType()) ||
3408 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3409 return Error(Loc, "load operand must be a pointer to a first class type");
3410
3411 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3412 return false;
3413}
3414
3415/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003416/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003417bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3418 bool isVolatile) {
3419 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3420 unsigned Alignment;
3421 if (ParseTypeAndValue(Val, Loc, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after store operand") ||
3423 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3424 ParseOptionalCommaAlignment(Alignment))
3425 return true;
3426
3427 if (!isa<PointerType>(Ptr->getType()))
3428 return Error(PtrLoc, "store operand must be a pointer");
3429 if (!Val->getType()->isFirstClassType())
3430 return Error(Loc, "store operand must be a first class value");
3431 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3432 return Error(Loc, "stored value and pointer type do not match");
3433
3434 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3435 return false;
3436}
3437
3438/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003439/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003440/// FIXME: Remove support for getresult in LLVM 3.0
3441bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3442 Value *Val; LocTy ValLoc, EltLoc;
3443 unsigned Element;
3444 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003446 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 return true;
3448
3449 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3450 return Error(ValLoc, "getresult inst requires an aggregate operand");
3451 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3452 return Error(EltLoc, "invalid getresult index for value");
3453 Inst = ExtractValueInst::Create(Val, Element);
3454 return false;
3455}
3456
3457/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003458/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003459bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3460 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003461
Dan Gohmandcb40a32009-07-29 15:58:36 +00003462 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003463
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003464 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003465
3466 if (!isa<PointerType>(Ptr->getType()))
3467 return Error(Loc, "base of getelementptr must be a pointer");
3468
3469 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003470 while (EatIfPresent(lltok::comma)) {
3471 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003472 if (!isa<IntegerType>(Val->getType()))
3473 return Error(EltLoc, "getelementptr index must be an integer");
3474 Indices.push_back(Val);
3475 }
3476
3477 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3478 Indices.begin(), Indices.end()))
3479 return Error(Loc, "invalid getelementptr indices");
3480 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003481 if (InBounds)
3482 cast<GEPOperator>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003483 return false;
3484}
3485
3486/// ParseExtractValue
3487/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3488bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3489 Value *Val; LocTy Loc;
3490 SmallVector<unsigned, 4> Indices;
3491 if (ParseTypeAndValue(Val, Loc, PFS) ||
3492 ParseIndexList(Indices))
3493 return true;
3494
3495 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3496 return Error(Loc, "extractvalue operand must be array or struct");
3497
3498 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3499 Indices.end()))
3500 return Error(Loc, "invalid indices for extractvalue");
3501 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3502 return false;
3503}
3504
3505/// ParseInsertValue
3506/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3507bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3508 Value *Val0, *Val1; LocTy Loc0, Loc1;
3509 SmallVector<unsigned, 4> Indices;
3510 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3511 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3512 ParseTypeAndValue(Val1, Loc1, PFS) ||
3513 ParseIndexList(Indices))
3514 return true;
3515
3516 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3517 return Error(Loc0, "extractvalue operand must be array or struct");
3518
3519 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3520 Indices.end()))
3521 return Error(Loc0, "invalid indices for insertvalue");
3522 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3523 return false;
3524}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003525
3526//===----------------------------------------------------------------------===//
3527// Embedded metadata.
3528//===----------------------------------------------------------------------===//
3529
3530/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003531/// ::= Element (',' Element)*
3532/// Element
3533/// ::= 'null' | TypeAndValue
3534bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003535 assert(Lex.getKind() == lltok::lbrace);
3536 Lex.Lex();
3537 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003538 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003539 if (Lex.getKind() == lltok::kw_null) {
3540 Lex.Lex();
3541 V = 0;
3542 } else {
Devang Patele54abc92009-07-22 17:43:22 +00003543 PATypeHolder Ty(Type::VoidTy);
3544 if (ParseType(Ty)) return true;
3545 if (Lex.getKind() == lltok::Metadata) {
3546 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003547 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003548 if (!ParseMDNode(Node))
3549 V = Node;
3550 else {
3551 MetadataBase *MDS = 0;
3552 if (ParseMDString(MDS)) return true;
3553 V = MDS;
3554 }
3555 } else {
3556 Constant *C;
3557 if (ParseGlobalValue(Ty, C)) return true;
3558 V = C;
3559 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003560 }
3561 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003562 } while (EatIfPresent(lltok::comma));
3563
3564 return false;
3565}