blob: 5ac4a82ccbe777aeac403e53237810d6be1a22cc [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
Devang Patel2a610c72009-08-25 05:24:07 +0000101 // Check debug info intrinsics.
102 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 return false;
104}
105
106//===----------------------------------------------------------------------===//
107// Top-Level Entities
108//===----------------------------------------------------------------------===//
109
110bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000111 while (1) {
112 switch (Lex.getKind()) {
113 default: return TokError("expected top-level entity");
114 case lltok::Eof: return false;
115 //case lltok::kw_define:
116 case lltok::kw_declare: if (ParseDeclare()) return true; break;
117 case lltok::kw_define: if (ParseDefine()) return true; break;
118 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
119 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
120 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
121 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000122 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
124 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000125 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000126 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000127 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Pateleff2ab62009-07-29 00:34:02 +0000128 case lltok::NamedMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000129
130 // The Global variable production with no name can have many different
131 // optional leading prefixes, the production is:
132 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
133 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000134 case lltok::kw_private : // OptionalLinkage
135 case lltok::kw_linker_private: // OptionalLinkage
136 case lltok::kw_internal: // OptionalLinkage
137 case lltok::kw_weak: // OptionalLinkage
138 case lltok::kw_weak_odr: // OptionalLinkage
139 case lltok::kw_linkonce: // OptionalLinkage
140 case lltok::kw_linkonce_odr: // OptionalLinkage
141 case lltok::kw_appending: // OptionalLinkage
142 case lltok::kw_dllexport: // OptionalLinkage
143 case lltok::kw_common: // OptionalLinkage
144 case lltok::kw_dllimport: // OptionalLinkage
145 case lltok::kw_extern_weak: // OptionalLinkage
146 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000147 unsigned Linkage, Visibility;
148 if (ParseOptionalLinkage(Linkage) ||
149 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000150 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000151 return true;
152 break;
153 }
154 case lltok::kw_default: // OptionalVisibility
155 case lltok::kw_hidden: // OptionalVisibility
156 case lltok::kw_protected: { // OptionalVisibility
157 unsigned Visibility;
158 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000159 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000160 return true;
161 break;
162 }
163
164 case lltok::kw_thread_local: // OptionalThreadLocal
165 case lltok::kw_addrspace: // OptionalAddrSpace
166 case lltok::kw_constant: // GlobalType
167 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000168 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 break;
170 }
171 }
172}
173
174
175/// toplevelentity
176/// ::= 'module' 'asm' STRINGCONSTANT
177bool LLParser::ParseModuleAsm() {
178 assert(Lex.getKind() == lltok::kw_module);
179 Lex.Lex();
180
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000181 std::string AsmStr;
182 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
183 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000184
185 const std::string &AsmSoFar = M->getModuleInlineAsm();
186 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000189 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000190 return false;
191}
192
193/// toplevelentity
194/// ::= 'target' 'triple' '=' STRINGCONSTANT
195/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
196bool LLParser::ParseTargetDefinition() {
197 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000198 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000199 switch (Lex.Lex()) {
200 default: return TokError("unknown target property");
201 case lltok::kw_triple:
202 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000203 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
204 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return false;
208 case lltok::kw_datalayout:
209 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000210 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
211 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000213 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 return false;
215 }
216}
217
218/// toplevelentity
219/// ::= 'deplibs' '=' '[' ']'
220/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
221bool LLParser::ParseDepLibs() {
222 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000223 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000224 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
225 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
226 return true;
227
228 if (EatIfPresent(lltok::rsquare))
229 return false;
230
231 std::string Str;
232 if (ParseStringConstant(Str)) return true;
233 M->addLibrary(Str);
234
235 while (EatIfPresent(lltok::comma)) {
236 if (ParseStringConstant(Str)) return true;
237 M->addLibrary(Str);
238 }
239
240 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000241}
242
Dan Gohman3845e502009-08-12 23:32:33 +0000243/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000244/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000245/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000246bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000247 unsigned TypeID = NumberedTypes.size();
248
249 // Handle the LocalVarID form.
250 if (Lex.getKind() == lltok::LocalVarID) {
251 if (Lex.getUIntVal() != TypeID)
252 return Error(Lex.getLoc(), "type expected to be numbered '%" +
253 utostr(TypeID) + "'");
254 Lex.Lex(); // eat LocalVarID;
255
256 if (ParseToken(lltok::equal, "expected '=' after name"))
257 return true;
258 }
259
Chris Lattnerdf986172009-01-02 07:01:27 +0000260 assert(Lex.getKind() == lltok::kw_type);
261 LocTy TypeLoc = Lex.getLoc();
262 Lex.Lex(); // eat kw_type
263
Owen Anderson1d0be152009-08-13 21:58:54 +0000264 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 if (ParseType(Ty)) return true;
266
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 // See if this type was previously referenced.
268 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
269 FI = ForwardRefTypeIDs.find(TypeID);
270 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000271 if (FI->second.first.get() == Ty)
272 return Error(TypeLoc, "self referential type is invalid");
273
Chris Lattnerdf986172009-01-02 07:01:27 +0000274 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
275 Ty = FI->second.first.get();
276 ForwardRefTypeIDs.erase(FI);
277 }
278
279 NumberedTypes.push_back(Ty);
280
281 return false;
282}
283
284/// toplevelentity
285/// ::= LocalVar '=' 'type' type
286bool LLParser::ParseNamedType() {
287 std::string Name = Lex.getStrVal();
288 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000289 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000290
Owen Anderson1d0be152009-08-13 21:58:54 +0000291 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000292
293 if (ParseToken(lltok::equal, "expected '=' after name") ||
294 ParseToken(lltok::kw_type, "expected 'type' after name") ||
295 ParseType(Ty))
296 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000297
Chris Lattnerdf986172009-01-02 07:01:27 +0000298 // Set the type name, checking for conflicts as we do so.
299 bool AlreadyExists = M->addTypeName(Name, Ty);
300 if (!AlreadyExists) return false;
301
302 // See if this type is a forward reference. We need to eagerly resolve
303 // types to allow recursive type redefinitions below.
304 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
305 FI = ForwardRefTypes.find(Name);
306 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000307 if (FI->second.first.get() == Ty)
308 return Error(NameLoc, "self referential type is invalid");
309
Chris Lattnerdf986172009-01-02 07:01:27 +0000310 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
311 Ty = FI->second.first.get();
312 ForwardRefTypes.erase(FI);
313 }
314
315 // Inserting a name that is already defined, get the existing name.
316 const Type *Existing = M->getTypeByName(Name);
317 assert(Existing && "Conflict but no matching type?!");
318
319 // Otherwise, this is an attempt to redefine a type. That's okay if
320 // the redefinition is identical to the original.
321 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
322 if (Existing == Ty) return false;
323
324 // Any other kind of (non-equivalent) redefinition is an error.
325 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
326 Ty->getDescription() + "'");
327}
328
329
330/// toplevelentity
331/// ::= 'declare' FunctionHeader
332bool LLParser::ParseDeclare() {
333 assert(Lex.getKind() == lltok::kw_declare);
334 Lex.Lex();
335
336 Function *F;
337 return ParseFunctionHeader(F, false);
338}
339
340/// toplevelentity
341/// ::= 'define' FunctionHeader '{' ...
342bool LLParser::ParseDefine() {
343 assert(Lex.getKind() == lltok::kw_define);
344 Lex.Lex();
345
346 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000347 return ParseFunctionHeader(F, true) ||
348 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000349}
350
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000351/// ParseGlobalType
352/// ::= 'constant'
353/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000354bool LLParser::ParseGlobalType(bool &IsConstant) {
355 if (Lex.getKind() == lltok::kw_constant)
356 IsConstant = true;
357 else if (Lex.getKind() == lltok::kw_global)
358 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000359 else {
360 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000361 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000362 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 Lex.Lex();
364 return false;
365}
366
Dan Gohman3845e502009-08-12 23:32:33 +0000367/// ParseUnnamedGlobal:
368/// OptionalVisibility ALIAS ...
369/// OptionalLinkage OptionalVisibility ... -> global variable
370/// GlobalID '=' OptionalVisibility ALIAS ...
371/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
372bool LLParser::ParseUnnamedGlobal() {
373 unsigned VarID = NumberedVals.size();
374 std::string Name;
375 LocTy NameLoc = Lex.getLoc();
376
377 // Handle the GlobalID form.
378 if (Lex.getKind() == lltok::GlobalID) {
379 if (Lex.getUIntVal() != VarID)
380 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
381 utostr(VarID) + "'");
382 Lex.Lex(); // eat GlobalID;
383
384 if (ParseToken(lltok::equal, "expected '=' after name"))
385 return true;
386 }
387
388 bool HasLinkage;
389 unsigned Linkage, Visibility;
390 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
391 ParseOptionalVisibility(Visibility))
392 return true;
393
394 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
395 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
396 return ParseAlias(Name, NameLoc, Visibility);
397}
398
Chris Lattnerdf986172009-01-02 07:01:27 +0000399/// ParseNamedGlobal:
400/// GlobalVar '=' OptionalVisibility ALIAS ...
401/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
402bool LLParser::ParseNamedGlobal() {
403 assert(Lex.getKind() == lltok::GlobalVar);
404 LocTy NameLoc = Lex.getLoc();
405 std::string Name = Lex.getStrVal();
406 Lex.Lex();
407
408 bool HasLinkage;
409 unsigned Linkage, Visibility;
410 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
411 ParseOptionalLinkage(Linkage, HasLinkage) ||
412 ParseOptionalVisibility(Visibility))
413 return true;
414
415 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
416 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
417 return ParseAlias(Name, NameLoc, Visibility);
418}
419
Devang Patel256be962009-07-20 19:00:08 +0000420// MDString:
421// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000422bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000423 std::string Str;
424 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000425 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000426 return false;
427}
428
429// MDNode:
430// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000431bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000432 // !{ ..., !42, ... }
433 unsigned MID = 0;
434 if (ParseUInt32(MID)) return true;
435
436 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000437 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000438 if (I != MetadataCache.end()) {
439 Node = I->second;
440 return false;
441 }
442
443 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000444 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000445 FI = ForwardRefMDNodes.find(MID);
446 if (FI != ForwardRefMDNodes.end()) {
447 Node = FI->second.first;
448 return false;
449 }
450
451 // Create MDNode forward reference
452 SmallVector<Value *, 1> Elts;
453 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000454 Elts.push_back(MDString::get(Context, FwdRefName));
455 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000456 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
457 Node = FwdNode;
458 return false;
459}
460
Devang Pateleff2ab62009-07-29 00:34:02 +0000461///ParseNamedMetadata:
462/// !foo = !{ !1, !2 }
463bool LLParser::ParseNamedMetadata() {
464 assert(Lex.getKind() == lltok::NamedMD);
465 Lex.Lex();
466 std::string Name = Lex.getStrVal();
467
468 if (ParseToken(lltok::equal, "expected '=' here"))
469 return true;
470
471 if (Lex.getKind() != lltok::Metadata)
472 return TokError("Expected '!' here");
473 Lex.Lex();
474
475 if (Lex.getKind() != lltok::lbrace)
476 return TokError("Expected '{' here");
477 Lex.Lex();
478 SmallVector<MetadataBase *, 8> Elts;
479 do {
480 if (Lex.getKind() != lltok::Metadata)
481 return TokError("Expected '!' here");
482 Lex.Lex();
483 MetadataBase *N = 0;
484 if (ParseMDNode(N)) return true;
485 Elts.push_back(N);
486 } while (EatIfPresent(lltok::comma));
487
488 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
489 return true;
490
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000492 return false;
493}
494
Devang Patel923078c2009-07-01 19:21:12 +0000495/// ParseStandaloneMetadata:
496/// !42 = !{...}
497bool LLParser::ParseStandaloneMetadata() {
498 assert(Lex.getKind() == lltok::Metadata);
499 Lex.Lex();
500 unsigned MetadataID = 0;
501 if (ParseUInt32(MetadataID))
502 return true;
503 if (MetadataCache.find(MetadataID) != MetadataCache.end())
504 return TokError("Metadata id is already used");
505 if (ParseToken(lltok::equal, "expected '=' here"))
506 return true;
507
508 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000509 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000510 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000511 return true;
512
Devang Patel104cf9e2009-07-23 01:07:34 +0000513 if (Lex.getKind() != lltok::Metadata)
514 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000515
Devang Patel104cf9e2009-07-23 01:07:34 +0000516 Lex.Lex();
517 if (Lex.getKind() != lltok::lbrace)
518 return TokError("Expected '{' here");
519
520 SmallVector<Value *, 16> Elts;
521 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000522 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000523 return true;
524
Owen Anderson647e3012009-07-31 21:35:40 +0000525 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000526 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000527 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000528 FI = ForwardRefMDNodes.find(MetadataID);
529 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000530 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000531 FwdNode->replaceAllUsesWith(Init);
532 ForwardRefMDNodes.erase(FI);
533 }
534
Devang Patel923078c2009-07-01 19:21:12 +0000535 return false;
536}
537
Chris Lattnerdf986172009-01-02 07:01:27 +0000538/// ParseAlias:
539/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
540/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000541/// ::= TypeAndValue
542/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000543/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000544///
545/// Everything through visibility has already been parsed.
546///
547bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
548 unsigned Visibility) {
549 assert(Lex.getKind() == lltok::kw_alias);
550 Lex.Lex();
551 unsigned Linkage;
552 LocTy LinkageLoc = Lex.getLoc();
553 if (ParseOptionalLinkage(Linkage))
554 return true;
555
556 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000557 Linkage != GlobalValue::WeakAnyLinkage &&
558 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000559 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000560 Linkage != GlobalValue::PrivateLinkage &&
561 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000562 return Error(LinkageLoc, "invalid linkage type for alias");
563
564 Constant *Aliasee;
565 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000566 if (Lex.getKind() != lltok::kw_bitcast &&
567 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000568 if (ParseGlobalTypeAndValue(Aliasee)) return true;
569 } else {
570 // The bitcast dest type is not present, it is implied by the dest type.
571 ValID ID;
572 if (ParseValID(ID)) return true;
573 if (ID.Kind != ValID::t_Constant)
574 return Error(AliaseeLoc, "invalid aliasee");
575 Aliasee = ID.ConstantVal;
576 }
577
578 if (!isa<PointerType>(Aliasee->getType()))
579 return Error(AliaseeLoc, "alias must have pointer type");
580
581 // Okay, create the alias but do not insert it into the module yet.
582 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
583 (GlobalValue::LinkageTypes)Linkage, Name,
584 Aliasee);
585 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
586
587 // See if this value already exists in the symbol table. If so, it is either
588 // a redefinition or a definition of a forward reference.
589 if (GlobalValue *Val =
590 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
591 // See if this was a redefinition. If so, there is no entry in
592 // ForwardRefVals.
593 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
594 I = ForwardRefVals.find(Name);
595 if (I == ForwardRefVals.end())
596 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
597
598 // Otherwise, this was a definition of forward ref. Verify that types
599 // agree.
600 if (Val->getType() != GA->getType())
601 return Error(NameLoc,
602 "forward reference and definition of alias have different types");
603
604 // If they agree, just RAUW the old value with the alias and remove the
605 // forward ref info.
606 Val->replaceAllUsesWith(GA);
607 Val->eraseFromParent();
608 ForwardRefVals.erase(I);
609 }
610
611 // Insert into the module, we know its name won't collide now.
612 M->getAliasList().push_back(GA);
613 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
614
615 return false;
616}
617
618/// ParseGlobal
619/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
620/// OptionalAddrSpace GlobalType Type Const
621/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
622/// OptionalAddrSpace GlobalType Type Const
623///
624/// Everything through visibility has been parsed already.
625///
626bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
627 unsigned Linkage, bool HasLinkage,
628 unsigned Visibility) {
629 unsigned AddrSpace;
630 bool ThreadLocal, IsConstant;
631 LocTy TyLoc;
632
Owen Anderson1d0be152009-08-13 21:58:54 +0000633 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000634 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
635 ParseOptionalAddrSpace(AddrSpace) ||
636 ParseGlobalType(IsConstant) ||
637 ParseType(Ty, TyLoc))
638 return true;
639
640 // If the linkage is specified and is external, then no initializer is
641 // present.
642 Constant *Init = 0;
643 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000644 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000645 Linkage != GlobalValue::ExternalLinkage)) {
646 if (ParseGlobalValue(Ty, Init))
647 return true;
648 }
649
Owen Anderson1d0be152009-08-13 21:58:54 +0000650 if (isa<FunctionType>(Ty) || Ty == Type::getLabelTy(Context))
Chris Lattner4a2f1122009-02-08 20:00:15 +0000651 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000652
653 GlobalVariable *GV = 0;
654
655 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000656 if (!Name.empty()) {
657 if ((GV = M->getGlobalVariable(Name, true)) &&
658 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 return Error(NameLoc, "redefinition of global '@" + Name + "'");
660 } else {
661 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
662 I = ForwardRefValIDs.find(NumberedVals.size());
663 if (I != ForwardRefValIDs.end()) {
664 GV = cast<GlobalVariable>(I->second.first);
665 ForwardRefValIDs.erase(I);
666 }
667 }
668
669 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000670 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
671 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 } else {
673 if (GV->getType()->getElementType() != Ty)
674 return Error(TyLoc,
675 "forward reference and definition of global have different types");
676
677 // Move the forward-reference to the correct spot in the module.
678 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
679 }
680
681 if (Name.empty())
682 NumberedVals.push_back(GV);
683
684 // Set the parsed properties on the global.
685 if (Init)
686 GV->setInitializer(Init);
687 GV->setConstant(IsConstant);
688 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
689 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
690 GV->setThreadLocal(ThreadLocal);
691
692 // Parse attributes on the global.
693 while (Lex.getKind() == lltok::comma) {
694 Lex.Lex();
695
696 if (Lex.getKind() == lltok::kw_section) {
697 Lex.Lex();
698 GV->setSection(Lex.getStrVal());
699 if (ParseToken(lltok::StringConstant, "expected global section string"))
700 return true;
701 } else if (Lex.getKind() == lltok::kw_align) {
702 unsigned Alignment;
703 if (ParseOptionalAlignment(Alignment)) return true;
704 GV->setAlignment(Alignment);
705 } else {
706 TokError("unknown global variable property!");
707 }
708 }
709
710 return false;
711}
712
713
714//===----------------------------------------------------------------------===//
715// GlobalValue Reference/Resolution Routines.
716//===----------------------------------------------------------------------===//
717
718/// GetGlobalVal - Get a value with the specified name or ID, creating a
719/// forward reference record if needed. This can return null if the value
720/// exists but does not have the right type.
721GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
722 LocTy Loc) {
723 const PointerType *PTy = dyn_cast<PointerType>(Ty);
724 if (PTy == 0) {
725 Error(Loc, "global variable reference must have pointer type");
726 return 0;
727 }
728
729 // Look this name up in the normal function symbol table.
730 GlobalValue *Val =
731 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
732
733 // If this is a forward reference for the value, see if we already created a
734 // forward ref record.
735 if (Val == 0) {
736 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
737 I = ForwardRefVals.find(Name);
738 if (I != ForwardRefVals.end())
739 Val = I->second.first;
740 }
741
742 // If we have the value in the symbol table or fwd-ref table, return it.
743 if (Val) {
744 if (Val->getType() == Ty) return Val;
745 Error(Loc, "'@" + Name + "' defined with type '" +
746 Val->getType()->getDescription() + "'");
747 return 0;
748 }
749
750 // Otherwise, create a new forward reference for this value and remember it.
751 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000752 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
753 // Function types can return opaque but functions can't.
754 if (isa<OpaqueType>(FT->getReturnType())) {
755 Error(Loc, "function may not return opaque type");
756 return 0;
757 }
758
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000759 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000760 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000761 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
762 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000763 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000764
765 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
766 return FwdVal;
767}
768
769GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
770 const PointerType *PTy = dyn_cast<PointerType>(Ty);
771 if (PTy == 0) {
772 Error(Loc, "global variable reference must have pointer type");
773 return 0;
774 }
775
776 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
777
778 // If this is a forward reference for the value, see if we already created a
779 // forward ref record.
780 if (Val == 0) {
781 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
782 I = ForwardRefValIDs.find(ID);
783 if (I != ForwardRefValIDs.end())
784 Val = I->second.first;
785 }
786
787 // If we have the value in the symbol table or fwd-ref table, return it.
788 if (Val) {
789 if (Val->getType() == Ty) return Val;
790 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
791 Val->getType()->getDescription() + "'");
792 return 0;
793 }
794
795 // Otherwise, create a new forward reference for this value and remember it.
796 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000797 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
798 // Function types can return opaque but functions can't.
799 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000800 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000801 return 0;
802 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000803 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000804 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000805 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
806 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000807 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000808
809 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
810 return FwdVal;
811}
812
813
814//===----------------------------------------------------------------------===//
815// Helper Routines.
816//===----------------------------------------------------------------------===//
817
818/// ParseToken - If the current token has the specified kind, eat it and return
819/// success. Otherwise, emit the specified error and return failure.
820bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
821 if (Lex.getKind() != T)
822 return TokError(ErrMsg);
823 Lex.Lex();
824 return false;
825}
826
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000827/// ParseStringConstant
828/// ::= StringConstant
829bool LLParser::ParseStringConstant(std::string &Result) {
830 if (Lex.getKind() != lltok::StringConstant)
831 return TokError("expected string constant");
832 Result = Lex.getStrVal();
833 Lex.Lex();
834 return false;
835}
836
837/// ParseUInt32
838/// ::= uint32
839bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000840 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
841 return TokError("expected integer");
842 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
843 if (Val64 != unsigned(Val64))
844 return TokError("expected 32-bit integer (too large)");
845 Val = Val64;
846 Lex.Lex();
847 return false;
848}
849
850
851/// ParseOptionalAddrSpace
852/// := /*empty*/
853/// := 'addrspace' '(' uint32 ')'
854bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
855 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000856 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000857 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000859 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000860 ParseToken(lltok::rparen, "expected ')' in address space");
861}
862
863/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
864/// indicates what kind of attribute list this is: 0: function arg, 1: result,
865/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000866/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000867bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
868 Attrs = Attribute::None;
869 LocTy AttrLoc = Lex.getLoc();
870
871 while (1) {
872 switch (Lex.getKind()) {
873 case lltok::kw_sext:
874 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000875 // Treat these as signext/zeroext if they occur in the argument list after
876 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
877 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
878 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000880 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000881 if (Lex.getKind() == lltok::kw_sext)
882 Attrs |= Attribute::SExt;
883 else
884 Attrs |= Attribute::ZExt;
885 break;
886 }
887 // FALL THROUGH.
888 default: // End of attributes.
889 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
890 return Error(AttrLoc, "invalid use of function-only attribute");
891
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000892 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000893 return Error(AttrLoc, "invalid use of parameter-only attribute");
894
895 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000896 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
897 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
898 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
899 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
900 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
901 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
902 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
903 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000904
Devang Patel578efa92009-06-05 21:57:13 +0000905 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
906 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
907 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
908 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
909 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
910 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
911 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
912 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
913 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
914 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
915 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000916 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000917
918 case lltok::kw_align: {
919 unsigned Alignment;
920 if (ParseOptionalAlignment(Alignment))
921 return true;
922 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
923 continue;
924 }
925 }
926 Lex.Lex();
927 }
928}
929
930/// ParseOptionalLinkage
931/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000932/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000933/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000934/// ::= 'internal'
935/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000936/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000937/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000938/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000939/// ::= 'appending'
940/// ::= 'dllexport'
941/// ::= 'common'
942/// ::= 'dllimport'
943/// ::= 'extern_weak'
944/// ::= 'external'
945bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
946 HasLinkage = false;
947 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000948 default: Res=GlobalValue::ExternalLinkage; return false;
949 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
950 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
951 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
952 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
953 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
954 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
955 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000956 case lltok::kw_available_externally:
957 Res = GlobalValue::AvailableExternallyLinkage;
958 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000959 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
960 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
961 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
962 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
963 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
964 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000965 }
966 Lex.Lex();
967 HasLinkage = true;
968 return false;
969}
970
971/// ParseOptionalVisibility
972/// ::= /*empty*/
973/// ::= 'default'
974/// ::= 'hidden'
975/// ::= 'protected'
976///
977bool LLParser::ParseOptionalVisibility(unsigned &Res) {
978 switch (Lex.getKind()) {
979 default: Res = GlobalValue::DefaultVisibility; return false;
980 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
981 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
982 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
983 }
984 Lex.Lex();
985 return false;
986}
987
988/// ParseOptionalCallingConv
989/// ::= /*empty*/
990/// ::= 'ccc'
991/// ::= 'fastcc'
992/// ::= 'coldcc'
993/// ::= 'x86_stdcallcc'
994/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000995/// ::= 'arm_apcscc'
996/// ::= 'arm_aapcscc'
997/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000998/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000999///
Chris Lattnerdf986172009-01-02 07:01:27 +00001000bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1001 switch (Lex.getKind()) {
1002 default: CC = CallingConv::C; return false;
1003 case lltok::kw_ccc: CC = CallingConv::C; break;
1004 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1005 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1006 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1007 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001008 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1009 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1010 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001011 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +00001012 }
1013 Lex.Lex();
1014 return false;
1015}
1016
1017/// ParseOptionalAlignment
1018/// ::= /* empty */
1019/// ::= 'align' 4
1020bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1021 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001022 if (!EatIfPresent(lltok::kw_align))
1023 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001024 LocTy AlignLoc = Lex.getLoc();
1025 if (ParseUInt32(Alignment)) return true;
1026 if (!isPowerOf2_32(Alignment))
1027 return Error(AlignLoc, "alignment is not a power of two");
1028 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001029}
1030
1031/// ParseOptionalCommaAlignment
1032/// ::= /* empty */
1033/// ::= ',' 'align' 4
1034bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1035 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001036 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00001037 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001038 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001039 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001040}
1041
1042/// ParseIndexList
1043/// ::= (',' uint32)+
1044bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1045 if (Lex.getKind() != lltok::comma)
1046 return TokError("expected ',' as start of index list");
1047
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001048 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001049 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001050 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001051 Indices.push_back(Idx);
1052 }
1053
1054 return false;
1055}
1056
1057//===----------------------------------------------------------------------===//
1058// Type Parsing.
1059//===----------------------------------------------------------------------===//
1060
1061/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001062bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1063 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001064 if (ParseTypeRec(Result)) return true;
1065
1066 // Verify no unresolved uprefs.
1067 if (!UpRefs.empty())
1068 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +00001069
Owen Anderson1d0be152009-08-13 21:58:54 +00001070 if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001071 return Error(TypeLoc, "void type only allowed for function results");
1072
Chris Lattnerdf986172009-01-02 07:01:27 +00001073 return false;
1074}
1075
1076/// HandleUpRefs - Every time we finish a new layer of types, this function is
1077/// called. It loops through the UpRefs vector, which is a list of the
1078/// currently active types. For each type, if the up-reference is contained in
1079/// the newly completed type, we decrement the level count. When the level
1080/// count reaches zero, the up-referenced type is the type that is passed in:
1081/// thus we can complete the cycle.
1082///
1083PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1084 // If Ty isn't abstract, or if there are no up-references in it, then there is
1085 // nothing to resolve here.
1086 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1087
1088 PATypeHolder Ty(ty);
1089#if 0
1090 errs() << "Type '" << Ty->getDescription()
1091 << "' newly formed. Resolving upreferences.\n"
1092 << UpRefs.size() << " upreferences active!\n";
1093#endif
1094
1095 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1096 // to zero), we resolve them all together before we resolve them to Ty. At
1097 // the end of the loop, if there is anything to resolve to Ty, it will be in
1098 // this variable.
1099 OpaqueType *TypeToResolve = 0;
1100
1101 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1102 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1103 bool ContainsType =
1104 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1105 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1106
1107#if 0
1108 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1109 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1110 << (ContainsType ? "true" : "false")
1111 << " level=" << UpRefs[i].NestingLevel << "\n";
1112#endif
1113 if (!ContainsType)
1114 continue;
1115
1116 // Decrement level of upreference
1117 unsigned Level = --UpRefs[i].NestingLevel;
1118 UpRefs[i].LastContainedTy = Ty;
1119
1120 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1121 if (Level != 0)
1122 continue;
1123
1124#if 0
1125 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1126#endif
1127 if (!TypeToResolve)
1128 TypeToResolve = UpRefs[i].UpRefTy;
1129 else
1130 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1131 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1132 --i; // Do not skip the next element.
1133 }
1134
1135 if (TypeToResolve)
1136 TypeToResolve->refineAbstractTypeTo(Ty);
1137
1138 return Ty;
1139}
1140
1141
1142/// ParseTypeRec - The recursive function used to process the internal
1143/// implementation details of types.
1144bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1145 switch (Lex.getKind()) {
1146 default:
1147 return TokError("expected type");
1148 case lltok::Type:
1149 // TypeRec ::= 'float' | 'void' (etc)
1150 Result = Lex.getTyVal();
1151 Lex.Lex();
1152 break;
1153 case lltok::kw_opaque:
1154 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001155 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 Lex.Lex();
1157 break;
1158 case lltok::lbrace:
1159 // TypeRec ::= '{' ... '}'
1160 if (ParseStructType(Result, false))
1161 return true;
1162 break;
1163 case lltok::lsquare:
1164 // TypeRec ::= '[' ... ']'
1165 Lex.Lex(); // eat the lsquare.
1166 if (ParseArrayVectorType(Result, false))
1167 return true;
1168 break;
1169 case lltok::less: // Either vector or packed struct.
1170 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001171 Lex.Lex();
1172 if (Lex.getKind() == lltok::lbrace) {
1173 if (ParseStructType(Result, true) ||
1174 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001176 } else if (ParseArrayVectorType(Result, true))
1177 return true;
1178 break;
1179 case lltok::LocalVar:
1180 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1181 // TypeRec ::= %foo
1182 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1183 Result = T;
1184 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001185 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001186 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1187 std::make_pair(Result,
1188 Lex.getLoc())));
1189 M->addTypeName(Lex.getStrVal(), Result.get());
1190 }
1191 Lex.Lex();
1192 break;
1193
1194 case lltok::LocalVarID:
1195 // TypeRec ::= %4
1196 if (Lex.getUIntVal() < NumberedTypes.size())
1197 Result = NumberedTypes[Lex.getUIntVal()];
1198 else {
1199 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1200 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1201 if (I != ForwardRefTypeIDs.end())
1202 Result = I->second.first;
1203 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001204 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001205 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1206 std::make_pair(Result,
1207 Lex.getLoc())));
1208 }
1209 }
1210 Lex.Lex();
1211 break;
1212 case lltok::backslash: {
1213 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001214 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001215 unsigned Val;
1216 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001217 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1219 Result = OT;
1220 break;
1221 }
1222 }
1223
1224 // Parse the type suffixes.
1225 while (1) {
1226 switch (Lex.getKind()) {
1227 // End of type.
1228 default: return false;
1229
1230 // TypeRec ::= TypeRec '*'
1231 case lltok::star:
Owen Anderson1d0be152009-08-13 21:58:54 +00001232 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001233 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001234 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001235 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001236 if (!PointerType::isValidElementType(Result.get()))
1237 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001238 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 Lex.Lex();
1240 break;
1241
1242 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1243 case lltok::kw_addrspace: {
Owen Anderson1d0be152009-08-13 21:58:54 +00001244 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001245 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001246 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001247 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001248 if (!PointerType::isValidElementType(Result.get()))
1249 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 unsigned AddrSpace;
1251 if (ParseOptionalAddrSpace(AddrSpace) ||
1252 ParseToken(lltok::star, "expected '*' in address space"))
1253 return true;
1254
Owen Andersondebcb012009-07-29 22:17:13 +00001255 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 break;
1257 }
1258
1259 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1260 case lltok::lparen:
1261 if (ParseFunctionType(Result))
1262 return true;
1263 break;
1264 }
1265 }
1266}
1267
1268/// ParseParameterList
1269/// ::= '(' ')'
1270/// ::= '(' Arg (',' Arg)* ')'
1271/// Arg
1272/// ::= Type OptionalAttributes Value OptionalAttributes
1273bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1274 PerFunctionState &PFS) {
1275 if (ParseToken(lltok::lparen, "expected '(' in call"))
1276 return true;
1277
1278 while (Lex.getKind() != lltok::rparen) {
1279 // If this isn't the first argument, we need a comma.
1280 if (!ArgList.empty() &&
1281 ParseToken(lltok::comma, "expected ',' in argument list"))
1282 return true;
1283
1284 // Parse the argument.
1285 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001286 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 unsigned ArgAttrs1, ArgAttrs2;
1288 Value *V;
1289 if (ParseType(ArgTy, ArgLoc) ||
1290 ParseOptionalAttrs(ArgAttrs1, 0) ||
1291 ParseValue(ArgTy, V, PFS) ||
1292 // FIXME: Should not allow attributes after the argument, remove this in
1293 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001294 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 return true;
1296 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1297 }
1298
1299 Lex.Lex(); // Lex the ')'.
1300 return false;
1301}
1302
1303
1304
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001305/// ParseArgumentList - Parse the argument list for a function type or function
1306/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001307/// ::= '(' ArgTypeListI ')'
1308/// ArgTypeListI
1309/// ::= /*empty*/
1310/// ::= '...'
1311/// ::= ArgTypeList ',' '...'
1312/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001313///
Chris Lattnerdf986172009-01-02 07:01:27 +00001314bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001315 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 isVarArg = false;
1317 assert(Lex.getKind() == lltok::lparen);
1318 Lex.Lex(); // eat the (.
1319
1320 if (Lex.getKind() == lltok::rparen) {
1321 // empty
1322 } else if (Lex.getKind() == lltok::dotdotdot) {
1323 isVarArg = true;
1324 Lex.Lex();
1325 } else {
1326 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001327 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001328 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001330
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001331 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1332 // types (such as a function returning a pointer to itself). If parsing a
1333 // function prototype, we require fully resolved types.
1334 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001335 ParseOptionalAttrs(Attrs, 0)) return true;
1336
Owen Anderson1d0be152009-08-13 21:58:54 +00001337 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001338 return Error(TypeLoc, "argument can not have void type");
1339
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 if (Lex.getKind() == lltok::LocalVar ||
1341 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1342 Name = Lex.getStrVal();
1343 Lex.Lex();
1344 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001345
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001346 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001347 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001348
1349 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1350
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001351 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001353 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 break;
1356 }
1357
1358 // Otherwise must be an argument type.
1359 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001360 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001361 ParseOptionalAttrs(Attrs, 0)) return true;
1362
Owen Anderson1d0be152009-08-13 21:58:54 +00001363 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001364 return Error(TypeLoc, "argument can not have void type");
1365
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 if (Lex.getKind() == lltok::LocalVar ||
1367 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1368 Name = Lex.getStrVal();
1369 Lex.Lex();
1370 } else {
1371 Name = "";
1372 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001373
1374 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1375 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001376
1377 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1378 }
1379 }
1380
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001381 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001382}
1383
1384/// ParseFunctionType
1385/// ::= Type ArgumentList OptionalAttrs
1386bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1387 assert(Lex.getKind() == lltok::lparen);
1388
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001389 if (!FunctionType::isValidReturnType(Result))
1390 return TokError("invalid function return type");
1391
Chris Lattnerdf986172009-01-02 07:01:27 +00001392 std::vector<ArgInfo> ArgList;
1393 bool isVarArg;
1394 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001395 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 // FIXME: Allow, but ignore attributes on function types!
1397 // FIXME: Remove in LLVM 3.0
1398 ParseOptionalAttrs(Attrs, 2))
1399 return true;
1400
1401 // Reject names on the arguments lists.
1402 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1403 if (!ArgList[i].Name.empty())
1404 return Error(ArgList[i].Loc, "argument name invalid in function type");
1405 if (!ArgList[i].Attrs != 0) {
1406 // Allow but ignore attributes on function types; this permits
1407 // auto-upgrade.
1408 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1409 }
1410 }
1411
1412 std::vector<const Type*> ArgListTy;
1413 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1414 ArgListTy.push_back(ArgList[i].Type);
1415
Owen Andersondebcb012009-07-29 22:17:13 +00001416 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001417 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 return false;
1419}
1420
1421/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1422/// TypeRec
1423/// ::= '{' '}'
1424/// ::= '{' TypeRec (',' TypeRec)* '}'
1425/// ::= '<' '{' '}' '>'
1426/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1427bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1428 assert(Lex.getKind() == lltok::lbrace);
1429 Lex.Lex(); // Consume the '{'
1430
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001431 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001432 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 return false;
1434 }
1435
1436 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001437 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 if (ParseTypeRec(Result)) return true;
1439 ParamsList.push_back(Result);
1440
Owen Anderson1d0be152009-08-13 21:58:54 +00001441 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001442 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001443 if (!StructType::isValidElementType(Result))
1444 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001445
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001446 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001447 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001449
Owen Anderson1d0be152009-08-13 21:58:54 +00001450 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001451 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001452 if (!StructType::isValidElementType(Result))
1453 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001454
Chris Lattnerdf986172009-01-02 07:01:27 +00001455 ParamsList.push_back(Result);
1456 }
1457
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001458 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1459 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001460
1461 std::vector<const Type*> ParamsListTy;
1462 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1463 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001464 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001465 return false;
1466}
1467
1468/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1469/// token has already been consumed.
1470/// TypeRec
1471/// ::= '[' APSINTVAL 'x' Types ']'
1472/// ::= '<' APSINTVAL 'x' Types '>'
1473bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1474 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1475 Lex.getAPSIntVal().getBitWidth() > 64)
1476 return TokError("expected number in address space");
1477
1478 LocTy SizeLoc = Lex.getLoc();
1479 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001480 Lex.Lex();
1481
1482 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1483 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001484
1485 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001486 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001487 if (ParseTypeRec(EltTy)) return true;
1488
Owen Anderson1d0be152009-08-13 21:58:54 +00001489 if (EltTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001490 return Error(TypeLoc, "array and vector element type cannot be void");
1491
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001492 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1493 "expected end of sequential type"))
1494 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001495
1496 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001497 if (Size == 0)
1498 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 if ((unsigned)Size != Size)
1500 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001501 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001502 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001503 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001505 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001506 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001507 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 }
1509 return false;
1510}
1511
1512//===----------------------------------------------------------------------===//
1513// Function Semantic Analysis.
1514//===----------------------------------------------------------------------===//
1515
1516LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1517 : P(p), F(f) {
1518
1519 // Insert unnamed arguments into the NumberedVals list.
1520 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1521 AI != E; ++AI)
1522 if (!AI->hasName())
1523 NumberedVals.push_back(AI);
1524}
1525
1526LLParser::PerFunctionState::~PerFunctionState() {
1527 // If there were any forward referenced non-basicblock values, delete them.
1528 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1529 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1530 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001531 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001532 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 delete I->second.first;
1534 I->second.first = 0;
1535 }
1536
1537 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1538 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1539 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001540 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001541 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 delete I->second.first;
1543 I->second.first = 0;
1544 }
1545}
1546
1547bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1548 if (!ForwardRefVals.empty())
1549 return P.Error(ForwardRefVals.begin()->second.second,
1550 "use of undefined value '%" + ForwardRefVals.begin()->first +
1551 "'");
1552 if (!ForwardRefValIDs.empty())
1553 return P.Error(ForwardRefValIDs.begin()->second.second,
1554 "use of undefined value '%" +
1555 utostr(ForwardRefValIDs.begin()->first) + "'");
1556 return false;
1557}
1558
1559
1560/// GetVal - Get a value with the specified name or ID, creating a
1561/// forward reference record if needed. This can return null if the value
1562/// exists but does not have the right type.
1563Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1564 const Type *Ty, LocTy Loc) {
1565 // Look this name up in the normal function symbol table.
1566 Value *Val = F.getValueSymbolTable().lookup(Name);
1567
1568 // If this is a forward reference for the value, see if we already created a
1569 // forward ref record.
1570 if (Val == 0) {
1571 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1572 I = ForwardRefVals.find(Name);
1573 if (I != ForwardRefVals.end())
1574 Val = I->second.first;
1575 }
1576
1577 // If we have the value in the symbol table or fwd-ref table, return it.
1578 if (Val) {
1579 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001580 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001581 P.Error(Loc, "'%" + Name + "' is not a basic block");
1582 else
1583 P.Error(Loc, "'%" + Name + "' defined with type '" +
1584 Val->getType()->getDescription() + "'");
1585 return 0;
1586 }
1587
1588 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001589 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1590 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001591 P.Error(Loc, "invalid use of a non-first-class type");
1592 return 0;
1593 }
1594
1595 // Otherwise, create a new forward reference for this value and remember it.
1596 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001597 if (Ty == Type::getLabelTy(F.getContext()))
1598 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 else
1600 FwdVal = new Argument(Ty, Name);
1601
1602 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1603 return FwdVal;
1604}
1605
1606Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1607 LocTy Loc) {
1608 // Look this name up in the normal function symbol table.
1609 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1610
1611 // If this is a forward reference for the value, see if we already created a
1612 // forward ref record.
1613 if (Val == 0) {
1614 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1615 I = ForwardRefValIDs.find(ID);
1616 if (I != ForwardRefValIDs.end())
1617 Val = I->second.first;
1618 }
1619
1620 // If we have the value in the symbol table or fwd-ref table, return it.
1621 if (Val) {
1622 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001623 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001624 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1625 else
1626 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1627 Val->getType()->getDescription() + "'");
1628 return 0;
1629 }
1630
Owen Anderson1d0be152009-08-13 21:58:54 +00001631 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1632 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001633 P.Error(Loc, "invalid use of a non-first-class type");
1634 return 0;
1635 }
1636
1637 // Otherwise, create a new forward reference for this value and remember it.
1638 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001639 if (Ty == Type::getLabelTy(F.getContext()))
1640 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 else
1642 FwdVal = new Argument(Ty);
1643
1644 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1645 return FwdVal;
1646}
1647
1648/// SetInstName - After an instruction is parsed and inserted into its
1649/// basic block, this installs its name.
1650bool LLParser::PerFunctionState::SetInstName(int NameID,
1651 const std::string &NameStr,
1652 LocTy NameLoc, Instruction *Inst) {
1653 // If this instruction has void type, it cannot have a name or ID specified.
Owen Anderson1d0be152009-08-13 21:58:54 +00001654 if (Inst->getType() == Type::getVoidTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001655 if (NameID != -1 || !NameStr.empty())
1656 return P.Error(NameLoc, "instructions returning void cannot have a name");
1657 return false;
1658 }
1659
1660 // If this was a numbered instruction, verify that the instruction is the
1661 // expected value and resolve any forward references.
1662 if (NameStr.empty()) {
1663 // If neither a name nor an ID was specified, just use the next ID.
1664 if (NameID == -1)
1665 NameID = NumberedVals.size();
1666
1667 if (unsigned(NameID) != NumberedVals.size())
1668 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1669 utostr(NumberedVals.size()) + "'");
1670
1671 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1672 ForwardRefValIDs.find(NameID);
1673 if (FI != ForwardRefValIDs.end()) {
1674 if (FI->second.first->getType() != Inst->getType())
1675 return P.Error(NameLoc, "instruction forward referenced with type '" +
1676 FI->second.first->getType()->getDescription() + "'");
1677 FI->second.first->replaceAllUsesWith(Inst);
1678 ForwardRefValIDs.erase(FI);
1679 }
1680
1681 NumberedVals.push_back(Inst);
1682 return false;
1683 }
1684
1685 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1686 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1687 FI = ForwardRefVals.find(NameStr);
1688 if (FI != ForwardRefVals.end()) {
1689 if (FI->second.first->getType() != Inst->getType())
1690 return P.Error(NameLoc, "instruction forward referenced with type '" +
1691 FI->second.first->getType()->getDescription() + "'");
1692 FI->second.first->replaceAllUsesWith(Inst);
1693 ForwardRefVals.erase(FI);
1694 }
1695
1696 // Set the name on the instruction.
1697 Inst->setName(NameStr);
1698
1699 if (Inst->getNameStr() != NameStr)
1700 return P.Error(NameLoc, "multiple definition of local value named '" +
1701 NameStr + "'");
1702 return false;
1703}
1704
1705/// GetBB - Get a basic block with the specified name or ID, creating a
1706/// forward reference record if needed.
1707BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1708 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001709 return cast_or_null<BasicBlock>(GetVal(Name,
1710 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001711}
1712
1713BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001714 return cast_or_null<BasicBlock>(GetVal(ID,
1715 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001716}
1717
1718/// DefineBB - Define the specified basic block, which is either named or
1719/// unnamed. If there is an error, this returns null otherwise it returns
1720/// the block being defined.
1721BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1722 LocTy Loc) {
1723 BasicBlock *BB;
1724 if (Name.empty())
1725 BB = GetBB(NumberedVals.size(), Loc);
1726 else
1727 BB = GetBB(Name, Loc);
1728 if (BB == 0) return 0; // Already diagnosed error.
1729
1730 // Move the block to the end of the function. Forward ref'd blocks are
1731 // inserted wherever they happen to be referenced.
1732 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1733
1734 // Remove the block from forward ref sets.
1735 if (Name.empty()) {
1736 ForwardRefValIDs.erase(NumberedVals.size());
1737 NumberedVals.push_back(BB);
1738 } else {
1739 // BB forward references are already in the function symbol table.
1740 ForwardRefVals.erase(Name);
1741 }
1742
1743 return BB;
1744}
1745
1746//===----------------------------------------------------------------------===//
1747// Constants.
1748//===----------------------------------------------------------------------===//
1749
1750/// ParseValID - Parse an abstract value that doesn't necessarily have a
1751/// type implied. For example, if we parse "4" we don't know what integer type
1752/// it has. The value will later be combined with its type and checked for
1753/// sanity.
1754bool LLParser::ParseValID(ValID &ID) {
1755 ID.Loc = Lex.getLoc();
1756 switch (Lex.getKind()) {
1757 default: return TokError("expected value token");
1758 case lltok::GlobalID: // @42
1759 ID.UIntVal = Lex.getUIntVal();
1760 ID.Kind = ValID::t_GlobalID;
1761 break;
1762 case lltok::GlobalVar: // @foo
1763 ID.StrVal = Lex.getStrVal();
1764 ID.Kind = ValID::t_GlobalName;
1765 break;
1766 case lltok::LocalVarID: // %42
1767 ID.UIntVal = Lex.getUIntVal();
1768 ID.Kind = ValID::t_LocalID;
1769 break;
1770 case lltok::LocalVar: // %foo
1771 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1772 ID.StrVal = Lex.getStrVal();
1773 ID.Kind = ValID::t_LocalName;
1774 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001775 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001776 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001777 Lex.Lex();
1778 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001779 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001780 if (ParseMDNodeVector(Elts) ||
1781 ParseToken(lltok::rbrace, "expected end of metadata node"))
1782 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001783
Owen Anderson647e3012009-07-31 21:35:40 +00001784 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001785 return false;
1786 }
1787
Devang Patel923078c2009-07-01 19:21:12 +00001788 // Standalone metadata reference
1789 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001790 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001791 return false;
Devang Patel256be962009-07-20 19:00:08 +00001792
Nick Lewycky21cc4462009-04-04 07:22:01 +00001793 // MDString:
1794 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001795 if (ParseMDString(ID.MetadataVal)) return true;
1796 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001797 return false;
1798 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001799 case lltok::APSInt:
1800 ID.APSIntVal = Lex.getAPSIntVal();
1801 ID.Kind = ValID::t_APSInt;
1802 break;
1803 case lltok::APFloat:
1804 ID.APFloatVal = Lex.getAPFloatVal();
1805 ID.Kind = ValID::t_APFloat;
1806 break;
1807 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001808 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 ID.Kind = ValID::t_Constant;
1810 break;
1811 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001812 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001813 ID.Kind = ValID::t_Constant;
1814 break;
1815 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1816 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1817 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1818
1819 case lltok::lbrace: {
1820 // ValID ::= '{' ConstVector '}'
1821 Lex.Lex();
1822 SmallVector<Constant*, 16> Elts;
1823 if (ParseGlobalValueVector(Elts) ||
1824 ParseToken(lltok::rbrace, "expected end of struct constant"))
1825 return true;
1826
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001827 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1828 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 ID.Kind = ValID::t_Constant;
1830 return false;
1831 }
1832 case lltok::less: {
1833 // ValID ::= '<' ConstVector '>' --> Vector.
1834 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1835 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001836 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001837
1838 SmallVector<Constant*, 16> Elts;
1839 LocTy FirstEltLoc = Lex.getLoc();
1840 if (ParseGlobalValueVector(Elts) ||
1841 (isPackedStruct &&
1842 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1843 ParseToken(lltok::greater, "expected end of constant"))
1844 return true;
1845
1846 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001847 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001848 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 ID.Kind = ValID::t_Constant;
1850 return false;
1851 }
1852
1853 if (Elts.empty())
1854 return Error(ID.Loc, "constant vector must not be empty");
1855
1856 if (!Elts[0]->getType()->isInteger() &&
1857 !Elts[0]->getType()->isFloatingPoint())
1858 return Error(FirstEltLoc,
1859 "vector elements must have integer or floating point type");
1860
1861 // Verify that all the vector elements have the same type.
1862 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1863 if (Elts[i]->getType() != Elts[0]->getType())
1864 return Error(FirstEltLoc,
1865 "vector element #" + utostr(i) +
1866 " is not of type '" + Elts[0]->getType()->getDescription());
1867
Owen Andersonaf7ec972009-07-28 21:19:26 +00001868 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 ID.Kind = ValID::t_Constant;
1870 return false;
1871 }
1872 case lltok::lsquare: { // Array Constant
1873 Lex.Lex();
1874 SmallVector<Constant*, 16> Elts;
1875 LocTy FirstEltLoc = Lex.getLoc();
1876 if (ParseGlobalValueVector(Elts) ||
1877 ParseToken(lltok::rsquare, "expected end of array constant"))
1878 return true;
1879
1880 // Handle empty element.
1881 if (Elts.empty()) {
1882 // Use undef instead of an array because it's inconvenient to determine
1883 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001884 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001885 return false;
1886 }
1887
1888 if (!Elts[0]->getType()->isFirstClassType())
1889 return Error(FirstEltLoc, "invalid array element type: " +
1890 Elts[0]->getType()->getDescription());
1891
Owen Andersondebcb012009-07-29 22:17:13 +00001892 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001893
1894 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001895 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001896 if (Elts[i]->getType() != Elts[0]->getType())
1897 return Error(FirstEltLoc,
1898 "array element #" + utostr(i) +
1899 " is not of type '" +Elts[0]->getType()->getDescription());
1900 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001901
Owen Anderson1fd70962009-07-28 18:32:17 +00001902 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 ID.Kind = ValID::t_Constant;
1904 return false;
1905 }
1906 case lltok::kw_c: // c "foo"
1907 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001908 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1910 ID.Kind = ValID::t_Constant;
1911 return false;
1912
1913 case lltok::kw_asm: {
1914 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1915 bool HasSideEffect;
1916 Lex.Lex();
1917 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001918 ParseStringConstant(ID.StrVal) ||
1919 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001920 ParseToken(lltok::StringConstant, "expected constraint string"))
1921 return true;
1922 ID.StrVal2 = Lex.getStrVal();
1923 ID.UIntVal = HasSideEffect;
1924 ID.Kind = ValID::t_InlineAsm;
1925 return false;
1926 }
1927
1928 case lltok::kw_trunc:
1929 case lltok::kw_zext:
1930 case lltok::kw_sext:
1931 case lltok::kw_fptrunc:
1932 case lltok::kw_fpext:
1933 case lltok::kw_bitcast:
1934 case lltok::kw_uitofp:
1935 case lltok::kw_sitofp:
1936 case lltok::kw_fptoui:
1937 case lltok::kw_fptosi:
1938 case lltok::kw_inttoptr:
1939 case lltok::kw_ptrtoint: {
1940 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00001941 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 Constant *SrcVal;
1943 Lex.Lex();
1944 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1945 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001946 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001947 ParseType(DestTy) ||
1948 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1949 return true;
1950 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1951 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1952 SrcVal->getType()->getDescription() + "' to '" +
1953 DestTy->getDescription() + "'");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001954 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00001955 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001956 ID.Kind = ValID::t_Constant;
1957 return false;
1958 }
1959 case lltok::kw_extractvalue: {
1960 Lex.Lex();
1961 Constant *Val;
1962 SmallVector<unsigned, 4> Indices;
1963 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1964 ParseGlobalTypeAndValue(Val) ||
1965 ParseIndexList(Indices) ||
1966 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1967 return true;
1968 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1969 return Error(ID.Loc, "extractvalue operand must be array or struct");
1970 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1971 Indices.end()))
1972 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001973 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001974 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 ID.Kind = ValID::t_Constant;
1976 return false;
1977 }
1978 case lltok::kw_insertvalue: {
1979 Lex.Lex();
1980 Constant *Val0, *Val1;
1981 SmallVector<unsigned, 4> Indices;
1982 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1983 ParseGlobalTypeAndValue(Val0) ||
1984 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1985 ParseGlobalTypeAndValue(Val1) ||
1986 ParseIndexList(Indices) ||
1987 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1988 return true;
1989 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1990 return Error(ID.Loc, "extractvalue operand must be array or struct");
1991 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1992 Indices.end()))
1993 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001994 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00001995 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001996 ID.Kind = ValID::t_Constant;
1997 return false;
1998 }
1999 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002000 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 unsigned PredVal, Opc = Lex.getUIntVal();
2002 Constant *Val0, *Val1;
2003 Lex.Lex();
2004 if (ParseCmpPredicate(PredVal, Opc) ||
2005 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2006 ParseGlobalTypeAndValue(Val0) ||
2007 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2008 ParseGlobalTypeAndValue(Val1) ||
2009 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2010 return true;
2011
2012 if (Val0->getType() != Val1->getType())
2013 return Error(ID.Loc, "compare operands must have the same type");
2014
2015 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2016
2017 if (Opc == Instruction::FCmp) {
2018 if (!Val0->getType()->isFPOrFPVector())
2019 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002020 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002021 } else {
2022 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 if (!Val0->getType()->isIntOrIntVector() &&
2024 !isa<PointerType>(Val0->getType()))
2025 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002026 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 }
2028 ID.Kind = ValID::t_Constant;
2029 return false;
2030 }
2031
2032 // Binary Operators.
2033 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002034 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002036 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002037 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002038 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 case lltok::kw_udiv:
2040 case lltok::kw_sdiv:
2041 case lltok::kw_fdiv:
2042 case lltok::kw_urem:
2043 case lltok::kw_srem:
2044 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002045 bool NUW = false;
2046 bool NSW = false;
2047 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 unsigned Opc = Lex.getUIntVal();
2049 Constant *Val0, *Val1;
2050 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002051 LocTy ModifierLoc = Lex.getLoc();
2052 if (Opc == Instruction::Add ||
2053 Opc == Instruction::Sub ||
2054 Opc == Instruction::Mul) {
2055 if (EatIfPresent(lltok::kw_nuw))
2056 NUW = true;
2057 if (EatIfPresent(lltok::kw_nsw)) {
2058 NSW = true;
2059 if (EatIfPresent(lltok::kw_nuw))
2060 NUW = true;
2061 }
2062 } else if (Opc == Instruction::SDiv) {
2063 if (EatIfPresent(lltok::kw_exact))
2064 Exact = true;
2065 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2067 ParseGlobalTypeAndValue(Val0) ||
2068 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2069 ParseGlobalTypeAndValue(Val1) ||
2070 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2071 return true;
2072 if (Val0->getType() != Val1->getType())
2073 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002074 if (!Val0->getType()->isIntOrIntVector()) {
2075 if (NUW)
2076 return Error(ModifierLoc, "nuw only applies to integer operations");
2077 if (NSW)
2078 return Error(ModifierLoc, "nsw only applies to integer operations");
2079 }
2080 // API compatibility: Accept either integer or floating-point types with
2081 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 if (!Val0->getType()->isIntOrIntVector() &&
2083 !Val0->getType()->isFPOrFPVector())
2084 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002085 Constant *C = ConstantExpr::get(Opc, Val0, Val1);
Dan Gohman59858cf2009-07-27 16:11:46 +00002086 if (NUW)
Dan Gohman5078f842009-08-20 17:11:38 +00002087 cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002088 if (NSW)
Dan Gohman5078f842009-08-20 17:11:38 +00002089 cast<OverflowingBinaryOperator>(C)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002090 if (Exact)
2091 cast<SDivOperator>(C)->setIsExact(true);
2092 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 ID.Kind = ValID::t_Constant;
2094 return false;
2095 }
2096
2097 // Logical Operations
2098 case lltok::kw_shl:
2099 case lltok::kw_lshr:
2100 case lltok::kw_ashr:
2101 case lltok::kw_and:
2102 case lltok::kw_or:
2103 case lltok::kw_xor: {
2104 unsigned Opc = Lex.getUIntVal();
2105 Constant *Val0, *Val1;
2106 Lex.Lex();
2107 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2108 ParseGlobalTypeAndValue(Val0) ||
2109 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2110 ParseGlobalTypeAndValue(Val1) ||
2111 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2112 return true;
2113 if (Val0->getType() != Val1->getType())
2114 return Error(ID.Loc, "operands of constexpr must have same type");
2115 if (!Val0->getType()->isIntOrIntVector())
2116 return Error(ID.Loc,
2117 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002118 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002119 ID.Kind = ValID::t_Constant;
2120 return false;
2121 }
2122
2123 case lltok::kw_getelementptr:
2124 case lltok::kw_shufflevector:
2125 case lltok::kw_insertelement:
2126 case lltok::kw_extractelement:
2127 case lltok::kw_select: {
2128 unsigned Opc = Lex.getUIntVal();
2129 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002130 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002132 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002133 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002134 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2135 ParseGlobalValueVector(Elts) ||
2136 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2137 return true;
2138
2139 if (Opc == Instruction::GetElementPtr) {
2140 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2141 return Error(ID.Loc, "getelementptr requires pointer operand");
2142
2143 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002144 (Value**)(Elts.data() + 1),
2145 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002147 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
Eli Friedman4e9bac32009-07-24 21:56:17 +00002148 Elts.data() + 1, Elts.size() - 1);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002149 if (InBounds)
2150 cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 } else if (Opc == Instruction::Select) {
2152 if (Elts.size() != 3)
2153 return Error(ID.Loc, "expected three operands to select");
2154 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2155 Elts[2]))
2156 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002157 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002158 } else if (Opc == Instruction::ShuffleVector) {
2159 if (Elts.size() != 3)
2160 return Error(ID.Loc, "expected three operands to shufflevector");
2161 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2162 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002163 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002164 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 } else if (Opc == Instruction::ExtractElement) {
2166 if (Elts.size() != 2)
2167 return Error(ID.Loc, "expected two operands to extractelement");
2168 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2169 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002170 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 } else {
2172 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2173 if (Elts.size() != 3)
2174 return Error(ID.Loc, "expected three operands to insertelement");
2175 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2176 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002177 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002178 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 }
2180
2181 ID.Kind = ValID::t_Constant;
2182 return false;
2183 }
2184 }
2185
2186 Lex.Lex();
2187 return false;
2188}
2189
2190/// ParseGlobalValue - Parse a global value with the specified type.
2191bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2192 V = 0;
2193 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002194 return ParseValID(ID) ||
2195 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002196}
2197
2198/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2199/// constant.
2200bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2201 Constant *&V) {
2202 if (isa<FunctionType>(Ty))
2203 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2204
2205 switch (ID.Kind) {
Devang Patele54abc92009-07-22 17:43:22 +00002206 default: llvm_unreachable("Unknown ValID!");
2207 case ValID::t_Metadata:
2208 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 case ValID::t_LocalID:
2210 case ValID::t_LocalName:
2211 return Error(ID.Loc, "invalid use of function-local name");
2212 case ValID::t_InlineAsm:
2213 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2214 case ValID::t_GlobalName:
2215 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2216 return V == 0;
2217 case ValID::t_GlobalID:
2218 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2219 return V == 0;
2220 case ValID::t_APSInt:
2221 if (!isa<IntegerType>(Ty))
2222 return Error(ID.Loc, "integer constant must have integer type");
2223 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002224 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 return false;
2226 case ValID::t_APFloat:
2227 if (!Ty->isFloatingPoint() ||
2228 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2229 return Error(ID.Loc, "floating point constant invalid for type");
2230
2231 // The lexer has no type info, so builds all float and double FP constants
2232 // as double. Fix this here. Long double does not need this.
2233 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002234 Ty == Type::getFloatTy(Context)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002235 bool Ignored;
2236 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2237 &Ignored);
2238 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002239 V = ConstantFP::get(Context, ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002240
2241 if (V->getType() != Ty)
2242 return Error(ID.Loc, "floating point constant does not have type '" +
2243 Ty->getDescription() + "'");
2244
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 return false;
2246 case ValID::t_Null:
2247 if (!isa<PointerType>(Ty))
2248 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002249 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 return false;
2251 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002252 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002253 if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002254 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002255 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002256 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002258 case ValID::t_EmptyArray:
2259 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2260 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002261 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002262 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002263 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002264 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002265 if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002266 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002267 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002268 return false;
2269 case ValID::t_Constant:
2270 if (ID.ConstantVal->getType() != Ty)
2271 return Error(ID.Loc, "constant expression type mismatch");
2272 V = ID.ConstantVal;
2273 return false;
2274 }
2275}
2276
2277bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002278 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 return ParseType(Type) ||
2280 ParseGlobalValue(Type, V);
2281}
2282
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002283/// ParseGlobalValueVector
2284/// ::= /*empty*/
2285/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002286bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2287 // Empty list.
2288 if (Lex.getKind() == lltok::rbrace ||
2289 Lex.getKind() == lltok::rsquare ||
2290 Lex.getKind() == lltok::greater ||
2291 Lex.getKind() == lltok::rparen)
2292 return false;
2293
2294 Constant *C;
2295 if (ParseGlobalTypeAndValue(C)) return true;
2296 Elts.push_back(C);
2297
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002298 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 if (ParseGlobalTypeAndValue(C)) return true;
2300 Elts.push_back(C);
2301 }
2302
2303 return false;
2304}
2305
2306
2307//===----------------------------------------------------------------------===//
2308// Function Parsing.
2309//===----------------------------------------------------------------------===//
2310
2311bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2312 PerFunctionState &PFS) {
2313 if (ID.Kind == ValID::t_LocalID)
2314 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2315 else if (ID.Kind == ValID::t_LocalName)
2316 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002317 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002318 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2319 const FunctionType *FTy =
2320 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2321 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2322 return Error(ID.Loc, "invalid type for inline asm constraint string");
2323 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2324 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002325 } else if (ID.Kind == ValID::t_Metadata) {
2326 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002327 } else {
2328 Constant *C;
2329 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2330 V = C;
2331 return false;
2332 }
2333
2334 return V == 0;
2335}
2336
2337bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2338 V = 0;
2339 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002340 return ParseValID(ID) ||
2341 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002342}
2343
2344bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002345 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002346 return ParseType(T) ||
2347 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002348}
2349
2350/// FunctionHeader
2351/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2352/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2353/// OptionalAlign OptGC
2354bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2355 // Parse the linkage.
2356 LocTy LinkageLoc = Lex.getLoc();
2357 unsigned Linkage;
2358
2359 unsigned Visibility, CC, RetAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00002360 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002361 LocTy RetTypeLoc = Lex.getLoc();
2362 if (ParseOptionalLinkage(Linkage) ||
2363 ParseOptionalVisibility(Visibility) ||
2364 ParseOptionalCallingConv(CC) ||
2365 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002366 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002367 return true;
2368
2369 // Verify that the linkage is ok.
2370 switch ((GlobalValue::LinkageTypes)Linkage) {
2371 case GlobalValue::ExternalLinkage:
2372 break; // always ok.
2373 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002374 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002375 if (isDefine)
2376 return Error(LinkageLoc, "invalid linkage for function definition");
2377 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002378 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002379 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002380 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002381 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002382 case GlobalValue::LinkOnceAnyLinkage:
2383 case GlobalValue::LinkOnceODRLinkage:
2384 case GlobalValue::WeakAnyLinkage:
2385 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 case GlobalValue::DLLExportLinkage:
2387 if (!isDefine)
2388 return Error(LinkageLoc, "invalid linkage for function declaration");
2389 break;
2390 case GlobalValue::AppendingLinkage:
2391 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002392 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 return Error(LinkageLoc, "invalid function linkage type");
2394 }
2395
Chris Lattner99bb3152009-01-05 08:00:30 +00002396 if (!FunctionType::isValidReturnType(RetType) ||
2397 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 return Error(RetTypeLoc, "invalid function return type");
2399
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002401
2402 std::string FunctionName;
2403 if (Lex.getKind() == lltok::GlobalVar) {
2404 FunctionName = Lex.getStrVal();
2405 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2406 unsigned NameID = Lex.getUIntVal();
2407
2408 if (NameID != NumberedVals.size())
2409 return TokError("function expected to be numbered '%" +
2410 utostr(NumberedVals.size()) + "'");
2411 } else {
2412 return TokError("expected function name");
2413 }
2414
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002415 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002416
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002417 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 return TokError("expected '(' in function argument list");
2419
2420 std::vector<ArgInfo> ArgList;
2421 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002424 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002425 std::string GC;
2426
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002427 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002428 ParseOptionalAttrs(FuncAttrs, 2) ||
2429 (EatIfPresent(lltok::kw_section) &&
2430 ParseStringConstant(Section)) ||
2431 ParseOptionalAlignment(Alignment) ||
2432 (EatIfPresent(lltok::kw_gc) &&
2433 ParseStringConstant(GC)))
2434 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002435
2436 // If the alignment was parsed as an attribute, move to the alignment field.
2437 if (FuncAttrs & Attribute::Alignment) {
2438 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2439 FuncAttrs &= ~Attribute::Alignment;
2440 }
2441
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 // Okay, if we got here, the function is syntactically valid. Convert types
2443 // and do semantic checks.
2444 std::vector<const Type*> ParamTypeList;
2445 SmallVector<AttributeWithIndex, 8> Attrs;
2446 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2447 // attributes.
2448 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2449 if (FuncAttrs & ObsoleteFuncAttrs) {
2450 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2451 FuncAttrs &= ~ObsoleteFuncAttrs;
2452 }
2453
2454 if (RetAttrs != Attribute::None)
2455 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2456
2457 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2458 ParamTypeList.push_back(ArgList[i].Type);
2459 if (ArgList[i].Attrs != Attribute::None)
2460 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2461 }
2462
2463 if (FuncAttrs != Attribute::None)
2464 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2465
2466 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2467
Chris Lattnera9a9e072009-03-09 04:49:14 +00002468 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002469 RetType != Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00002470 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2471
Owen Andersonfba933c2009-07-01 23:57:11 +00002472 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002473 FunctionType::get(RetType, ParamTypeList, isVarArg);
2474 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002475
2476 Fn = 0;
2477 if (!FunctionName.empty()) {
2478 // If this was a definition of a forward reference, remove the definition
2479 // from the forward reference table and fill in the forward ref.
2480 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2481 ForwardRefVals.find(FunctionName);
2482 if (FRVI != ForwardRefVals.end()) {
2483 Fn = M->getFunction(FunctionName);
2484 ForwardRefVals.erase(FRVI);
2485 } else if ((Fn = M->getFunction(FunctionName))) {
2486 // If this function already exists in the symbol table, then it is
2487 // multiply defined. We accept a few cases for old backwards compat.
2488 // FIXME: Remove this stuff for LLVM 3.0.
2489 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2490 (!Fn->isDeclaration() && isDefine)) {
2491 // If the redefinition has different type or different attributes,
2492 // reject it. If both have bodies, reject it.
2493 return Error(NameLoc, "invalid redefinition of function '" +
2494 FunctionName + "'");
2495 } else if (Fn->isDeclaration()) {
2496 // Make sure to strip off any argument names so we can't get conflicts.
2497 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2498 AI != AE; ++AI)
2499 AI->setName("");
2500 }
2501 }
2502
2503 } else if (FunctionName.empty()) {
2504 // If this is a definition of a forward referenced function, make sure the
2505 // types agree.
2506 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2507 = ForwardRefValIDs.find(NumberedVals.size());
2508 if (I != ForwardRefValIDs.end()) {
2509 Fn = cast<Function>(I->second.first);
2510 if (Fn->getType() != PFT)
2511 return Error(NameLoc, "type of definition and forward reference of '@" +
2512 utostr(NumberedVals.size()) +"' disagree");
2513 ForwardRefValIDs.erase(I);
2514 }
2515 }
2516
2517 if (Fn == 0)
2518 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2519 else // Move the forward-reference to the correct spot in the module.
2520 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2521
2522 if (FunctionName.empty())
2523 NumberedVals.push_back(Fn);
2524
2525 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2526 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2527 Fn->setCallingConv(CC);
2528 Fn->setAttributes(PAL);
2529 Fn->setAlignment(Alignment);
2530 Fn->setSection(Section);
2531 if (!GC.empty()) Fn->setGC(GC.c_str());
2532
2533 // Add all of the arguments we parsed to the function.
2534 Function::arg_iterator ArgIt = Fn->arg_begin();
2535 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2536 // If the argument has a name, insert it into the argument symbol table.
2537 if (ArgList[i].Name.empty()) continue;
2538
2539 // Set the name, if it conflicted, it will be auto-renamed.
2540 ArgIt->setName(ArgList[i].Name);
2541
2542 if (ArgIt->getNameStr() != ArgList[i].Name)
2543 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2544 ArgList[i].Name + "'");
2545 }
2546
2547 return false;
2548}
2549
2550
2551/// ParseFunctionBody
2552/// ::= '{' BasicBlock+ '}'
2553/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2554///
2555bool LLParser::ParseFunctionBody(Function &Fn) {
2556 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2557 return TokError("expected '{' in function body");
2558 Lex.Lex(); // eat the {.
2559
2560 PerFunctionState PFS(*this, Fn);
2561
2562 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2563 if (ParseBasicBlock(PFS)) return true;
2564
2565 // Eat the }.
2566 Lex.Lex();
2567
2568 // Verify function is ok.
2569 return PFS.VerifyFunctionComplete();
2570}
2571
2572/// ParseBasicBlock
2573/// ::= LabelStr? Instruction*
2574bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2575 // If this basic block starts out with a name, remember it.
2576 std::string Name;
2577 LocTy NameLoc = Lex.getLoc();
2578 if (Lex.getKind() == lltok::LabelStr) {
2579 Name = Lex.getStrVal();
2580 Lex.Lex();
2581 }
2582
2583 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2584 if (BB == 0) return true;
2585
2586 std::string NameStr;
2587
2588 // Parse the instructions in this block until we get a terminator.
2589 Instruction *Inst;
2590 do {
2591 // This instruction may have three possibilities for a name: a) none
2592 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2593 LocTy NameLoc = Lex.getLoc();
2594 int NameID = -1;
2595 NameStr = "";
2596
2597 if (Lex.getKind() == lltok::LocalVarID) {
2598 NameID = Lex.getUIntVal();
2599 Lex.Lex();
2600 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2601 return true;
2602 } else if (Lex.getKind() == lltok::LocalVar ||
2603 // FIXME: REMOVE IN LLVM 3.0
2604 Lex.getKind() == lltok::StringConstant) {
2605 NameStr = Lex.getStrVal();
2606 Lex.Lex();
2607 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2608 return true;
2609 }
2610
2611 if (ParseInstruction(Inst, BB, PFS)) return true;
2612
2613 BB->getInstList().push_back(Inst);
2614
2615 // Set the name on the instruction.
2616 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2617 } while (!isa<TerminatorInst>(Inst));
2618
2619 return false;
2620}
2621
2622//===----------------------------------------------------------------------===//
2623// Instruction Parsing.
2624//===----------------------------------------------------------------------===//
2625
2626/// ParseInstruction - Parse one of the many different instructions.
2627///
2628bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2629 PerFunctionState &PFS) {
2630 lltok::Kind Token = Lex.getKind();
2631 if (Token == lltok::Eof)
2632 return TokError("found end of file when expecting more instructions");
2633 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002634 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002635 Lex.Lex(); // Eat the keyword.
2636
2637 switch (Token) {
2638 default: return Error(Loc, "expected instruction opcode");
2639 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002640 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2641 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2643 case lltok::kw_br: return ParseBr(Inst, PFS);
2644 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2645 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2646 // Binary Operators.
2647 case lltok::kw_add:
2648 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002649 case lltok::kw_mul: {
2650 bool NUW = false;
2651 bool NSW = false;
2652 LocTy ModifierLoc = Lex.getLoc();
2653 if (EatIfPresent(lltok::kw_nuw))
2654 NUW = true;
2655 if (EatIfPresent(lltok::kw_nsw)) {
2656 NSW = true;
2657 if (EatIfPresent(lltok::kw_nuw))
2658 NUW = true;
2659 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002660 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002661 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2662 if (!Result) {
2663 if (!Inst->getType()->isIntOrIntVector()) {
2664 if (NUW)
2665 return Error(ModifierLoc, "nuw only applies to integer operations");
2666 if (NSW)
2667 return Error(ModifierLoc, "nsw only applies to integer operations");
2668 }
2669 if (NUW)
Dan Gohman5078f842009-08-20 17:11:38 +00002670 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002671 if (NSW)
Dan Gohman5078f842009-08-20 17:11:38 +00002672 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002673 }
2674 return Result;
2675 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002676 case lltok::kw_fadd:
2677 case lltok::kw_fsub:
2678 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2679
Dan Gohman59858cf2009-07-27 16:11:46 +00002680 case lltok::kw_sdiv: {
2681 bool Exact = false;
2682 if (EatIfPresent(lltok::kw_exact))
2683 Exact = true;
2684 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2685 if (!Result)
2686 if (Exact)
2687 cast<SDivOperator>(Inst)->setIsExact(true);
2688 return Result;
2689 }
2690
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002693 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002694 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002695 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 case lltok::kw_shl:
2697 case lltok::kw_lshr:
2698 case lltok::kw_ashr:
2699 case lltok::kw_and:
2700 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002701 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002703 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002704 // Casts.
2705 case lltok::kw_trunc:
2706 case lltok::kw_zext:
2707 case lltok::kw_sext:
2708 case lltok::kw_fptrunc:
2709 case lltok::kw_fpext:
2710 case lltok::kw_bitcast:
2711 case lltok::kw_uitofp:
2712 case lltok::kw_sitofp:
2713 case lltok::kw_fptoui:
2714 case lltok::kw_fptosi:
2715 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002716 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002717 // Other.
2718 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002719 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2721 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2722 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2723 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2724 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2725 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2726 // Memory.
2727 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002728 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002729 case lltok::kw_free: return ParseFree(Inst, PFS);
2730 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2731 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2732 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002733 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002735 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002736 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002737 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002738 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002739 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2740 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2741 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2742 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2743 }
2744}
2745
2746/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2747bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002748 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002749 switch (Lex.getKind()) {
2750 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2751 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2752 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2753 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2754 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2755 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2756 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2757 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2758 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2759 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2760 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2761 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2762 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2763 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2764 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2765 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2766 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2767 }
2768 } else {
2769 switch (Lex.getKind()) {
2770 default: TokError("expected icmp predicate (e.g. 'eq')");
2771 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2772 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2773 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2774 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2775 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2776 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2777 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2778 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2779 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2780 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2781 }
2782 }
2783 Lex.Lex();
2784 return false;
2785}
2786
2787//===----------------------------------------------------------------------===//
2788// Terminator Instructions.
2789//===----------------------------------------------------------------------===//
2790
2791/// ParseRet - Parse a return instruction.
2792/// ::= 'ret' void
2793/// ::= 'ret' TypeAndValue
2794/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2795bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2796 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002797 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002798 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002799
Owen Anderson1d0be152009-08-13 21:58:54 +00002800 if (Ty == Type::getVoidTy(Context)) {
2801 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002802 return false;
2803 }
2804
2805 Value *RV;
2806 if (ParseValue(Ty, RV, PFS)) return true;
2807
2808 // The normal case is one return value.
2809 if (Lex.getKind() == lltok::comma) {
2810 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2811 // of 'ret {i32,i32} {i32 1, i32 2}'
2812 SmallVector<Value*, 8> RVs;
2813 RVs.push_back(RV);
2814
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002815 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 if (ParseTypeAndValue(RV, PFS)) return true;
2817 RVs.push_back(RV);
2818 }
2819
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002820 RV = UndefValue::get(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2822 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2823 BB->getInstList().push_back(I);
2824 RV = I;
2825 }
2826 }
Owen Anderson1d0be152009-08-13 21:58:54 +00002827 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 return false;
2829}
2830
2831
2832/// ParseBr
2833/// ::= 'br' TypeAndValue
2834/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2835bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2836 LocTy Loc, Loc2;
2837 Value *Op0, *Op1, *Op2;
2838 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2839
2840 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2841 Inst = BranchInst::Create(BB);
2842 return false;
2843 }
2844
Owen Anderson1d0be152009-08-13 21:58:54 +00002845 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002846 return Error(Loc, "branch condition must have 'i1' type");
2847
2848 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2849 ParseTypeAndValue(Op1, Loc, PFS) ||
2850 ParseToken(lltok::comma, "expected ',' after true destination") ||
2851 ParseTypeAndValue(Op2, Loc2, PFS))
2852 return true;
2853
2854 if (!isa<BasicBlock>(Op1))
2855 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002856 if (!isa<BasicBlock>(Op2))
2857 return Error(Loc2, "true destination of branch must be a basic block");
2858
2859 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2860 return false;
2861}
2862
2863/// ParseSwitch
2864/// Instruction
2865/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2866/// JumpTable
2867/// ::= (TypeAndValue ',' TypeAndValue)*
2868bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2869 LocTy CondLoc, BBLoc;
2870 Value *Cond, *DefaultBB;
2871 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2872 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2873 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2874 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2875 return true;
2876
2877 if (!isa<IntegerType>(Cond->getType()))
2878 return Error(CondLoc, "switch condition must have integer type");
2879 if (!isa<BasicBlock>(DefaultBB))
2880 return Error(BBLoc, "default destination must be a basic block");
2881
2882 // Parse the jump table pairs.
2883 SmallPtrSet<Value*, 32> SeenCases;
2884 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2885 while (Lex.getKind() != lltok::rsquare) {
2886 Value *Constant, *DestBB;
2887
2888 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2889 ParseToken(lltok::comma, "expected ',' after case value") ||
2890 ParseTypeAndValue(DestBB, BBLoc, PFS))
2891 return true;
2892
2893 if (!SeenCases.insert(Constant))
2894 return Error(CondLoc, "duplicate case value in switch");
2895 if (!isa<ConstantInt>(Constant))
2896 return Error(CondLoc, "case value is not a constant integer");
2897 if (!isa<BasicBlock>(DestBB))
2898 return Error(BBLoc, "case destination is not a basic block");
2899
2900 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2901 cast<BasicBlock>(DestBB)));
2902 }
2903
2904 Lex.Lex(); // Eat the ']'.
2905
2906 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2907 Table.size());
2908 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2909 SI->addCase(Table[i].first, Table[i].second);
2910 Inst = SI;
2911 return false;
2912}
2913
2914/// ParseInvoke
2915/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2916/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2917bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2918 LocTy CallLoc = Lex.getLoc();
2919 unsigned CC, RetAttrs, FnAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00002920 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002921 LocTy RetTypeLoc;
2922 ValID CalleeID;
2923 SmallVector<ParamInfo, 16> ArgList;
2924
2925 Value *NormalBB, *UnwindBB;
2926 if (ParseOptionalCallingConv(CC) ||
2927 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002928 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 ParseValID(CalleeID) ||
2930 ParseParameterList(ArgList, PFS) ||
2931 ParseOptionalAttrs(FnAttrs, 2) ||
2932 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2933 ParseTypeAndValue(NormalBB, PFS) ||
2934 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2935 ParseTypeAndValue(UnwindBB, PFS))
2936 return true;
2937
2938 if (!isa<BasicBlock>(NormalBB))
2939 return Error(CallLoc, "normal destination is not a basic block");
2940 if (!isa<BasicBlock>(UnwindBB))
2941 return Error(CallLoc, "unwind destination is not a basic block");
2942
2943 // If RetType is a non-function pointer type, then this is the short syntax
2944 // for the call, which means that RetType is just the return type. Infer the
2945 // rest of the function argument types from the arguments that are present.
2946 const PointerType *PFTy = 0;
2947 const FunctionType *Ty = 0;
2948 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2949 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2950 // Pull out the types of all of the arguments...
2951 std::vector<const Type*> ParamTypes;
2952 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2953 ParamTypes.push_back(ArgList[i].V->getType());
2954
2955 if (!FunctionType::isValidReturnType(RetType))
2956 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2957
Owen Andersondebcb012009-07-29 22:17:13 +00002958 Ty = FunctionType::get(RetType, ParamTypes, false);
2959 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002960 }
2961
2962 // Look up the callee.
2963 Value *Callee;
2964 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2965
2966 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2967 // function attributes.
2968 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2969 if (FnAttrs & ObsoleteFuncAttrs) {
2970 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2971 FnAttrs &= ~ObsoleteFuncAttrs;
2972 }
2973
2974 // Set up the Attributes for the function.
2975 SmallVector<AttributeWithIndex, 8> Attrs;
2976 if (RetAttrs != Attribute::None)
2977 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2978
2979 SmallVector<Value*, 8> Args;
2980
2981 // Loop through FunctionType's arguments and ensure they are specified
2982 // correctly. Also, gather any parameter attributes.
2983 FunctionType::param_iterator I = Ty->param_begin();
2984 FunctionType::param_iterator E = Ty->param_end();
2985 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2986 const Type *ExpectedTy = 0;
2987 if (I != E) {
2988 ExpectedTy = *I++;
2989 } else if (!Ty->isVarArg()) {
2990 return Error(ArgList[i].Loc, "too many arguments specified");
2991 }
2992
2993 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2994 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2995 ExpectedTy->getDescription() + "'");
2996 Args.push_back(ArgList[i].V);
2997 if (ArgList[i].Attrs != Attribute::None)
2998 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2999 }
3000
3001 if (I != E)
3002 return Error(CallLoc, "not enough parameters specified for call");
3003
3004 if (FnAttrs != Attribute::None)
3005 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3006
3007 // Finish off the Attributes and check them
3008 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3009
3010 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3011 cast<BasicBlock>(UnwindBB),
3012 Args.begin(), Args.end());
3013 II->setCallingConv(CC);
3014 II->setAttributes(PAL);
3015 Inst = II;
3016 return false;
3017}
3018
3019
3020
3021//===----------------------------------------------------------------------===//
3022// Binary Operators.
3023//===----------------------------------------------------------------------===//
3024
3025/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003026/// ::= ArithmeticOps TypeAndValue ',' Value
3027///
3028/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3029/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003030bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003031 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 LocTy Loc; Value *LHS, *RHS;
3033 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3034 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3035 ParseValue(LHS->getType(), RHS, PFS))
3036 return true;
3037
Chris Lattnere914b592009-01-05 08:24:46 +00003038 bool Valid;
3039 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003040 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003041 case 0: // int or FP.
3042 Valid = LHS->getType()->isIntOrIntVector() ||
3043 LHS->getType()->isFPOrFPVector();
3044 break;
3045 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3046 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3047 }
3048
3049 if (!Valid)
3050 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00003051
3052 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3053 return false;
3054}
3055
3056/// ParseLogical
3057/// ::= ArithmeticOps TypeAndValue ',' Value {
3058bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3059 unsigned Opc) {
3060 LocTy Loc; Value *LHS, *RHS;
3061 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3062 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3063 ParseValue(LHS->getType(), RHS, PFS))
3064 return true;
3065
3066 if (!LHS->getType()->isIntOrIntVector())
3067 return Error(Loc,"instruction requires integer or integer vector operands");
3068
3069 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3070 return false;
3071}
3072
3073
3074/// ParseCompare
3075/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3076/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003077bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3078 unsigned Opc) {
3079 // Parse the integer/fp comparison predicate.
3080 LocTy Loc;
3081 unsigned Pred;
3082 Value *LHS, *RHS;
3083 if (ParseCmpPredicate(Pred, Opc) ||
3084 ParseTypeAndValue(LHS, Loc, PFS) ||
3085 ParseToken(lltok::comma, "expected ',' after compare value") ||
3086 ParseValue(LHS->getType(), RHS, PFS))
3087 return true;
3088
3089 if (Opc == Instruction::FCmp) {
3090 if (!LHS->getType()->isFPOrFPVector())
3091 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003092 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003093 } else {
3094 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 if (!LHS->getType()->isIntOrIntVector() &&
3096 !isa<PointerType>(LHS->getType()))
3097 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003098 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 }
3100 return false;
3101}
3102
3103//===----------------------------------------------------------------------===//
3104// Other Instructions.
3105//===----------------------------------------------------------------------===//
3106
3107
3108/// ParseCast
3109/// ::= CastOpc TypeAndValue 'to' Type
3110bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3111 unsigned Opc) {
3112 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003113 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003114 if (ParseTypeAndValue(Op, Loc, PFS) ||
3115 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3116 ParseType(DestTy))
3117 return true;
3118
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003119 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3120 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003121 return Error(Loc, "invalid cast opcode for cast from '" +
3122 Op->getType()->getDescription() + "' to '" +
3123 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003124 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003125 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3126 return false;
3127}
3128
3129/// ParseSelect
3130/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3131bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3132 LocTy Loc;
3133 Value *Op0, *Op1, *Op2;
3134 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3135 ParseToken(lltok::comma, "expected ',' after select condition") ||
3136 ParseTypeAndValue(Op1, PFS) ||
3137 ParseToken(lltok::comma, "expected ',' after select value") ||
3138 ParseTypeAndValue(Op2, PFS))
3139 return true;
3140
3141 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3142 return Error(Loc, Reason);
3143
3144 Inst = SelectInst::Create(Op0, Op1, Op2);
3145 return false;
3146}
3147
Chris Lattner0088a5c2009-01-05 08:18:44 +00003148/// ParseVA_Arg
3149/// ::= 'va_arg' TypeAndValue ',' Type
3150bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003152 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003153 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003154 if (ParseTypeAndValue(Op, PFS) ||
3155 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003156 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003158
3159 if (!EltTy->isFirstClassType())
3160 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003161
3162 Inst = new VAArgInst(Op, EltTy);
3163 return false;
3164}
3165
3166/// ParseExtractElement
3167/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3168bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3169 LocTy Loc;
3170 Value *Op0, *Op1;
3171 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3172 ParseToken(lltok::comma, "expected ',' after extract value") ||
3173 ParseTypeAndValue(Op1, PFS))
3174 return true;
3175
3176 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3177 return Error(Loc, "invalid extractelement operands");
3178
Eric Christophera3500da2009-07-25 02:28:41 +00003179 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003180 return false;
3181}
3182
3183/// ParseInsertElement
3184/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3185bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3186 LocTy Loc;
3187 Value *Op0, *Op1, *Op2;
3188 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3189 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3190 ParseTypeAndValue(Op1, PFS) ||
3191 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3192 ParseTypeAndValue(Op2, PFS))
3193 return true;
3194
3195 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003196 return Error(Loc, "invalid insertelement operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00003197
3198 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3199 return false;
3200}
3201
3202/// ParseShuffleVector
3203/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3204bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3205 LocTy Loc;
3206 Value *Op0, *Op1, *Op2;
3207 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3208 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3209 ParseTypeAndValue(Op1, PFS) ||
3210 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3211 ParseTypeAndValue(Op2, PFS))
3212 return true;
3213
3214 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3215 return Error(Loc, "invalid extractelement operands");
3216
3217 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3218 return false;
3219}
3220
3221/// ParsePHI
3222/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3223bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003224 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 Value *Op0, *Op1;
3226 LocTy TypeLoc = Lex.getLoc();
3227
3228 if (ParseType(Ty) ||
3229 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3230 ParseValue(Ty, Op0, PFS) ||
3231 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003232 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003233 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3234 return true;
3235
3236 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3237 while (1) {
3238 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3239
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003240 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003241 break;
3242
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003243 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003244 ParseValue(Ty, Op0, PFS) ||
3245 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003246 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3248 return true;
3249 }
3250
3251 if (!Ty->isFirstClassType())
3252 return Error(TypeLoc, "phi node must have first class type");
3253
3254 PHINode *PN = PHINode::Create(Ty);
3255 PN->reserveOperandSpace(PHIVals.size());
3256 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3257 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3258 Inst = PN;
3259 return false;
3260}
3261
3262/// ParseCall
3263/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3264/// ParameterList OptionalAttrs
3265bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3266 bool isTail) {
3267 unsigned CC, RetAttrs, FnAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00003268 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 LocTy RetTypeLoc;
3270 ValID CalleeID;
3271 SmallVector<ParamInfo, 16> ArgList;
3272 LocTy CallLoc = Lex.getLoc();
3273
3274 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3275 ParseOptionalCallingConv(CC) ||
3276 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003277 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003278 ParseValID(CalleeID) ||
3279 ParseParameterList(ArgList, PFS) ||
3280 ParseOptionalAttrs(FnAttrs, 2))
3281 return true;
3282
3283 // If RetType is a non-function pointer type, then this is the short syntax
3284 // for the call, which means that RetType is just the return type. Infer the
3285 // rest of the function argument types from the arguments that are present.
3286 const PointerType *PFTy = 0;
3287 const FunctionType *Ty = 0;
3288 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3289 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3290 // Pull out the types of all of the arguments...
3291 std::vector<const Type*> ParamTypes;
3292 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3293 ParamTypes.push_back(ArgList[i].V->getType());
3294
3295 if (!FunctionType::isValidReturnType(RetType))
3296 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3297
Owen Andersondebcb012009-07-29 22:17:13 +00003298 Ty = FunctionType::get(RetType, ParamTypes, false);
3299 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 }
3301
3302 // Look up the callee.
3303 Value *Callee;
3304 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3305
Chris Lattnerdf986172009-01-02 07:01:27 +00003306 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3307 // function attributes.
3308 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3309 if (FnAttrs & ObsoleteFuncAttrs) {
3310 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3311 FnAttrs &= ~ObsoleteFuncAttrs;
3312 }
3313
3314 // Set up the Attributes for the function.
3315 SmallVector<AttributeWithIndex, 8> Attrs;
3316 if (RetAttrs != Attribute::None)
3317 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3318
3319 SmallVector<Value*, 8> Args;
3320
3321 // Loop through FunctionType's arguments and ensure they are specified
3322 // correctly. Also, gather any parameter attributes.
3323 FunctionType::param_iterator I = Ty->param_begin();
3324 FunctionType::param_iterator E = Ty->param_end();
3325 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3326 const Type *ExpectedTy = 0;
3327 if (I != E) {
3328 ExpectedTy = *I++;
3329 } else if (!Ty->isVarArg()) {
3330 return Error(ArgList[i].Loc, "too many arguments specified");
3331 }
3332
3333 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3334 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3335 ExpectedTy->getDescription() + "'");
3336 Args.push_back(ArgList[i].V);
3337 if (ArgList[i].Attrs != Attribute::None)
3338 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3339 }
3340
3341 if (I != E)
3342 return Error(CallLoc, "not enough parameters specified for call");
3343
3344 if (FnAttrs != Attribute::None)
3345 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3346
3347 // Finish off the Attributes and check them
3348 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3349
3350 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3351 CI->setTailCall(isTail);
3352 CI->setCallingConv(CC);
3353 CI->setAttributes(PAL);
3354 Inst = CI;
3355 return false;
3356}
3357
3358//===----------------------------------------------------------------------===//
3359// Memory Instructions.
3360//===----------------------------------------------------------------------===//
3361
3362/// ParseAlloc
3363/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3364/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3365bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3366 unsigned Opc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003367 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003369 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003371 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003372
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003373 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003374 if (Lex.getKind() == lltok::kw_align) {
3375 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003376 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3377 ParseOptionalCommaAlignment(Alignment)) {
3378 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003379 }
3380 }
3381
Owen Anderson1d0be152009-08-13 21:58:54 +00003382 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 return Error(SizeLoc, "element count must be i32");
3384
3385 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003386 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 else
Owen Anderson50dead02009-07-15 23:53:25 +00003388 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003389 return false;
3390}
3391
3392/// ParseFree
3393/// ::= 'free' TypeAndValue
3394bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3395 Value *Val; LocTy Loc;
3396 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3397 if (!isa<PointerType>(Val->getType()))
3398 return Error(Loc, "operand to free must be a pointer");
3399 Inst = new FreeInst(Val);
3400 return false;
3401}
3402
3403/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003404/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003405bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3406 bool isVolatile) {
3407 Value *Val; LocTy Loc;
3408 unsigned Alignment;
3409 if (ParseTypeAndValue(Val, Loc, PFS) ||
3410 ParseOptionalCommaAlignment(Alignment))
3411 return true;
3412
3413 if (!isa<PointerType>(Val->getType()) ||
3414 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3415 return Error(Loc, "load operand must be a pointer to a first class type");
3416
3417 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3418 return false;
3419}
3420
3421/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003422/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003423bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3424 bool isVolatile) {
3425 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3426 unsigned Alignment;
3427 if (ParseTypeAndValue(Val, Loc, PFS) ||
3428 ParseToken(lltok::comma, "expected ',' after store operand") ||
3429 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3430 ParseOptionalCommaAlignment(Alignment))
3431 return true;
3432
3433 if (!isa<PointerType>(Ptr->getType()))
3434 return Error(PtrLoc, "store operand must be a pointer");
3435 if (!Val->getType()->isFirstClassType())
3436 return Error(Loc, "store operand must be a first class value");
3437 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3438 return Error(Loc, "stored value and pointer type do not match");
3439
3440 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3441 return false;
3442}
3443
3444/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003445/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003446/// FIXME: Remove support for getresult in LLVM 3.0
3447bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3448 Value *Val; LocTy ValLoc, EltLoc;
3449 unsigned Element;
3450 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3451 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003452 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003453 return true;
3454
3455 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3456 return Error(ValLoc, "getresult inst requires an aggregate operand");
3457 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3458 return Error(EltLoc, "invalid getresult index for value");
3459 Inst = ExtractValueInst::Create(Val, Element);
3460 return false;
3461}
3462
3463/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003464/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003465bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3466 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003467
Dan Gohmandcb40a32009-07-29 15:58:36 +00003468 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003469
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003470 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003471
3472 if (!isa<PointerType>(Ptr->getType()))
3473 return Error(Loc, "base of getelementptr must be a pointer");
3474
3475 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003476 while (EatIfPresent(lltok::comma)) {
3477 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003478 if (!isa<IntegerType>(Val->getType()))
3479 return Error(EltLoc, "getelementptr index must be an integer");
3480 Indices.push_back(Val);
3481 }
3482
3483 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3484 Indices.begin(), Indices.end()))
3485 return Error(Loc, "invalid getelementptr indices");
3486 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003487 if (InBounds)
3488 cast<GEPOperator>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003489 return false;
3490}
3491
3492/// ParseExtractValue
3493/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3494bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3495 Value *Val; LocTy Loc;
3496 SmallVector<unsigned, 4> Indices;
3497 if (ParseTypeAndValue(Val, Loc, PFS) ||
3498 ParseIndexList(Indices))
3499 return true;
3500
3501 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3502 return Error(Loc, "extractvalue operand must be array or struct");
3503
3504 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3505 Indices.end()))
3506 return Error(Loc, "invalid indices for extractvalue");
3507 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3508 return false;
3509}
3510
3511/// ParseInsertValue
3512/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3513bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3514 Value *Val0, *Val1; LocTy Loc0, Loc1;
3515 SmallVector<unsigned, 4> Indices;
3516 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3517 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3518 ParseTypeAndValue(Val1, Loc1, PFS) ||
3519 ParseIndexList(Indices))
3520 return true;
3521
3522 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3523 return Error(Loc0, "extractvalue operand must be array or struct");
3524
3525 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3526 Indices.end()))
3527 return Error(Loc0, "invalid indices for insertvalue");
3528 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3529 return false;
3530}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003531
3532//===----------------------------------------------------------------------===//
3533// Embedded metadata.
3534//===----------------------------------------------------------------------===//
3535
3536/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003537/// ::= Element (',' Element)*
3538/// Element
3539/// ::= 'null' | TypeAndValue
3540bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003541 assert(Lex.getKind() == lltok::lbrace);
3542 Lex.Lex();
3543 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003544 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003545 if (Lex.getKind() == lltok::kw_null) {
3546 Lex.Lex();
3547 V = 0;
3548 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003549 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003550 if (ParseType(Ty)) return true;
3551 if (Lex.getKind() == lltok::Metadata) {
3552 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003553 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003554 if (!ParseMDNode(Node))
3555 V = Node;
3556 else {
3557 MetadataBase *MDS = 0;
3558 if (ParseMDString(MDS)) return true;
3559 V = MDS;
3560 }
3561 } else {
3562 Constant *C;
3563 if (ParseGlobalValue(Ty, C)) return true;
3564 V = C;
3565 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003566 }
3567 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003568 } while (EatIfPresent(lltok::comma));
3569
3570 return false;
3571}